Welcome to Scribd, the world's digital library. Read, publish, and share books and documents. See more
Standard view
Full view
of .
Look up keyword
Like this
0 of .
Results for:
No results containing your search query
P. 1


Ratings: (0)|Views: 50 |Likes:
Published by aravinddasa715

More info:

Published by: aravinddasa715 on Oct 27, 2008
Copyright:Attribution Non-commercial


Read on Scribd mobile: iPhone, iPad and Android.
download as DOC, PDF, TXT or read online from Scribd
See more
See less





In this article, you will learn about concepts, advantages, types of caching and aboutimplementation of caching in ASP.NET applications. The code also serves as anexample of using inline coding, creating user controls, trace mechanism, etc.
What is Caching?
Caching is a technique of persisting the data in memory for immediate access torequesting program calls. Many in the developer community consider caching as oneof the features available to improve performance of Web applications.
Why Caching?
Consider a page that has list of Employee name, contact numbers and mail-Ids of existing employees of a company on an intranet accessible by all employees. This isvery useful information that is available throughout the company and could also beone of the most accessed pages. The functionality of adding, updating or deleting isusually less intensive compared to more transaction-based systems like Purchaseordering, Voucher creation etc. Now in a normal scenario the process of queryingdatabase for each request is not cost-effective in terms of server resources, hence islot better to cache or persist the data to avoid this costly loss of resources.
The .NET Advantage
ASP.NET provides the flexibility in terms of caching at different levels.
1. Page Level Output Caching
This is at the page level and one of the easiest means for caching pages. Thisrequires 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 andthe value "none" for VaryByParam* attribute makes sure that there is a singlecached page available for this duration specified.* VaryByParam can take various "key" parameter names in query string. Also thereare other attributes like VaryByHeader, VaryByCustom etc. Please refer to MSDN formore on this.
2. Fragment Caching
Even though this definition refers to caching portion/s of page, it is actually caching auser control that can be used in a base web form page. In theory, if you have usedinclude files in the traditional ASP model then this caching model is like caching theseinclude 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 thatcan 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 levelcaching as shown above, but the power of fragment caching comes from theattribute "VaryByControl". Using this attribute one can cache a user control based onthe properties exposed.Syntax: <%@ OutputCache Duration="60" VaryByControl="DepartmentId" %>
The above syntax when declared within an *.ascx file ensures that the control iscached for 60 seconds and the number of representations of cached control isdependant on the property "DepartmentId" declared in the control.Add the following into an *.ascx file. Please note the use of tag "Control" and thecache declaration.<%@ Control Language="C#"%><%@ outputcache duration="60" varybycontrol="DepartMentId" %><script runat="server"> private int_Departmentid=0; public intDepartMentId {get{return_Departmentid;} set{_Departmentid =value;} } //Load event of controlvoidPage_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; thedeclaration of control using syntax <[TagPrefix]:[TagName]>; Usage of property "DepartMentId". Open the page in two browsers and closely watch the Base formtiming and the User control timing. Also note that the following page results in twocopies or representation of user control in the cache.<%@ Page Language="C#" Trace="true" %><%@ Register TagPrefix="CacheSample" TagName="Text"Src="CachingControl.ascx" %><script runat=server> void Page_Load(Object sender, EventArgs e){this.lbltime.Text ="Base form time is " + DateTime.Now.ToString() + "\n";}</script><html><head></head><body><form runat="server" ID="Form2"> <table><tbody><tr><td><asp:Label id="lbltime" runat="server"></asp:Label> </td></tr><tr><td>
<CACHESAMPLE:TEXT id="instance1" runat="Server" DepartMentId="0"> </CACHESAMPLE:TEXT></td></tr><tr><td><CACHESAMPLE:TEXT id="instance2" runat="Server" DepartMentId="1"> </CACHESAMPLE:TEXT></td></tr></tbody></table>  </form></body></html> 
3. Application Level Caching
With Page level Output caching one cannot cache objects between pages within anapplication. Fragment caching is great in that sense but has limitations by using usercontrols as means to do. We can use the Cache object programmatically to takeadvantage of caching objects and share the same between pages. Further theavailability of different overloaded methods gives a greater flexibility for our Cachepolicy like Timespan, Absolute expiration etc. But one of the biggest takes is theCacheDependancy. This means that one can create a cache and associate with it adependency that is either another cache key or a file.In almost all Web applications there could be numerous master tables that act aslookups to application specific tables. For e.g. if you take up adding a Employee,usually one has master tables like "tblQualification" to get list of qualifications,"tblLocations" to get list of locations etc. These tables* are usually set during theinitial application configuration phase and could be modified once a month or evenless than that. Hence it makes sense for us to use them in our Cache rather thanmaking calls to database on each request. But then what Cache Policy do we adopt?We cannot hold these objects in Cache for entire application instance, because if anybody changes data in these tables one has to also refresh the cache. It is herethat CacheDependancy can be used.* Even though these tables are less frequently used for updates, they are extensivelyused in our select statements through out the applications.Find below the snippet that uses CacheDependancy. Here what I have done is toprovide a list view of existing employees. You need to create a Database in SqlServer, setup some data before you can continue. The schema scripts are enclosed inthe article.Add database connection value in Web.Config and change the value as per yoursetup.<appSettings><add key="conn" value="Data Source=vishnu;trusted_connection=yes;Initial Catalog=Users"/></appSettings>

You're Reading a Free Preview

/*********** DO NOT ALTER ANYTHING BELOW THIS LINE ! ************/ var s_code=s.t();if(s_code)document.write(s_code)//-->