Prizes & Awards
My Profile
Active Members
TodayLast 7 Days
more...
|
New Feature: Community Sites:
Create your own .NET community website and start earning from Google AdSense !
It's Free !
|
Caching in ASP.NET
|
Caching ASP.Net pages.
Caching can be achieved in ASP.Net pages by the following 2 ways.
1).Specify the @OutputCache directive at the top of the ASP.Net page 2).Program against the HttpCachePolicy class. This class can be accessed from the HttpResponse.Cache property of the Page.Response property. When one of these are added to the ASP.Net page, the response page is saved in the cache when the first Get method is made for the page. Subsequent GET, POST and HEAD requests for the page then refer to the cache untill the cache expires.
Responses generated by the GET request with query strings or the POST request can be cached with explicit settings. In that case, the GET requests with identical key-value pairs refer to the cache as long as the duration is set. Only when the case is changed or with different values or pairs, a new response is generated (and cached for later use).
Following are some of the key concepts for caching ASP.Net pages.
1).Set the expiration policy.
Using @OutputCache directive. Include this directive at the top of the aspx page which you want to cache.
<%@ OutputCache Duration="60" VaryByParam="None" %>
Duration is the lifetime of the cache in seconds. We will discuss the VaryByParam attribute in detail in some time.
Using the Cache class in your code-behind class or in the code for the aspx page.
Response.Cache.SetExpires(DateTime.Now.AddSeconds(60)); Response.Cache.SetCacheability(HttpCacheability.Public);
2).Set the Location of the Cache.
Using the @OutputCache Directive :
Client Cache :
<%@ OutputCache Duration="60" Location="Client" %>
Proxy Server Cache :
<%@ OutputCache Duration="60" Location="Downstream" %>
Server Cache: <%@ OutputCache Duration="60" Location="Server" %>
No Cache:
<%@ OutputCache Location="None" %>
Using the Cache Class
Client Cache
Response.Cache.SetExpires(DateTime.Now.AddSeconds(60)); Response.Cache.SetCacheability(HttpCacheability.Private);
Proxy Server Cache
Response.Cache.SetExpires(DateTime.Now.AddSeconds(60)); Response.Cache.SetCacheability(HttpCacheability.Public); Response.Cache.SetNoServerCaching();
Server Caching
Response.Cache.SetExpires(DateTime.Now.AddSeconds(60)); Response.Cache.SetCacheability(HttpCacheability.Server);
No Cache
Use HttpCacheability.NoCache
3).Caching Multiple Versions of a Page.
i).Caching Based on query string and form POST parameters – specify the attributes in a semi-colon separated list in ValueByParams in the OutputCache directive. Each request that arrives with that attribute and a different value will be cached separately.
<%@ OutputCache Duration="65" VaryByParam="DeptId;EmpId" %>
You can use the wildcard * to specify all values.
The first time the page is requested, the response is generated and added to the cache. If the page is requested within 65 seconds with the same values for DeptId and EmpId, then the cached version is used.
ii).Caching based on the HTTP header specifies in the ValueByHeader attribute in the OutputCache directive.
<%@ OutputCache Duration="60" VaryByHeader="Referer" %>
The first time the page is requested, the response is generated and added to the cache. If the page is requested from the same link within 60 seconds, the copy from the cache is used.
iii).Caching based on a custom function. Include a VaryByCustom attribute and override the HttpApplication.GetVaryByCustomString in the Global.asax file.
Include this at the top of the aspx page
<%@ OutputCache Duration="60" VaryByCustom="Frames" %>
Include this in the global.asax page.
public override string GetVaryByCustomString(HttpContext context, string arg) { switch (arg) { case "Frames": return "Frames=" + context.Request.Browser.Frames; case "JavaScript": return "JavaScript=" + context.Request.Browser.JavaScript; default: return ""; } }
Caching Portions of ASP.Net pages
This is also called fragment caching. Parts of the ASP.Net page which are to be cached are encapsulated in Web Forms User Controls. Include the @OutputCache directive at the top of the user control page.
<%@ OutputCache Duration="65" %>
You can add an ID attribute in the user control tag that you have decided to cache. You should check for the existence of the user control in the output cache before using it. Any program logic that must occur to create the control must be included in the user control class itself in events like Page_Load or Page_Prerender.
4).Cache multiple versions based on values set for properties of the control.
<%@ OutputCache Duration="10" VaryByControl="EmpId;Dept" VaryByParam="*"%>
Cache multiple versions based on values of declarative attributes set in the user control tags
Caching Application Requests.
You can add expensive objects or frequently used objects to the cache. The objects are stored in name-value pairs similar to dictionary in the cache.
Add an item to the cache
By specifying the key value:
Cache["Asset"] = txtAsset.value;
By using the Insert method
Cache.Insert("Asset", oString);
By using the Add method
Cache.Add("Asset", oString);
You can specify an expiration date in terms of absolute time interval or in terms of interval of time since the last access.
Absolute Expiration of 1 minute:
Cache.Insert("Asset", oString, null, DateTime.Now.AddMinutes(1), NoSlidingExpiration);
Sliding Expiration of 1 minute from the last access time:
Cache.Insert("Asset", oString, null, NoAbsoluteExpiration, TimeSpan.FromSeconds(60));
You can specify validation based on another file, directory or another cached item. This is called file dependency or key dependency.
Cache.Insert("Asset", oString, new CacheDependency(Server.MapPath(\\Server\myDependency.xml)));
When the myDependency.xml file changes, the cached copy of oString is removed.
You can specify the priority of the cache item using the CacheItemPriority enumeration values or the CacheItemPriorityDecay enumeration values. When the system resources like memory are low, the server deletes of the least used or unimportant items from the cache. This is called scavenging. The items to be deleted are decided based on the priority set for the item.
Retrieve an item from the cache
. . .
Source = (DataView)Cache["MyData1"];
if(Source != null ) {
. . .
}
Note that we have to check for the existence of the cached item before using it.
Delete Items from Cache
Items are deleted from cache when the expiration is set or when the dependency file changes or when the server needs to free memory.
Cache.Remove("oString");
5).Notify an Application when an item is removed from the cache.
The CacheItemRemovedCallback delegate in the .Net framework defines the signature to use when you want to write event handlers to respond when an item is deleted from cache. Typically, the event handler would include code to add the item in cache again.
i).Create the local variable that raises the event for the CacheItemRemovedCallBack delegate.
private static CacheItemRemovedCallback onRemove = null;
ii).Create an event handler to respond when the item is removed from cache.
public void onRemoveCallBack(string str1, object obj1, CacheItemRemovedReason r) { . . . DataSet ds = GetEmpInfo Cache["empDS"] = ds; . . . }
iii).Create an instance of the CachedItemRemovedCallBack delegate that calls the event handler
onRemove = new CacheItemRemovedCallback(this. onRemoveCallBack);
iv).Add the item to cache using the Add or Insert method.
Cache.Insert("empDS", ds, null, DateTime.Now.AddMinutes(1), NoSlidingExpiration, CacheItemPriority.High, CacheItemPriorityDecay.Slow, onRemove);
Conclusion
ASP.Net Caching is a very easy and powerful way to improve the performance of aspx web pages.
|
Responses
|
No responses found. Be the first to respond and make money from revenue sharing program.
|
|