Caching Application Pages and Data

Caching is the process of storing frequently used data on the server to fulfill subsequent requests. It uses to increases performance and scalability of site and mostly uses for static content or same data on site using many times.

Types of Caching:

There are 3 types of caching-

  1. Output Caching / Page Caching
  2. Partial Page Caching
  3. Data Caching

1. Output Caching

It caches an entire page. We can enable Page Output Caching by adding an <%@ OutputCache %> directive to a page. When page is cached then the .NET classes that corresponds to the page is not executed with each page request. The page is cached in multiple locations. By default, the page is cached on the web browser, any proxy servers, and on web server.
For example below page content caches for 60 seconds:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="PageCache.aspx.cs" Inherits="PageCache" %>
<%@ OutputCache Duration="60" VaryByParam="none" VaryByCustom="browser" Location="Client" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<%: DateTime.Now.ToString() %>
<hr />
<%: Request.UserAgent %>
</div>
</form>
</body>
</html>

Parameters for output caching:

  1. VaryByParam : the ASP.NET engine will cache the dynamic page based on different query strings provided. If your page generates different content based on the query string, then you need to put that in the output cache directive or else all your users will see the same content.
  2. VaryByHeader : To create different cached version of a page when the value of particular browser header change.
  3. VaryByControl: This attribute enables to generate different versions of a page depending on the value of a particular control in the page. This attribute is useful when we need to create a single page Master/Detail form.
  4. VaryByCustom:In this we can specify a custom function that determines when a different cache version of a page is generated. For this we create the common function in the Global.asax.
    public override string GetVaryByCustomString(HttpContext context, string custom)
        {
            if (custom == "css")
            {
                return Request.Browser.SupportsCss.ToString();
            }
            return base.GetVaryByCustomString(context, custom);
        }

2. Partial Caching:

In this cache technique, Cache portion of page instead of whole page. There are two option for it.

  1. Control Caching: In control caching, also known as fragment caching, you can cache parts of the page output by creating user controls to contain the cached content and then marking the user controls as cacheable. This allows specific content within a page to be cached, while the overall page is recreated each time. In the user control source file, add an OutputCache directive specifying the Duration and VaryByParamattributes. When that user control is loaded into a page at runtime, it is cached. When we set Shared attribute true then all subsequent pages that reference that same user control will retrieve it from the same cache.
  2. Post Cache Substitution : It is the opposite. The page is cached, but fragments within the page are dynamic and should therefore not be cached. Post-cache substitution is used internally by the AdRotator control. Even when you use Page Output Caching to cache a page that contains an Adrotator control, the content rendered by the AdRotator control is not cached. For example:
    UI PartialPageCache.aspx

    <%@ Page Language="C#" AutoEventWireup="true" CodeFile="PartialPageCache.aspx.cs" Inherits="PartialPageCache" %>
    <%@ OutputCache VaryByParam="none" Duration="60" %>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-ransitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head id="Head1" runat="server">
    <title></title>
    </head>
    <body>
    <form id="form1" runat="server">
    <div>
    Cache Time : <%:DateTime.Now %><br />
    Non Cache Time :<asp:Substitution ID="subTime" runat="server" MethodName="GetTime"/>
    </div>
    </form>
    </body>
    </html>
    

    Code File PartialPageCache.aspx.cs

    using System;
    using System.Web;
    
    public partial class PartialPageCache : System.Web.UI.Page
    {
        public static string GetTime(HttpContext context)
        {
            return DateTime.Now.ToString();
        }
    }
    

3.Data Caching:

Data caching stores the required data in cache so that the web server will not send requests to the DB server every time for each and every request, which increases web site performance.

Write and Read Data in Cache:

private DataTable GetMovies()
    {
        if (Cache["Movie"] == null)
        {
            DataTable movieTable = new DataTable();
            using (SqlConnection conn = new SqlConnection("data source=sandeepss-PC; initial catalog= development; user id=sa; password=knowdev"))
            {
                SqlCommand cmd = new SqlCommand("Select * from Movies", conn);
                if (conn.State == ConnectionState.Closed)
                {
                    conn.Open();
                }
                SqlDataReader dr = cmd.ExecuteReader();
                movieTable.Load(dr);
                dr.Close();
                //Cache["Movie"] = movieTable;
                Cache.Insert("Movie", movieTable);
            }
        }
        return (DataTable)Cache["Movie"];
    }

One Response to Caching Application Pages and Data

  1. Towanda says:

    Usually I don’t read article on blogs, but I would like to say that this write-up very compelled me to check out and do so! Your writing style has been surprised me. Thank you, quite nice article.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: