Published on: 14 July, 2013

ASP.Net Caching

Posted by andy | 1450 views 0 likes 0 favourites 0 comments
Tumblr Digg Google Plus

Why you need to use ASP.Net Caching? Well, the quick answer is to improve the performance of your website application. ASP.Net provide a caching feature where you can store data objects or pages into memory. Examine this specific case, let's say you have a page on your site that require a heavy mix data retrival from the database. Rather than re-connect to database and display the output every time the page loads, you can save the existing data into memory caching. This will save the time and fasten the page load especially if you have big images or other resources like css or javascripts. And the other important expensive resource is the connection and data retrieval from database.

When to use Caching feature?

You will only use caching feature if the data takes quite long time to produce and when the data that is not frequently used. For example: if you create an auction website, you do not want to cache each individual page, because every second, the data of the auction or bid will always change. On the other hand, there is an expensive matter as well if you are over use of caching. It can fill up your memory server faster and create a freeze or lag on your server. Note, although IIS has their own application pool control, it is a good practice only to use this feature if it is required.

Types of Caching

There are two caching types available in ASP.Net. They are Output caching and Data caching.

1. Output Caching

Output caching is used to store the final html rendered page. This is actually the best performance caching, as it will skip all the code execution and will return the stored html output. To use this caching method is pretty simple, you can just add this code at the top of your page code. Note: you can specify the duration of the cache expiration time in seconds. The VaryByParam attribute with asterisk(*) value will tell ASP.Net to cache a page as a separate copy cache if the url is different. Example url is : http://www.example.com/myproduct.aspx?id=1 and http://www.example.com/myproduct.aspx?id=2

    <%@ OutputCache Duration="60" VaryByParam="*" %>

You can also specify the case by identifying the required querystring only. Examine this particular url. Let's say this is a product details page, http://www.example.com/myproduct.aspx?productid=1&sort=true&order=ascending. In this particular example, the important query string is actually id only. If you change the sort value to false or order value to descending, the page details will still output the same product details page. In this particular case, we can use this method.

    <%@ OutputCache Duration="60" VaryByParam="productid" %>

If you have more than one query string to against with, you can use a semicolon to separate the value. See below example.

    <%@ OutputCache Duration="60" VaryByParam="productid;brandid" %>

2. Data Caching

Data caching is basically done in the code, you can cache any data like dataset, string or any other data objects. Below example on how to add a data string to a cache item. Note: There are more than one method to store the cache. We have included two samples below.

    protected void btnStoreCache_Click(object sender, EventArgs e) {
        Cache["MyData"] = "The value goes in here";
    
        /* cache name, value, dependencies, expired cache, sliding expiration, priority, onRemoveCallBack */
        Cache.Insert("MyData", "The value goes in here", null, DateTime.Now.AddDays(1), TimeSpan.Zero, System.Web.Caching.CacheItemPriority.Normal, null);
    }

To check if a cache is exist and how to grab the cache value, you can use this method.

    protected void btnGetCache_Click(object sender, EventArgs e) {
        if (Cache["MyData"] != null) {
            string myValue = (string)Cache["MyData"];
            Response.Write("The cache value is " + myValue);
        }
    }

To remove a cache, you can use the following method. Always check if a cache key is exists.

    protected void btnRemoveCache_Click(object sender, EventArgs e) {
        if (Cache["MyData"] != null) {
            Cache.Remove("MyData");
            Response.Write("The cache value has been removed.");
        }
    }

Below is a sample code on how to use the dependency data to clear the cache, if the dependency data has changed.

    /* This will create a depency file object for the cache object */
    System.Web.Caching.CacheDependency dependencyFile = new System.Web.Caching.CacheDependency(Server.MapPath("/dependencyfile.txt"));

    /* cache name, value, dependencies, expired cache, sliding expiration, priority, onRemoveCallBack */
    Cache.Insert("MyData", "The value goes in here", dependencyFile, DateTime.Now.AddDays(1), TimeSpan.Zero, System.Web.Caching.CacheItemPriority.Normal, null);
Comments

There are no comments available.

Write Comment
0 characters entered. Maximum characters allowed are 1000 characters.
Related Articles
Published on: 13 February, 2017
One thing to remember when publishing your ASP.Net web applications, you may find out, some files could be not completely published due to the settings on the file properties. One example that I had are some font types file. In order to fix this problem you can navigate to the files that are missing and right click the properties.
Published on: 11 May, 2016
The slidingExpiration attribute is used in ASP.Net form authentication. This property is used to reset the expiration time for a valid authentication cookie if a request that has already being made has passed the timeout interval. Which means, if it is already expires, the current user will require to re-authentication again.