.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
 
Sign In
Register
 
Win Surprise Gifts!!!
Congratulations!!!



Home >> Articles >> LINQ >> Post New Resource Bookmark and Share

 Subscribe to Articles

Image Manipulation using LINQ to SQL from ASP.Net Application

Posted By :Dhananjay Kumar      Posted Date :14/05/2010   Points :25   Category: LINQ    URL: http://www.dhananjaykumar.net

In this article, I am going to show you How to insert an image from ASP.Net application to SQL Server using LINQ to SQL and how to retrieve image from SQL Server data base using LINQ to SQL and display to an Image control.
 


This article was previously published in my blog Inserting and Retrieving Image using LINQ to SQL from ASP.Net Application


Objective

In this article, I am going to show you How to insert an image from ASP.Net application to SQL Server using LINQ to SQL and how to retrieve image from SQL Server data base using LINQ to SQL and display to an Image control.

Block Diagram of solution

figure1.gif

Description of table


For my purpose, I have created a table called ImageTable.

figure2.gif

  1. Id is primary key.
  2. Name column will contain name of the image file.
  3. FileSource column will contain binary of image. Type of this column is image.
Create ASP.Net Web Application

Open visual studio and from File menu select New Project and then from Web tab select new web application. Give meaningful name to your web application.

Create DBML file using LINQ to SQL class.

For detail description on how to use LINQ to SQL class read HERE
  1. Right click on the project and select add new item.
  2. From DATA tab select LINQ to SQL Class.
  3. On design surface select server explorer.
  4. In server explorer and add new connection.
  5. Give database server name and select database.
  6. Dragged the table on the design surface.
Once all the steps done, you will have a dbml file created.

Design the page
  1. I have dragged one FileUpload control and a button for upload purpose.
  2. One text box. In this text box user will enter Id of the image to be fetched.
  3. One button to fetch the image from database.
  4. One Image control to display image from database.
Default.aspx

figure3.gif

Code View of the above Image

<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">    
    <asp:FileUpload ID="FileUpload1" runat="server" Width="251px" />  
    <asp:Button ID="Button1" runat="server" Text="Upload" onclick="Button1_Click" 
        style="margin-left: 0px" />
    <asp:TextBox ID="TextBox1" runat="server" Width="164px" 
        Text=" " ontextchanged="TextBox1_TextChanged"></asp:TextBox>
    <asp:Button ID="Button2" runat="server" Text="Show" onclick="Button2_Click" 
        Width="102px" />
      <br />   
    <asp:Image ID="Image1" runat="server" Width="570px" />
</asp:Content>

Saving image in table

On click event of Button 1 Image upload will be done.

figure4.gif

Code view of the above image
        protected void Button1_Click(object sender, EventArgs e)
        {
            if (FileUpload1.HasFile && FileUpload1.PostedFile.ContentLength > 0)
            {
                string fileName = FileUpload1.FileName;            
               
                byte[] fileByte = FileUpload1.FileBytes;
                Binary binaryObj = new Binary(fileByte);
                DataClasses1DataContext context = new DataClasses1DataContext();
                context.ImageTables.InsertOnSubmit(
                    new ImageTable { Id = "xyz", 
                        Name = fileName, 
                        FileSource = binaryObj });
                context.SubmitChanges(); 


            }
        }

In this code
  1. First checking whether FileUplad control contains file or not.
  2. Saving the file name in a string variable.
  3. Reading file content in Byte array.
  4. Then converting Byte array in Binary Object.
  5. Creating instance of data context class.
  6. Creating instance of ImageTable class using object initializer. Passing Id as hard coded value. Name as file name and FileSource as binary object.
Retrieving Image from table

On click event of button2 Image will be fetched of a particular Id. Image Id will be given by user in text box.

figure5.gif

Codeview of the above image

        protected void Button2_Click(object sender, EventArgs e)
        {
            Image1.ImageUrl = "~/MyPhoto.ashx?Id="+TextBox1.Text;         
        }


In above code, I am calling a generic HTTP handler. As query string value from textbox1 is appended to the URL of HTTP handler. To add HTTP handler, right click on project and add new item. Then select generic handler from web tab.

figure6.gif

Code View of the above Image

        public void ProcessRequest(HttpContext context)
        {

            string id = context.Request.QueryString["Id"];
            context.Response.ContentType = "image/jpeg";
            Stream strm = ShowEmpImage(id);
            byte[] buffer = new byte[4096];
            int byteSeq = strm.Read(buffer, 0, 4096);
            while (byteSeq > 0)
            {
                context.Response.OutputStream.Write(buffer, 0, byteSeq);
                byteSeq = strm.Read(buffer, 0, 4096);
            }   
        }

        public Stream ShowEmpImage(string id)
        {
            DataClasses1DataContext context1 = new DataClasses1DataContext();
            var r = (from a in context1.ImageTables where a.Id == id select a).First();
            return new MemoryStream(r.FileSource.ToArray());          

        }


In above code,
  1. Reading query string in a variable.
  2. Calling a function returning ShowEmpImage returning Stream.
  3. In ShowEmpImage , creating object DataContext class .
  4. Using LINQ fetching a particular raw from table of a particular ID.
  5. Converting image column in memory stream. In this case FileSource column is containing image.
  6. Converting stream into byte array.
  7. Reading byte array in series of integer.
  8. Using Output stream writing the integer sequence.
Running application

figure7.gif

figure8.gif

figure9.gif

For your reference Source code is given as below

Default.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.Linq;
using System.IO;

namespace uploadingImageusingLInqtoSQl
{
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            if (FileUpload1.HasFile && FileUpload1.PostedFile.ContentLength > 0)
            {
                string fileName = FileUpload1.FileName;            
               
                byte[] fileByte = FileUpload1.FileBytes;
                Binary binaryObj = new Binary(fileByte);
                DataClasses1DataContext context = new DataClasses1DataContext();
                context.ImageTables.InsertOnSubmit(
                    new ImageTable { Id = "xyz", 
                        Name = fileName, 
                        FileSource = binaryObj });
                context.SubmitChanges(); 


            }
        }

        protected void Button2_Click(object sender, EventArgs e)
        {
            Image1.ImageUrl = "~/MyPhoto.ashx?Id="+TextBox1.Text;         
        }

       
    }
}

MyPhto.ashx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using System.Web.UI;
using System.Web.UI.WebControls;


namespace uploadingImageusingLInqtoSQl
{
    /// <summary>
    /// Summary description for MyPhoto
    /// </summary>
    public class MyPhoto : IHttpHandler
    {
        
        public void ProcessRequest(HttpContext context)
        {

            string id = context.Request.QueryString["Id"];
            context.Response.ContentType = "image/jpeg";
            Stream strm = ShowEmpImage(id);
            byte[] buffer = new byte[4096];
            int byteSeq = strm.Read(buffer, 0, 4096);
            while (byteSeq > 0)
            {
                context.Response.OutputStream.Write(buffer, 0, byteSeq);
                byteSeq = strm.Read(buffer, 0, 4096);
            }   
        }

        public Stream ShowEmpImage(string id)
        {
            DataClasses1DataContext context1 = new DataClasses1DataContext();
            var r = (from a in context1.ImageTables where a.Id == id select a).First();
            return new MemoryStream(r.FileSource.ToArray());          

        }
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}
You can also download the sample project used the above example

I hope this post is useful. Thanks for reading. Happy Coding.



Featured Articles


Best Practices No 5: - Detecting .NET application memory leaks
Memory leaks in .NET application have always being programmer's nightmare. Memory leaks are biggest problems when it comes to production servers. Productions servers normally need to run with least down time. Memory leaks grow slowly and after sometime they bring down the server by consuming huge chunks of memory. Maximum time people reboot the system, make it work temporarily and send a sorry note to the customer for the downtime. ... Read More
.NET Best Practice No: 1:- Detecting High Memory consuming functions in .NET code
One of the important factors for performance degradation in .NET code is memory consumption. Many developers just concentrate on execution time to determine performance bottle necks in a .NET application. Only measuring execution time does not clearly give idea of where the performance issue resides. Ok, said and done one of the biggest task is to understand which function, assembly or class has consumed how much memory. In this tutorial we will see how we can find which functions consume how much memory. This article discusses the best practices involved using CLR profiler for studying memory allocation.... Read More
How to improve your LINQ query performance by 5 X times ?
LINQ has been criticized by many early adopters for its performance issues. Well if you are just going to drag and drop using DBML code generator I am sure you will land up in to mess. Try doing this make a simple LINQ to SQL project using DBML and see your SQL profiler, I am sure you will never like to touch DBML code generator again. ... Read More
Responses

No response found. Be the first to respond this post

Post Comment
You must Sign In To post reply
Find More Articles on C#, ASP.Net, Vb.Net, SQL Server and more Here

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend