Serving Information Simply

Sunday, 14 April 2013

Caching Concept in ASP.NET


Caching is a technique of storing frequently used data/information in memory, so that, when the same data/information is needed next time, it could be directly retrieved from the memory instead of being generated by the application.
Caching is extremely important for performance boosting in ASP.Net, as the pages and controls are dynamically generated here. It is especially important for data related transactions, as these are expensive in terms of response time.
You can access items in the cache using an indexer and may control the lifetime of objects in the cache and set up links between the cached objects and their physical sources.
In short:-Caching is a feature that stores data in local memory, allowing incoming requests to be served from memory directly.

Benefits of Caching

The following are the benefits of using Caching
•         Faster page rendering
•         Minimization of database hits
•         Minimization of the consumption of server resources

Types of Caching:-

Caching in ASP.NET can be of the following types
•         Page Output Caching
•         Page Fragment Caching
•         Data Caching

Page Output Caching:

 Output cache stores a copy of the finally rendered HTML pages or part of pages sent to the client. When the next client requests for this page, instead of regenerating the page, a cached copy of the page is sent, thus saving time.

Syntax of output caching

At design time:-

<%@ OutputCache Duration="no of seconds"  Location="Any | Client | Server | None" VaryByParam="parameter" %>

Programmetically:-

Response.Cache.SetCacheability(HttpCacheability.Server);
Response.Cache.SetExpires(DateTime.Now.AddSeconds(30));
Response.Cache.SetValidUntilExpires(true);
Response.Cache.VaryByParams["EmployeeID"]= true;

Page Fragment Caching:

This type of caching is used with user controls in asp.net.

Syntax of fragment caching

 <%@ OutputCache  Duration="15"  VaryByParam="*" %>  
This directive is placed at the top of any User Control (.ascx file).
 Data Caching
 Data caching means caching data from a data source. As long as the cache is not expired, a request for the data will be fulfilled from the cache. When the cache is expired, fresh data is obtained by the data source and the cache is refilled.
 Example:-1

x=new OleDbConnection("provider=microsoft.jet.oledb.4.0;data source=c:\\db1.mdb");
x.Open();
y = new OleDbDataAdapter("select * from emp", x)
  ds = new DataSet();
  y.Fill(ds, "emp");
  Cache.Insert("abc", ds);
  ds =(DataSet) Cache["abc"];
  GridView1.DataSource = ds.Tables["emp"];
  GridView1.DataBind();

Example-2

OleDbConnection x;
 OleDbDataAdapter y;
 DataSet z;
    protected void Button1_Click(object sender, EventArgs e)
    {
        DataSet z = new DataSet();
        Cache.Remove("abc"); 
        z=(DataSet)Cache["abc"];
        if(z != null)
        {
            GridView1.DataSource =z.Tables["emp"];
            GridView1.DataBind();
        }
        else
        {
            //z.Dispose();
            x = new OleDbConnection("provider=msdaora;user id=scott;password=tiger");
            x.Open();
            y = new OleDbDataAdapter("select * from emp", x);
             z = new DataSet();
            y.Fill(z, "emp");
            Cache.Insert("abc", z);
            GridView1.DataSource = Cache["abc"];
            GridView1.DataBind();
            x.Close();
        }
    }

Cache Expirations
 Time Based Expiration
 This is used to specify a specific period of time for which the page would remain in the cache. The following statement specifies
such expiration for a page in the code behind of a file using C#.
Response.Cache.SetExpires(DateTime.Now.AddSeconds(120));
Cache.Insert("userInfo", ds, null, DateTime.Now.AddMinutes(2),
NoSlidingExpiration, CacheItemPriority.High,
CacheItemPriorityDecay.Slow, onRemove);
 The Cache Class
 The Add/Insert method of the Cache class is used to add/insert an item into the cache. The Remove method removes a specified item from the cache. The Cache class contains the following properties and methods.
 Properties
•         Count
•         Item
 Methods
 •         Add
•         Equals
•         Get
•         GetEnumerator
•         GetHashCode
•         GetType
•         Insert
•         Remove (Overloaded)
•         ToString
-------------------------------------------------------------------------------------
 Thank you guys... keep visiting ….:)
If you like this post then please join this site and like it’s Facebook page for getting updates and contributing into the problem solving of members of this blog.you can also post your issues on this blog's Facebook page and can get the solutions.



No comments:

Post a Comment