HOW TO: Implement Key-Based Dependencies for Data Caching in ASP.NET by Using Visual C# .NET

Article translations Article translations
Article ID: 308147 - View products that this article applies to.
This article was previously published under Q308147
Expand all | Collapse all

On This Page

SUMMARY

This article demonstrates how to implement data caching by using key-based dependencies in a Microsoft ASP.NET application. The example that is presented in this article creates and inserts a DataSet object into the cache with a dependency set on another cache entry item by referencing its key. For examples of data caching with time or file-based dependencies, refer to the "References" section in this article.

Requirements

  • Microsoft Windows 2000 or Microsoft Windows XP
  • Microsoft Internet Information Server (IIS)
  • Microsoft .NET Framework
  • Microsoft SQL Server

Create an ASP.NET Web Application

Use Microsoft Visual C# .NET to create a Microsoft ASP.NET Web application named DataCacher:
  1. Open Microsoft Visual Studio .NET.
  2. On the File menu, point to New, and then click Project.
  3. In the New Project dialog box, click Visual C# Projects under Project Types, and then click ASP.NET Web Application under Templates.
  4. In the Location box, type DataCacher as the project name by replacing the default WebApplication# name in the URL path. If you are using the local server, you can leave the server name as http://localhost, which sets the location to http://localhost/DataCacher.

Build the Web Form

NOTE: The code that is included in this section is explained in more detail in the "Running the Code" section.

To build the data caching sample:
  1. Add a new Web Form named DataCacheSample.aspx to your project in Visual Studio .NET:
    1. Right-click the project node in Solution Explorer.
    2. Click Add, and then click Add New WebForm.
    3. Name the Web Form DataCacheSample.aspx.
    4. Click Open.
  2. On the Design view tab for the Web Form in the the Visual Studio .NET IDE (integrated development environment), add a Web Form button to the page:
    1. Use a drag-and-drop operation to move a Web Form button onto the page.
    2. Click to select the new button. Change the ID property to CreateNewOrCached, and then change the Text property to Create New Or Cached.
  3. Add a second Web Form button:
    1. Use a drag-and-drop operation to move another Web Form button onto the page from the toolbox.
    2. Click to select the new button. Change the ID property to Remove, and then change the Text property to Remove.
  4. Add a Web Form label:
    1. Use a drag-and-drop operation to move a Web Form label onto the page from the toolbox.
    2. Click to select the new label. Change the ID property to CacheStatus, and then clear the Text property.
  5. Use a drag-and-drop operation to move a Web Form DataGrid control onto the page from the toolbox. For this control, leave the ID property set to the default setting of DataGrid1 in the Properties pane.

Adding the Code

Add the code to insert cache items, to remove cache items, and to build the cache dependency:
  1. Right-click the .aspx page, and then click View Code to open the code-behind page.
  2. For this sample, make sure that the System.Data.SqlClient, the System.Data, and the System.Web.Caching namespaces are added to the namespace listing in the code-behind page. If you use Visual Studio. NET to create the Web Form, your namespace listing in the code-behind page will look similar to the following:
    using System;
    using System.Collections;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Web;
    using System.Web.SessionState;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Web.UI.HtmlControls;
    using System.Data.SqlClient;
    using System.Web.Caching;
    						
    NOTE: You will receive warnings if either the namespace is not listed, or if a redundant listing of a namespace exists.
  3. On the Design view tab, double-click the CreateNewOrCached button to open the CreateNewOrCached_Click event in the code-behind page.
  4. Add the following code to the CreateNewOrCached_Click event:
    private void CreateNewOrCached_Click(object sender, System.EventArgs e) {
    	//Attempt to create a DataSet object from the cache entry with the key "CacheDataSetEmployees" 
    	object CacheDataSetEmployees = (DataSet)Cache.Get("CacheDataSetEmployees");
    	
            //Check to see if the object is null
    	if(CacheDataSetEmployees == null)
    	{
    	     //Set a value for the cache entry that will serve as the 
    	     //key for the dependency to be created on
    	     Cache["SqlPubsEmployees"] = "SomeValue";
    
    	     //Create the array of cache key item names
    	     string[] keys = new String[1];
    	     keys[0] = "SqlPubsEmployees";
    				
    	     DataSet ds = new DataSet();
    	     //Create the connection and pass in the ConnectionString
    	    SqlConnection MySqlConn = new SqlConnection("Server=kronicas17;Trusted_Connection=Yes;initial catalog=pubs");
    	     //Create the Data Adapter and pass in the command text and connection to use
    	     SqlDataAdapter MySda = new SqlDataAdapter("SELECT TOP 10 * FROM Employee", MySqlConn);
    	     //Populate the DataTable "Employees" in the DataSet
    	     MySda.Fill(ds,"Employee");
    	     //Set the DataGrid's DataSource to the "Employee" DataTable
    	     DataGrid1.DataSource = ds.Tables["Employee"];
    				
    	     //Create a dependency object referencing the array of cachekeys (keys)
    	     CacheDependency MyDependency = new CacheDependency(null, keys);
    	     //Insert the DataSet into Cache with a dependency on MyDependency
    	     Cache.Insert("CacheDataSetEmployees", ds, MyDependency);
    				MySqlConn.Close();
    				
    	     //Display the status of the DataSet/Cache Entry
    	     CacheStatus.Text = "New Version Created";
    	}
    	else
    	{
    	     //Display the status of the DataSet/Cache Entry
    	     CacheStatus.Text = "Cached Version Used";
    	     //Set the DataSource to the cached version of the DataSet
    	     DataGrid1.DataSource = CacheDataSetEmployees;
            }
            //Bind the DataGrid to the DataSource
    	DataGrid1.DataBind();
    }
    						
    NOTE: You may need to modify ConnectionString in the code in this step to work correctly with your SQL server. For the code to work properly, you need to have the SQL Server Pubs database installed.
  5. On the Design view tab for the DataCacheSample.aspx page, double-click the Remove button to open the Remove_Click event in the code-behind page.
  6. Add the following code to the Remove_Click event:
    private void Remove_Click(object sender, System.EventArgs e)
         {
    	//Remove the cache item listed in the cachekeys array (keys)
    	Cache.Remove("SqlPubsEmployees"); 	//Display the status of the cache item
    	CacheStatus.Text = "Cache Item Removed";
         }
    					
  7. Add the following element to the Web.config file between <system.web> and </system.web>:
    <identity impersonate=”true” />
    
  8. On the File menu, click Save All to save the Web Form and the other associated project files.
  9. On the Build menu in the Visual Studio .NET IDE, click Build to build the project.

Running the Code

  1. To run the code, right-click the DataCacheSample.aspx page in Solution Explorer, and then click View in Browser.
  2. Click the CreateNewOrCached button; the CacheStatus label should display "New Version Created" and the DataGrid control is populated.

    NOTES:
    • The New Version Created setting for the CacheStatus label is the result of the cache key CacheDataSetEmployees that is not yet referencing a valid cache item when entering the event. In this case, the DataSet is created, the DataGrid control is bound to the DataSet, and the DataSet is entered into cache by using the cache key "CacheDataSetEmployees".
    • From the previous step you should have also noticed the creation of the new CacheDependency object named MyDependency. The MyDependency object is listed as the dependency for the CacheDataSetEmployees item when it is added to cache by using the Insert method. It is important to note that, while this sample demonstrates key-based dependencies, you can use other types of dependency-based caching criteria, such as files or a time stamp, as well.
  3. Click the CreateNewOrCached button again. The CacheStatus label displays "Cached Version", which states that the cached DataSet was used. You can verify that this is cached data by modifying one of the displayed records in the Pubs database by using SQL Query Analyzer or another tool. After you modify the record, click the CreateNewOrCached button again. Note that the changes you made are not displayed. Click Remove, and then click CreateNewOrCached again to see the changes that you made to the database.
  4. Click the Remove button. The CacheStatus label displays "Cache Entry Removed". The cache item with the key "SqlPubsEmployees" is removed by using the Cache.Remove method in the Remove_Click event. Because you listed the array (which contains the cache key name of the removed item) with MyDependency when you created it, the "CacheDataSetEmployees" item is removed because you created it by using the Insert method and by referencing MyDependency as its dependency parameter.
  5. Click the CreateNewOrCached button again. The CacheStatus label displays the message "New Version Created" because the DataSet was created based on the fact that it no longer existed in cache when the event was fired.
  6. You may also notice that the DataGrid control is displayed as populated with data even after the DataSet item is removed from cache. This is the result of the EnableViewState property being set to True by default. This enables the state of the control to be maintained, and this is not related to the cache entry manipulation in the code. For a more visual representation of the control's state at each phase, you can set EnableViewState to False.
NOTE: In regards to this example, in an actual situation, the cache key array (the keys array in the sample code) might hold cache keys for other tables or other cache items so that if one of those items were to change, the cache entry (CacheDataSetEmployees in this sample) for the item that was created with this dependency would be removed from the cache as well. You could then act as necessary by using callbacks; for more information on callbacks, refer to the "References" section in this article.

Troubleshooting

  • The key names that are listed in the cache keys array must be associated with actual cache items. If they are not, the item for which the dependency is used is not properly retained in the cache. An example of this would be if the keys array in the sample code held another array element and the element was set to an invalid cache key name.
  • The cache keys array has no specific meaning until it is used with a CacheDependency object.
  • If you insert an item into the cache with no dependency or other expiration, the runtime controls when the item is removed from the cache.

REFERENCES

For more information about using the CacheItemRemovedCallback delegate, see the following Microsoft Web site:
CacheItemRemovedCallback Delegate
http://msdn2.microsoft.com/en-us/library/system.web.caching.cacheitemremovedcallback(vs.71).aspx
NOTE: The CacheItemRemovedCallback delegate defines a callback method for notifying applications when a cached item is removed from the cache.

For more information about the CacheDependency class, see the following Microsoft Web site:
CacheDependency Class
http://msdn2.microsoft.com/en-us/library/system.web.caching.cachedependency(vs.71).aspx
NOTE: The CacheDependency class tracks cache dependencies, which can be files, directories, or keys to other objects in your application's cache.

For more information about the various caching options that are available for ASP.NET, refer to the following Microsoft .NET Framework SDK documentation:
Adding Items to the Cache
http://msdn.microsoft.com/en-us/library/cc511535.aspx
For additional information about the various caching options that are available for ASP.NET, click the article numbers below to view the articles in the Microsoft Knowledge Base:
305140 ASP.NET Roadmap
307225 INFO: ASP.NET Caching Overview

Properties

Article ID: 308147 - Last Review: August 28, 2007 - Revision: 2.8
APPLIES TO
  • Microsoft ASP.NET 1.1
  • Microsoft ASP.NET 1.0
  • Microsoft Visual C# .NET 2003 Standard Edition
  • Microsoft Visual C# .NET 2002 Standard Edition
Keywords: 
kbcaching kbdatabase kbhowtomaster KB308147

Give Feedback

 

Contact us for more help

Contact us for more help
Connect with Answer Desk for expert help.
Get more support from smallbusiness.support.microsoft.com