ASP.NET is basically a stateless environment, as was ASP classic. Every time a user requests a page, ASP.NET renders the output without any knowledge of previous requests. To enable you to track the state of your applications, ASP.NET provides several mechanisms at various levels. For example, the ViewState object allows a single page to track its own state, but ViewState doesn't help as users move from page to page. For more information on the ViewState object, see "ViewState of the Mind." If you've worked with ASP classic for any length of time, you probably have encountered the Session object. For more information on ASP.NET, see " HTML5 for the ASP.NET Developer " and " ASP.NET MVC Tutorial: Handling Errors and Exceptions. " Among other things, this object provides a property bag in which you can store a dictionary of name-value pairs, using code like this:
' To store a value: Session("VariableName") = Value ' To retrieve a value: Value = Session("VariableName")
In addition, ASP classic's Session object provides the SessionID and TimeOut properties as well as an Abandon method.
In ASP.NET, you can write code that takes advantage of the Session object as you might in ASP classic - from within your VB .NET or C# code. You should note, however, that the Session object you're using is now an instance of the HttpSessionState class, and this class provides you with many properties and methods new in ASP.NET. This class provides access to the same type of session-state values as you used in ASP classic, and it also provides properties that allow you to manage session-level settings. HttpSessionState also provides some useful lifetime management methods. I'll provide an overview of the HttpSessionState class, including its properties and methods. (I won't attempt to dig into the many concepts and details involved in managing session state or the new out-of-process options ASP.NET provides because these topics require an article of their own.)
Although you can write code that works with Session values in ASP.NET as you might have written it in ASP classic, you're really working with a property of the Page object now. That is, when you write:
Session("VariableName") = Value
you're actually writing:
Page.Session("VariableName") = Value.
The current page's Session property is an HttpSessionState object that contains the current Session object ASP.NET provides. ASP.NET provides the Page.Session property as a convenience for you. This isn't critical to your use of the Session object - you simply use the Session object as you might in ASP classic - but it's nice to know where it's coming from.
Simple HttpSessionState Properties
The HttpSessionState class provides many simple properties you can use to retrieve information about the current session. Although most of the properties are read-only, a few also allow you to set values. Figure 1 shows Default.aspx from this article's downloadable sample project (see the Download box at the beginning of the article for details). This page allows you to investigate most of the HttpSessionState class' simple properties.
Figure 1. This sample form allows you to investigate the simple properties of the HttpSessionState class.
The HttpSessionState class provides several informational properties. IsCookieless returns True if the SessionID value is embedded in the URL, and it returns False otherwise. Typically, you control this behavior by setting the appropriate value in your site's web.config file. If this value is True, your session information is available whether or not the user has enabled cookies.
IsNewSession returns True if the session was created with the current request. This value should appear as True on the sample page the first time you display it. If you click on Submit, forcing a post-back to the current page, the value should change to False (because the session no longer is new).
IsReadOnly gets a value indicating whether the current session is read-only. (You can use read-only session state for a page by setting the EnableSessionState attribute in the Page directive to the value ReadOnly.)
Although the LCID property is provided only for backward compatibility (the property ends up calling the LCID method of the CultureInfo class under the covers; the Session state doesn't store this value), it's interesting and is included on the sample page. This property allows you to get or set the local ID of the current session.
Mode gets the current mode of the session. It can be one of the SessionState.SessionStateMode enumerated values: InProc, Off, SQLServer, or StateServer. Normally, you set this information in the site's web.config file.
The SessionID property retrieves the current session ID. The session ID allows ASP.NET to look up values in its session variables dictionary. The session ID normally passes between client and server in a cookie named ASP.NET_SessionID. If the IsCookieless property is True, ASP.NET passes this value as part of each request, encoded in the URL.
Finally, the TimeOut property sets or retrieves the session timeout (in minutes). The default value is 20 minutes, but you can change the timeout interval by setting this property.
But what about properties you might have used previously that aren't included here? ASP.NET provides certain properties for backward compatibility. CodePage returns the code-page identifier for the current session. ASP.NET doesn't supply code-page information in its session state. Instead, check out the Response object's ContentEncoding.CodePage property. (As with the Session object, the Response object of a page is actually an instance of a .NET class: the HttpResponse class. But that's another column, for another day.)
Contents retrieves a reference to the current session-state object. This property isn't necessary in ASP.NET but is provided for backward compatibility.
The StaticObjects property retrieves a collection of session variables declared statically within the Global.asax file. Generally, you won't use these objects; instead, you will use the Session object's collection of dynamic objects.
Work With Session Variables
In addition to the simple properties you've seen already, the HttpSessionState class provides a range of properties and methods that let you add, retrieve, and modify session-state values. Figure 2 shows the sample page, SessionVariables.aspx, you can use to try out these members.
Figure 2. Use the SessionVariables.aspx page to test the members of the HttpSessionState class that manage session variables.
The sample page's Load event handler runs this code:
If Not Page.IsPostBack Then Session("LoadTime") = Now Session("UserName") = "Mary" Session("ItemsSold") = 13 End If
Each statement loads a value into a session-state variable:
Session("LoadTime") = Now
The value on the right-hand side of the assignment, the value being stored, generally can be most any object type. There are restrictions when using out-of-process session management, but session variables generally are flexible.
For backward compatibility, though this isn't the recommended technique, you also can refer to the current session state, using the Contents property of the Session object:
Session.Contents("LoadTime") = Now
When you refer to a session variable from VB .NET, you're actually using the class's Item property, and you can reference the property explicitly if you like. In C#, Item is the default indexer, and you'll never refer to it explicitly:
' In VB.NET only: Session.Item("LoadTime") = Now
The values you retrieve from session variables are all of type System.Object, so you'll need to cast them to specific types explicitly if you're using C# or if you've turned on Option Strict in VB .NET. If you attempt to retrieve a value that doesn't exist, the object will be Nothing (null, in C#). The sample page treats all the values as strings, for display purposes, and handles invalid session variable names. The lstKeys_SelectedIndexChanged event handler uses this code to display the value of the selected session variable (if it exists):
Dim strItem As String Dim objValue As Object strItem = lstKeys.SelectedItem.ToString objValue = Session(strItem) If objValue Is Nothing Then txtName.Text = String.Empty txtValue.Text = String.Empty Else txtName.Text = strItem txtValue.Text = objValue.ToString End If
The HttpSessionState class provides two properties that allow you to work with session variables: Count, which returns the number of items in the collection of session variables; and Keys, which returns a KeysCollection object (a collection of strings) containing a list of all the current key names stored as session values.
The sample page provides the DisplaySessionVariables procedure, which includes this code that displays the list of current keys in the lstKeys list box:
lblCount.Text = Session.Count.ToString lstKeys.DataSource = Session.Keys lstKeys.DataBind()
The HttpSessionState class also provides a range of methods that allow you to manipulate the values stored in session state. The Add method allows you to add a single value to the collection of session variables. This method is somewhat superfluous because you can add items to the collection simply by assigning the appropriate value. These two statements are equivalent, if the Age session variable doesn't exist already:
Session("Age") = 46 Session.Add("Age", 46)
Next, CopyTo copies the Session object's Keys property to a one-dimensional array, starting at the specified index. The documentation states that this method copies the values, but testing shows that it instead copies the keys. The sample page uses this code to display a comma-delimited list of the keys:
Private Sub HandleKeysAsArray() If Session.Count > 0 Then Dim astrKeys(Session.Count - 1) As String Session.CopyTo(astrKeys, 0) lblKeysAsArray.Text = String.Join(", ", astrKeys) End If End Sub
The Remove method deletes a session value, given a string key name. For example, you might write code such as:
The sample page uses this code in the btnRemove_Click procedure:
If lstKeys.SelectedIndex >= 0 Then Session.Remove(lstKeys.SelectedItem.ToString) End If
Clear clears the session variables. RemoveAll duplicates the Clear method's behavior. After calling this method, the collection of session variables contains no values and the Count property returns 0.
RemoveAt removes a session value, given its index within the collection of values. This method isn't as useful as the Remove method, but it does allow you to remove items by index. The sample page uses this code to remove items by index:
If lstKeys.SelectedIndex >= 0 Then Session.RemoveAt(lstKeys.SelectedIndex) End If
Finally, the HttpSessionState class provides the Abandon method, which allows you to abandon a session and its session variables programmatically. Of course, if the number of minutes specified in the TimeOut property passes between requests, the session ends automatically. You can force an immediate abandonment of the session by calling this method. The Abandon button on the sample page calls this method and then refreshes the display of session variables. (You might need to refresh the page twice in order to verify that the session variables have indeed been abandoned.)
After working through the examples in this article, you'll also want to investigate the events the HttpApplication object provides. (Normally, you place the event handlers for these events in the global.asmx file.) In addition, you'll want to look into different ways of managing state (in-process vs. out of process). Managing session state is much simpler in ASP.NET than it was in ASP classic, but it still requires careful study and investigation.
The project referenced in this article is available for download.
Ken Getz is a senior consultant with MCW Technologies and splits his time between programming, writing, and training. He specializes in tools and applications written in Visual Studio .NET and Visual Basic, and he is co-author of Access 2002 Developer's Handbook Desktop Edition as well as the training materials for AppDev's ASP.NET, Access 97 and 2000, Visual Basic 5.0, and Visual Basic 6.0 classes. He speaks frequently at technical conferences and is a contributing writer for asp.netPRO. E-mail Ken at mailto:[email protected].