Tuesday 20 December 2016

ASP.Net Caching technique with example in C#

Caching in ASP.Net


  • Output Caching
    • Page Output Caching: Caching complete page including user controls.
    • Fragment Caching: We can set cache duration for each user control, explicitly.
  • Object Caching (Application Cache)
    • In side application we can create cache of any object, and can set expiration.
  • Cache dependency
    • Data Dependency Caching: Create cache based on other objects cache. If one object changes other cache would be change.
    • File Dependency Caching: Cache based on file changed, if file changes the cache change automatically.
    • SQL Dependency Caching: We can cache sql data inside application.
    • Remove Cache: With dependency cache we can trap remove event and can remove other cache.


Fragment and partial page caching in Asp.net web form

Partial cache in asp.net allow us to cache complete page including user controls.
<%@ Page ...
<%@ OutputCache Duration="5" VaryByParam="None" %>

Fragment caching in asp.net allows us to cache particular portion of web page instead of whole page and this can be achieved by using user controls in asp.net.
<%@ Control ...
<%@ OutputCache Duration="5" VaryByParam="None" %>

Important attributes:
VaryByParam="*"
VaryByParam="none"
VaryByParam="productid,productcategory"
VaryByControl="CategoryDropDownList"
VaryByCustom="browser" Shared="true"

Few Important points

Q: Can we set page OutputCache on master page in asp.net?
Ans: We can't use OutputCache directive for master page. And will get error message like this:
The directive 'outputcache' is not allowed in this page.


Q: Is this statement is true?
<%@ OutputCache Duration="5" %>
Ans: NO, The directive is missing a 'VaryByParam' attribute, which should be set to "none", "*", or a semicolon separated list of values.


Q: If we set these two options on page and control which would be work?
<%@ Page ...
<%@ OutputCache Duration="20" VaryByParam="None" %>

<%@ Control ...
<%@ OutputCache Duration="5" VaryByParam="None" %>

Ans: If we have OutputCache on page, it will ignore control OutputCache.


Complete Example of Cache Dependency

<%@ Page Language="C#" AutoEventWireup="true"   %>
<%@ Import Namespace="System.IO" %>
<%@ Import Namespace="System.Web.Caching" %>



<script runat="server">

//Absolute Expiration: Absolute expiration means It will expire cache after some time period set at the time of activating cache. This will be absolute expiration whether cache will be used or not It will expire the cache. This type of expiration used to cache data which are not frequently changing.

//Sliding Expiration: Sliding expiration means It will expire cache after time period at the time of activating cache if any request is not made during this time period. This type of expiration is useful when there are so many data to cache. So It will put those items in the cache which are frequently used in the application. So it will not going to use unnecessary memory.
//https://msdn.microsoft.com/en-us/library/system.web.caching.cache.noslidingexpiration.aspx
   
   
       protected void Page_Load(object sender, EventArgs e)
       {
           string filedata = "";
           if (Cache["filedata"] == null)
           {
               filedata = File.ReadAllText(Server.MapPath("users.xml"));
               
               //Cache.Insert("filedata", filedata, new System.Web.Caching.CacheDependency(Server.MapPath("users.xml")));
               //default cache expiration never expire. Only expire at the time of low memory.

               //Cache.Insert("filedata", filedata, new System.Web.Caching.CacheDependency(Server.MapPath("users.xml")), DateTime.Now.AddSeconds(15), Cache.NoSlidingExpiration);
               //expire at fixed interval, each file changes.
               
               //Cache.Insert("filedata", filedata, new System.Web.Caching.CacheDependency(Server.MapPath("users.xml")), Cache.NoAbsoluteExpiration, TimeSpan.FromSeconds(20));
               //Expire if there is no incoming request in certain time interval.
               
               
               Cache.Insert("filedata",
                   filedata,
                   new System.Web.Caching.CacheDependency(Server.MapPath("users.xml")),
                   DateTime.Now.AddSeconds(15),
                   Cache.NoSlidingExpiration,
                   System.Web.Caching.CacheItemPriority.Default,
                   new System.Web.Caching.CacheItemRemovedCallback(CacheItemRemovedCallBack));
               //On the remove of this cache we can remove other cache from memory.
               //Cache.Remove("filedata");
               filedata = "File Data : " + filedata;

           }
           else {
               filedata = "Cache Data : " + Cache["filedata"];
           }
           Response.Write(filedata);
           
       }

       private void CacheItemRemovedCallBack(string key, object value,
                  CacheItemRemovedReason reason)
       {
           switch (key)//necessary to check key
       {
               case "filedata":
                   {
                       Response.Write("filedata removed");
                       break;
                   }
           }
            
       }


</script>