WEBSITE

Building ASP.NET Web Applications : Understanding State Management

10/10/2010 3:21:12 PM
State is managed via some special objects: Application, Cache, Context, Session, and ViewState. All of them work with the Object type, and you use them like dictionaries, so they accept key/value pairs. The next subsections give you explanation and examples.

The Application State

One of the most common situations with websites is that you have many people using the website concurrently. If you want to hold shared information across all the application instances, you use the Application state. The following is an example:

Application("SharedKey") = "Shared value"


Dim sharedString As String = CStr(Application("SharedKey"))

Notice the key/value semantics and how you need to perform an explicit conversion from Object to String. You will not use Application often because each application instance runs on a separate thread that could modify the information and therefore could corrupt the values, too.

The Cache State

The ASP.NET Cache has the same scope of Application, meaning that both can be accessed by all page requests. The primary difference is that Cache enables holding information in memory, which avoids the need of re-creating and retrieving objects. This is good if you want to maintain updatable objects but could cause overhead (always considering that the bigger the amount of data to transfer is, the lower is the performance) because it requires memory, so it should be used when actually needed or when you ensure that performance is acceptable. The following is an example of storing and retrieving information with Cache:

Cache("MyUpdatableDataKey") = "My updatable data"
Dim myUpdatableData As String = CStr(Cache("MyUpdatableDataKey"))

There is also an alternative way for adding objects to the cache, which is the Cache.Add method that provides the ability of setting advanced settings for the object, as demonstrated in this code:

Protected Sub Page_Load(ByVal sender As Object,
ByVal e As System.EventArgs) _
Handles Me.Load

Dim callBack As New CacheItemRemovedCallback( _
AddressOf Cache_ItemRemoved)

'Sets the key, adds the data, sets the CacheDependency,
'sets the expiration mode, expiration time, priority
'and delegate to invoke when the item is removed
Cache.Add("MyUpdatableDataKey", "My updatable data", Nothing,
Cache.NoAbsoluteExpiration, New TimeSpan(0, 0, 45),
CacheItemPriority.High, callBack)

'Removes the item
Cache.Remove("MyUpdatableDataKey")
End Sub

Private Sub Cache_ItemRemoved(ByVal key As String,
ByVal item As Object,
ByVal reason As CacheItemRemovedReason)
'The item has been removed
End Sub

The most interesting settings are the expiration mode and the priority. The first one can be Cache.NoAbsoluteExpiration (like in the preceding code), which means that the data will always be available during the page lifetime, whereas Cache.SlidingExpiration means that the data will be removed after it is not accessed for the specified amount of time. Priority is also important in case you have lots of objects in memory and ASP.NET is about to encounter out-of-memory problems. At this point ASP.NET begins evicting items according to its priority. (An object with lower priority is evicted before another one with high priority.)

The Context State

You use the Context state when you want to hold state only for the lifetime of a single request. This is useful when you need to have information in memory for a long period of time, and you do need to ensure that keeping such information does not affect scalability. This is an example:

Context.Items("MyStringKey") = "My string value"
Dim contextString As String = CStr(Context.Items("MyStringKey"))

The context information is accessed at the page level and will not be available again on the next request.

Using Cookies for Saving Information

Cookies are pieces of information that user’s browser can hold and that can have a max size of 4 Kbytes. Each time the browser opens your web application, it recalls all cookies provided by the website. The following are examples of writing and reading cookies:

'Write a cookie
Dim aCookie As New HttpCookie("MyCookie")
aCookie.Value = "Information to store"
aCookie.Expires = New DateTime(10, 10, 2010)
Response.Cookies.Add(aCookie)

'Read a cookie
Dim getCookie As HttpCookie = Request.Cookies("MyCookie")
Dim cookieVale As String = getCookie.Value

Notice that the Expires property of type Date is required to specify that the cookie information will no longer be valid after that date, whereas the Value property is of type String so that you can store information without conversions.

The Session State

ASP.NET provides the ability of holding per-user information via the Session object. When a user opens the website, ASP.NET creates a cookie with a session identifier and then manages the session for that user based on the ID. The only issue is that you have no way for understanding when the user leaves the website, so a Session state expires after 20 minutes as a default. The following is an example:

Session("MyKey") = "User level information"
Dim userInfo As String = CStr(Session("MyKey"))

The ViewState State

To provide support for the work that a page needs to do in its lifetime, ASP.NET provides a mechanism known as ViewState. Basically it provides the infrastructure that serializes values for each control in the page. For example, when a page is rendered, a control has a particular value. When this value changes, and such change raises an event, ASP.NET makes a comparison between the ViewState and form variables so that it can update the control value. (The TextBox control with its TextChanged event is the most common examples.) Such a mechanism is available behind the scenes, but you can also use the ViewState by yourself. The following is an example that makes an object available at page level:

ViewState("MyPageDataKey") = "Page-level information"
Dim myPageData As String = CStr(ViewState("MyPageDataKey"))

Making this information at the page level means making it available also when the page is posted back, but that decreases performance because the size of bytes to transfer is bigger. Excluding the user controls necessary to your Web form, you should use ViewState for your needs with care.

Other  
 
Most View
Sending And Sharing Large Files Over The Web (Part 1)
The Truth About Free Trials (Part 1)
Nokia Lumia 620 Review - Basic Smartphone With Good Performance And Stunning Design (Part 1)
HTC Butterfly Android Smartphone
Cool Stuffs Of The Month – March 2013 (Part 3) : Acer Iconia W510, Simmtronics SIMM X720, PANASONIC AE 8000
Big Zoom Compacts: Smaller And Lighter Than A Typical Telephoto Lens (Part 2)
Sharepoint 2013 : PowerShell Basics (part 2)
Installing Configuration Manager 2007 : Site Installation (part 1) - Installing ConfigMgr
Sharepoint 2013 : Creating an eDiscovery query
Asus Taichi - The Incredible Fusion Of Notebook And Tablet
Top 10
Sharepoint 2013 : Farm Management - Disable a Timer Job,Start a Timer Job, Set the Schedule for a Timer Job
Sharepoint 2013 : Farm Management - Display Available Timer Jobs on the Farm, Get a Specific Timer Job, Enable a Timer Job
Sharepoint 2013 : Farm Management - Review Workflow Configuration Settings,Modify Workflow Configuration Settings
Sharepoint 2013 : Farm Management - Review SharePoint Designer Settings, Configure SharePoint Designer Settings
Sharepoint 2013 : Farm Management - Remove a Managed Path, Merge Log Files, End the Current Log File
SQL Server 2012 : Policy Based Management - Evaluating Policies
SQL Server 2012 : Defining Policies (part 3) - Creating Policies
SQL Server 2012 : Defining Policies (part 2) - Conditions
SQL Server 2012 : Defining Policies (part 1) - Management Facets
Microsoft Exchange Server 2010 : Configuring Anti-Spam and Message Filtering Options (part 4) - Preventing Internal Servers from Being Filtered