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"];
    }
Advertisements

Response.Redirect Method

Response is object of HttpResponse class and Redirect method of the HttpResponse class

  1. Respone.Redirect method first sends request for new page to web browser then web browser sends this request to web server then web server sends to response web browser and page change.
  2. Response.Redirect method  can be use for redirect on any type of pages like .aspx,.html,.pdf etc from .aspx page.
  3. Response.Redirect  method changes url of web browser.
  4. Response.Redirect is two overloaded method.

There are two ways of using Response.Redirect-

  1. Response.Redirect(“home.aspx”); //url of new page
  2. Response.Redirect(“home.aspx”, false);/*first parameter url of page, second parameter for endResponse*/

Whenever we use Response.Redirect method a ThreadAbortException exception occurs because Response.Redirect  method call Response.End() internally.

Problem :

When Response.Redirect method call in try block  then catch block excute and exception write in log file means extra code will be execute.

  
try
{
    Response.Redirect("home.aspx");//url of new page
}
catch(Exception ee)
{
    Response.Write(ee.Message);
}

Above code catch block excute and give Exception :

Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack.

Solution :

Response.Redirect method executes after that should not execute Response.End() method. For this Response.Redirect method second parameter set false so that Response.Redirect  method not internal call of Response.End() method.

try
{
    Response.Redirect("home.aspx", false);/*first parameter url of page,second parameter for endResponse*/
}
catch (Exception ee)
{
    Response.Write(ee.Message);
}

Here catch block does not call.