Advertisements

Archive

Posts Tagged ‘Fragment Caching’

How to implement Cache mechanism in ASP.Net/C# using simple example OR What is Output Caching and Fragment Caching in ASP.Net/C#

May 30, 2013 7 comments

What is Caching in ASP.NET AND How can get access to cache object?

ASP.NET Caching is used to build high-performance, scalable ASP.NET web applications by storing responses in memory. On subsequent requests, the page code is not executed and the cached output is used to serve the request. The Cache object is defined in the ‘System.Web.Caching’ namespace. You can get a reference to

the Cache object by using the Cache property of the HttpContext class in the ‘System.Web’

namespace or by using the Cache property of the Page object.

 

What are dependencies in cache and types of dependencies?

When you add an item to the cache, you can define dependency relationships that can force that

item to be removed from the cache under specific activities of dependencies. Example if the

cache object is dependent on file and when the file data changes you want the cache object to be

update. Following are the supported dependency:-

File dependency: – Allows you to invalidate a specific cache item when a disk

based file or files change.

Time-based expiration: – Allows you to invalidate a specific cache item depending

on predefined time.

Key dependency:- Allows you to invalidate a specific cache item depending when

another cached item changes.

 

What are different types of caching using cache object of ASP.NET?

You can use two types of output caching to cache information that is to be transmitted to and

displayed in a Web browser:

Page Output Caching

Page output caching adds the response of page to cache object. Later when

page is requested page is displayed from cache rather than creating the

page object and displaying it. Page output caching is good if the site is

fairly static.

Page Fragment Caching If parts of the page are changing, you can wrap the static sections as user

controls and cache the user controls using page fragment caching.

 

How will implement Page Output Caching?

Output cache functionality is achieved by using “OutputCache” attribute on ASP.NET page

header. Below is the syntax

<%@ OutputCache Duration="20" Location="Server" VaryByParam="state"VaryByCustom="minorversion" VaryByHeader="Accept-Language"%>
  • VaryByParam: – Caches different version depending on input parameters send

through HTTP POST/GET.

  • VaryByHeader: – Caches different version depending on the contents of the page

header.

  • VaryByCustom: –Lets you customize the way the cache handles page variations

by declaring the attribute and overriding the GetVaryByCustomString handler.

  • VaryByControl: –Caches different versions of a user control based on the value of

properties of ASP objects in the control.

 

Simple Example for Implementing Output Caching in ASP.Net/C#

Here we are going to demonstrate a very simple example for implementing ASP.Net Output Cache mechanism. In the below ASPX page we included Output Cache tage with duration of 20Sec. So the page will be cached for the next 20 Secs. After 20 Seconds, it will again loaded from the server.

 

Using Duration option

<%@ OutputCache Duration="20" VaryByParam="none" %>
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="OutputCaching.aspx.cs" Inherits="FragmentCaching.OutputCaching" %>
<!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 runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
   <div>
        <asp:Label ID="lblResult" runat="server"></asp:Label>        <br />
        <br />
        <asp:Button ID="btnPostBack" runat="server" Text="Post Back"  />
        <p>
            The page will be cached 20seconds, and then you can                   click Button to update datetime.
        </p>
    </div>
    </form>
</body>
</html>

 

Using VaryByControl option

<%@ OutputCache Duration="2000" VaryByControl="ddlOption" %>
<!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>OutPut Cache Using VaryByControl Option</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Label ID="lblResult" runat="server"></asp:Label>        <br />
        <br />
        <asp:DropDownList ID="ddlOption" runat="server" AutoPostBack="True" OnSelectedIndexChanged="ddlOption_SelectedIndexChanged"><asp:ListItem Selected="True">Option One</asp:ListItem>            <asp:ListItem>Option Two</asp:ListItem>
            <asp:ListItem>Option Three</asp:ListItem>
        </asp:DropDownList>
        <p>
            The page will be rendered from cache basing on the selected item of DropDownList.
            The different item has corresponding cache.
    </p>
    </div>
    </form>
</body>
</html>

 

Using VaryByCustom

<%@ OutputCache Duration="2000" VaryByCustom="browser" VaryByParam="none" %>
<!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>OutPut Cache Using VaryByCustom Option</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Label ID="lblResult" runat="server"></asp:Label>        <br />
        <br />
        <asp:Button ID="btnPostBack" runat="server" Text="Submit" />
        <p>
            The page will be rendered from cache basing            on the version of browser, such as IE and FireFox.
        </p>
    </div>
    </form>
</body>
</html> 

Using VaryByParam

<%@ OutputCache Duration="2000" VaryByParam="productID" %>
<!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="myHeader" runat="server">
    <title>OutPut Cache Using VaryByParam Option</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Label ID="lblResult" runat="server"></asp:Label>
        <p>
            The page will be rendered from cache until the value of QueryString named "productID" is changed or Duration is expiration.        </p>
    </div>
    </form>
</body>
</html>

 

How will implement Page Fragment Caching?

 

FragmentCaching.aspx:

Fragment caching is useful when you need to cache only a subset of a page. Navigation bars, header, and footers are good candidates for fragment caching. Here we are creating a ASPX page with two usercontrols inside it. We can control the caching of each usercontrols using fragment option as follows.

 

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="FragmentCaching.aspx.cs" Inherits="ExperimentLab.FragmentCaching" %>
<%@ Register TagPrefix="uc1" TagName="FragmentCtrl1" Src="FragmentCtrl1.ascx" %>
<%@ Register TagPrefix="uc1" TagName="FragmentCtrl2" Src="FragmentCtrl2.ascx" %>
<!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 runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <p>
            WebForm Time:
            <asp:Label ID="Time" runat="server" ForeColor="Blue"></asp:Label>
        </p>
        <p>
            <uc1:FragmentCtrl1 ID="FragmentCtrl11" runat="server"></uc1:FragmentCtrl1>
        </p>
        <p>
            <uc1:FragmentCtrl2 ID="FragmentCtrl21" runat="server"></uc1:FragmentCtrl2>
        </p>
    </div>
    </form>
</body>
</html>

 

CodeBehind

protected void Page_Load(object sender, EventArgs e)        
{           
Time.Text = "WebFormTime: " + DateTime.Now.TimeOfDay.ToString();  }

FragmentCtrl1.ascx:

<%@ OutputCache Duration="40" VaryByParam="none"%>
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="FragmentCtrl1.ascx.cs" Inherits="ExperimentLab.FragmentCtrl1" %>
<asp:Label ID="CacheEntryTime" runat="server"></asp:Label>

 

CodeBehind :

protected void Page_Load(object sender, EventArgs e)        
{            
CacheEntryTime.Text = "FragmentCtrl1: " + DateTime.Now.TimeOfDay.ToString();       
}

 

FragmentCtrl2.ascx:

<%@ OutputCache Duration="60" VaryByParam="none" VaryByControl="MyRadioButtonList"%>
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="FragmentCtrl2.ascx.cs" Inherits="ExperimentLab.FragmentCtrl2" %>
<asp:Label ID="CacheEntryTime" runat="server"></asp:Label>
<p>
    <asp:RadioButtonList ID="MyRadioButtonList" runat="server">        <asp:ListItem Selected="True">Yes</asp:ListItem>
        <asp:ListItem>No</asp:ListItem>
        <asp:ListItem>Maybe</asp:ListItem>
    </asp:RadioButtonList>
</p>
<p>
    <asp:Button ID="Button1" runat="server" Text="Submit" />
</p>

 

Code Behind :

protected void Page_Load(object sender, EventArgs e)        
{           
CacheEntryTime.Text = "FragmentCtrl2: " + DateTime.Now.TimeOfDay.ToString();       
}
Advertisements
%d bloggers like this: