Articles‎ > ‎

[ Article ] How to configure and use Enterprise Library 5.0 caching block


Caching in applications is an important factor for performance. The Enterprise Library Caching Application Block provides a flexible and extensible caching framework with a set of APIs that can be used at any layer of an application. Enterprise Library supports both an in-memory cache and optionally a backing store that can be either a database store or an isolated storage. Implementing caching using the Caching Application Block improves the performance of applications and also reduces development time and cost. Enterprise Library application block provides all kinds of functions like adding, removing, and managing the expiration of cache. Enterprise Library Caching Application Block is very generic and can be used in different applications without any change in code. Enterprise Library Caching Application Block provides a ready to use caching framework. We can also Configure expiration and scavenging policies of the application block. Implementing Caching can help to overcome some of these challenges
  • Performance. Caching improves application performance by storing relevant data as close as possible to the data consumer. This avoids repetitive data creation, processing, and transportation.
  • Scalability. Storing information in a cache helps save resources and increases scalability as the demands on the application increase.
  • Availability. By storing data in a local cache, the application may be able to survive system failures such as network latency, Web service problems, and hardware failures.
The Caching Application Block is suitable if your application encounter any of the following situations:
  • You must repeatedly access static data or data that rarely changes.
  • Data access is expensive in terms of creation, access, or transportation.
  • Data must always be available, even when the source, such as a server, is not available.
In this article, we can see how to configure and use the Caching Application Block of Enterprise Library 5.0 in windows application.

How to configure Enterprise Library 5.0 caching block with an in-memory cache

Open Enterprise Library 5.0 configuration editor. From the blocks menu tab select “Add Caching Settings”. It will provide you with a block to configure. For using it as in-memory cache, we don’t have to configure much; the default values are good enough. The things which we can configure are

  • Expiration polling frequency in seconds - It is time in seconds between each cycle that removes expired cached items. If we are configuring an expiration policy for the item that we are storing in the cache, then it will be reviewed in every cycle and if the items expiration time has reached then it will be removed from the cache.
  • Maximum elements in cache before scavenging - This is the maximum number of items allowed in the cache. If we try to add an item after the maximum number have reached, then a scavenging will happen which removes old items from cache.
  • Number to remove when scavenging - This is the number of items removed at a time from the cache when the maximum number of allowed items has reached in the cache.

Now save the configuration into a config file and copy the configuration to your application configuration file.

Now add reference to the following in to your project.

Microsoft.Practices.EnterpriseLibrary.Caching;

Microsoft.Practices.EnterpriseLibrary.Common;

Now in your code, do as what follows.

 

/*in your code, add reference to the following namespace */

using Microsoft.Practices.EnterpriseLibrary.Caching;

using Microsoft.Practices.EnterpriseLibrary.Caching.Expirations;

/*below will be your code block*/

{

/*create an instance of cache manager. If you left the GetCacheManager() without providing any parameter then the default configuration will be used. You can specify the cacheManagers name to use as a parameter to GetCacheManager() so that instead of default it uses a different cache manager*/

ICacheManager cacheManager = CacheFactory.GetCacheManager();

cacheManager.Add("testkey1","testvalue",CacheItemPriority.High,null);

cacheManager.Add("testkey2", "Some Text");

/*the below object will never expire from cache*/

cacheManager.Add("testkey3", "Some Text3", CacheItemPriority.High, null,new NeverExpired());

/*below object will expire on the date specified*/

cacheManager.Add("testkey4", "Some Text4", CacheItemPriority.Normal,null, new AbsoluteTime(new DateTime(2099, 12, 31)));

/* Below item will expire after ten seconds*/

cacheManager.Add("testkey5", "Some Text5",CacheItemPriority.Low, null,new SlidingTime(new TimeSpan(0, 0, 10)));

object o1 = cacheManager.GetData("testkey1");

object o2 = cacheManager.GetData("testkey2");

object o3 = cacheManager.GetData("testkey3");

object o4 = cacheManager.GetData("testkey4");

object o5 = cacheManager.GetData("testkey5");

string data = (string)cacheManager.GetData("testkey1");

}

Hurdle

You may get an exception like "Mixed mode assembly is built against version 'v2.0.50727' of the runtime and cannot be loaded in the 4.0 runtime without additional configuration information." . refer to this post to fix this


How to configure Enterprise Library 5.0 caching with Isolated Storage backing store

When using isolated storage, applications save data to a unique data compartment that is associated with some aspect of the code's identity, such as its publisher or signature. The data compartment is an abstraction, not a specific storage location; it consists of one or more isolated storage files, called stores, which contain the actual directory locations where data is stored.

To create an isolated backing store, click on the backing store (+) button and select “Isolated Storage Cache Store” as shown in the image. After this only thing that you need to configure is the “Partition Name” which is the section or partition of the Isolated Storage area for the cached data. This allows different users to cache data on the same machine safely and prevents different users accessing the same cache data. This can be any unique name. Normally this is your application name suffixed by a cache (ApplicationNameCache). 

Adding Isolated Storage backing store

Now in the cache manager block, from the Backing store drop-down select the newly added backing store which will be listed in the drop-down as "Isolated Storage Cache Store"

Caching Block After configuration


Now save the config file and copy the content to your application configuration file. Now there wont be any coding change from the code which I have shown above. You can try the same code. The difference here is only where the cached data is stored. The advantage of using a persistent data store is that the cache will be available until it expires and it will be safe in the persistent store. If you relaunch the application after stopping and try to access the cache, it will be available!

Hurdles

 You may get an exception like "Mixed mode assembly is built against version 'v2.0.50727' of the runtime and cannot be loaded in the 4.0 runtime without additional configuration information." . refer to this post to fix this


 How to configure Enterprise Library 5.0 caching with database backing store

Now let’s see how to cache data into database.
From the backing store section in your configuration editor, add Data cache store. After this  you need to configure the “Partition Name” which is to uniquely identify the partition of the database for the cached data. This allows different users to cache data on the same database safely and prevents different users accessing the same cache data. This can be any unique name. Normally this is your application name suffixed by a cache (ApplicationNameCache). Now from the database Instance section, configure the Database Provider section and select System.Data.SqlClient. Now configure the Connection String. Change the connection string to have proper database name. Let’s change the database name to Database=Caching;Server=(local)\SQLEXPRESS;Integrated Security=SSPI.

Cache block with database backing store configuration


Now save the configuration to a config file and save it to your application configuration file. If you try to run the application now, you will get one error as “Activation error occurred while trying to get instance of type ICacheManager”. This is because enterprise library expects some stored procedures and some tables in your database. Let’s see how to fix this 

Now to have the database to hold the cache data, we need some tables and stored procedures.  Enterprise library will provide you with one command batch file which you need to run against your database. This batch file will run Sql commands against your database and will create the stored procedures and required tables. You can find this batch file at, “EntLib50Src\Blocks\Caching\Src\Database\Scripts”. This is just a relative path. Actual path may vary based on your installation. You can find two files here; one is CreateCachingDb.cmd which has command which will run one sql script which will create tables and stored procedures to your database. Second is CreateCachingDatabase.sql which will have sql query to create necessary stored procedures and tables. If you can’t find the scripts folder, then you may have to install the “Enterprise Library 5.0 - Source Code.msi” which comes along with Enterprise library 5.0 install. You can find this at “Microsoft Enterprise Library 5.0\src” folder. Now recollect that I have named the database as “Caching” this is because the script which comes along with Enterprise Library 5.0 has one sql query file and in which they have specified database name as “Caching”. If you need another database, then you can edit the sql query file and have your database name instead of the default database name. After doing this, you can run the application and can see it working!. You can try the same code which I have shown above. The difference here is only where the cached data is stored. The advantage of using a persistent data store is that the cache will be available until it expires and it will be safe in the persistent store. If you relaunch the application after stopping and try to access the cache, it will be available!

You can configure other databases as-well provided the stored procedure and tables must be available.  

Hurdles

  1. You may get an exception like "Mixed mode assembly is built against version 'v2.0.50727' of the runtime and cannot be loaded in the 4.0 runtime without additional configuration information." . refer to this post to fix this
  2. The type 'Microsoft.Practices.EnterpriseLibrary.Caching.Database.DataBackingStore, Microsoft.Practices.EnterpriseLibrary.Caching.Database, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' cannot be resolved. Please verify the spelling is correct or that the full type name is provided. Find the solution Microsoft.Practices.EnterpriseLibrary.Caching.Database.DataBackingStore cannot be resolved. Please verify the spelling is correct or that the full type name is provided Or          To fix this: In your project, add reference to Enterprise Library Caching Data Provider.
  3. you may get an exception like  “Activation error occurred while trying to get instance of type ICacheManager”. This is because you missed to run the script which will create the tables and stored procedures. Find the solution here Activation error occurred while trying to get instance of type ICacheManager

Comments