Manage Session Variables with Intellisense
This article demonstrates how to apply session variables in your .NET web applications.
- Jing Ding, Senior Systems Consultant for The Ohio State University Medical Center

August 6, 2008
Iron Speed Designer V5.X
Introduction
Session variables are among the most frequently used methods to pass information among pages and/or postbacks. However, there are inconveniences to using session variables, including the following:
  • Session variables are accessed by their string names. Since misspelled names are not detected at compile time, this can lead to runtime errors that are difficult to debug.


  • Renaming session variables is an error-prone process.


  • The value of a session variable is not strongly typed. A value of any type can be stored in a session variable, but the compiler does not enforce type check. Once a variable is retrieved from a session, it must be explicitly cast to be useful. A missed cast session variable is a frequent error at compile time. On the other hand, the compiler allows a session variable to be cast to any type. Any miscast session variable can cause a runtime error.
In the example below, I will demonstrate how to make session variables strongly typed by applying an intellisense solution to overcome these inconveniences.
Solution
This intellisense solution was inspired by a Code Project article, Wrap Those Session Variables! The basic idea is to encapsulate session variables into static properties of a specific class by hiding the string names, and then providing strong types and using intellisense.
Implementation
Below is a sample implementation of the class. It is essentially an empty place holder, except for a private static property currentSession as a shortcut for HttpContext.Current.Session. It also provides a safety check in case the session is not available within the context. The class file can be put under an application’s App_Code folder, or Iron Speed Designer’s project templates’ App_Code folder.

C#: MyAppSession.cs

using System;
using System.Web;
using System.Web.SessionState;
 
namespace ProjectNamespace.UI {
    /// <summary>
    /// MyAppSession provides access to session variables as static properties.
    /// </summary>
    public class MyAppSession {
        /// <summary>
        /// Private shortcut to HttpContext.Current.Session. Check its availability.
        /// </summary>
        private static HttpSessionState currentSession {
            get {
                if (HttpContext.Current.Session == null)
                     throw new Exception("Session is not available in the current context.");
                else
                     return HttpContext.Current.Session;
            }
        }
    }
}

Visual Basic .NET: MyAppSession.vb

Imports System
Imports System.Web
Imports System.Web.SessionState
 
Namespace ProjectNamespace.UI
    ''' <summary>
    ''' MyAppSession provides access to session variables as static properties.
    ''' </summary>
    Public Class MyAppSession
        ''' <summary>
        ''' Private shortcut to HttpContext.Current.Session. Check its availability.
        ''' </summary>
        Private Shared ReadOnly Property currentSession() As HttpSessionState
            Get
                If HttpContext.Current.Session = Nothing Then
                    Throw New Exception("Session is not available in the current context.")
                Else
                    Return HttpContext.Current.Session
                End If
            End Get
        End Property
    End Class
End Namespace
To encapsulate a session variable, add a private static (Shared) string field and a public static (Shared) typed property. The string field serves as the session variable’s key, and the property is the access point of the variable. Below are some sample session variables of different types.

Example I: A bool variable.

C#:

private static string myBoolVarKey = "myBoolVarKey";
public static bool MyBoolVar {
    get { return currentSession[myBoolVarKey] != null; }
    set {
        if (value)
            currentSession[myBoolVarKey] = value;
        else
            currentSession.Remove(myBoolVarKey);
    }
}

Visual Basic .NET:

Private Shared myBoolVarKey As String = "myBoolVarKey"
Public Shared Property MyBoolVar() As Boolean
    Get
        Return currentSession(myBoolVarKey) <> Nothing
    End Get
    Set
        If value Then
            currentSession(myBoolVarKey) = value
        Else
            currentSession.Remove(myBoolVarKey)
        End If
    End Set
End Property
Example II: A value type (int) variable without any default value. Please note that the type is nullable.

C#:

private static string myIntNoDefKey = "key2";
public static int? MyIntNoDefVar {
    get { return (int?)currentSession[myIntNoDefKey]; }
    set {
    if (value != null)
            currentSession[myIntNoDefKey] = value;
    else
            currentSession.Remove(myIntNoDefKey);
    }
}

Visual Basic .NET:

Private Shared myIntNoDefKey As String = "key2" Public Shared Property MyIntNoDefVar() As System.Nullable(Of Integer)
    Get
        Return DirectCast(currentSession(myIntNoDefKey), System.Nullable(Of Integer))
    End Get
    Set
        If value <> Nothing Then
            currentSession(myIntNoDefKey) = value
        Else
            currentSession.Remove(myIntNoDefKey)
        End If
    End Set
End Property

Example III: A value type (int) variable with a default value.

C#:

private static string myIntKey = "key3";
public static int MyIntVar {
    get {
        if (currentSession[myIntKey] == null)
            return 0;
        else
            return (int)currentSession[myIntKey];
    }
    set {
        currentSession[myIntKey] = value;
    }
}

Visual Basic .NET:

Private Shared myIntKey As String = "key3"
Public Shared Property MyIntVar() As Integer
    Get
        If currentSession(myIntKey) = Nothing Then
            Return 0
        Else
            Return DirectCast(currentSession(myIntKey), Integer)
        End If
    End Get
    Set
        currentSession(myIntKey) = value
    End Set
End Property

Example IV: A reference type (string) session variable.

C#:

private static string myStrKey = "key4";
public static string MyStrVar {
    get { return currentSession[myStrKey] as string; }
    set {
        if (value != null)
            currentSession[myStrKey] = value;
        else
            currentSession.Remove(myStrKey);
    }
}

Visual Basic .NET:

Private Shared myStrKey As String = "key4"
Public Shared Property MyStrVar() As String
    Get
        Return TryCast(currentSession(myStrKey), String)
    End Get
    Set
        If value <> Nothing Then
            currentSession(myStrKey) = value
        Else
            currentSession.Remove(myStrKey)
        End If
    End Set
End Property

Example V: A read-only, lazy-initialized session variable.

C#:

private static string shoppingCartKey = "shoppingCartKey";
public static ArrayList ShoppingCart {
    get {
        if (currentSession[shoppingCartKey] == null)
            currentSession[shoppingCartKey] = new ArrayList();
        return currentSession[shoppingCartKey] as ArrayList;
    }
}

Visual Basic .NET:

Private Shared shoppingCartKey As String = "shoppingCartKey"
Public Shared ReadOnly Property ShoppingCart() As ArrayList
    Get
        If currentSession(shoppingCartKey) = Nothing Then
            currentSession(shoppingCartKey) = New ArrayList()
        End If
        Return TryCast(currentSession(shoppingCartKey), ArrayList)
    End Get
End Property

Conclusion
Using intellisense and encapsulating session variables into static properties can make programming easier:
  • There is no need to remember or even type session variable names; intellisense will do it for you.
  • Renaming session variables is no longer painful. Refactoring makes it a piece of cake.
  • Variables are strongly typed. The variable is type-checked at compile-time, thus avoiding type mismatch exceptions at runtime.
About the Author
Jing Ding has a PhD in Computer Engineering, Bioinformatics and Computational Biology, and an M.S. in Toxicology from Iowa State University. He received his B.S. in biophysics from Fundan University in Shanghai, China. He is a self-taught programmer who "played" with assembly, C and C++ in the 1990s. He took a break from programming from 1997 to 2000. When he picked it up again in 2001, he worked with Java. Jing began working with C# and .NET in 2006.


  Privacy Statement