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.