C#: Microsoft Enterprise Library: Caching
By: Zack Turnbow
Introduction
Following in line in this short series on Microsoft’s Enterprise Library, this article will cover some of the common uses of the Caching Application Block (CAB). Nearly every application, web or windows application pulls data that is needed by the end user. There is data that is used more often than other data. To keep the overhead down on accessing the database every time that common data is needed, a developer would either create their own caching mechanism or if it is a web application that data would often end up session, which could cause performance issues. So, the CAB was created so a developer wouldn’t have to use the previous methods.
Yes, it is possible to find a good web host. Sometimes it takes a while. After trying several, we went with Server Intellect and have been very happy. They are the most professional, customer service friendly and technically knowledgeable host we've found so far.
Implementation
The CAB supplies the simple functionality of actually constructing and configuring a cache, the ability to add an object to the cache, remove an object from the cache, retrieve an object from the cache, and expire a cache. So, to get started, the project from the previous article will be used to as a starting point. Open up the project in Visual Studio add a reference to the Enterprise Library Caching dll file.
[Click to see full-size]
Don’t forget to add a using statement for the CAB:
using Microsoft.Practices.EnterpriseLibrary.Caching;
using Microsoft.Practices.EnterpriseLibrary.Caching.Expirations;
Next, open the web.config for the project in the Enterprise Library Configuration application.
[Click to see full-size]
We chose Server Intellect for its dedicated servers, for our web hosting. They have managed to handle virtually everything for us, from start to finish. And their customer service is stellar.
Right click the file in the left pane and select New – Caching Application block. Then right click the Cache Managers and select New – Cache Manager and give it a name of Product Cache.
[Click to see full-size]
Now go back to the Visual Studio project and open the Defualt.aspx page and add two separate labels. These labels will be used to display the contents of the cache when the application is tested. So now some code needs to be written to demonstrate caching. Open the code behind to the Default.aspx page and add the following class definitions with the following code:
{
string productID;
string productName;
string productNumber;
string lastUpdated;
public Product()
{
}
public Product(string id, string name, string number, string modDate)
{
productID = id;
productName = name;
productNumber = number;
lastUpdated = modDate;
}
public string GetProductDetails()
{
return (" " + productID + " " + productName + " " + productNumber + " " +
lastUpdated);
}
public string GetProductID()
{
return productID;
}
}
class RefreshCache : ICacheItemRefreshAction
{
public void Refresh(string keyToRemove, object expireTime, CacheItemRemovedReason
removeReason)
{
CacheFactory.GetCacheManager().Add(keyToRemove, expireTime);
string productID = "1";
string productName = "Widget";
string productNumber = "123";
string lastUpdated = DateTime.Now.ToLongTimeString();
Product product = new Product(productID, productName, productNumber,
lastUpdated);
CacheFactory.GetCacheManager("ProductCache").Add(product.GetProductID(), product,
CacheItemPriority.Normal, new RefreshCache(), new
SlidingTime(TimeSpan.FromSeconds(5)));
}
}
We migrated our web sites to Server Intellect over one weekend and the setup was so smooth that we were up and running right away. They assisted us with everything we needed to do for all of our applications. With Server Intellect's help, we were able to avoid any headaches!
Finally add code under the Page_Load event to actually use the cache.
{
CacheManager productCache = CacheFactory.GetCacheManager("ProductCache");
string productID = "1";
string productName = "Widget";
string productNumber = "123";
string lastUpdated = DateTime.Now.ToLongTimeString();
Product productNew = (Product)productCache.GetData("1");
if (productNew == null)
{
this.Label2.Text = "Could not retrieve";
Product product = new Product(productID, productName, productNumber,lastUpdated);
productCache.Add(product.GetProductID(), product, CacheItemPriority.Normal,
new RefreshCache(), new SlidingTime(TimeSpan.FromSeconds(10)));
}
else
{
this.Label1.Text = productNew.GetProductDetails();
}
}
catch (System.Exception ex)
{
this.Label2.Text = ex.StackTrace;
}
In the above code, the CacheFactory.GetCacheManager method gets the configuration for the cache from the web.config. The GetData method is what retrieves the data from the cache where as the Add method handles adding the object into the cache. The cache refresh is set to 10 seconds so when the cache actually refreshes it will have a different last updated date while the other information remains the same.
Now run the application to see the results. Remember to wait 10 seconds to refresh the page so the change in the cache can be seen.
We moved our web sites to Server Intellect and have found them to be incredibly professional. Their setup is very easy and we were up and running in no time.
[Click to see full-size]
[Click to see full-size]
Using this example, the Enterprise Library Caching Application Block gives another option when there is a need to use data on a regular basis instead of accessing the database each time it is needed.
What have we learned?
Need help with Windows Dedicated Hosting? Try Server Intellect. I'm a happy customer!
How to add a reference to the Enterprise Library Caching Application Block.
How to configure the CAB in the Enterprise Library Configuration application.
How to implement the CAB in code by adding and refreshing objects in the cache.
Attachments
|