Login | Register   
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


advertisement
 

Caching Data with a Web Service in Enterprise Library : Page 7

If you've ever wondered whether you might be able to use a web service to cache data—or whether it would be fast enough to be useful—wonder no more.


advertisement
Using the Web Service Cache Provider in ASP.NET
The sample code for this article contains a simple ASP.NET application that you can use to test the web service-based caching mechanism. The default configuration specifies two instances of the custom Web Service Caching provider, with different values for the partition name.

Author's Note: Before you use the test application, you must ensure that the URL of the target web service for both backing store instances points to the location of the Caching Web Service (SampleCacheWebService) you want to use. The easiest way to set this up is to install the SampleCacheWebService into Internet Information Services (IIS)—this can be on the same machine or a remote machine. After installing and testing the web service by opening it in a web browser, copy the URL into the test web site configuration. You can edit the configuration file (web.config) using the version of the Configuration Console in your EntLibSrc\App Blocks\bin folder, or directly in a text editor. Also ensure that the server running the web service has a C:\Temp folder available with permission for the ASPNET or NETWORK SERVICE account to read, write, and delete files, and create subfolders. You can edit the path in the web service class file to use a different folder for the cache root if you prefer.

Here's the relevant section of the web.config file for the test web site, showing the values for the two Web Service Cache backing store providers (note that some lines have wrapped in the listing due to the limitations of page width):

<backingStores> <add webServiceUrl="http://localhost/SampleCacheWebService /SampleCachingWebService.asmx" partitionName="FirstTestPartition" defaultCacheDuration="7200" encryptionProviderName="" type="Microsoft.Practices.EnterpriseLibrary.Caching .BackingStoreImplementations. CustomWebServiceBackingStore, Microsoft.Practices.EnterpriseLibrary.Caching, Version=3.0.0.0, Culture=neutral, PublicKeyToken=null" name="CustomWebServiceManager_1" /> <add webServiceUrl="http://localhost/SampleCacheWebService /SampleCachingWebService.asmx " partitionName="AnotherPartition" defaultCacheDuration="600" encryptionProviderName="" type="Microsoft.Practices.EnterpriseLibrary.Caching .BackingStoreImplementations. CustomWebServiceBackingStore, Microsoft.Practices.EnterpriseLibrary.Caching, Version=3.0.0.0, Culture=neutral, PublicKeyToken=null" name="CustomWebServiceManager_2" /> </backingStores>

 
Figure 5. Sample ASP.NET Application: You can use this application to test the custom web service-based caching mechanism.
The page Default.aspx (in the TestWebSite subfolder of the samples) contains two option buttons that let you select which of the two configured instances of the custom Web Service Caching provider you want to use. After the option buttons, you'll see a series of buttons and text boxes where you can enter the name of the cache key and (for a text or numeric type) the value to cache.

You can cache Strings, Doubles, Object Arrays, or a DataSet. Each has different cache durations; the Object Array uses the default duration setting of the selected provider.

When you click one of the buttons to cache a value or an object, the page displays the number of items currently in the selected cache partition, as you can see in Figure 5.

You can also retrieve and display items you previously cached, or remove them from the cache. When you remove an item, the page again displays the number of items currently in the cache. You can also remove all items from the cache. If you try to retrieve or remove an item that does not exist (either because you already removed it or it has expired), the page displays a suitable error message. It also displays details of any other exceptions that may occur—for example, if you specify an incorrect URL for a provider or the provider encounters an error.

Adding Items to the Cache in the Sample Application
The sample page's code-behind is relatively simple. For example, this is the handler for the first button on the page, which caches a String value:

protected void btn_CacheString_Click( object sender, EventArgs e) { try { // create the selected cache manager instance CacheManager cm = CacheFactory.GetCacheManager( optCacheManager.SelectedValue); // cache the item with a short sliding expiry duration cm.Add(txtStringKey.Text, txtStringValue.Text, CacheItemPriority.Normal, null, new SlidingTime( new TimeSpan(0, 0, 20))); // display number of items in cache and set list items DisplayResultsAndUpdateButtonLists(cm.Count, txtStringKey.Text); } catch (Exception ex) { lblResults.Text = "<b>ERROR</b>: " + ex.Message; } }

The code creates an instance of the appropriate CacheManager by using the value selected in the RadioButtonList control at the top of the page. It then calls the Add method, passing the name of the cache key and the value from the text boxes on the page, the cache priority (although this implementation of the provider always uses Normal priority, irrespective of the value you specify here), null for the call-back parameter, and a 20-second sliding time expiry value.

The final step is a call to the DisplayResultsAndUpdateButtonLists routine located at the end of the page code that passes the number of items in the cache (obtained from the CacheManager.Count property) and the name of the key for the item just added. The routine (shown below), uses these values to display the number of items in the cache, update the two lists of cache keys for the Retrieve and Remove buttons, and set the Enabled property of these two buttons to the appropriate value:



private void DisplayResultsAndUpdateButtonLists( Int32 cacheCount, String keyText) { // display number of items in cache lblResults.Text = String.Format( "Cache '{0}' contains {1} item(s).", optCacheManager.SelectedValue, cacheCount.ToString()); // add the current key to the "Retrieve" list if (! lstRetrieveItem.Items.Contains(new ListItem(keyText))) { lstRetrieveItem.Items.Add(keyText); } // set enabled state of "Retrieve" button btn_Retrieve.Enabled = (lstRetrieveItem.Items.Count != 0); // add the current key to the "Remove" list if (!lstRemoveItem.Items.Contains(new ListItem(keyText))) { lstRemoveItem.Items.Add(keyText); } // set enabled state of "Remove" button btn_Remove.Enabled = (lstRemoveItem.Items.Count != 0); }

The button handlers that add Doubles, Object Arrays, and DataSets to the cache are much the same as that for the String value. The handler for a numeric value converts the String from the text box into a Double type using the Double.Parse method, while the code in the handler that caches an Object Array just creates the array before caching it. Notice that it takes advantage of the short form of the Add method, which uses default values for the cache priority and duration:

... // populate an Object Array Object[] vals = new Object[3]; vals[0] = "Some text"; vals[1] = 42; vals[2] = DateTime.Now; // create the selected cache manager instance CacheManager cm = CacheFactory.GetCacheManager( optCacheManager.SelectedValue); // cache the item with the default sliding expiry duration cm.Add(txtArrayKey.Text, vals); ...

The code that caches a DataSet creates the DataSet by loading an XML schema and an XML document from the xmldata subfolder of the examples.



Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap