Search - Articles
DevASP.NET for ASP.NET, VB.NET, XML and C# (C-Sharp) Developers Tuesday, March 03, 2009
Dev Articles
Search Directory
ASP.NET
VB.Net
C-Sharp
SQL Server
 

Data Caching in ASP.NET

Author: Richard Wand
Download Source Code : 1269_DataCaching in ASP.NET.zip

Data caching is a powerful way to cache data for entire application in ASP.NET. This article will demonstrate data caching with an example.

 

Data caching was explained in a previous article on DevASP.NET. Read here to grab the concept of Data Caching.

 

Caching your data is really a great improvement in performance when you have static data in your application and you need to get that data from database server. Getting same data every time from database server is not a good option as for as the performance of your application is concern. ASP.NET provides a good way of caching data so that you can increase performance of your application to a certain extent.
 
We will see data caching in this article with an example of getting data first time from SQL Server, caching it and then getting data from cache.
 
Let’s start our example. All sample code is available as attachment; you can download it but make sure you have downloaded NORTHWIND Sample Database for this example and change the connection string as per your server name.
 
  1. Open Visual Studio 2010, go to File from menu > New > Web Site
  2. Create ASP.NET Empty Web Site either in VB.NET or C#
  3. Go to Website from menu > Add New Item > Web Form  and Click on Add
  4. Add a Label control and a GridView Control in aspx page or copy and paste code below

    <asp:Label ID="Label1" runat="server"></asp:Label>
       
    <asp:GridView ID="GridView1" runat="server"> </asp:GridView>
     
  5. Now add code below in code behind file 

    C#
     
    using System.Data;
    using System.Data.Sql;
    using System.Data.SqlClient;
     
    protected void Page_Load(object sender, EventArgs e) {
            if (Cache["dataCache"] == null) {
                Cache.Insert("dataCache", ProductData(), null, DateTime.Now.AddSeconds(10), TimeSpan.Zero);
                GridView1.DataSource = ProductData();
                GridView1.DataBind();
                Label1.Text = "This data is from Database";
            }
            else {
                GridView1.DataSource = Cache["dataCache"];
                GridView1.DataBind();
                Label1.Text = "This data is from Data Cache";
            }
        }
     
        private DataTable ProductData() {
            SqlConnection con = new SqlConnection("Data Source=DEV01-PC;Initial Catalog=C:\\SQL SERVER 2000 SAMPLE DATABASES\\NORTHWND.MDF;Integrated Security=True");
            con.Open();
            string sql = "SELECT * FROM Products";
            SqlCommand cmd = new SqlCommand(sql, con);
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            DataTable dt = new DataTable();
            da.Fill(dt);
            con.Close();
            return dt;
        }
     
     
    VB.NET
     
    Imports System.Data
    Imports System.Data.Sql
    Imports System.Data.SqlClient
     
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
            If Cache("dataCache") Is Nothing Then
                Cache.Insert("dataCache", ProductData(), Nothing, DateTime.Now.AddSeconds(10), TimeSpan.Zero)
                GridView1.DataSource = ProductData()
                GridView1.DataBind()
                Label1.Text = "This data is from Database"
            Else
                GridView1.DataSource = Cache("dataCache")
                GridView1.DataBind()
                Label1.Text = "This data is from Data Cache"
            End If
        End Sub
     
        Private Function ProductData() As DataTable
            Dim con As SqlConnection = New SqlConnection("Data Source=DEV01-PC;Initial Catalog=C:\SQL SERVER 2000 SAMPLE DATABASES\NORTHWND.MDF;Integrated Security=True")
            con.Open()
            Dim sql As String = "SELECT * FROM Products"
            Dim cmd As SqlCommand = New SqlCommand(sql, con)
            Dim da As SqlDataAdapter = New SqlDataAdapter(cmd)
            Dim dt As DataTable = New DataTable()
            da.Fill(dt)
            con.Close()
            Return dt
        End Function


    First you have to use or import namespaces mentioned at the top of the code. I have written a function ProductData() to get data from SQL Server. It returns DataTable. You have to provide connection string in SqlConnenction() as per your Server Name and Database. In Page Load method, first I am checking Cache object. If it is null or it has nothing in it then insert data into it and bind our DataGrid with ProductData() function. Notice that I have passed five parameters to Insert() method of Cache object. First two are the key-value pair of Cache object. For this example, key is “dataCache” and the value is the ProductData() function. Third is the dependency which is nothing for this example. Fourth and fifth are the Absolute Expiration and Sliding Expiration for cache. I have mentioned Absolute Expiration for 10 seconds. If Cache object has the data in it then GridView is populated from that cache object.
     
  6. Press F5 or Ctrl + F5 to see in browser. Refresh the Page within 10 seconds to see cached data.

 

   
Add Article Comment:
Name :
Email Address :
   
Comments :
 
   
<< How to add CheckBox in a GridView in ASP.NET

Disclaimer - Privacy
© 2002-2017 DevASP.net