Click here to Skip to main content
15,883,795 members
Articles / Web Development / HTML
Tip/Trick

Web Caching with SqlCacheDependency Simplified

Rate me:
Please Sign up or sign in to vote.
4.64/5 (8 votes)
20 Jun 2014CPOL1 min read 43.3K   336   16   18
Using SqlCacheDependency with Web caching

Introduction

This tip explains using the SqlCacheDependency with Web Caching in a simple way.

Background

I had a requirement to implement server data push to clients without clients having to poll the server. We decided to use the SignalR framework. But in the business layer with a timer, I wanted to query the database only when there are data changes. Going through many articles online on SqlCacheDependency, SqlQueryNotifications, I had difficultly understanding a proper way to implement all the layers. At last, I came out with the below solution without having to use the SqlQueryNotification.

Using the Code

The sample is developed in VS 2012 and SQL 2012. It uses the Northwind database.

The first step will be to enable broker in SQL Server with the below command:

SQL
ALTER DATABASE [<db_name>] SET ENABLE_BROKER WITH NO_WAIT

You have your connection string in web.config:

XML
<connectionStrings>
    <add name="default" connectionString="server=.; 
    initial catalog=NorthWind; integrated security=true;" />
</connectionStrings>

Next, add the following in web.config, under <system.web>:

XML
<caching>
      <sqlCacheDependency enabled="true">
        <databases>
          <add name="NorthwindCache" 
          connectionStringName="default" pollTime="500"/>
        </databases>
      </sqlCacheDependency>
</caching>   

The code on aspx page load is below, which has a GridView object named grvCategory and a Label named lblMessage.

ASP.NET
protected void Page_Load(object sender, EventArgs e)
{
            bool isDataFromCache = false;

            grvCategory.DataSource = DbManager.GetCategory(out isDataFromCache);
            grvCategory.DataBind();

            lblMessage.Text = isDataFromCache ? 
            "Cache Data : " : "Data refreshed at ";
            lblMessage.Text += DateTime.Now.ToString();
}

The dbManager class retrieves data from the database. It also manages the cache objects.

C#
public class DbManager
{
        private static object GetCacheData(string cacheItemName)
        {
            return HostingEnvironment.Cache.Get(cacheItemName);

        }

        private static void SetCacheData
        (string cacheItemName, object dataSet, string connString, string tableName)
        {
            string cacheEntryname = "NorthwindCache";

            SqlDependency.Start(connString);
            
            SqlCacheDependencyAdmin.EnableNotifications(connString);
            SqlCacheDependencyAdmin.EnableTableForNotifications(connString, tableName);

            SqlCacheDependency dependency = new SqlCacheDependency(cacheEntryname, tableName);
            HostingEnvironment.Cache.Insert(cacheItemName, dataSet, dependency);
        }

        public static DataTable GetCategory(out bool isDataFromCache)
        {
            string sqlQuery = "SELECT [CategoryID],
            [CategoryName] FROM [dbo].[Categories]";
            string tableName = "Categories";

            string connStringName = "default";
            string connString = System.Configuration.ConfigurationManager.ConnectionStrings[connStringName].ToString();

            isDataFromCache = false;
            DataTable dtTemp = null;
            string cacheItemName = sqlQuery;

            object obj = GetCacheData(cacheItemName);
            dtTemp = (DataTable)obj;

            if (dtTemp == null)
            {
                SqlConnection cnMain = new SqlConnection(connString);
                SqlDataAdapter da = new SqlDataAdapter(sqlQuery, cnMain);

                dtTemp = new DataTable();
                da.Fill(dtTemp);

                SetCacheData(cacheItemName, dtTemp, connString, tableName);
            }
            else
            {
                isDataFromCache = true;
            }

            return dtTemp;
        }
}

After running the web page, the initial data is taken from database and subsequent page refresh fetches data from the cache as displayed in the label control of the page. The cache expires as soon as you insert or update in the Categories table.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Technical Lead
India India
.net developer

Comments and Discussions

 
QuestionParameterized or using Command Pin
HackensackNJ16-Oct-18 6:52
HackensackNJ16-Oct-18 6:52 
Questionany DB changes needed for Northwind Pin
prams_hi19-May-17 13:11
prams_hi19-May-17 13:11 
AnswerRe: any DB changes needed for Northwind Pin
sazakir14-Dec-17 23:46
sazakir14-Dec-17 23:46 
QuestionSQL Server version Pin
MarekMi25-Sep-15 0:37
professionalMarekMi25-Sep-15 0:37 
AnswerRe: SQL Server version Pin
sazakir26-Oct-15 1:38
sazakir26-Oct-15 1:38 
QuestionYour code is using extremely outdated methods Pin
sevin76-Jan-15 7:59
sevin76-Jan-15 7:59 
AnswerRe: Your code is using extremely outdated methods Pin
PIEBALDconsult6-Jan-15 8:21
mvePIEBALDconsult6-Jan-15 8:21 
GeneralRe: Your code is using extremely outdated methods Pin
sevin76-Jan-15 22:56
sevin76-Jan-15 22:56 
GeneralRe: Your code is using extremely outdated methods Pin
sazakir6-Jan-15 23:54
sazakir6-Jan-15 23:54 
GeneralRe: Your code is using extremely outdated methods Pin
sevin77-Jan-15 3:52
sevin77-Jan-15 3:52 
SuggestionRead-through to avoid cache miss and reloading data Pin
sameer@alachisoft.com28-Dec-14 1:35
sameer@alachisoft.com28-Dec-14 1:35 
GeneralRe: Read-through to avoid cache miss and reloading data Pin
sazakir7-Jan-15 0:04
sazakir7-Jan-15 0:04 
QuestionHi, very clear and simple, thanks! Pin
User-243813324-Nov-14 10:54
User-243813324-Nov-14 10:54 
AnswerRe: Hi, very clear and simple, thanks! Pin
User-243813325-Nov-14 3:59
User-243813325-Nov-14 3:59 
AnswerRe: Hi, very clear and simple, thanks! Pin
slishnevsky26-Nov-14 6:18
slishnevsky26-Nov-14 6:18 
QuestionDo you need Service Broker enabled on the database to run this project? Pin
Member 790852914-Jul-14 4:22
Member 790852914-Jul-14 4:22 
AnswerRe: Do you need Service Broker enabled on the database to run this project? Pin
sazakir15-Jul-14 0:40
sazakir15-Jul-14 0:40 
GeneralRe: Do you need Service Broker enabled on the database to run this project? Pin
Member 790852915-Jul-14 7:51
Member 790852915-Jul-14 7:51 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.