Blue Theme Orange Theme Green Theme Red Theme
 
Home | Forums | Videos | Photos | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
 Resources  
Close
 Our Network  
Close
Search :       Advanced Search »
Home » .NET Best Practices » ASP.NET Caching: SQL Cache Dependency With SQL Server 2000

ASP.NET Caching: SQL Cache Dependency With SQL Server 2000


SQL cache dependencies are one of the most wonderful new features in ASP.NET 2.0, the ability to automatically invalidate a cached data object (such as a DataSet or Custom Data Type) when the related data is modified in the database. This feature is supported in both SQL Server 2005 and in SQL Server 2000, although the underlying plumbing is quite different.

Author Rank:
Total page views :  61709
Total downloads :  659
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
CacheDependencyDemo.zip
 
Become a Sponsor

Introducing Cache Dependencies:

As time passes, the data source may change in response to other actions. However, if your code uses caching, you may remain unaware of the changes and continue using out-of-date information from the cache. To help mitigate this problem, ASP.NET supports cache dependencies. Cache dependencies allow you to make a cached item dependent on another resource so that when that resource changes the cached item is removed automatically. ASP.NET includes three types of dependencies:

  • Dependencies on other cache items.
  • Dependencies on files or folders.
  • Dependencies on a database query.

Introducing SQL Cache Notifications:

SQL cache dependencies are one of the most wonderful new features in ASP.NET 2.0, the ability to automatically invalidate a cached data object (such as a DataSet or Custom Data Type) when the related data is modified in the database. This feature is supported in both SQL Server 2005 and in SQL Server 2000, although the underlying plumbing is quite different.

Cache Notifications in SQL Server 2000:

Before you can use SQL Server cache invalidation, you need to enable notifications for the database. This task is performed with the aspnet_regsql.exe command-line utility, which is located in the c:\[WinDir]\Microsoft.NET\Framework\[Version] directory. To enable notifications, you need to use the -ed command-line switch. You also need to identify the server (use -E for a trusted connection and -S to choose a server other than the current computer) and the database (use -d). Here's an example that enables notifications for the Northwind database on the current server:

aspnet_regsql -ed -E -d Northwind

After executing this command, a new table named SqlCacheTablesForChangeNotification is added to the database Northwind. The SqlCacheTablesForChangeNotification table has three columns: tableName, notificationCreated, and changeId. This table is used to track changes. Essentially, when a change takes place, a record is written into this table. The SQL Server polling queries this table. Also a set of stored procedures is added to the database as well. See the following table.

Procedure Name Description
AspNet_SqlCacheRegisterTableStoredProcedure Sets a table up to support notifications. This process works by adding a notification trigger to the table, which will fire when any row is inserted, deleted, or updated.
AspNet_SqlCacheUnRegisterTableStoredProcedure Takes a registered table and removes the notification trigger so that notifications won't be generated.
AspNet_SqlCacheUpdateChangeIdStoredProcedure The notification trigger calls this stored procedure to update the AspNet_SqlCacheTablesForChangeNotification table, thereby indicating that the table has changed.
AspNet_SqlCacheQueryRegisteredTablesStoredProcedure Extracts just the table names fromthe AspNet_SqlCacheTablesForChangeNotification table. Used to get a quick look at all the registered tables.
AspNet_SqlCachePollingStoredProcedure Gets the list of changes from the AspNet_SqlCacheTablesForChangeNotification table. Used to perform the polling.

After this, need to enable notification support for each individual table. You can do this manually using the AspNet_SqlCacheRegisterTableStoredProcedure, to that, open your query analyzer and select your Database you've enabled for SQL Cache Notification for example Northwind database and write the following command:

exec AspNet_SqlCacheRegisterTableStoredProcedure 'TableName'

Or you can use aspnet_regsql, using the -et parameter to enable a able for sql cache dependency notifications and the -t parameter to name the table. Here's an example that enables notifications for the Employees table:

aspnet_regsql -et -E -d Northwind -t Products

Both options generates the notification trigger for the Products table as the following:

CREATE TRIGGER dbo.[Products_AspNet_SqlCacheNotification_Trigger] ON
[Products]
FOR INSERT, UPDATE, DELETE
AS
BEGIN

SET NOCOUNT ON
EXEC dbo.AspNet_SqlCacheUpdateChangeIdStoredProcedure N'Products'
END

So any record is inserted, deleted or updated in Products table will update ChangeId field in AspNet_SqlCacheTablesForChangeNotification table.

How Notificaions Works:

The AspNet_SqlCacheTablesForChangeNotification contains a single record for every table you're monitoring. When you make a change in the table (such as inserting ,deleting or updating a record), the changeId column is incremented by 1 -see AspNet_SqlCacheUpdateChangeIdStoredProcedure procedure-. ASP.NET queries this table repeatedly and keeps track of the most recent changeId values for every table. When this value changes in a subsequent read, ASP.NET knows that the table has changed.

In this scenario, Any change to the table is deemed to invalidate any query for that table. In other words, if you use this query:

SELECT * FROM Products WHERE CategoryID=1

The caching still works in the same way. That means if any product record is touched, even if the product resides in another category (and therefore isn't one of the cached records), the notification is still sent and the cached item is considered invalid. Also keep in mind it doesn't make sense to cache tables that change frequently.

Enable ASP.Net Polling:

To enable ASP.NET polling , you need to use the <sqlCacheDepency> element in the web.config file. Set the enabled attribute to true to turn it on, and set the pollTime attribute to the number of milliseconds between each poll. (The higher the poll time, the longer the potential delay before a change is detected.) You also need to supply the connection string information.

Creating the Cache Dependency:

Now that we've seen how to set up a database to support SQL Server notifications, the only remaining detail is the code, which is quite straightforward. We can use our cache dependency with programmatic data caching, a data source control, and output caching.

For programmatic data caching, we need to create a new SqlCacheDependency and supply that to the Cache.Insert() method. In the SqlCacheDependency constructor, you supply two strings. The first is the name of the database you defined in the element in the section of the web.config file e.g: Northwind. The second is the name of the linked table e.g: Products.

Example:

private static void CacheProductsList(List<NWProductItem> products)
{

SqlCacheDependency sqlDependency = new SqlCacheDependency("Northwind", "Products");
HttpContext.Current.Cache.Insert("ProductsList", products, sqlDependency, DateTime.Now.AddDays(1), Cache.NoSlidingExpiration);

}

private static List<NWProductItem> GetCachedProductList()
{

return HttpContext.Current.Cache["ProductsList"] as List<NWProductItem>;

}

NWProductItem is business class, and here we are trying to cache a list of NWProductItem instead of DataSet or DataTable.

The following method is used by an ObjectDataSource Control to retrieve List of Products

public static List<NWProductItem> GetProductsList(int catId, string sortBy)
{

//Try to Get Products List from the Cache
List<NWProductItem> products = GetCachedProductList();
if (products == null)
{

//Products List not in the cache, so we need to query the Database by using a Data Layer
NWProductsDB db = new NWProductsDB(_connectionString);
DbDataReader reader = null;
products = new List<NWProductItem>(80);

if (catId > 0)
{

//Return Product List from the Data Layer
reader = db.GetProductsList(catId);

}
else
{

//Return Product List from the Data Layer
reader = db.GetProductsList();

}
//Create List of Products -List if NWProductItem-
products = BuildProductsList(reader);
reader.Close();

//Add entry to products list in the Cache
CacheProductsList(products);

}
products.Sort(new NWProductItemComparer(sortBy));

if (sortBy.Contains("DESC")) products.Reverse();
return products;

}

To perform the same trick with output caching, you simply need to set the SqlDependency property with the database dependency name and the table name, separated by a colon:

<%@ OutputCache Duration="600" SqlDependency="Northwind:Products" VaryByParam="none" %>

The same technique works with the SqlDataSource and ObjectDataSource controls:

<asp:SqlDataSource EnableCaching="True" SqlCacheDependency="Northwind:Products" ... />

Important Note:

ObjectDataSource doesn't support built in caching for Custom types such as the one in our example. It only support this feature for DataSets and DataTables.

To test this feature, download the attached demo. It contains an editable GridView. Set a break point at the GetProductList method and run in debug mode. Update any record and notice the changes. Also you can edit the solution and remove the cache dependency and note the deference after update.

Also you can remove the SqlDependency from the output cache in the OutputCaching.aspx page, and notice that whatever update you made to the data source, the page still retrieves the old version of data.


Login to add your contents and source code to this article
 About the author
 
Muhammad Mosa
Muhammad M. Mosa Soliman: Software Engineer, graduated from the Faculty of Computers & Information Systems year 2003-Ain Shams University- in Cairo. Working with Microsoft .NET technology since early beta releases. Main experiance based on ASP.NET, SharePoint Portal 2003 & SQL Server. Worked as trainer for Microsoft .NET for 2 years in Cairo. Likes to read about new technologies and self-learning. Extremly Hard worker when motivated. MCT MCSD.NET MCTS: .Net 2.0 Web/Windows Applications MCPD: Enterprise Application Developer MCTS: WSS 3.0 & MOSS 2007 Config
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
SQL and .NET performance profiling in one place
Investigate SQL and .NET code side-by-side with ANTS Performance Profiler 6, so you can see which is causing the problem without switching tools.
Go.NET
Build custom interactive diagrams, network, workflow editors, flowcharts, or software design tools. Includes many predefined kinds of nodes, links, and basic shapes. Supports layers, scrolling, zooming, selection, drag-and-drop, clipboard, in-place editing, tooltips, grids, printing, overview window, palette. 100% implemented in C# as a managed .NET Control. Document/View/Tool architecture with many properties&events. Optional automatic layout.
Dundas Software
Dundas Chart for .NET is the most advanced .NET charting package available today.  With an extremely complete feature set, elegant architecture and easy implementation, Dundas Chart can quickly add advanced Charting functionality to enhance and transform ASP.NET and Windows Forms applications.  Whether you are implementing charting into internal projects, or building applications for clients, Dundas Chart offers advanced technology and advanced results to get the most out of data.
60 FREE UI Controls from DevExpress
Register for your FREE copy on over 60 free presentation controls from DevExpress - Absolutely Free-of-Charge without any royalties or distribution costs. Visit Devexpress.com/60 today. Free controls include advanced lists box, dropdown calendar, rich text edit, spin edit, tab control and so much more!

DevExpress engineers feature rich presentation controls and reporting tools for WinForms, ASP.NET, WPF, and Silverlight. Our technologies help you build your best, see complex software with greater clarity and deliver compelling business solutions for Windows and the web in the shortest possible time.
Clickatell's SMS Gateway
Clickatell's Developer Solutions allow you to SMS enable any website or application via a range of API's. Learn More about our API connections.
Free access to .NET Memory Management video
Everything you need to know about Garbage Collection, Temporary Objects, Fragmentation, Finalization and common causes of memory leaks in .NET. Watch the video here.
Microsoft Visual Studio 2010
Visualize your workspace with new multiple monitor support, powerful Web development, new SharePoint support with tons of templates and Web parts, and more accurate targeting of any version of the .NET Framework. Get set to unleash your creativity.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
Developer-Ready ASP.NET 2.0 Web Hosting with 3 MONTHS FREE
Now supporting .NET 3.0 Framework with Windows Workflow Foundation, Windows Communication Foundation (WCF), Windows Presentation Foundation (WPF), windows CardSpace (WCS)! Providing more flexibility for Developers with Web Services Support and a User/Permission Manger. Also supporting MS SQL 2005/2000 with Real-Time Backups, FREE Automated Attach .MDF Tool, FREE SQL Restore and Shrink SQL DB Tools, and SQL
Read the Top 10 Books for Microsoft Developers, 15 Days FREE
Read the Top 10 Books for Microsoft Developers, 15 Days FREE
Try Safari Books Online - 15 Days FREE + 15% Off for 1 Year
Try Safari Books Online - 15 Days FREE + 15% Off for 1 Year
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
Become a Sponsor
 Comments
It works! by shariq_abbasi On July 6, 2007
I have tried your soultion and It works!
Reply | Email | Delete | Modify | 
It works! by shariq_abbasi On July 6, 2007
I have tried your soultion and It works!
Reply | Email | Delete | Modify | 
Cache in 3-tier architecture by india_ritesh On January 3, 2008
What happen when Business lAyer and Data Layer are seperate DLL. Right now in your solution they might be sitting under website appcode folder,You can access Cache object. But when DLL are seperate for different layer how you can cache data in Data layer. Ritesh riteshag77@hotmail.com
Reply | Email | Delete | Modify | 
Re: Cache in 3-tier architecture by Muhammad On February 12, 2008
who is responsible for caching is not Business or Data Layers. Presentation layer will take this job, or may be a layer in between. My code reside in app_code folder but still you can divide your code to Business logic and Date logic within that folder.
Reply | Email | Delete | Modify | 
Re: ASP.NET Caching: SQL Cache Dependency With SQL Server 2000 by Ed On November 19, 2008
Hi Mosa! Great post! SQL Cache Dependencies is a good feature and also tries to fill up the holes of ASP.NET cache, but due to its in-process and standalone nature it is not scalable. My question is that what you would do if you want to scale out your web application. I think right way to solve this scalability problem is through an in-memory distributed cache. And Microsoft realized this as well and came up with its distributed caching solution. I personally like NCache which is really impressive because of its scalability and high reliability. The great thing is that it also has NCache Express which is free for 2-server environments. You can check it here: http://www.alachisoft.com/ncache/asp-net-cache.html
Reply | Email | Delete | Modify | 
Excellent by Zenou On October 8, 2009
Excellent tutorial
Reply | Email | Delete | Modify | 
Oracle 10G by vijay On October 13, 2009
Do we have equvivalent of this in Oracle 10G/Visual Studio 2008.
Reply | Email | Delete | Modify | 

 Hosted by MaximumASP  |  Found a broken link?  |  Contact Us  |  Terms & conditions  |  Privacy Policy  |  Site Map  |  Suggest an Idea  |  Media Kit
Current Version: 5.2010.8.14
 © 2010  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.