Monday, October 27, 2008

Displaying images in ASP.NET using HttpHandlers

Introduction

Most of the time when developing web applications/projects we find the need to display images dynamically on the ASP.NET pages. This can include customer pictures or your product pictures. And normally there are two way of storing the pictures on your database. First, stored the images file in the database, and second one would be storing the images binary data inside the database. Most of the database including MSSQL support storing images as binary format.

Retrieving images dynamically from database based on filename can be quite simple. What we normally do is store all the images on certain folder , get the file name from the database, and then set the image server control path based on the filename and path that we get from database.


Retrieving images dynamically from database based the image binary format on the other hand also is simple. You just need to do Response.BinaryWrite,after you have got the data from the database.
In this tutorial, I will show you how to simplify the code of displaying images by using the HttpHandler. By using HTTPHandler, you only need one single line of html code to dynamically find and display your images from database regardless of you are storing the image only or you are storing the image data.

What is HTTPHandler

HttpHandlers are the earliest possible point where we have access to the requests made to the web server (IIS). When a request is made to the web server for an ASP.NET resource (.aspx, .asmx, etc.), the worker process of the ASP.NET creates the right HttpHandler for the request which responds to the request. The default handlers for each request type that ASP.NET handles are set in the machine.config file. For example, all the requests made to ASP.NET (.aspx) pages are handled by System.Web.UI.PageHandlerFactory. So whenever an ASP.NET is requested at the web server, the PageHandlerFactory will fulfill the request.

Why Http Handlers

Almost everything we do in an HttpHandler, we can simply do it in a normal .aspx page. Then why do we need HttpHandlers? First, the HttpHandlers are more reusable and portable than the normal .aspx pages. Since there are no visual elements in an HttpHandler, they can be easily placed into their own assembly and reused from project to project. Second, HttpHandlers are relatively less expensive than the PageHandler. For a page to be processed at the server, it goes through a set of events (onInit, onLoad, etc.), viewstate and postbacks or simply the complete Page Life Cycle. When you really have nothing to do with the complete page life cycle (like displaying images), HttpHandlers are very useful.


Creating an HttpHandler

To create HTTPHandler, your class need to implement IHttpHandler interface and you need to override two methods. The method name is IsReusable and ProcessRequest. HttpHandler has been known with .ashx extension in ASP.NET World.
Now, lets start coding HttpHandler.

Create new ashx file from VisualStudio
<%@ WebHandler Language="C#" Class="getImage" %>

using System;
using System.Web;
using dsImagesTableAdapters;

public class DisplayImage: IHttpHandler {

public void ProcessRequest (HttpContext context) {
int iImageId;
if (context.Request.QueryString["id"] != null)
{
iImageId = Convert.ToInt32(context.Request.QueryString["id"]);
}
else {
throw new ArgumentException("No parameter specified");
}

DataSet dsImages = GetDataSetImagesfromDatabase();
DataTable dtImgTable = dsImages.Tables[0];
if (dtImgTable .Rows.Count > 0)
{
if (dtImgTable [0]["Image"] != DBNull.Value)
{
context.Response.ContentType =
dtImgTable [0]["ImageType"].ToString();
context.Response.BinaryWrite((byte[])dtImgTable[0]["Image"]);
}
}
}

public bool IsReusable {
get {
return false;
}
}
The code above is quite self explanatory. We search the images data based on the query string passed into the HttpHandler. Please note that the code above assume that we are storing the image binary format into database and thats why we are using Response.BinaryWrite to output the result to client.
You can change the code above by using your own logic.


Now, to use the HttpHandler on your ASP.NET Pages,

<img alt="httpHandler" src="DisplayImage.ashx?id=1">

Conclusion

As you can see from the code sample above, your code is very easy to read if you are using HttpHandler to handle some of the operation on your ASP.NET pages such as displaying images. There are lots more things you can do in HttpHandler to make your code easier to read and maintain. Please leave me a comment if you have any difficulties in understanding the concept of HttpHandler.

No comments: