Monday, May 27, 2013

Aps.net Cache Concepts

Cache is the technique of persisting the data in the memory for immediate access to requesting program calls. One of the most important factors in building high-performance, scalable Web applications is the ability to store items, whether data objects, pages, or parts of a page, in memory the initial time they are requested.

Although both Application and Cache objects look the same, the key difference between them is the added features provided by the Cache object like the expiration policies and dependencies. It means that the data stored in the cache object can be expired/removed based on some predefined time limit set by the application code or when the dependent entity gets changed whereas this feature is not available in the Application object.
Caches are two different types:

·         Page Level Output Caching
·         Fragment Caching              

Page Level Output Caching:
This is at the page level and one of the easiest means for caching pages. This requires one to specify Duration of cache and Attribute of caching.

Syntax: 
<%@ OutputCache Duration="60" VaryByParam="none" %>

The above syntax specifies that the page be cached for duration of 60 seconds and the value "none" for VaryByParam* attribute makes sure that there is a single cached page available for this duration specified.

* VaryByParam can take various "key" parameter names in query string. Also there are other attributes like VaryByHeader, VaryByCustom etc.

Fragment Caching:
Even though this definition refers to caching portion/s of page, it is actually caching a user control that can be used in a base web form page. In theory, if you have used include files in the traditional ASP model then this caching model is like caching these include files separately. In ASP.NET more often this is done through User Controls. Initially even though one feels a bit misleading, this is a significant technique that can be used especially when implementing "n" instances of the controls in various *.aspx pages. We can use the same syntax that we declared for the page level caching as shown above, but the power of fragment caching comes from the attribute "VaryByControl". Using this attribute one can cache a user control based on the properties exposed.

Syntax: 
<%@ OutputCache Duration="60" VaryByControl="DepartmentId" %>

The above syntax when declared within an *.ascx file ensures that the control is cached for 60 seconds and the number of representations of cached control is dependant on the property "DepartmentId" declared in the control. 

Add the following into an *.ascx file. Please note the use of tag "Control" and the cache declaration.

<%@ Control Language="C#"%>
<%@ outputcache duration="60" varybycontrol="DepartMentId" %>

<script runat="server">
private
 int _Departmentid=0;
public int DepartMentId
{
get{return _Departmentid;}
set{_Departmentid =value;}
}
//Load event of control
void Page_Load(Object sender, EventArgs e)
{
lblText.Text = "Time is " + DateTime.Now.ToString() + " for Department id = " 
+ _Departmentid + "\n";
}
</script>
<
asp:Label id="lblText" runat="server"></asp:Label>

Add the following to an *.aspx file. Please note the way "Register" tag is used; the declaration of control using syntax <[TagPrefix]:[TagName]>; Usage of property " DepartMentId". Open the page in two browsers and closely watch the Base form timing and the User control timing. Also note that the following page results in two copies or representation of user control in the cache.
Let us discuss about different expiration polices and dependencies that are supported.

Dependency:
Dependency means that the ad item can be removed from cache when the dependent gets changed So a dependent relationship can be defined on an item whose removal from the cache will depend on the dependent. There are three types of dependencies supported in ASP.NET.

·             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.

File dependency:
public void displayAnnouncement()
        {
            string announcement = string.Empty;
            if( Cache["announcement"]==null )
            {
                StreamReader file = new StreamReader(@"D:\sekhar.txt");
                announcement = file.ReadToEnd();
                file.Close();
                CacheDependency depends = new CacheDependency(@"D:\sekhar.txt");
                Cache.Insert("announcement", announcement, depends);
                Response.Write(Convert.ToString(Cache["announcement"]));
            }
        }
        protected void Page_Init(object sender, EventArgs e)
        {
            displayAnnouncement();
        }

Above given method displayAnnouncement() displays banner text from Announcement.txt file
which is lying in application path of the file . Above method, first checks whether the
Cache object is nothing, if the cache object is nothing then it moves further to load the cache data
from the file. Whenever the file data changes the cache object is removed and set to nothing.

Time-based expiration:
Time based expiration provides an option to expire an item in the cache at a predefined time. The expiration time can be set as absolute time like 31st October 2005 12:00 or sliding time i.e. relative to the current time when the item is accessed.

    //Absolute Expiration
            Cache.Insert("StudentName", "Anish", null, DateTime.Now.AddDays(1), Cache.NoSlidingExpiration);
            ////Sliding Expiration
            Cache.Insert("StudentName", "Akarsh", null, DateTime.Now.AddDays(1),TimeSpan.FromSeconds(60));

Key dependency: Key dependency is similar to file dependency but the only difference is that instead of a file the item is dependent on another item in the cache and gets invalidated when the dependent item gets changed or removed. This option is useful when multiple related items are added to the cache and those items are to be removed if the primary item is changed. For e.g. employee number, name, address and salary are added to the cache and if the employee number is updated/removed all the related employee information are removed. In this case the employee number dependency can be used for other employee information.

string[] relatedKeys = new string[1];
            relatedKeys[0] = "EMP_NUM";
            CacheDependency keyDependency = new CacheDependency(null, relatedKeys);
            Cache["EMP_NUM"] = 5435;
            Cache.Insert("EMP_NAME", "Anish", keyDependency);
            Cache.Insert("EMP_ADDR", "Tampa", keyDependency);
            Cache.Insert("EMP_SAL", "33647", keyDependency);


No comments:

Post a Comment