Wednesday, May 30, 2012

Caching in Asp.Net Part III

Here in this part of the article we will see how we can use page caching in programming and how to use create file dependency for page caching.
So Lets get started with following steps:

Step 1. Create a website with a page PageCaching.aspx with the following markup

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="PageCaching.aspx.cs" Inherits="_Default" %>
<!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>Page Caching</title>
    <script type="text/javascript" language="javascript">
        function ShowTime()
        {
            var dt = new Date();
            document.getElementById("<%= TextBox2.ClientID %>").value = dt.toLocaleTimeString();
            window.setTimeout("ShowTime()", 1000);
        }
    </script>
</head>
<body onload="ShowTime();">
    <form id="form1" runat="server">
        <div>
            <h1> Output Caching Demo(Using File Dependency)<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox></h1>
        </div>
        <div>
            This page is cached for a duration of 60 seconds or dependentfile.txt changes whichever first. 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" BackColor="ButtonHighlight" 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>
</html>

Note that unlike our previous article for page caching we don't use <%@ OutputCache Duration="60" VaryByParam="none" %>  here.. instead we will do that in code.
Step 2. In page load event of the page

protected void Page_Load(object sender, EventArgs e)
    {
        string fileDependencyPath = Server.MapPath("~/dependentfile.txt");//may be somekind of config file
        Response.AddFileDependency(fileDependencyPath);
//or we can use AddFileDependencies if we want a multiple files on which this page is to be dependent.
//so now it know this page is depends on that file unless that file changes this page will be cached.
//we can set some other policy information too.
        Response.Cache.SetExpires(DateTime.Now.AddSeconds(60));//60 sec from now
        //the file will not be cached whenever the file has been changed or the 60 sec has been expired whichever
        //comes first.
        //we will set cachebility
        Response.Cache.SetCacheability(HttpCacheability.Public);
        //we want this to be valid until expires.
        Response.Cache.SetValidUntilExpires(true);

    }

Step 3. The code is self descriptive. Now when you run the page and refresh the page you will see that the time remain constant because the page is being cached.
Now change the content of the file dependentfile.text which is in your project before 60 sec as this is the second criteria.. as soon as you changes file and save it and then refreshes your page the time get changed.

Note that whatever comes first . i.e either 60 second expires or dependentfile.txt changes the cached version of the page will be discarded and regenrated.

More on Caching in future articles..

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.