Click here to Skip to main content
16,019,514 members
Articles / Web Development / ASP.NET

Manage ASP.NET Session Variables using the Facade Design Pattern

Rate me:
Please Sign up or sign in to vote.
4.62/5 (54 votes)
6 Nov 2012CPOL7 min read 299.1K   138   57
Reduce bugs in ASP.NET applications by improving access to Session variables

Introduction

Just about every ASP.NET application needs to keep track of data for a user's session. ASP.NET provides the HttpSessionState class to store session-state values. An instance of the HttpSessionState class for each HTTP request is accessible throughout your application using the static HttpContext.Current.Session property. Access to the same instance is made simpler on every Page and UserControl using the Session property of the Page or UserControl.

The HttpSessionState class provides a collection of key/value pairs, where the keys are of type String and the values are of type Object. This means that Session is extremely flexible and you can store just about any type of data in Session.

But (there is always a but) this flexibility does not come without a cost. The cost is the ease with which bugs can be introduced into your application. Many of the bugs that can be introduced will not be found by unit testing, and probably not by any form of structured testing. These bugs often only surface when the application has been deployed to the production environment. When they do surface it is often very difficult, if not impossible, to determine how they occurred and be able to reproduce the bug. This means they are very expensive to fix.

This article presents a strategy to help prevent this type of bug. It uses a Design Pattern called a Facade, in that it wraps the very free interface provided by the HttpSessionState class (that can meet the requirements of any application) with a well designed and controlled interface that is the purpose built for a specific application. If you are not familiar with Design Patterns or the Facade pattern, a quick internet search of "facade design pattern" will provide you with plenty of background. However, you do not have to understand design patterns in order to understand this article.

The example code shown in this article is written in C#, but the concepts are applicable to any .NET language.

What is the Problem?

In this section of the article, I will describe the problems with direct access to the HttpSessionState class, without the facade. I will describe the kinds of bugs that can be introduced.

The following shows the typical code written to access session-state variables.

C#
// Save a session variable
Session["some string"] = anyOldObject;
// Read a session variable
DateTime startDate = (DateTime)Session["StartDate"];

The problems arise from the flexible interface provided by HttpSessionState: the keys are just strings and the values are not strongly typed.

Using String Literals as Keys

If string literals are used as the keys, the string value of the key is not checked by the compiler. It is easy to create new session values by simple typing errors.

C#
Session["received"] = 27;
...
Session["recieved"] = 32;

In the code above, two separate session values have been saved.

Most bugs like this will be identified by unit testing – but not always. It may not always be apparent that the value has not changed as expected.

We can avoid this kind of bug by using constants:

C#
private const string received = "received";
...
Session[received] = 27;
...
Session[received] = 32;

No Type Checking

There is no type checking of the values being stored in session variables. The compiler cannot check correctness of what is being stored.

Consider the following code:

C#
Session["maxValue"] = 27;
...
int maxValue = (int)Session["maxValue"];

Elsewhere the following code is used to update the value:

C#
Session["maxValue"] = 56.7;

If the code to read the "maxValue" session variable into the maxValue int variable is executed again there will be an InvalidCastException thrown.

Most bugs like this will be identified by unit testing – but not always.

Re-using a Key Unintentionally

Even when we define constants on each page for the session keys, it is possible to unintentionally use the same key across pages. Consider the following example:

Code on one page:

C#
private const string edit = "edit";
...
Session[edit] = true;

Code on a second page, displayed after the first page:

C#
private const string edit = "edit";
...
if ((bool)Session[edit])
{
    ...
}

Code on a third, unrelated, page:

C#
private const string edit = "edit";
...
Session[edit] = false;

If the third page is displayed for some reason before the second page is displayed, the value may not be what was expected. The code will probably still run, but the results will be wrong.

Usually this bug will NOT be picked up in testing. It is only when a user does some particular combination of page navigation (or opening a new browser window) that the bug manifests.

At its worst, no one is aware that the bug has manifested, we may just end up modifying data to an unintended value.

Re-using a Key Unintentionally - Again

In the example above, the same data type was stored in the session variable. Because there is no type checking of what gets stored, the problem of incompatible data types can also occur.

Code on one page:

C#
Session["FollowUp"] = "true";

Code on a second page:

C#
Session["FollowUp"] = 1;

Code on a third page:

C#
Session["FollowUp"] = true;

When the bug manifests, there will be an InvalidCastException thrown.

Usually this bug will NOT be picked up in testing. It is only when a user does some particular combination of page navigation (or opening a new browser window) that the bug manifests.

What Can We Do?

The First Quick Fix

The first and most simple thing we can do is make sure we never use string literals for session keys. Always use constants and so avoid simple typing mistakes.

C#
private const string limit = "limit";
...
Session[limit] = 27;
...
Session[limit] = 32;

However, when constants are defined locally (e.g. at page level), we might still re-use the same key unintentionally.

A Better Quick Fix

Rather than define constants on each page, group all session key constants into a single location and provide documentation that will appear in Intellisense. The documentation should clearly indicate what the session variable is used for. For example, define a class just for the session keys:

C#
public static class SessionKeys
{
    /// <summary>
    ///     The maximum ...
    /// </summary>
    public const string Limit = "limit";
}

...

    Session[SessionKeys.Limit] = 27;

When you need a new session variable, if you choose a name that has already been used you will know this when you add the constant to the SessionKeys class. You can see how it is currently being used and can determine if you should be using a different key.

However, we are still not ensuring consistency of data type.

A Much Better Way - Using a Facade

Only access the HttpSessionState from within one single static class in your application - the facade. There must be no direct access to the Session property from within code on pages or controls, and no direct access to HttpContext.Current.Session other than from within the facade.

All session variables will be exposed as properties of the facade class.

This has the same advantages as using a single class for all the session keys, plus the following advantages:

  • Strong typing of what gets put into session variables.
  • No need for casting in code where session variables are used.
  • All the benefits of property setters to validate what gets put into session variables (more than just type).
  • All the benefits of property getters when accessing session variables. For example, initialising a variable the first time it is accessed.

An Example Session Facade Class

Here is an example class to implement the Session facade for an application called MyApplication.

C#
/// <summary>
///     MyApplicationSession provides a facade to the ASP.NET Session object.
///     All access to Session variables must be through this class.
/// </summary>
public static class MyApplicationSession
{
    # region Private Constants
    //---------------------------------------------------------------------
    private const string userAuthorisation = "UserAuthorisation";
    private const string teamManagementState = "TeamManagementState";
    private const string startDate = "StartDate";
    private const string endDate = "EndDate";
    //---------------------------------------------------------------------
    # endregion

    # region Public Properties
    //---------------------------------------------------------------------
    /// <summary>
    ///     The Username is the domain name and username of the current user.
    /// </summary>
    public static string Username
    {
        get { return HttpContext.Current.User.Identity.Name; }
    }


    /// <summary>
    ///     UserAuthorisation contains the authorisation information for
    ///     the current user.
    /// </summary>
    public static UserAuthorisation UserAuthorisation
    {
        get 
        {
            UserAuthorisation userAuth 
                     = (UserAuthorisation)HttpContext.Current.Session[userAuthorisation];

            // Check whether the UserAuthorisation has expired
            if (
                 userAuth == null || 
                 (userAuth.Created.AddMinutes(
                   MyApplication.Settings.Caching.AuthorisationCache.CacheExpiryMinutes)) 
                     < DateTime.Now
               )
            {
                userAuth = UserAuthorisation.GetUserAuthorisation(Username);
                UserAuthorisation = userAuth;
            }

            return userAuth;
        }

        private set
        {
            HttpContext.Current.Session[userAuthorisation] = value;
        }
    }

    /// <summary>
    ///     TeamManagementState is used to store the current state of the 
    ///     TeamManagement.aspx page.
    /// </summary>
    public static TeamManagementState TeamManagementState
    {
        get 
        {
            return (TeamManagementState)HttpContext.Current.Session[teamManagementState];
        }

        set
        {
            HttpContext.Current.Session[teamManagementState] = value;
        }
    }

    /// <summary>
    ///     StartDate is the earliest date used to filter records.
    /// </summary>
    public static DateTime StartDate
    {
        get 
        {
            if (HttpContext.Current.Session[startDate] == null)
                return DateTime.MinValue;
            else
                return (DateTime)HttpContext.Current.Session[startDate];
        }

        set
        {
            HttpContext.Current.Session[startDate] = value;
        }
    }

    /// <summary>
    ///     EndDate is the latest date used to filter records.
    /// </summary>
    public static DateTime EndDate
    {
        get 
        {
            if (HttpContext.Current.Session[endDate] == null)
                return DateTime.MaxValue;
            else
                return (DateTime)HttpContext.Current.Session[endDate];
        }

        set
        {
            HttpContext.Current.Session[endDate] = value;
        }
    }
    //---------------------------------------------------------------------
    # endregion
}

The class demonstrates the use of property getters that can provide default values if a value has not been explicitly stored. For example, the StartDate property provides DateTime.MinValue as a default.

The property getter for the UserAuthorisation property provides a simple cache of the UserAuthorisation class instance, ensuring that the instance in the session variables is kept up to date. This property also shows the use of a private setter, so that the value in the session variable can only be set under the control of facade class.

The Username property demonstrates a value that may once have been stored as a session variable but is no longer stored this way.

The following code shows how a session variable can be accessed through the facade. Note that there is no need to do any casting in this code.

C#
// Save a session variable
MyApplicationSession.StartDate = DateTime.Today.AddDays(-1);
// Read a session variable
DateTime startDate = MyApplicationSession.StartDate;

Additional Benefits

An additional benefit of the facade design pattern is that it hides the internal implementation from the rest of the application. Perhaps in the future you may decide to use another mechanism of implementing session-state, other than the built-in ASP.NET HttpSessionState class. You only need to change the internals of the facade - you do not need to change anything else in the rest of the application.

Summary

The use of a facade for HttpSessionState provides a much more robust way to access session variables. This is a very simple technique to implement, but with great benefit.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Web Developer
Australia Australia
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionWhat about JavaScript? Pin
fmarto17-Jan-14 17:18
fmarto17-Jan-14 17:18 
GeneralGood technique, but could be improved a bit Pin
Jarmo Muukka20-Nov-13 5:51
Jarmo Muukka20-Nov-13 5:51 
GeneralMy vote of 5 Pin
Prasad Khandekar24-May-13 1:40
professionalPrasad Khandekar24-May-13 1:40 
GeneralMy vote of 5 Pin
Humayun Kabir Mamun2-May-13 23:00
Humayun Kabir Mamun2-May-13 23:00 
QuestionNot bad. Pin
R. Giskard Reventlov5-Apr-13 10:49
R. Giskard Reventlov5-Apr-13 10:49 
GeneralMy vote of 5 Pin
Tim Tatum25-Mar-13 10:02
Tim Tatum25-Mar-13 10:02 
GeneralMy vote of 5 Pin
WebMaster27-Dec-12 15:54
WebMaster27-Dec-12 15:54 
GeneralMy vote of 5 Pin
Savalia Manoj M7-Nov-12 1:07
Savalia Manoj M7-Nov-12 1:07 
GeneralMy vote of 5 Pin
J. Wijaya6-Nov-12 22:58
J. Wijaya6-Nov-12 22:58 
QuestionNice share Pin
J. Wijaya6-Nov-12 22:58
J. Wijaya6-Nov-12 22:58 
GeneralMy vote of 4 Pin
n.podbielski6-Nov-12 5:52
n.podbielski6-Nov-12 5:52 
GeneralMy vote of 4 Pin
Paulo Zemek6-Nov-12 4:25
Paulo Zemek6-Nov-12 4:25 
QuestionSpellcheck ravaged this example..... Pin
Sarah Cartwright5-Nov-12 23:03
Sarah Cartwright5-Nov-12 23:03 
AnswerRe: Spellcheck ravaged this example..... Pin
David Hay6-Nov-12 3:04
David Hay6-Nov-12 3:04 
GeneralIs there any way to restrict direct access to HttpContext.Current.Session? Pin
juancamilo20-May-11 10:41
juancamilo20-May-11 10:41 
AnswerRe: Is there any way to restrict direct access to HttpContext.Current.Session? Pin
David Hay20-May-11 19:03
David Hay20-May-11 19:03 
GeneralFacade Pattern Pin
rahpune19998-Dec-09 20:36
rahpune19998-Dec-09 20:36 
AnswerRe: Facade Pattern Pin
David Hay9-Dec-09 10:56
David Hay9-Dec-09 10:56 
GeneralRe: Facade Pattern Pin
NEMEE11-Jan-13 4:20
NEMEE11-Jan-13 4:20 
GeneralThank you Pin
yaron1130-Aug-09 14:02
yaron1130-Aug-09 14:02 
GeneralSession Variables Are Not Persisting Between Pages Pin
rconnell25-Feb-09 10:20
rconnell25-Feb-09 10:20 
GeneralRe: Session Variables Are Not Persisting Between Pages Pin
David Hay25-Feb-09 11:35
David Hay25-Feb-09 11:35 
QuestionHow to Share Session State Between aspx page and asp page Pin
NidhiKanu7-Jan-09 20:44
professionalNidhiKanu7-Jan-09 20:44 
AnswerRe: How to Share Session State Between aspx page and asp page Pin
Anjum.Rizwi11-Jan-09 19:19
professionalAnjum.Rizwi11-Jan-09 19:19 
GeneralRe: How to Share Session State Between aspx page and asp page Pin
NidhiKanu11-Jan-09 19:46
professionalNidhiKanu11-Jan-09 19:46 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.