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



The information in this article applies to:

  • Microsoft ASP.NET (included with the .NET Framework) 1.0
  • Microsoft Visual Basic .NET (2002)
  • Microsoft ASP.NET (included with the .NET Framework 1.1)
  • Microsoft Visual Basic .NET (2003)

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

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
  1. Start Microsoft Visual Studio .NET.
  2. On the File menu, point to New, and then click Project.
  3. In the New Project dialog box, under Project Types, click Visual Basic Projects. Under Templates, click ASP.NET Web Application.
  4. 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 "Run the Code" section later in this article.
  1. Add a new WebForm named DataCacheSample.aspx to your project in Visual Studio .NET. To do this, follow these steps:
    1. Right-click the project node in Solution Explorer, point to Add, and then click Add New WebForm.
    2. Name the WebForm DataCacheSample.aspx, and then click Open.
  2. In the Visual Studio .NET Integrated Development Environment (IDE), switch to Design view.
  3. Add a WebForm button to the page:
    1. Drag a WebForm button onto the page.
    2. Select the WebForm button. Change the ID property to CreateNewOrCached, and change the Text property to Create New Or Cached.
  4. Add a second WebForm button:
    1. Drag another WebForm button onto the page, and place it after the CreateNewOrCached button.
    2. Select the WebForm button, change the ID property to RemoveEntry, and then change the Text property to RemoveEntry.
  5. Add a WebForm Label:
    1. Drag a WebForm label onto the page from Toolbox.
    2. Select the WebForm label, and change the ID property to CacheStatus, and then clear the Text property.
  6. Add a DataGrid:
    1. Drag a WebForm DataGrid control onto the page. Keep the default ID property of DataGrid1.
Back to the top

Add the code

Add 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 display the code.
  2. 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.
  3. Switch to Design view.
  4. 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("CacheDataSetEmployees"), 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("SqlPubsEmployees") = "SomeValue"
    
                ' Create the array of cache key item names.
                Dim keys() As String = {"SqlPubsEmployees"}
    
    
                Dim ds As DataSet = New DataSet()
                ' Create the connection and pass in the ConnectionString.
                Dim MySqlConn As SqlConnection = New SqlConnection("Server=localhost;Database=Pubs;uid=sa;pwd=")
                ' Create the Data Adapter and pass the command text and 
                ' connection to use.
                Dim MySda As SqlDataAdapter = 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 cache 
                ' keys (keys).
                Dim MyDependency As New CacheDependency(Nothing, 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
            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.
  5. Switch back to Design view in the DataCacheSample.aspx page.
  6. Double-click the RemoveEntry button to display the RemoveEntry_Click event code.
  7. 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("SqlPubsEmployees")
    
            ' Display the status of the cache item.
            CacheStatus.Text = "Cache Item Removed"
    End Sub
    					
  8. On the File menu, click Save All to save the WebForm and other associated project files.
  9. Build the project: on the Build menu in the Visual Studio .NET IDE, click Build Solution.
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:
    • 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.
    • 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.
  4. 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.
  5. 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 "References" 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

REFERENCES

For information about file-based dependencies, visit the following Microsoft Web site: For information about CacheItemRemovedCallback, visit the following Microsoft Web site: NoteCacheItemRemovedCallback defines a callback method for notifying applications when a cached item is removed from the cache.

For information about the CacheDependency class, visit the following Microsoft Web site: The CacheDependency class tracks cache dependencies, such as files, folders, or keys to other objects in the application's cache.

For a brief overview of the various caching options available for ASP.NET, visit the following Microsoft Web site: For additional information, click the article numbers below to view the articles in the Microsoft Knowledge Base:

305140 INFO: ASP.NET Roadmap

307225 ASP.NET caching overview

Back to the top

Modification Type:MinorLast Reviewed:1/13/2006
Keywords:kbCaching kbDatabase kbHOWTOmaster KB312358 kbAudDeveloper