Dynamic Page Headers

Learn how to dynamically change a page header banner based on an image stored in the database through HTTP Handler class.
- Jaime Jegonia, Chief IT Consultant of JimiTron Software

October 31, 2008
Iron Speed Designer V5.X

Introduction

While contemplating a few options for dynamic loading of a Page Headers, I came across many articles that focused on displaying images stored in the database. I found the most efficient way of doing the job is by using ASP.Net HTTP Handler (.ashx).

An ASP.NET HTTP Handler is a simple class that allows you to process a request and return a response to the browser. Simply put, a handler is responsible for fulfilling requests from the browser. A handler processes one request at a time, this provides high performance. A handler class implements the HttpHandler interface.

Reference: http://www.aspdotnetcodes.com/Insert_Images_Database.aspx

Solution

Start by creating a handler (ShowImage.ashx) at the shared folder using a generic handler template from Microsoft Visual Studio (2005 or 2008). Copy the sample code and edit it according to your table properties and connectionString. Check for the available image and corresponding call at the Header.ascx.cs (or Header.ascx.vb).

Implementation

The ShowImage.ashx handler contains only one method called ProcessRequest. This method performs a data retrieval process and returns only the Image Content field as bytes of array. The Image Content field is automatically pulled by the header to display in every page.

The code sample that follows retrieves the banner from the database to display in the header.

C#: ShowImage.ashx

<%@ WebHandler Language="C#" Class="ShowImage" %>
 
 
 
using System;
using System.Configuration;
using System.Web;
using System.IO;
using System.Data;
using System.Data.SqlClient;
 
public class ShowImage : IHttpHandler
{
 
    public void ProcessRequest(HttpContext context)
  {
      try
      {
         int compno;
         if (!(context.Request.QueryString["cid"] == null))
         {
                  compno = Convert.ToInt32(context.Request.QueryString["cid"]);
         }
         else
         {
                  throw new ArgumentException("No parameter specified");
         }
         context.Response.ContentType = "image/jpeg"; // also works with gif
 
 
         Stream strm = ShowEmpImage(compno);
 
         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);
         }
    }
    catch
    {
         // Do Nothing
    }
  }
 
 
  public Stream ShowEmpImage(int compno)
  {
    string conn = ConfigurationManager.AppSettings["DatabaseBanner1"];
    SqlConnection connection = new SqlConnection(conn);
    string sql = "SELECT HdrBanner FROM tblCompany WHERE CompanyID = @CID";
    SqlCommand cmd = new SqlCommand(sql, connection);
    cmd.CommandType = CommandType.Text;
    cmd.Parameters.AddWithValue("@CID", compno);
    connection.Open();
    object img = cmd.ExecuteScalar();
    try
    {
         return new MemoryStream((byte[])img);
    }
    catch
    {
         return null;
    }
    finally
    {
         connection.Close();
    }
  }
 
  public bool IsReusable
  {
    get
    {
         return false;
    }
  }
}

Visual Basic .NET: ShowImage.ashx

<%@ WebHandler Language="vb" Class="ShowImage" %>  
Imports System
Imports System.Configuration
Imports System.Web
Imports System.IO
Imports System.Data
Imports System.Data.SqlClient
 
Public Class ShowImage
  Implements IHttpHandler
  Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
    Try
        Dim compno As Integer
        If Not context.Request.QueryString("cid") Is Nothing Then
           compno = Convert.ToInt32(context.Request.QueryString("cid"))
        Else
           Throw New ArgumentException("No parameter specified")
        End If
 
 
        context.Response.ContentType = "image/jpeg" // also works with gif
        Dim strm As Stream = ShowEmpImage(compno)
        Dim buffer As Byte() = New Byte(4095) {}
        Dim byteSeq As Integer = strm.Read(buffer, 0, 4096)
 
        Do While byteSeq > 0
           context.Response.OutputStream.Write(buffer, 0, byteSeq)
           byteSeq = strm.Read(buffer, 0, 4096)
        Loop
 
    Catch
        'Do Nothing
    End Try
 
  End Sub
 
  Public Function ShowEmpImage(ByVal compno As Integer) As Stream
    Dim conn As String = ConfigurationManager.AppSettings("DatabaseBanner1")
    Dim connection As SqlConnection = New SqlConnection(conn)
    Dim sql As String = "SELECT HdrBanner FROM tblCompany WHERE CompanyID = @CID"
    Dim cmd As SqlCommand = New SqlCommand(sql, connection)
    cmd.CommandType = CommandType.Text
    cmd.Parameters.AddWithValue("@CID", compno)
    connection.Open()
    Dim img As Object = cmd.ExecuteScalar()
 
    Try
        Return New MemoryStream(CType(img, Byte()))
    Catch
        Return Nothing
 
    Finally
        connection.Close()
    End Try
  End Function
 
  Public ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
    Get
        Return False
    End Get
  End Property
 
 
End Class

The call is done at the header’s LoadData() to display the banner in a synchronized fashion.

C#: Header.ascx.cs

public void LoadData()   {  
    LoadData_Base();
     try
     {
    string userId = ((BaseApplicationPage)this.Page).SystemUtils.GetUserID();
 
          VCompanyBannerRecord uC = VCompanyBannerView.GetRecord("UserID = " + userId);
 
          int compid = uC.CompanyID;
 
 
          if (uC.HdrBanner == null)
          {
          // Display the default banner from Images folder
           PageHeader__Logo.ImageUrl = "../Images/logo.gif";
          }
          else
          {
          // Display the HeaderBanner from the database
           PageHeader__Logo.ImageUrl = ("../Shared/ShowImage.ashx?cid=" + compid);
          }
     }
     catch
     {
          // Do Nothing
     }
 
  }

Visual Basic .NET: Header.ascx.vb

Public Sub LoadData()
 
  LoadData_Base()
 
  Try
    Dim userId As String = (CType(Me.Page, BaseApplicationPage)).SystemUtils.GetUserID()
    Dim uC As VCompanyBannerRecord = VCompanyBannerView.GetRecord("UserID = "
    + userId)
    Dim compid As Integer = uC.CompanyID
 
        If uC.HdrBanner Is Nothing Then
            ' Display the default banner from Images folder
          PageHeader__Logo.ImageUrl = "../Images/et_headerbanner.jpg"
        Else
            ' Display the HeaderBanner from the database
          PageHeader__Logo.ImageUrl = "../Shared/ShowImage.ashx?cid=" & compid
        End If
 
  Catch
        'Do Nothing
  End Try
 
End Sub

Conclusion

This method of image retrieval and display is very effective!

Download the working sample at www.jimitron.net/download/DynamicHeaderArticle.rar
(The download also includes 30 different page headers to play with.)

About the Author

Jaime is a Chemical Engineer by training and a .NET web developer by avocation. His passion for development has transformed him into an Information Technology Consultant and owner of JimiTron Software. He is a recognized Microsoft Independent Software Vendor and is also a member of the Microsoft Partner Program.

Jaime holds a degree in Chemical Engineering from the University of San Agustin of Iloilo City, Philippines.



  Privacy Statement