Wednesday, 9 January 2013

Short Term Storage Using HttpContext.Current.Items is's best secret

Click to Download C# Example
Click to Download VB.NET Example

ASP.NET’s best kept secrets is The Items collection of HttpContext. This is an IDictionary key/value collection of objects that’s shared and access across the life of a single HttpRequest. This short term storage because it stores data in single HttpRequest.

There are some reasons why we should need this type of storage.
  • Communicate between two instances of the same UserControl on the same page : This situations occurs when you have one and and put one user control two times on different section of page and display same content. At that time we get data from database when first control load and after that we preserve this data in HttpContext.Current.Items and when second control load it will check that data is exist in Items if yes then directly get data from that and we avoid unnecessary database trip. Another scenario , You develop user control which display advertise and you put two instances of that control on same page and you want to display unique advertise at that time HttpContext very helpful.

  • Store the results of expensive calls that might happen twice or more on a page: If we have multiple User Controls on same page and each display a data from a large, more expensive database retrieval, those UserControls can retrieve the necessary data from HttpContext.Items. The database is hit only once.
  • Share content between IHttpModules and IHttpHandlers: If we write a custom IHttpModule, we can store context about the user for use later in a page.

The Items collection store objects, like many of the collections. When you retrieved those stored objects you need to cast those objects back to their specific type.

Before you implement any caching mechanism you need to analyze your requirement. If you put caching unnecessary it will put burden on your server.
Do not cache just because it is good; cache because it makes sense.

Here is example for this.
This example checks the Items collection of the current HttpContext to see whether the data is already there. If it is not then data is retrieved from the database and store in the Items collection. Subsequent calls to this function within the same HttpRequest receive the already cached object.
 In this example we create one user control name "WebUserControl_WithHttpContext.ascx". This control has one method "GetExpensiveCount". This method return cont string which may come for very expensive database call. In this method when data retrieve from database it will store in HTTPContext item collection when in single HttpRequest again this method called at that time it will check that if data is exist in cache it will give from that cache so we avoid one unnecessary Database call. We need to specify one key for retrieve specific data.

ASPX Code (ImplementHTTPContext.aspx) :

<%@ Register src="WebUserControl_WithHttpContext.ascx" tagname="WebUserControl_WithHttpContext" tagprefix="uc1" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">
<html xmlns="">
<head runat="server">
    <form id="form1" runat="server">
            <tr style="height:50px">
                    Header: <br />
                    <uc1:WebUserControl_WithHttpContext ID="WebUserControl_WithHttpContext_Header" 
            <tr style="height:300px">
            <tr style="height:50px">
                    Footer : <br />
                    <uc1:WebUserControl_WithHttpContext ID="WebUserControl_WithHttpContext2_Footer" runat="server"></uc1:WebUserControl_WithHttpContext>

User Control .ascx Code ("WebUserControl_WithHttpContext.ascx"):

Expensive Count : <asp:Label runat="server" ID="lblCount"></asp:Label>

C#. Net  Example("WebUserControl_WithHttpContext.ascx.cs") :

    protected void Page_Load(object sender, EventArgs e)
        lblCount.Text = GetExpensiveCount("count").ToString();

    public string GetExpensiveCount(string KeyID)
        string strRef = string.Empty;
        string key = "count_data" + KeyID;
        object obj = HttpContext.Current.Items[key];
        int intCount = 0;
        if (obj != null)
            //Get from cache
            intCount = (int)obj;
            strRef = "From cache , ";
            //Call Database query and get result and store
            intCount = 20;
            HttpContext.Current.Items[key] = intCount;
            strRef = "From Database , ";
        return strRef + intCount.ToString();

VB.Net Examples ("WebUserControl_WithHttpContext.ascx.vb") :

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        lblCount.Text = GetExpensiveCount("count").ToString()
    End Sub

    Public Function GetExpensiveCount(ByVal KeyID As String) As String
        Dim strRef As String = String.Empty
        Dim key As String = "count_data" & KeyID
        Dim obj As Object = HttpContext.Current.Items(key)
        Dim intCount As Integer = 0
        If obj IsNot Nothing Then
            'Get from cache
            intCount = CInt(obj)
            strRef = "From cache , "
            'Call Database query and get result and store
            intCount = 20
            HttpContext.Current.Items(key) = intCount
            strRef = "From Database , "
        End If
        Return strRef & intCount.ToString()
    End Function

Output : 

Short Term Storage in

Note : Give Us your valuable feedback in comments. Give your suggestions in this article so we can update our articles according to that.

No comments:

Post a Comment