Wednesday, May 30, 2012

Caching in Asp.Net Part II

In this section
i) how to remove cache programmatically
ii) Page caching using cache profiler

This is second in the series of article for Asp.Net caching.
In the first part we saw how to use page caching.
Let's start with discarding the cached version of a page.
Suppose you have a page and a button on it. and you want each time the button is clicked the fresh version of the page should be load. Its just a simple. just add the following line of code in the click event of the button.


<body>
    <form id="form1" runat="server">
    <div>
    <h1> Output Caching Demo</h1>
   </div>
   <div>
This page is cached for a duration of 5 seconds. When this page was last cached the date/time was <span style="color:Red;"> <%=DateTime.Now.ToLongTimeString()%>. </span>
<br />Refresh repeatedly and <b>you'll see that this time remains constant until the cache is expired</b>, then it is updated to the current time.
<br />The reason this time stays constant is because the HTML generated by this ASP.NET Web page is cached using Output Caching. <br />To enable Output Caching, simply add the following declaration to the top of your ASP.NET Web page:
<asp:Label ID="lblOutputCache" runat="server" BorderWidth="1" Text="< %@OutputCache Duration='durationInSeconds' VaryByParam='varyBy' % >"></asp:Label>
</div>
<div>
<h3>Removing Cache:</h3>
<span>following button will remove the Cache and each time following button is <br />
clicked a fresh version will be seen.</span>
 <asp:Button ID="btnRemoveCache" runat="server" Text="Remove Cache Version"
           onclick="btnRemoveCache_Click" />
</div>
   
    </form>
</body>


protected void btnRemoveCache_Click(object sender, EventArgs e)
    {
        Response.Cache.SetCacheability(HttpCacheability.NoCache);
    }
 
Ok so far so good!
 Now lets see the next stuff. Page caching using cache profile.

We can as an alternate  way to our first article create the cache in web.config as below


<system.web>
<caching>
          <outputCacheSettings>
          <outputCacheProfiles>
          <add name="cache60Seconds" duration="60" varyByParam="none"></add>
          </outputCacheProfiles>
        </outputCacheSettings>
      </caching>

 </system.web>

This creates a cache profile which we can use in the page we want using following markup.


<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>
<%@ OutputCache  CacheProfile="Cache60Seconds" %>

In the next article we will see how can we create a dependency for the cache. i.e the cache should remain valid until the content of some given file (may be configuration file) changes.

 

No comments:

Post a Comment