Using ASP.NET Caching with SQL Server
- Enabling Cache Notification for SQL Server
- On the Windows Start menu, point to All Programs, point to Accessories, and then click Command Prompt to open a command prompt window.
- Locate the Aspnet_regsql.exe executable file on your disk drive. This file is installed with the .NET Framework version 2.0 in the following location:
%windir%\Microsoft.NET\Framework\FrameworkVersion
Be sure that %windir% represents your Windows directory and that the .NET Framework version is 2.0 or later. The path might look like the following:
C:\WINDOWS\Microsoft.NET\Framework\v2.0.40217
- Use the following command to enable cache notification for the dimProductCategory table in the AdventureWorksDW database:
aspnet_regsql.exe -S <Server> -U <Username> -P <Password> -ed -d AdventureWorksDW -et –t dimProductCategory
- Configuring the Web Page for Caching
<%@ OutputCache Duration="3600" SqlDependency=" AdventureWorksDW: DimProductCategory
" VaryByParam="none" %>
- Setting Caching Configuration in the Web.config File
Add the following XML to the Web.config file as a child of the system.web element:
<!-- caching section group -->
<caching>
<sqlCacheDependency
enabled = "true"
pollTime = "1000" >
<databases>
<add
name="AdventureWorksDW" connectionStringName="AdventureWorksDWConnectionString"
pollTime = "1000"/>
</databases>
</sqlCacheDependency>
</caching>
- To configure application-level caching
<!-- caching section group -->
<caching>
<outputCacheSettings>
<outputCacheProfiles>
<add
name="AppCache1"
enabled="true"
duration="60"/></outputCacheProfiles>
</outputCacheSettings>
</caching>
Add the OutputCache into the page
<%@ OutputCache CacheProfile="AppCache1" VaryByParam="none" %>
The sqlDependency table can also specify in the web config as below:
<!-- caching section group -->
<caching>
<outputCacheSettings>
<outputCacheProfiles>
<add
name="AppCache1"
enabled="true" sqlDependency="AdventureWorksDW:DimProductCategory"
duration="60"/>
</outputCacheProfiles>
</outputCacheSettings>
</caching>
- Cache the data object
The sample codes below can set up the SqlCacheDependency with the tables or the sql queries
// Declare the SqlCacheDependency instance, SqlDep.
SqlCacheDependency SqlDep = null;
// Check the Cache for the SqlSource key.
// If it isn't there, create it with a dependency
// on a SQL Server table using the SqlCacheDependency class.
if (Cache["SqlSource"] == null)
{
// Because of possible exceptions thrown when this
// code runs, use Try...Catch...Finally syntax.
try
{
// Instantiate SqlDep using the SqlCacheDependency constructor.
SqlDep = new SqlCacheDependency("AdventureWorksDW", "DimProductCategory");
}
// Handle the DatabaseNotEnabledForNotificationException with
// a call to the SqlCacheDependencyAdmin.EnableNotifications method.
catch (DatabaseNotEnabledForNotificationException exDBDis)
{
try
{
SqlCacheDependencyAdmin.EnableNotifications("AdventureWorksDW");
}
// If the database does not have permissions set for creating tables,
// the UnauthorizedAccessException is thrown. Handle it by redirecting
// to an error page.
catch (UnauthorizedAccessException exPerm)
{
throw new Exception(exPerm.Message, exPerm);
}
}
// Handle the TableNotEnabledForNotificationException with
// a call to the SqlCacheDependencyAdmin.EnableTableForNotifications method.
catch (TableNotEnabledForNotificationException exTabDis)
{
try
{
SqlCacheDependencyAdmin.EnableTableForNotifications("Northwind", "Categories");
}
// If a SqlException is thrown, redirect to an error page.
catch (SqlException exc)
{
throw new Exception(exc.Message, exc);
}
}
// If all the other code is successful, add MySource to the Cache
// with a dependency on SqlDep. If the Categories table changes,
// MySource will be removed from the Cache. Then generate a message
// that the data is newly created and added to the cache.
finally
{
Cache.Insert("SqlSource", this.SqlDataSource1, SqlDep);
//The data object was created explicitly;
}
}
else
{
//The data was retrieved from the Cache;
}
3. Multiple Table Dependencies
SqlCacheDependency
dep1 = new SqlCacheDependency ("MyDb", "Users"),
dep2 = new SqlCacheDependency ("MyDb", "UserRoles"),
dep3 = new SqlCacheDependency ("MyDb", "Policies");
AggregateCacheDependency aggDep = new AggregateCacheDependency ();
aggDep.Add (dep1, dep2, dep3);
Cache.Insert ("SomeKey", someData, aggDep);