Mobile Content

Saturday, December 24, 2011

Caching in - Output Caching

Caching is the process of storing frequently used data, usually data that is costly to generate, for reuse. Typically this data is stored in memory since retrieving data from memory is much more efficient than retrieving the data from other locations, such as a database.

Caching enables you to store the expensive data into Cache object and later retrieve it without doing expensive operations. A very common example where you want to use caching is datagrid paging. I am sure you all are familiar with datagrid paging which enables you to view the records in multiple pages. Each time you visit a different page all the records are fetched from the database. This becomes very expensive operation. Caching can save a lot of expensive operations since you can store all the records in the cache object and use the cache object as the data source. In this article we will see some important features that caching provides.

There are 3 Caching Type
a. Output Caching
b. Data Caching
c. Fragment Caching

 Output Caching:
The rendered html page is stored into the cache before sending it to the client. Now, if the same page is requested by some other client the already rendered htm page is retrieved from the server memory and sent to the client, which saves the time requires rendering and processing the complete page.
.Declaration: To use output caching, declare the below line at the page:
<@ OutputCache Duration="20" VaryByParam="None">
It means that the page will be cached for the 20 seconds. If any client requests for the same page under this time, the rendered page is sent to it. After 20 seconds the updated/latest version of rendered page replaces the earlier version.
Note: The page is automatically removed when the application is recompiled.

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="caching.aspx.vb" Inherits="caching"  %>
<%@ OutputCache Duration="60" VaryByParam="None" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">

<html xmlns="">
<head runat="server">
    <form id="form1" runat="server">
        <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>

protected void Page_Load(object sender, EventArgs e)
       Label1.Text = DateTime.Now.ToLongTimeString(); 

Label1 get change after 60 sec.
2.Output Caching and Query String: Output caching also supports the query string values to cache the specific pages. On basis of query string parameter values, different pages are cached. For example, in the below declaration:
<@ OutputCache Duration="20" VaryByParam="ProductID">
Different version of page is cached based on different ProductId value. And later when the page is requested with specific query string value (ProductId value), the matching page is retrieved.
It is also possible to specify more than one query string parameter. In those cases the combined value of both the parameter work as a key for pages to be cached. There is also a special case, where "*" is passed as a parameter. In this case, pages are cached for all the separate combinations of the query string arguments.
<@ OutputCache Duration="20" VaryByParam="*">

<%@ OutputCache Duration="60" VaryByParam="*" %>
 <div align="right">
   <a href="OutputCachingTest2.aspx">No Query String</a> | 
   <a href="OutputCachingTest2.aspx?id=1">ID 1</a> | 
   <a href="OutputCachingTest2.aspx?id=2">ID 2</a> | 
   <a href="OutputCachingTest2.aspx?id=3">ID 3</a> |
   <a href="OutputCachingTest2.aspx?id=3&langid=1">ID 3</a>
In the sample project, I am passing a different “ID” in the query string. ASP.NET stores a separate copy for each “ID” and this technique is good in this scenario. But this technique has some problems, if page is accepting wide range of different query strings. In this case, ASP.NET caches separate a copy of page according to query string parameters and potentially lowers the reusability. In this case, you can specify important query string variable names in VarByParam attribute.
 <%@ OutputCache Duration="60" VaryByParam="id;langid" %>
In this case, ASP.NET caches separate version differs by “id” or “langid”.

3.Custom Caching Control: It provides a flexibility to user to cache the page based on their own built custom string. Let's take below example:
<@ OutputCache Duration="20" VaryByParam="None" VaryByCustom="Browser">
User has defined a custom string that will be used to generate the custom cache string. In this case, user wants to cache pages based on browser version. It requires the below method implementation under global.asax page (or should have the below structure):
Public override function GetVaryByCustomString(byval context as HttpContext, byval arg as string) as string
    // Check for the requested type of caching.
    If (arg == "browser") then
        // Determine the current browser.
        dim browserName as string = _
        Context.Request.Browser.Browser + Context.Request.Browser.MajorVersion.ToString() 
        // Indicate that this string should be used to vary caching.
        return browserName
    Else if (arg=="SomeCustomString") then
        //Define the custom cache value for the custom string
    Else MyBase.GetVaryByCustomString(context, arg)
    End If
End Function

 <%@ OutputCache Duration="20" VaryByParam="None" VaryByCustom="browser" %>
You also need to create a method that will generate a custom string for cache. Syntax of the method is:
 public override string GetVaryByCustomString(HttpContext context, string custom)
    if (custom == "browser")
       return context.Request.Browser.Browser +
       return base.GetVaryByCustomString(context, custom);
4.Caching using HttpCachePolicy Class:
It contains methods to perform caching programmatically. Response.Cache property provides the instance of HttpCachePolicy class. Let's see the below example:
Public sub CacheCurrentPage()
    // Cache this page on the server.
    // Use the cached copy of this page for the next 60 seconds.
    // Ensures that the browser can't invalidate the page on click of Refresh button              
End Sub
But, it's awkward to embedded caching through the code.

No comments:

Post a Comment