Introduction
This is the 2nd part of Caching FAQ's. In this section we will touch base on one of important concepts in .Net Caching.
For Caching Part 1, click here
Happy job hunting.......
(I) How do we enable SQL Cache Dependency in ASP.NET 2.0?
Below are the broader steps to enable a SQL Cache Dependency:-
- Enable notifications for the database.
- Enable notifications for individual tables.
- Enable ASP.NET polling using "web.config" file
- Finally use the Cache dependency object in your ASP.NET code
Enable notifications for the database.
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.
aspnet_regsql -ed -E -d Northwind
-ed :- command-line switch
-E: - Use trusted connection
-S: - Specify server name it other than the current computer you are working on
-d: - Database Name
So now, let us try to understand what happens in the database because of "aspnet_regsql.exe". After we execute the "aspnet_regsql -ed -E -d Northwind" command you will see one new table and four new stored procedures created.
Figure 5.1: - SQL Cache table created for notification
Essentially, when a change takes place, a record is written in this table. The SQL Server polling queries this table for changes.
Figure 5.2: - New stored procedures created
Just to make brief run of what the stored procedures do.
"AspNet_SqlCacheRegisterTableStoredProcedure" :- This stored procedure sets a table 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":- This stored procedure 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_SqlCacheTablesFor ChangeNotification table, thereby indicating that the table has changed.
Asp Net_Sql Cache Query Registered Tables Stored Procedure:- This extracts just the table names from the AspNet_SqlCacheTablesForChangeNotification table. It is used to get a quick look at all the registered tables.
AspNet_SqlCachePollingStoredProcedure:- This will get the list of changes from the AspNet_SqlCacheTablesForChangeNotification table. It is used to perform polling.
Enabling notification for individual tables
Once the necessary stored procedure and tables are created then we have to notify saying which table needs to be enabled for notifications.
That can be achieved by two ways:-
- aspnet_regsql -et -E -d Northwind -t Products
- Exec spNet_SqlCacheRegisterTableStoredProcedure 'TableName'
Registering tables for notification internally creates triggerfor the tables. For instance, for a "products" table the following trigger is created. So any modifications done to the "Products" table will update the "AspNet_SqlCacheNotification" table.
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
"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 change Id column is incremented by 1.ASP.NET queries this table repeatedly keeps track of the most recent changed values for every table. When this value changes in a subsequent read, ASP.NET knows that the table has changed.
Figure 5.3: - Entries in the Cache notification table
Enable ASP.NET polling using "web.config" file
Now that all our database side is configured in order to get the SQL Cache working in the ASP.NET side we need to do some configuration in the web.config file.
We need to set two attributes in the "web.config" file:-
- Set "Enabled" attribute to true to set the caching on.
- Set the poll time attribute to the number of milliseconds between each poll
Below is the snapshot of the web.config file.
Figure 5.4:- Web.config file modifications for SQL cache
Finally use the Cache dependency object in your ASP.NET code
Now comes the final step to 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.
private static void CacheProductsList(List<ClsProductItem> products)
{
SqlCacheDependency sqlDependency = new SqlCacheDependency("Northwind", "Products");
HttpContext.Current.Cache.Insert("ProductsList", products, sqlDependency, DateTime.Now.AddDays(1), Cache.NoSlidingExpiration);
}
private static List<ClsProductItem> GetCachedProductList()
{ return HttpContext.Current.Cache["ProductsList"] as List<ClsProductItem>; }
ClsProductItem is business class, and here we are trying to cache a list of ClsProductItem instead of DataSet or DataTable.
The following method is used by an ObjectDataSource Control to retrieve List of Products
public static List<ClsProductItem> GetProductsList(int catId, string sortBy)
{//Try to Get Products List from the Cache
List<ClsProductItem> products = GetCachedProductList();
if (products == null)
{
//Products List not in the cache, so query the Database layer
ClsProductsDB db = new ClsProductsDB(_connectionString);
DbDataReader reader = null;
products = new List<ClsProductItem>(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 ClsProductItem-
products = BuildProductsList(reader);
reader.Close();
//Add entry to products list in the Cache
CacheProductsList(products);
}
products.Sort(new ClsProductItemComparer(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" ... />
Note:- ObjectDataSource doesn't support built in caching for Custom types such as the one in our example. It only supports this feature for DataSets and DataTables.
Just to make a sample check run the SQL Server profiler and see that does the SQL actually hit the database after the first run.
(I) What is Post Cache substitution?
Post cache substitution is used when we want to cache the whole page but also need some dynamic region inside that cached page. Some examples like QuoteoftheDay, RandomPhotos, and AdRotator etc. are examples where we can implement Post Cache Substitution.
Post-cache substitution can be achieved by two means:
- Call the new Response.WriteSubstitution method, passing it a reference to the desired substitution method callback.
- Add a <asp:Substitution> control to the page at the desired location, and set its methodName attribute to the name of the callback method.
Figure 5.5: - "Writesubstitution" in action
You can see we have a static function here "GetDateToString()". We pass the response substitution callback to the "WriteSubstitution" method. So now, when ASP.NET page framework retrieves the cached page, it automatically triggers your callback method to get the dynamic content. It then inserts your content into the cached HTML of the page. Even if your page has not been cached yet (for example, it's being rendered for the first time), ASP.NET still calls your callback in the same way to get the dynamic content. So you create a method that generates some dynamic content, and by doing so you guarantee that your method is always called, and it's content is never cached.
Ok the above example was by using "WriteSubstitution" now lets try to see how we can do by using "<asp:substitution>" control. You can get the "<asp:substitution>" control from the editor toolbox.
Figure 5.6: - Substitution Control
Figure 5.7: - Substitution in Action
Below is a sample code that shows how substitution control works. We have ASPX code at the right hand side and class code at the behind code at the left hand side. We need to provide the method name in the "methodname" attribute of the substitution control.
(I) Why do we need methods to be static for Post Cache substitution?
ASP.NET should be able to call this method even when there is not an instance of your page class available. When your page is served from the cache, the page object is not created. Therefore, ASP.NET skips the page life cycle when the page is coming from cache, which means it will not create any control objects or raise any control events. If your dynamic content depends on the values of other controls, you will need to use a different technique, because these control objects will not be available to your callback.