Microsoft KB Archive/308147

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

Article ID: 308147

Article Last Modified on 8/28/2007

-

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

-



This article was previously published under Q308147



For a Microsoft VB .NET version of this article, see 312358.

This article refers to the following Microsoft .NET Framework Class Library namespaces:
 * System.Web.Caching
 * System.Web.SessionState
 * System.Data.SqlClient

IN THIS TASK

 * SUMMARY
 * Requirements
 * Create an ASP.NET Web Application
 * Build the Web Form
 * Adding the Code
 * Running the Code
 * Troubleshooting
 * REFERENCES



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 &quot;References&quot; section in this article.

back to the top

Requirements

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

back to the top

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   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.

back to the top

Build the Web Form
NOTE: The code that is included in this section is explained in more detail in the &quot;Running the Code&quot; section.

To build the data caching sample:  Add a new Web Form named DataCacheSample.aspx to your project in Visual Studio .NET:  Right-click the project node in Solution Explorer. Click Add, and then click Add New WebForm. Name the Web Form DataCacheSample.aspx. Click Open.  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:  Use a drag-and-drop operation to move a Web Form button onto the page.</li> Click to select the new button. Change the ID property to CreateNewOrCached, and then change the Text property to Create New Or Cached.</li></ol> </li> Add a second Web Form button:  Use a drag-and-drop operation to move another Web Form button onto the page from the toolbox.</li> Click to select the new button. Change the ID property to Remove, and then change the Text property to Remove.</li></ol> </li> Add a Web Form label:  Use a drag-and-drop operation to move a Web Form label onto the page from the toolbox.</li> Click to select the new label. Change the ID property to CacheStatus, and then clear the Text property.</li></ol> </li> 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.</li></ol>

back to the top

Adding the Code
Add the code to insert cache items, to remove cache items, and to build the cache dependency:  Right-click the .aspx page, and then click View Code to open the code-behind page.</li>  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. </li> <li>On the Design view tab, double-click the CreateNewOrCached button to open the CreateNewOrCached_Click event in the code-behind page.</li> <li> 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 &quot;CacheDataSetEmployees&quot; object CacheDataSetEmployees = (DataSet)Cache.Get(&quot;CacheDataSetEmployees&quot;); //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[&quot;SqlPubsEmployees&quot;] = &quot;SomeValue&quot;;

//Create the array of cache key item names string[] keys = new String[1]; keys[0] = &quot;SqlPubsEmployees&quot;; DataSet ds = new DataSet; //Create the connection and pass in the ConnectionString SqlConnection MySqlConn = new SqlConnection(&quot;Server=kronicas17;Trusted_Connection=Yes;initial catalog=pubs&quot;); //Create the Data Adapter and pass in the command text and connection to use SqlDataAdapter MySda = new SqlDataAdapter(&quot;SELECT TOP 10 * FROM Employee&quot;, MySqlConn); //Populate the DataTable &quot;Employees&quot; in the DataSet MySda.Fill(ds,&quot;Employee&quot;); //Set the DataGrid's DataSource to the &quot;Employee&quot; DataTable DataGrid1.DataSource = ds.Tables[&quot;Employee&quot;]; //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(&quot;CacheDataSetEmployees&quot;, ds, MyDependency); MySqlConn.Close; //Display the status of the DataSet/Cache Entry CacheStatus.Text = &quot;New Version Created&quot;; }   else {        //Display the status of the DataSet/Cache Entry CacheStatus.Text = &quot;Cached Version Used&quot;; //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. </li> <li>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.</li> <li> 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(&quot;SqlPubsEmployees&quot;);  //Display the status of the cache item CacheStatus.Text = &quot;Cache Item Removed&quot;; }                   </li> <li> Add the following element to the Web.config file between <system.web> and </system.web>: <identity impersonate=”true” /> </li> <li>On the File menu, click Save All to save the Web Form and the other associated project files.</li> <li>On the Build menu in the Visual Studio .NET IDE, click Build to build the project.</li></ol>

back to the top

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 &quot;New Version Created&quot; and the DataGrid control is populated.

NOTES:
 * 1) * 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 &quot;CacheDataSetEmployees&quot;.
 * 2) * 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 &quot;Cached Version&quot;, 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 &quot;Cache Entry Removed&quot;. The cache item with the key &quot;SqlPubsEmployees&quot; 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 &quot;CacheDataSetEmployees&quot; 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 &quot;New Version Created&quot; 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 &quot;References&quot; section in this article.

back to the top

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.

back to the top

<div class="references_section">