DataSource Caching in Asp.Net - ProgramIdea

DataSource Caching in Asp.Net

We learnt page output cache and user control cache. Now, we are learning Data Source cache in Asp.Net.

When your page is containing details control like GridView and all then instead of page output caching and partial page caching, we can use DataSource Caching. Advantage of DataSource caching is that the Data Source control automatically reload when the data is updated. Following Asp.Net DataSource controls supporting cache:

  • 1. SqlDataSource
  • 2. ObjectDataSource
  • 3. XmlDataSource

(Note:- LinqDataSource doesn’t support cache)

SqlDataSource Caching

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

    <title>Data Source Cache</title>

</head>

<body>

    <form id="form1" runat="server">

    <div>

        <asp:GridView ID="GridView1" runat="server" DataSourceID="SqlDataSource1">           

        </asp:GridView>        

 

        <asp:SqlDataSource ID="SqlDataSource1" runat="server"

          EnableCaching="true"

          CacheDuration="3600"

          CacheExpirationPolicy="Absolute"

          ConnectionString="<%$ ConnectionStrings:db_Test %>"

          SelectCommand="SELECT [Id], [Name], [Branch], [City] FROM [tbl_Student]">

        </asp:SqlDataSource>

    </div>

    </form>

</body>

</html>

Using  Absolute Cache Expiration Policy

Absolute cache expiration policy provides your data in cache memory for a particular interval of time. It’s very important in case of data that does not changed often like your data change in once in every hour.

        <asp:SqlDataSource ID="SqlDataSource1" runat="server"

          EnableCaching="true"

          CacheDuration="3600"

          CacheExpirationPolicy="Absolute"

          ConnectionString="<%$ ConnectionStrings:db_Test %>"

          SelectCommand="SELECT [Id], [Name], [Branch], [City] FROM [tbl_Student]">

        </asp:SqlDataSource>

Using Sliding Cache Expiration Policy

When you are working with large data, then you should be used to sliding cache policy. Advantage of this policy is that data remains in cache as long as continues to be requested within particular interval of time.

For better understanding, we are taking an example. Suppose you are using sliding cache expiration policy for default.aspx page for 30 seconds. When first time it will open then page is cached for next 30 seconds. If there will be no any request come for this page then page is removed from cache but, if any request comes in 30 seconds then again page is cached foe next 30 seconds, means if request came at 20th second then page is cached from that point of time to next 30 seconds and this will be continue.

        <asp:SqlDataSource ID="SqlDataSource1" runat="server"

          EnableCaching="true"

          CacheDuration="30"

          CacheExpirationPolicy="Sliding"

          ConnectionString="<%$ ConnectionStrings:db_Test %>"

          SelectCommand="SELECT [Id], [Name], [Branch], [City] FROM [tbl_Student]">

        </asp:SqlDataSource>

ObjectDataSource Caching

ObjectDataSource having same cache properties as SqlDataSource like: EnableCaching, CacheDuration and CacheExpirationPolicy. ObjectDataSource having property SelectMethod that indicate which method you are using for binding data and TypeName property indicates that which class file containing that method.

For example, we are binding data by using GetStudentData() method which is inside DataConnection.cs class.

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

    <title>Data Source Cache</title>

</head>

<body>

    <form id="form1" runat="server">

    <div>

        <asp:GridView ID="GridView1" runat="server" DataSourceID="ObjectDataSource1">           

        </asp:GridView>        

        <asp:ObjectDataSource ID="ObjectDataSource1" runat="server"

             EnableCaching="true"

             CacheExpirationPolicy="Absolute"

             CacheDuration="15"           

             SelectMethod="GetStudentData"

             TypeName="DataConnection">

        </asp:ObjectDataSource>

    </div>

    </form>

</body>

</html>

DataConnection.cs class that contains GetStudentData() method.

using System.Data;

using System.Data.SqlClient;

using System.Configuration;

 

public class DataConnection

{

 

    public static DataTable GetStudentData()

    {

     SqlConnection con =

                                     new SqlConnection(ConfigurationManager.ConnectionStrings["db_Test"].ToString());

        DataTable dt = new DataTable ();       

        con.Open();

        SqlDataAdapter da = new SqlDataAdapter( "Select * from tbl_Student" , con);

        da.Fill(dt);

        con.Close();

       

        return dt;

    }

}

XmlDataSource Caching

XmlDataSource having same properties as SqlDataSource and ObjectDataSource like EnableCaching, CacheDuration and CacheExpirationPolicy but, XmlDataSource having greate cache flexibility as compare to SqlDataSource and ObjectDataSource because XmlDataSource cache by default enabled and its automatically creates file dependency on attached xml file, means when xml file is modified, its automatically reloads data.

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

    <title>Data Source Cache</title>

</head>

<body>

    <form id="form1" runat="server">

    <div>

        <asp:GridView ID="GridView1" runat="server" DataSourceID="XmlDataSource1" >

        </asp:GridView>

        <asp:XmlDataSource ID="XmlDataSource1" runat="server"

             DataFile="~/Student.xml">

        </asp:XmlDataSource>

    </div>

    </form>

</body>

</html>

Automatically SqlDataSource control reload cache data when source data updated

Here we are creating key dependency of SqlDataSource control. Advantage of creating key dependency is that when sql table updated then, SqlDataSource automatically reload cache data. So no worry about cache duration.

Here we are demonstrate that how it's working. First of all take a GridView and bind with SqlDataSource, set EnableCaching true and CacheDuration is Infinite. Ok, for automatically upload you need to use CacheKeyDependency property to your specific custome key.

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="true"

            DataSourceID="SqlDataSource1"></asp:GridView>      

       

        <asp:SqlDataSource ID="SqlDataSource1" runat="server"

          EnableCaching="true"

          CacheDuration="Infinite"

          CacheExpirationPolicy="Absolute"

          CacheKeyDependency="CacheStudentKey"

          ConnectionString="<%$ ConnectionStrings:db_Test %>"

          SelectCommand="SELECT [Id], [Name], [Branch], [City] FROM [tbl_Student]">

        </asp:SqlDataSource>

Now, go to Global.asax page and create first CacheStudentKey cache item. Whenever application will start, it's store CacheStudentKey cache.

// Global.asax Page

 

void Application_Start(object sender, EventArgs e)

{

   // Code that runs on application startup

   HttpContext context = HttpContext.Current;

   context.Cache.Insert("CacheStudentKey", DateTime.Now, null, DateTime.MaxValue,

                                         Cache.NoSlidingExpiration, CacheItemPriority.NotRemovable, null);

}

Finally, when you inserted into new row in sql table, just reinsert CacheStudentkey in cache. It's reload all SqlDataSource control automatically that are using CacheStudentKey key dependency.

For example, in tbl_Student new row entry comes from Registration.aspx page, when user fill the form and click the Save button. So, on Save button click, just reinsert StudentCacheKey in to cache.

protected void btnSave_Click(object sender, EventArgs e)

{

    // Your all logic and stuffs here

 

    // Insert new row in tbl_Student table here

 

    // After inserted in table, just call below code

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

}

Demo:

Sql DataSource Demo