Please navigate to the bottom of the page for Table of Contents

Thursday, May 26, 2011

Manage state across entire application in ASP.NET

How can you manage application state across the entire application? In other words, How can you share data across all pages and all users for the entire web application? Another way: How can you enable sharing of global information across multiple sessions and requests within an ASP.NET application?

All these questions are intended to test your knowledge about the HttpApplicationState and Cache classes. Let's look into these 2 classes in more detail. An ASP.NET application is the sum of all files, pages, handlers, modules, and code within the scope of a virtual directory and its subdirectories on a single Web server.

HttpApplicationState Class

HttpApplicationState class enables sharing of global information across multiple sessions and requests within an ASP.NET application. This allows you to store data which is accessible from any page. In other words, Application state is a data repository that is available to all classes in an ASP.NET application.

A single instance of an HttpApplicationState class is created the first time a client requests any URL resource from within a particular ASP.NET application virtual directory. A separate single instance is created for each ASP.NET application on a Web server. A reference to each instance is then exposed via the intrinsic Application object. Application state is not shared across either a Web farm (in which an application is hosted across multiple servers) or a Web garden (in which an application is hosted across multiple processes on the same computer).

Application state is stored in memory on the server and is faster than storing and retrieving information in a database. Unlike session state, which is specific to a single user session, application state applies to all users and sessions. Therefore, application state is a useful place to store small amounts of often-used data that does not change from one user to another. If the application is restarted, application state data is lost.

Application state stores data as Object data types. Therefore, you must convert the data back to the appropriate type when retrieving it.

How to save a value in application state
Application["Message"] = "Welcome!";

How to write a value to application state when the application starts

In Application_Start handler of your application's Global.asax file, set the value of the application state variable as shown below:

Application["Message"] = "Welcome!";
Application["PageRequestCount"] = 0;
Application state variables can be accessed by multiple threads at the same time. Therefore, to prevent invalid data, you must lock application state for writing by only one thread before setting values.
How to write a Value to Application State with Locking

In the code where you set the application variable, call the HttpApplicationState ..::.Lock method, set the application state value, and then call the HttpApplicationState ..::.UnLock method to unlock the application state, freeing it for other write requests.

Application.Lock();
Application["PageRequestCount"] = ((int)Application["PageRequestCount"])+1;
Application.UnLock();


How to Read Values from Application State

Application state stores data typed as Object. Therefore, even though you do not have to serialize the data when storing it in application state, you must cast the data to the appropriate type when retrieving it. Although you can cast a null ( Nothing in Visual Basic) object, if you attempt to use a non-existent application-state entry in some other way (for example, to examine its type), a NullReferenceException exception is thrown.

if (Application["AppStartTime"] != null)
{
DateTime myAppStartTime = (DateTime)Application["AppStartTime"];
}

 


Cache Class

Now let's review the Cache class. Cache class implements the cache for a Web application. This class cannot be inherited (sealed). One instance of this class is created per application domain, and it remains valid as long as the application domain remains active. Information about an instance of this class is available through the Cache property of the HttpContext object or the Cache property of the Page object.

You can access items in the application cache using the Cache object. You can add an item to the application cache using the Cache object's Insert method. The method adds an item to the cache and has several overloads that enable you to add the item with different options for setting dependencies, expiration, and removal notification. If you use the Insert method to add an item to the cache and an item with the same name already exists, the existing item in the cache is replaced.


You can also add items to the cache using the Add method. This method enables you to set all the same options as the Insert method; however, Add method returns the object you added to the cache. Additionally, if you use the Add method and an item with the same name already exists in the cache, the method will not replace the item and will not raise an exception.


Shown below are some examples of adding data to the Cache class.

Cache["CacheItem1"] = "Cached Item 1";
Cache.Insert("CacheItem2", "Cached Item 2");

The following code example adds an item named CacheItem3 that is dependent on another item in the cache named CacheItem2:

string[] dependencies = { "CacheItem2" };
Cache.Insert("CacheItem3", "Cached Item 3",
new System.Web.Caching.CacheDependency(null, dependencies));


The following code example adds an item to the cache with an absolute expiration of one minute:

Cache.Insert("CacheItem6", "Cached Item 6",
null, DateTime.Now.AddMinutes(1d),
System.Web.Caching.Cache.NoSlidingExpiration);

The following code example adds an item to the cache with a sliding expiration time of 10 minutes:

Cache.Insert("CacheItem7", "Cached Item 7",
null, System.Web.Caching.Cache.NoAbsoluteExpiration,
new TimeSpan(0, 10, 0));

The following code example adds an item to the cache with a priority value of High:

Cache.Insert("CacheItem8", "Cached Item 8",
null, System.Web.Caching.Cache.NoAbsoluteExpiration,
System.Web.Caching.Cache.NoSlidingExpiration,
System.Web.Caching.CacheItemPriority.High, null);

The following code example adds an item to the cache named CacheItem9 and sets the value of the variable CachedItem9 to be the item that was added.

string CachedItem9 = (string)Cache.Add("CacheItem9",
"Cached Item 9", null,
System.Web.Caching.Cache.NoAbsoluteExpiration,
System.Web.Caching.Cache.NoSlidingExpiration,
System.Web.Caching.CacheItemPriority.Default,
null);


These examples should give you enough understanding about the ApplicationState and Cache classes. MSDN documentation is very good and explains these concepts in far more details than I have covered here.

No comments:

Post a Comment