Wednesday, April 4, 2012

How to Preview a image stored in SQL Server using vb.net in Asp.net

In one of my previous posts i showed you you how to store a image SQL SERVER database. This time im going to show how to  preview it back.

So lets move on...............

First of all lets write a method to get the image form the database.


 Public Function getImage(ByVal  CLI_ID  As Integer) As Byte()
        Dim img As Byte() = Nothing
        Dim cmd As New SqlCommand()
        cmd.Connection = con
        cmd.CommandType = CommandType.Text
        cmd.CommandText = "SELECT image  FROM Image WHERE Customer_id=@Customer_id"

        cmd.Parameters.Add("@Customer_id", SqlDbType.VarChar).Value = CLI_ID
        img =   cmd.ExecuteScalar() 
       

        Return img
End Function


Then add this code to your code behind of the aspx page



Dim img As Byte() = getImage(clientID)
        If Not img Is Nothing Then
            Response.BinaryWrite(img)
        End If



So thats all you have to do.
Hope his will help you guys
Cheers...........:)

Monday, April 2, 2012

How to call Server Side function from Client Side Code using Javascript using webMethods

You cannot call server-side code ‘directly’ from client-side code. This is a problem which i faced during a project. Finally i found the solution for it. So i thought of telling you the solution, which might help you too.

 In my case im a taking date from the client side and passing it to the server side. And want to execute a method in server side and return a value to client side according to the value i passed from client side.

So lets see how it goes...................

Following is my javascript method which i wrote to execute the server side method in Calender.aspx .
which contains a method called GetSchedule().
The value Im passing is key. You can reference at  server side as TDate.



function getSchedule(key) {

    var returnMessage = '';
    $.ajax({
        async: false,
        type: 'POST',
        url: './Calender.aspx/GetSchedule',
        data: '{"TDate":"' + key + '"}',
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        success: function(d, status) {
            if (d.d == null) { returnMessage = '';}
            else{
            returnMessage = d.d;}
        },
        error: function(xhr, msg, e) {
            alert(msg);
        }
    });   
    return returnMessage;    


}



This my webMethod written in the code behind....
Don't forget to use the same reference name you used in the javascript method.
Do what ever you want to do inside the method and return the value.


 <WebMethod()> _
   Public Shared Function GetSchedule(ByVal TDate As String) As String
        Dim sdate As DateTime = Convert.ToDateTime(TDate)
       ........................................
       ........................................................
       .................................................................
        Return com
    End Function





In the javascript method you can get the return value using the parameter  d


Hope this will be helpful for you guys.
Cheers........:)






Sunday, April 1, 2012

How to store a image in SQL Server using vb.net in Asp.net

After a long time, I thought of continuing my blog with the new things i learned. Therefore in this post im going give you a brief description about saving images in MSSQL DB and how to preview them.

Database Table

CREATE TABLE Image(
Customer_id int Primary Key NOT NULL,
image image NOT NULL


Simply drag and drop a file uploader from the Toobox , and a button to your aspx page.

AddImage.aspx page


 <asp:FileUpload ID="FileUpload1" runat="server"/>
<br/>
<asp:Button ID="Button7" runat="server" Text="Upload" />

AddImage.aspx.vb 


Declare the following at the top of the page


Public connectionString As String = "Data Source=localhost;Initial Catalog=DatabaseName;Integrated Security=SSPI;User ID=username;Password=password"
Public sqlCmd As SqlCommand
Public adapters As New SqlDataAdapter


I have a seperate method  in the code behind to read the image and return the image as Byte array.

 Private Function ReadFile(ByVal sPath As String) As Byte()
        'Initialize byte array with a null value initially.
        Dim data As Byte() = Nothing


        'Use FileInfo object to get file size.
        Dim fInfo As New FileInfo(sPath)
        Dim numBytes As Long = fInfo.Length


        'Open FileStream to read file
        Dim fStream As New FileStream(sPath, FileMode.Open, FileAccess.Read)


        'Use BinaryReader to read file stream into byte array.
        Dim br As New BinaryReader(fStream)


        'When you use BinaryReader, you need to supply number of bytes to read from file.
        'In this case we want to read entire file. So supplying total number of bytes.
        data = br.ReadBytes(CInt(numBytes))
        Return data
    End Function

Then i m calling my ReadFile method to another method which will make things much more easy and understandable.

Public Function insertImage(ByVal CLI_ID As Integer, ByVal path As String) As Boolean
    
            Dim imageData As Byte() = ReadFile(path) 'Calling the ReadFile() Method
            


        Dim con As New SqlConnection(connectionString)
        con.Open()
        Dim cmd As New SqlCommand()
        cmd.Connection = con
        cmd.CommandType = CommandType.Text
        cmd.CommandText = "INSERT INTO Image(   Customer_id , image ) VALUES(@Customer_id, @name)"
        cmd.Parameters.Add("@Customer_id", SqlDbType.VarChar).Value = CLI_ID 
        cmd.Parameters.Add("@ image ", SqlDbType.Binary).Value = imageData 
      
        con.Close()
        BindData()
.
        End Using

    End Function

After that im calling the insertImage() method to Button click event.

Protected Sub Button7_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button7.Click

        If FileUpload1.PostedFile IsNot Nothing AndAlso FileUpload1.PostedFile.FileName <> "" Then
            Dim imageSize As Byte() = New Byte(FileUpload1.PostedFile.ContentLength - 1) {}
            Dim uploadedImage__1 As HttpPostedFile = FileUpload1.PostedFile
            uploadedImage__1.InputStream.Read(imageSize, 0, CInt(FileUpload1.PostedFile.ContentLength))


            Dim path As String = FileUpload1.PostedFile.FileName
            Dim clientId As Integer = 000001  'Enter client id
            insertImage(clientId, path)


        End If
    End Sub


So thats all you have to do. Just copy paste the Content in appropriate places then it will work fine.
Hope this will help you guys.
Cheers.....:)

Friday, January 7, 2011

How to Connect GridView to MySql

First of all u need to install the MySql Connecter(MySql.Data).
Then add the MySql.Data , by rightClicking on References , in the Solution Explorer.

MySqlConnection conn = new MySqlConnection(ConfigurationManager.ConnectionStrings["NetsGate"].ToString());


//select data from database
  MySqlCommand cmdGetData = new MySqlCommand("SELECT * FROM Employee",conn);

                conn.Open();
                MySqlDataAdapter daGetData = new MySqlDataAdapter(cmdGetData);
                DataSet dsGetData = new DataSet();
                daGetData.Fill(dsGetData);
                conn.Close();

                GridView1.DataSource = dsGetData;
                GridView1.DataBind();


Don't forget declare the connection String in the web.Config

Place this tag within the <connectionStrings> tag in web.Config
<add name="NetsGate" connectionString="SERVER=localhost;UID=root;DATABASE=leave_mub;PASSWORD="
   providerName="System.Data.SqlClient" />



Hope this will be helpfull for u guys ........................