Microsoft KB Archive/312358

= How to implement key-based dependencies for data caching in ASP.NET by using Visual Basic .NET =

Article ID: 312358

Article Last Modified on 8/28/2007

-

APPLIES TO


 * Microsoft ASP.NET 1.0
 * Microsoft Visual Basic .NET 2002 Standard Edition
 * Microsoft ASP.NET 1.1
 * Microsoft Visual Basic .NET 2003 Standard Edition

-



This article was previously published under Q312358



For a Microsoft Visual C# .NET version of this article, see 308147.

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 by using Visual Basic .NET
 * Build the Web form
 * Add the code
 * Run the code
 * Troubleshoot
 * REFERENCES



SUMMARY
Use this step-by-step guide to implement key-based dependencies for data caching in an ASP.NET application.

This example creates and inserts a DataSet object into a cache with a dependency set on another cache entry item by referencing its key. For additional information and examples of data caching with time-based or file-based dependencies, see the REFERENCES section in this article.

Back to the top

Requirements
The following list outlines the recommended hardware, software, network infrastructure, and service packs that you need:
 * Microsoft Windows 2000 or Microsoft Windows XP.
 * Microsoft Internet Information Services (IIS).
 * Microsoft .NET Framework.
 * Microsoft SQL Server.

Back to the top

Create an ASP.NET Web application by using Visual Basic .NET
The following procedure creates a new ASP.NET Web application named DataCacher  Start Microsoft Visual Studio .NET. On the File menu, point to New, and then click Project. In the New Project dialog box, under Project Types, click Visual Basic Projects. Under Templates, click ASP.NET Web Application. In the Location box, replace WebApplication# with the new project name: DataCacher. If you are using the local server, leave the server name as http://localhost. The Location box looks similar to this:

http://localhost/DataCacher



Back to the top

Build the Web form
Note For additional information, see the &quot;Run the Code&quot; section later in this article.  Add a new WebForm named DataCacheSample.aspx to your project in Visual Studio .NET. To do this, follow these steps:  Right-click the project node in Solution Explorer, point to Add, and then click Add New WebForm.</li> Name the WebForm DataCacheSample.aspx, and then click Open.</li></ol> </li> In the Visual Studio .NET Integrated Development Environment (IDE), switch to Design view.</li> Add a WebForm button to the page:  Drag a WebForm button onto the page.</li> Select the WebForm button. Change the ID property to CreateNewOrCached, and change the Text property to Create New Or Cached.</li></ol> </li> Add a second WebForm button:  Drag another WebForm button onto the page, and place it after the CreateNewOrCached button.</li> Select the WebForm button, change the ID property to RemoveEntry, and then change the Text property to RemoveEntry.</li></ol> </li> Add a WebForm Label:  Drag a WebForm label onto the page from Toolbox.</li> Select the WebForm label, and change the ID property to CacheStatus, and then clear the Text property.</li></ol> </li> Add a DataGrid: <ol style="list-style-type: lower-alpha;"> <li>Drag a WebForm DataGrid control onto the page. Keep the default ID property of DataGrid1.</li></ol> </li></ol>

Back to the top

Add the code
Add code to insert cache items, to remove cache items, and to build the cache dependency: <ol> <li>Right-click the .aspx page, and then click View Code to display the code.</li> <li> Add the following namespaces to the namespace listing: Imports System.Data.SqlClient Imports System.Web.Caching Note If either namespace is omitted, or if you have a redundant listing of namespaces, you will receive a warning message. </li> <li>Switch to Design view.</li> <li> Double-click the CreateNewOrCached button to display the code for the CreateNewOrCached_Click event. Add the following code to the CreateNewOrCached_Click event.

Note This code requires that you install the SQL Server Pubs database. Private Sub CreateNewOrCached_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CreateNewOrCached.Click ' Create a DataSet object from the cache entry with the ' CacheDataSetEmployees key. Dim CacheDataSetEmployees As Object = CType(Cache.Get(&quot;CacheDataSetEmployees&quot;), DataSet)

' Verify if the object is null. If (CacheDataSetEmployees Is Nothing) Then

' Set a value for the cache entry that serves as the ' key for the dependency. Cache(&quot;SqlPubsEmployees&quot;) = &quot;SomeValue&quot;

' Create the array of cache key item names. Dim keys As String = {&quot;SqlPubsEmployees&quot;}

Dim ds As DataSet = New DataSet ' Create the connection and pass in the ConnectionString. Dim MySqlConn As SqlConnection = New SqlConnection(&quot;Server=localhost;Database=Pubs;uid=sa;pwd=&quot;) ' Create the Data Adapter and pass the command text and ' connection to use. Dim MySda As SqlDataAdapter = 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 cache ' keys (keys). Dim MyDependency As New CacheDependency(Nothing, 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 End If

' Bind the DataGrid to the DataSource. DataGrid1.DataBind

End Sub Note Modify the ConnectionString in the aforementioned code to work correctly with your SQL Server. </li> <li>Switch back to Design view in the DataCacheSample.aspx page.</li> <li>Double-click the RemoveEntry button to display the RemoveEntry_Click event code.</li> <li> Add the following code to the RemoveEntry_Click event: Private Sub RemoveEntry_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RemoveEntry.Click ' 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; End Sub </li> <li>On the File menu, click Save All to save the WebForm and other associated project files.</li> <li>Build the project: on the Build menu in the Visual Studio .NET IDE, click Build Solution.</li></ol>

Back to the top

Run the code

 * 1) Right-click the DataCacheSample.aspx page in Solution Explorer, and then click View in Browser.
 * 2) Click the CreateNewOrCached button. The CacheStatus label displays New Version Created, and the DataGrid control is populated.

Notes:
 * 1) * The New Version Created setting for the CacheStatus label appears because the CacheDataSetEmployees cache key does not reference a valid cache item when you enter the event. In this case, the DataSet is created, the DataGrid control is bound to the DataSet, and the DataSet is entered into the cache by using the CacheDataSetEmployees cache key.
 * 2) * A new CacheDependency object named MyDependency is created. The MyDependency object is listed as the dependency for the CacheDataSetEmployees item when it is added to the cache by using the Insert method. Although this sample demonstrates key-based dependencies, you can also use other types of dependency-based caching criteria, such as file or timestamp.
 * 3) Click the CreateNewOrCached button again.

Notice that the CacheStatus label displays Cached Version Used. This means that the cached DataSet is being used. To verify that this is cached data, modify 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. Notice that the changes you made are not displayed. Click RemoveEntry and then click CreateNewOrCached again to see the changes you made to the database.
 * 1) Click the RemoveEntry button.

Notice that the CacheStatus label displays Cache Item Removed. The cache item with the SqlPubsEmployees key is removed by using the Cache.Remove method in the RemoveEntry_Click event. The array containing the cache key name of the removed item is listed with MyDependency when it is created. The CacheDataSetEmployees item will be removed because it was created by using the Insert method and references MyDependency as its dependency parameter.
 * 1) Click CreateNewOrCached again.

Notice that the CacheStatus label displays New Version Created. The DataSet is created based on the fact that it no longer exists in the cache when the event fires.

Also, notice that the DataGrid control is displayed as populated with data even after the DataSet item is removed from the cache. This is because the EnableViewState property is set to True by default. This maintains the state of the control and it is not related to the cache entry manipulation in the code. For a more visual representation of the control's state at each phase, set the EnableViewState to False.

In a real world situation, the cache key array (in this example, the keys array) may hold cache keys for other tables or other cache items. If one of those items changes, then the cache entry (in this example, CacheDataSetEmployees) for the item created with this dependency is removed from the cache. You can react through a callback if you have to. For more information about callbacks, see the &quot;References&quot; section later in this article.

Back to the top

Troubleshoot

 * The key names 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 will not be retained in the cache properly--for example, if the keys array in the sample code holds another array element, and the element is 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, then the run-time control determines when to remove the item from the cache.

Back to the top

<div class="references_section">