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

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


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
  1. August 7, 2013 at 4:49 pm

    With havin so much written content do you ever
    run into any issues of plagorism or copyright violation?
    My blog has a lot of completely unique content I’ve either written myself or outsourced but it seems a lot of it is popping it up all over the web without my authorization. Do you know any methods to help protect against content from being stolen? I’d
    truly appreciate it.

  2. August 12, 2013 at 10:14 am

    Hi,
    There are some copy right methods to implement in the blogs.
    Please post your email id so that I will explain more details if I have got information.
    Thanks,
    Tuvian

  3. August 13, 2013 at 1:58 pm

    Pretty part of content. I simply stumbled upon your blog and in accession
    capital to claim that I acquire in fact loved account your blog posts.

    Anyway I’ll be subscribing in your augment and even I achievement you access constantly fast.

  4. August 13, 2013 at 4:17 pm

    I must thank you for the efforts you’ve put in writing this blog. I really hope to see the same high-grade content by you later on as well. In truth, your creative writing abilities has inspired me to get my very own blog now 😉

  5. August 26, 2013 at 4:02 pm

    Thank you for the good writeup. It in fact was a amusement account
    it. Look advanced to more added agreeable from you!

    By the way, how can we communicate?

  6. October 25, 2013 at 5:46 am

    Howdy are using WordPress for your blog platform? I’m new to the blog
    world but I’m trying to get started and create my own.
    Do you require any html coding knowledge to make your own blog?
    Any help would be really appreciated!

  7. November 2, 2013 at 5:46 pm

    My brother suggested I might like this website.

    He was totally right. This post truly made my day. You
    can not imagine simply how much time I had spent for
    this info! Thanks!

  1. No trackbacks yet.

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

%d bloggers like this: