17 August, 2011

ASP.NET Caching Dependencies in Asp.net


Caching can depend on several items which include user request, file, database tables, table rows, duration, user controls, query strings, browsers and also other cached items. Let's start with the Caching dependency on other cached items.


Caching Dependency on Cached Items

It is interesting to note that your cached item can depend on other cached items. This means that if the item A is removed from the cache you can also remove item B from the cache. Let's start by creating and inserting the item A and item B in the Cache object.



protected void Button_Click(object sender, EventArgs e)
{
    // create item A and item B

    string itemA = "ItemA";
    string itemB = "ItemB";
    Cache.Insert("ItemA", itemA, null, DateTime.Now.AddMinutes(10), 
    TimeSpan.Zero,
    CacheItemPriority.Default, MyItemRemovedCallBack);
    Cache.Insert("ItemB", itemB, null, DateTime.Now.AddMinutes(10), 
    TimeSpan.Zero,
    CacheItemPriority.Default, MyItemRemovedCallBack);
}

In the code above I am creating two items "itemA" and "itemB". After creating the items I simply put the items in the Cache object using the Insert method. The last parameter is the callback method "MyItemRemovedCallBack" which will be fired when either of the two items is removed from the Cache.

It is not a good idea to insert the items into the Cache inside the callback method because you might not need the item right away and hence you will be wasting valuable resources to create them.

Let's take a look at the MyItemRemovedCallBack implementation.
private void MyItemRemovedCallBack(string key, object value,
                   CacheItemRemovedReason reason)
{
    // remove the item from the cache

    if (key == "ItemA" ) Cache.Remove("ItemB");
    else if (key.Equals == "ItemB") Cache.Remove("ItemB");
}

The MyItemRemovedCallBack method takes three parameters.

key: This is the key which is used to identify the items in the Cache.
value: The value assigned to the item which is inserted in the Cache.

reason: The variable "reason" is of type CacheItemRemovedReason enumeration and it identifies the reason the item was removed from the Cache.

The code given below removes an item from the Cache and as soon as the item is removed the "MyItemRemovedCallBack" method is fired and removed the other item from the Cache.
protected void Btn_RemoveCacheItem(object sender, EventArgs e)
{
    Cache.Remove("ItemA");
}


Cache Dependency on SQL

My main goal of this post is cache base on sql.

In simple words,caching can also depend on the database table means that your chaching value will remains in memory untill table in the database updates.so, when you will fire INSERT,UPDATE or DELETE quary on table,it will chage the table data so will remove chache automatically from memory and reload it again from the Connection string you have defined.

lets see in detail :

------------------------------------------------------------------------------------------------

First of all, you have tp enable the SQ Cache dependency on database to perform this opration. you can not cache particulat database or table without doing this settings. 

You can enable the SQL Cache dependency by using the aspnet_regsql.exe command line tool. to enable it perform following steps :

open command line prompt by going to start->run->cmd.

Then navigate to framework path of your system.

for eg:  cd C:\Windows\Microsoft.NET\Framework\v2.0.50727

Then, run this command--> aspnet_regsql.exe -S localhost -ed  -E -d DatabaseName
this means , you are trying to enable(-e) SQl DEPENDENCY option for particular database (-d) on localhost.
for eg:  my database name is "db1" then-->  aspnet_regsql.exe -S localhost -ed  -E -d db1

Then, enable SQl DEPENDENCY for table in the database like this.-->
aspnet_regsql.exe -S localhost -et  -E -d DatabaseName -t TableName


-------------------------------------------------------------------------------------------------------------------------------------


The next step is to create the connectionString in the connectionStrings section andsqlCacheDependency in the web.config file. Take a look at the code below:

Note : here i have one database having name "School" with table "Users".

    



    
        
            
                
            
        
    

As, you have noticed that the sqlCacheDependency have a pollTime attribute which is set to "1000" milliseconds. This means that the ASP.NET will check the database table for any changes every 10 seconds. The database section of the contains the connectionString which is used to connect to the database.

The final step is to use the caching in your code. You can do this in various ways. Take a look at the following code which uses caching programmatically.

private void BindData()
{
    // if null then fetch from the database

    if (Cache["Users"] == null)
    {
        // Create the cache dependency

        SqlCacheDependency dep = new SqlCacheDependency("School", "Users");
        string connectionString = ConfigurationManager.ConnectionStrings[
                                        "ConnectionString"].ConnectionString;
        SqlConnection myConnection = new SqlConnection(connectionString);
        SqlDataAdapter ad = new SqlDataAdapter("SELECT FirstName, LastName " +
                                               "FROM Users", myConnection);
        DataSet ds = new DataSet();
        ad.Fill(ds);

        // put in the cache object

        Cache.Insert("Users", ds, dep);
    }

    gvUsers.DataSource = Cache["Users"] as DataSet;
    gvUsers.DataBind();
}

The line SqlCacheDependency dep = new SqlCacheDependency("School", "Users"); is used to create the caching on the School database and Users table. In the beginning of the BindData method I check that if the item is already in the Cache. If it is then I simply return the item using caller by casting it from the Cache object. If the item is not in the Cache then the data is fetched from the database and inserted into the Cache object. The Cache will be discarded anytime you make a change in the database table "Users". This means that if you INSERT, DELETE, UPDATE any data in any row in the Users table then the Cache will be considered obsolete and a copy of the fresh data will be fetched from the database.

Caching in SQL Server 2005 have a different architecture then in SQL Server 2000. You don't have to write any lines in web.config to enable Caching in SQL Server 2005. Also, in SQL Server 2005 the Cache is only expired when the row is changed in the database table.

No comments:

Post a Comment