How to store and retrieve Image in Database using C# ASP.Net jQuery

In this article, I’ll explain how to store and retrieve Image in Database using C# ASP.Net jQuery. There is many other way to do that but here is the easiest way to do it.
Database:
For this tutorial, I am using following database.

CREATE TABLE [dbo].[tblImage](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[image] [image] NULL,
 CONSTRAINT [PK_tblImage] PRIMARY KEY CLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

GO

Connection string:
Below is the connection string to connect to the database.

<connectionStrings>
    <add name="TempConnectionString" connectionString="Data Source=ASHISH;Initial Catalog=Temp;Persist Security Info=True;User ID=sa;Password=Temp1234567" providerName="System.Data.SqlClient"/>
</connectionStrings>

Page:
In this tutorial, there one aspx page and one handler.
1. UploadImage.aspx – To Store image into database
2. DisplayImage.aspx – To display image from handler
3. DisplayImage.ashx – To read image from database (Handler)

1. UploadImage.aspx
Upload image
Below HTML Markup of the page, you will notice that I have placed FileUpload to upload image into database.

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="UploadImge.aspx.cs" Inherits="UploadImge" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Ashish Blog</title>
</head>
<body>
    <form id="form1" runat="server">
    <strong>Upload Image into database</strong><br />
    <br />
    Select
Image: <asp:FileUpload ID="FileUpload1" runat="server" /><br />
<br />
<asp:Button ID="butSubmit" runat="server" Text="Submit"
onclick="butSubmit_Click" /><br />
<asp:Label ID="lblStatus" runat="server"></asp:Label>
   <br />
    <br />
    <a href="DisplayImage.aspx">Display Image</a></form>
</body>
</html>

Codebehind:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;

public partial class UploadImge : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
    }
    protected void butSubmit_Click(object sender, EventArgs e)
    {
        try
        {
            Byte[] imgByte = null;
            if (FileUpload1.HasFile &amp;&amp; FileUpload1.PostedFile != null)
            {
                HttpPostedFile File = FileUpload1.PostedFile;
                imgByte = new Byte[File.ContentLength];
                File.InputStream.Read(imgByte, 0, File.ContentLength);
            }
            string cs = ConfigurationManager.ConnectionStrings["TempConnectionString"].ConnectionString;
           using( SqlConnection connection = new SqlConnection(cs))
           {
               connection.Open();
               string sql = "INSERT INTO tblImage(image) VALUES(@theImage) SELECT @@IDENTITY";
               using (SqlCommand cmd = new SqlCommand(sql, connection))
               {
                   cmd.Parameters.AddWithValue("@theImage", imgByte);
                   int id = Convert.ToInt32(cmd.ExecuteScalar());
                   lblStatus.Text = String.Format("Image is Uploaded successfully!! and Image ID is {0}", id);
                   cmd.Dispose();
               }
               connection.Close();
               connection.Dispose();
           }
        }
        catch(Exception ex)
        {
            lblStatus.Text = "There was an error" + ex.Message ;
        }
       
    }
}

2. DisplayImage.aspx
display image
Below HTML Markup of the page, you will notice that I have placed jQuery function to display Image from database. You may also notice that I created Img variable and call ReadImage.ashx handler by passing Image ID in scr attribute of Img then append this Img to div.display.

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="DisplayImage.aspx.cs" Inherits="DisplayImage" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $("#Button1").click(function (e) {
                $('.display').text('');   //clean div display
                var ID = $("#txtID").val();
                if (ID.length > 0) {
                    var newImage = $('<img />');
                    newImage.attr('src', 'ReadImage.ashx?id=' + ID); // call handler with id
                    $('.display').append(newImage);
                }
                e.preventDefault();
            });
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
     Display Image<br />
    <br />
    Id
    <asp:TextBox ID="txtID" runat="server"></asp:TextBox>
&amp;amp;nbsp;<asp:Button ID="Button1" runat="server" Text="Display" />
    <br />
    <br />
    <div class="display"></div>
    <br />
    <br />
    </form>
</body>
</html>

3. DisplayImage.ashx (Handler)

<%@ WebHandler Language="C#" Class="ReadImage" %>

using System;
using System.Web;
using System.Data.SqlClient;
using System.IO;
using System.Configuration;

public class ReadImage : IHttpHandler
{
    
    public void ProcessRequest (HttpContext context) {
        Int32 theID;
        if (context.Request.QueryString["id"] != null)
            theID = Convert.ToInt32(context.Request.QueryString["id"]);
        else
            throw new ArgumentException("No parameter specified");

        context.Response.ContentType = "image/jpeg";
        Stream strm = DisplayImage(theID);
        byte[] buffer = new byte[2048];
        int byteSeq = strm.Read(buffer, 0, 2048);

        while (byteSeq > 0)
        {
            context.Response.OutputStream.Write(buffer, 0, byteSeq);
            byteSeq = strm.Read(buffer, 0, 2048);
        }
    }
    public Stream DisplayImage(int theID)
    { 
        string cs = ConfigurationManager.ConnectionStrings["TempConnectionString"].ConnectionString;
           using( SqlConnection connection = new SqlConnection(cs))
           {
            string sql = "SELECT image FROM tblImage WHERE id = @ID";
            using (SqlCommand cmd = new SqlCommand(sql, connection))
            {
                cmd.CommandType = System.Data.CommandType.Text;
                cmd.Parameters.AddWithValue("@ID", theID);
                connection.Open();
                object theImg = cmd.ExecuteScalar();
                try
                {
                    return new MemoryStream((byte[])theImg);
                }
                catch
                {
                    return null;
                }
                finally
                {
                    cmd.Dispose();
                    connection.Close();
                    connection.Dispose();
                    
                }
            }
        }
        
    }

    public bool IsReusable {
        get {
            return false;
        }
    }
}

Thanks

Download

[wpdm_file id=5]

How to open jQuery UI Dialog from codebehind

In this blog I will show how to open jQuery UI Dialog from codebehind. Basically what we are going to do is render the neccessary JS code for UI dialog from codebehind and when the page will render, it will show the dialog.

Here is Code:

<%@ Page Language="C#" AutoEventWireup="true"  %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Ashish's Blog</title>
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.8/themes/base/jquery-ui.css" type="text/css" media="all" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js" type="text/javascript"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.9/jquery-ui.min.js" type="text/javascript"></script>
<script runat="server">
protected void Button1_Click(object sender, EventArgs e)
{
StringBuilder sb = new StringBuilder();
sb.Append("$(function() { ");
sb.Append(" $('#dialog').dialog({");
sb.Append("    width: 350");
sb.Append(" });");
sb.Append("});");
Page.ClientScript.RegisterStartupScript(typeof(Page), "myscript", sb.ToString(), true);
}
</script>
</head>
<body>
<form id="form2" runat="server">
<div id="dialog" style="display: none">
Welcome to Ashish's Blog
</div>
<asp:Button ID="Button1" runat="server" Text="Test" OnClick="Button1_Click" />
</form>
</body>
</html>

Thanks

Redirection from iframe in asp.net or javascript

In this tutorial we will learn how to perform redirection from IFrame in asp.net.
For example, I has a webpage that contains the form containing two textboxes and one asp:button. When click on button it redirects the user to another page but problem was that the next page was being opened inside the iframe rather than in parent window because the webpage that containing the form was also in iframe.

Solution 1
Here we using the server side onClick event of asp:button to redirecting user to another page and client side OnClientClick event to open new page in parent window. NewWindow() JavaScript code that we have written in the OnClientClick event of asp:button will take care that user must be redirected to next page within parent window rather than IFrame.

Code: (iFrame)

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Ashish Blog</title>
    <script type="text/javascript">
        function NewWindow() {
            document.forms[0].target = "_top";
        }
</script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    Ashish&amp;amp;#39;s Blog<br />
        UserName:<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <br />
        Password:<asp:TextBox ID="TextBox2" runat="server" ></asp:TextBox>
        <br />
        <asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="NewWindow();" onclick="Button1_Click"  />
    </div>
    </form>
</body>
</html>
 protected void Button1_Click(object sender, EventArgs e)
    {
        Response.Redirect("Default.aspx");
    }

Solution 2:

 protected void Button1_Click(object sender, EventArgs e)
    {
       
        ClientScript.RegisterStartupScript(this.GetType(), "redirect", "if(top!=self) {top.location.href = 'Default.aspx';}", true);  
    }

Note:- In case if this code is not working properly in IE9 then you have to give the absolute path of targeting webpage such as

 protected void Button1_Click(object sender, EventArgs e)
    {
       
        ClientScript.RegisterStartupScript(this.GetType(), "redirect", "if(top!=self) {top.location.href = 'http://ashishblog.com/Default.aspx';}", true);  
    }

Display Notification Messages using jQuery

In this article, I am going to show you how to display notification messages in Webpage. Toastmessage-plugin is a JQuery plugin which provides android-like notification messages. The toasted messages arriving on the screen in a seamless and natural way. It’s a quite nice way to report info or error or warning to the user.

Demo

Demo


The plugin is entirely customizable. So you can change the positioning, the required user action, the style and so on.

Installation
The plugin is download from here .

jquery.toastmessage.js        -- the plugin
css/jquery.toastmessage.css   -- the css file
images/error.png              -- image
images/close.gif              -- image
images/notice.png             -- image
images/success.png            -- image
images/warning.png            -- image

Types of messages
4 different types message you can use. Each type comes with its own icon and colored border. The types are:

  • notice
  • success
  • warning
  • error

Easy to use
The following methods will display a toast message:

$().toastmessage('showNoticeToast', 'some message here');
$().toastmessage('showSuccessToast', 'some message here');
$().toastmessage('showWarningToast', 'some message here');
$().toastmessage('showErrorToast', 'some message here');

You can alter the configuration to your special use case.

// user configuration of all toastmessages to come:
$().toastmessage({
    text     : 'Ashish Blog',     // content of the item
    sticky   : true,               // should the toast item sticky or not?
    position : 'top-right',       // top-left, top-center, top-right, middle-left, middle-center, middle-right
                                      // Position of the toast container holding different toast.
                                      // Position can be set only once at the very first call,
                                     // changing the position after the first call does nothing
    type     : 'success',        // notice, warning, error, success
    close    : function () {console.log('toast is closed ...');}
});

Here is example of all type of message code:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>Ashish's Blog</title>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
    <script src="jquery.toastmessage.js" type="text/javascript"></script>
    <link href="jquery.toastmessage.css" rel="stylesheet" type="text/css" />
    <script type="text/javascript">

        function showSuccessToast() {
            $().toastmessage('showSuccessToast', "Success Dialog which is fading away ...");
        }
        function showStickySuccessToast() {
            $().toastmessage('showToast', {
                text: 'Success Dialog which is sticky',
                sticky: true,
                position: 'top-right',
                type: 'success',
                closeText: '',
                close: function () {
                    console.log("toast is closed ...");
                }
            });

        }
        function showNoticeToast() {
            $().toastmessage('showNoticeToast', "Notice  Dialog which is fading away ...");
        }
        function showStickyNoticeToast() {
            $().toastmessage('showToast', {
                text: 'Notice Dialog which is sticky',
                sticky: true,
                position: 'top-left',
                type: 'notice',
                closeText: '',
                close: function () { console.log("toast is closed ..."); }
            });
        }
        function showWarningToast() {
            $().toastmessage('showWarningToast', "Warning Dialog which is fading away ...");
        }
        function showStickyWarningToast() {
            $().toastmessage('showToast', {
                text: 'Warning Dialog which is sticky',
                sticky: true,
                position: 'middle-right',
                type: 'warning',
                closeText: '',
                close: function () {
                    console.log("toast is closed ...");
                }
            });
        }
        function showErrorToast() {
            $().toastmessage('showErrorToast', "Error Dialog which is fading away ...");
        }
        function showStickyErrorToast() {
            $().toastmessage('showToast', {
                text: 'Error Dialog which is sticky',
                sticky: true,
                position: 'center',
                type: 'error',
                closeText: '',
                close: function () {
                    console.log("toast is closed ...");
                }
            });
        }
 
</script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
 
    <p>
            <span class="description">Show a success toast</span> <a href="javascript:showSuccessToast();">not
            sticky</a>|<a href="javascript:showStickySuccessToast();">sticky</a>
        </p>
 
        <p>
            <span class="description">Show a notice toast</span> <a href="javascript:showNoticeToast();">not sticky</a>|<a
                href="javascript:showStickyNoticeToast();">sticky</a>
        </p>
 
        <p>
            <span class="description">Show a warning toast</span> <a href="javascript:showWarningToast();">not
            sticky</a>|<a href="javascript:showStickyWarningToast();">sticky</a>
        </p>
 
        <p>
            <span class="description">Show a error toast</span> <a href="javascript:showErrorToast();">not sticky</a>|<a
                href="javascript:showStickyErrorToast();">sticky</a>
        </p>
 
    </div>
    </form>
</body>
</html>

Thanks.