Data Caching in Asp.Net - ProgramIdea

Data Caching in ASP.NET

Asp.Net framework internally uses the cache object in any type of cache. So, cache object is fundamental mechanism for all type of caching in Asp.Net Framework. In every Asp.Net application, one cache object is created and any item can be accessed from anywhere in application which is added in the cache.

Adding Items to the Cache

Here we are binding GridView from sql server database. GetSqlTable() method is used to retrieve database table from student table. Every time bind GridView from sql server is taking too much of time Instead of binding first time from database and after that from cache. So, we are binding GridView first time from database and after that from cache.

First we are checking cache already stored data or not by using cache-key, If key is not present means, either item is not present in cache or cache is expired. If key exists in cache, then retrieve data from cache and bind the GridView. Due to use of cache you can improve performance of your application.

You can add items to the cache by insert method of Cache object. Insert method provided multiple overloaded versions.

    protected void BindGridView()

    {

        DataSet ds = new DataSet();

 

        // When first time execute

        if (Cache["StudentKey"] == null)

        {

            ds = GetSqlTable("Select * from tbl_Student");

            // Store into Cache

            Cache.Insert("StudentKey", ds);

        }

        else

        {

            // Already cache exist

            ds = (DataSet)Cache["StudentKey"];

        }

 

        GridView1.DataSource = ds;

        GridView1.DataBind();

    }

    protected DataSet GetSqlTable(string query)

    {

        SqlConnection con = new SqlConnection(@"Data Source=JITESH-PC; 

                            Initial Catalog = db_Test;Integrated Security = True");

        DataSet ds = new DataSet();

        SqlDataAdapter da = new SqlDataAdapter(query, con);

        con.Open();

        da.Fill(ds);

        con.Close();

        return ds;

    }

Adding Items with an Absolute Expiration Policy

Use absolute expiration policy, when you want to cache an item in specific period of time.

Here we are using Absolute Expiration policy for above cache example. We set cache expire time 30 minutes. So after 30 minutes cache will automatically reload fresh data when someone request this page.

protected void BindGridView()

    {

        DataSet ds = new DataSet();

 

        // When first time execute

        if (Cache["StudentKey"] == null)

        {

            ds = GetSqlTable("Select * from tbl_Student");

            // Store into Cache with absolute policy

           Cache.Insert("StudentKey",ds,null,DateTime.Now.AddMinutes(30), Cache.NoSlidingExpiration);

        }

        else

        {

            // Already cache exist

            ds = (DataSet)Cache["StudentKey"];

        }

 

        GridView1.DataSource = ds;

        GridView1.DataBind();

    }

Adding Items with a Sliding Expiration Policy

Sliding cache expiration policy keeps the most requested items in memory and remaining items are dropped from memory automatically.

Here we are using slide Expire Policy for storing data in cache object. We set slide cache expire time to 30 seconds. So, if someone request this page before 30 seconds, it will again cached for next 30 seconds. If this page is not executed in next 30 seconds then page will be automatically removed from cache.

protected void BindGridView()

    {

        DataSet ds = new DataSet();

 

        // When first time execute

        if (Cache["StudentKey"] == null)

        {

            ds = GetSqlTable("Select * from tbl_Student");

            // Store into Cache with absolute policy

           Cache.Insert("StudentKey",ds, null, Cache.NoAbsoluteExpiration, TimeSpan.FromSeconds(30));

        }

        else

        {

            // Already cache exist

            ds = (DataSet)Cache["StudentKey"];

        }

 

        GridView1.DataSource = ds;

        GridView1.DataBind();

    }

Cache dependency

Cache dependency playing very important role in caching concept. Here we are binding a GridView by Student.xml file. So, if want to cache the binding data and binding data automatically reload when xml file updated otherwise cache will expire on infinite, then we have to go for dependency concept of cache. If Student.xml file is modified then cached data automatically updated.

protected void BindGridView()

    {

        DataSet ds = new DataSet();

 

        // When first time execute

        if (Cache["StudentKey"] == null)

        {

            ds.ReadXml(MapPath("~/programidea.xml"));

            CacheDependency dependency = new CacheDependency(MapPath("~/programidea.xml"));

            // Store into Cache with absolute policy

            Cache.Insert("StudentKey", dt, dependency);

        }

        else

        {

            // Already cache exist

            ds = (DataSet)Cache["StudentKey"];

        }

 

        GridView1.DataSource = ds;

        GridView1.DataBind();

    }

Remove cache

For removing any item from cache, use Remove method of cache and just pass cache-key in it.

// Remove cache item using key

Cache.Remove("StudentKey");

Retrieving total cached items from cache

Here we are inserting different key with different object item in cache and after that we retrieve all cached details. Purpose of this is to show all cached key with cached object.

        Cache.Insert("TestKey1", DateTime.Now);

        Cache.Insert("TestKey2", "Test");

        Cache.Insert("TestKey3", 10);

        Cache.Insert("TestKey4", true);

        Cache.Insert("TestKey5", GetSqlTable("select * from tbl_Student"));

We are collecting one by one cache key and object value and store in List collection after that show in GridView.

    private void GetCache()

    {

        List<CacheItem> list = new List<CacheItem>();

 

        foreach (DictionaryEntry item in Cache)

        {

            list.Add(new CacheItem() { CacheKey = item.Key.ToString(), CacheValue = item.Value });

        }

 

        GridView1.DataSource = list;

        GridView1.DataBind();

    }

   

    class CacheItem

    {

        public object CacheValue { get ; set; }

        public string CacheKey { get ; set; }

    }

        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" >

            <Columns>

                <asp:BoundField DataField="CacheKey" HeaderText="Key" />

                <asp:BoundField DataField="CacheValue" HeaderText="Value" />

            </Columns>

        </asp:GridView>

Example

Demo

Add and Insert both method use to add an item in cache. If item already exists in cache, Add method fails and Insert method replace it.