Briefly we can say like “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 ( while post backs we don’t want to go every time to fetch the data from databse)
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
This is a concept by virtue of which the output of pages is cached using an Output Cache engine and all subsequent requests are served from the cache. Whenever a new request comes, this engine would check if there is a corresponding cache entry for this page. If there is a cache hit, i.e., if the engine finds a corresponding cache entry for this page, the page is rendered from the cache, else, the page being requested is rendered dynamically.
This is particularly useful for pages that are static and thus do not change for a considerable period of time.
Page output caching can be implemented in either of the following two ways:
At design time using the OutputCache directive
At runtime using the HttpPolicy class
The following is the complete syntax of page output caching directive
<%@ OutputCache Duration="no of seconds"
Location="Any | Client | Downstream | Server | None"
VaryByControl="control"
VaryByCustom="browser |customstring"
VaryByHeader="headers"
VaryByParam="parameter" %>
The following statement is used to implement output caching in an aspx page at design time. The directive is placed at the top of the .aspx page.
<%@OutputCache Duration="30"
VaryByParam="none" %>
The duration parameter specifies for how long the page would be in cache and the VaryByParam parameter is used to cache different views of the page. In the code example above, the cache duration is 30 seconds. Cache duration is a required field, and must be set to an integer greater than zero. The VaryByParam parameter, which is also required, specifies whether the cached page would differ in versions based on any parameter. A value of * in the same parameter indicates that the page would be cached based on all the Get/Post parameters. We can also specify one or more Get/Post parameter(s). Hence, the same statement shown above can have the following variations. The VaryByParam parameter is particularly useful in situations where we require caching a page based on certain criteria. As an example, we might require to cache a specific page based on the EmployeeID.
<%@OutputCache Duration="30"
VaryByParam="*" Location = "Any"%>
<%@OutputCache Duration="30"
VaryByParam="EmployeeID" Location = "Client" %>
<%@OutputCache Duration="30"
VaryByParam="EmployeeID;Basic" %>
The VaryByParam parameter can also have multiple parameters as shown in the example above.
The location parameter is used to specify the cache location, either the server of the client.
To set a page's cacheability programmatically we have to use the method Response.Cache.SetCacheability. This method accepts the following parameters
NoCache
Private
Public
Server
The code snippet below shows how to set a page’s cacheability programmatically:
Response.Cache.SetCacheability(HttpCacheability.Server);
Additionally we can set other properties which map to the same fields available when using the OutputCache directive on the page:
Response.Cache.SetExpires(DateTime.Now.AddSeconds(30));
Response.Cache.SetValidUntilExpires(true);
Response.Cache.VaryByParams["EmployeeID"]= true;
Page Fragment Caching
This allows specific portions of the page to be cached rather than caching the whole page. This is useful in situations where we can have a page that contains both static and dynamic content. The following code depicts how this can be accomplished.
<%@ OutputCache Duration="15"
VaryByControl="EmpID;DeptID" VaryByParam="*"%> // this is on top of the control
Data Caching
public DataSet GetUserDetails()
{
string cacheKey = "UserDetails";
DataSet ds = Cache[cacheKey] as DataSet;
if (ds == null)
{
ds = GetUserDetailsFromDatabase();
Cache.Insert(cacheKey, ds, null, NoAbsoluteExpiration,
TimeSpan.FromHours(15),CacheItemPriority.High, null);
}
return ds;
}
DataSet GetUserDetailsFromDatabase() {
The following code is an implementation of On-Demand caching. The method GetUserDetails checks to see if the data exists in the cache. If it is present, it is returned from the cache, else, the GetUserDetailsFromDatabase method fills the DataSet from the database and then populates the Cache.
// Usual code to populate a data set from thedatabase. This data set
// object is then returned.
}
Cache Expirations
Cache expirations can be of the following types
Time Based Expiration
Dependency Based Expiration
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));
This can also be accomplished by stating the same in the output cache directive as shown here.
<%@OutputCache Duration="60" VaryByParam="None" %>
Cache Expiration
Cache expiration strategies can be implemented in either of the following two ways:
Time Based
File Based
Key Based
Time Based Expiration
This is implemented by specifying a specific duration for which the item would remain in the cache. When the time elapses, the item is removed from the cache and subsequent requests to retrieve the item returns a null. Time based expiration strategies can be of the following two types:
Absolute
Sliding
Absolute
Cache.Insert("UserDetails", dsUserDetails, null,
DateTime.Now.AddMinutes(1), NoSlidingExpiration);
Sliding
Cache.Insert("UserDetails", dsUserDetails, null,
NoAbsoluteExpiration,
TimeSpan.FromSeconds(60));
Note that you cannot use both Absolute and Sliding expirations at the same time.
File Based Expiration
This is implemented by using a file as a dependency. Whenever the contents of the dependency file are changed, the cached is invalidated. Please refer to the code below.
CacheDependency cacheDependency = newCacheDependency("UserDetails.xml");
Cache.Insert("UserDetails", xmldocObject,cacheDependency);
In addition to files, entire folders can be monitored for changes using the CacheDependency class.
Key Based Expiration
The third type of dependency is the key dependency. With it, a cache entry can be made to depend on another, existing dependency. When the depended-upon entry changes or expires, the dependent entry will also be expired. An array of keys can be specified as a single CacheDependency.
string[] keys = new string[] {"key"};
CacheDependency cacheDependency = newCacheDependency(null,keys);
Cache.Insert("UserDetails", xmldocObject,cacheDependency);
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
Conclusion and a small example:
protected void Page_Load(object sender, EventArgs e)
{
Label1.Text = DateTime.Now.ToLongTimeString();
}
Now let us go ahead and enable caching for this page by adding the following declaration to the page:
<%@ OutputCache Duration="10" VaryByParam="none"%>
Here we are saying that this page should be cached for 10 seconds, We can verify this by pressing the button. The time string will not change for 10 seconds and the second property VaryByParam specifies that caching doesn't depend on anything doing so can lead to a situation where user can see stale data, like in our case for 10 seconds if we write something in textbox and do a postback, it will keep reverting to the old data that was in the textbox at the time page was cached.
This is How Microsoft caching implemented and given a good chance to reduce developer coding and loading time.
|