Wednesday, July 22, 2009

Caching in ASP.NET

Caching

is one of the best technique of persisting the data in memory for immediate access to requesting program calls.Caching is about storing data in memory the first time it is requested and then re-using it for the following requests for a specified period of time.

Why Caching is important ?

Every time we have to querying database for each request is not cost-effective in terms of server resources, hence is lot better to cache or persist the data to avoid this costly loss of resources.so in this case we are imporve the system performance and avoid the consistancy.

ASP.Net Provides the flexibility in terms of caching at different levels.

  • Fragment Caching


  • in this case caching a user control that can be used in a base web form page.if you have used include files in the traditional ASP model then this caching model is like caching these include files separately. In ASP.NET more often this is done through User Controls. Initially even though one feels a bit misleading, this is a significant technique that can be used especially when implementing "n" instances of the controls in various *.aspx pages. We can use the same syntax that we declared for the page level caching as shown above, but the power of fragment caching comes from the attribute "VaryByControl". Using this attribute one can cache a user control based on the properties exposed.

    Syntax: <%@ OutputCache Duration="60" VaryByControl="DepartmentId" %>

    The above syntax when declared within an *.ascx file ensures that the control is cached for 60 seconds and the number of representations of cached control is dependant on the property "DepartmentId" declared in the control.

    Add the following into an *.ascx file. Please note the use of tag "Control" and the cache declaration.

    <script runat="server">
    private int _Departmentid=0;
    public int DepartMentId
    {
    get{return _Departmentid;}
    set{_Departmentid =value;}
    }
    //Load event of control
    void Page_Load(Object sender, EventArgs e)
    {
    lblText.Text = "Time is " + DateTime.Now.ToString() + " for Department id = "
    + _Departmentid + "\n";
    }
    </script>
    <asp:Label id="lblText" runat="server"></asp:Label>




    Add the following to an *.aspx file. Please note the way "Register" tag is used;

    the declaration of control using syntax <[TagPrefix]:[TagName]>



    <%@ Page Language="C#" Trace="true" %>
    <%@ Register TagPrefix="CacheSample" TagName="Text" Src="CachingControl.ascx" %>
    <script runat=server>
    void Page_Load(Object sender, EventArgs e)
    {
    this.lbltime.Text ="Base form time is " + DateTime.Now.ToString() + "\n";
    }
    </script>
    <html><head><title></title><body>
    <asp:Label id="lbltime" runat="server"></asp:Label>
    <CACHESAMPLE:TEXT id="instance1" runat="Server" DepartMentId="0">
    </CACHESAMPLE:TEXT>
    <CACHESAMPLE:TEXT id="instance2" runat="Server" DepartMentId="1">
    </CACHESAMPLE:TEXT>
    </body>
    </html>

  • Application Level Caching


  • With Page level Output caching one cannot cache objects between pages within an application. Fragment caching is great in that sense but has limitations by using user controls as means to do. We can use the Cache object programmatically to take advantage of caching objects and share the same between pages. Further the availability of different overloaded methods gives a greater flexibility for our Cache policy like Timespan, Absolute expiration etc. But one of the biggest takes is the CacheDependancy. This means that one can create a cache and associate with it a dependency that is either another cache key or a file.

    Find below the snippet that uses CacheDependancy. Here what I have done is to provide a list view of existing employees. You need to create a Database in Sql Server, setup some data before you can continue. The schema scripts are enclosed in the article.

    Add database connection value in Web.Config and change the value as per your setup.


    <appSettings>
    <add key="conn" value="Data Source=vishnu;trusted_connection=yes;Initial Catalog=Users"/>
    </appSettings>


    First I get the dataset into which I fill the user list. But before this I check for the cache initially if it exists I directly cast it to a dataset, if not create a cache again.
    daUsers.Fill(dsUsers,"tblUsers");

  • Page Level Output Caching

  • This is at the page level and one of the easiest means for caching pages. This requires one to specify Duration of cache and Attribute of caching.


Syntax: <%@ OutputCache Duration="60" VaryByParam="none" %>

The above syntax specifies that the page be cached for duration of 60 seconds and the value "none" for VaryByParam* attribute makes sure that there is a single cached page available for this duration specified.

so at last Caching is a technique that definitely improves the performance of web applications if one is careful to have a balance in terms of which data needs to be cached and parameter values for expiration policy.

hope this article helps you to imporve your applicaiton performance and best result ever

- you can find more information here
- how to perform Cache Optimization

No comments:

Post a Comment