Web Session Management and Centralization Class

For most web-based applications, developers employ some type of session-based data store/access. It’s fairly common practice to use session to pass data back and forth for the duration of a user’s visit, especially when that data is not completely persistent, as in the case of storing data directly back to the database.

Because this is such common practice, when reviewing code, I often find that developers simply access session whenever they need it from whichever page they are calling/saving from. Though this is probably the easiest way to do things it can get pretty messy.

Check out the following example of what I’m talking about:

A Messy, But Common Example of Session Usage

login.aspx.cs

protected void btnSubmit_Click(object sender, ImageClickEventArgs e)
{
    bool result = SomeBusinessEntity.CheckLogin(tbEmail.Text, tbPassword.Text);
    if (result)
    {
        //Add some values to session to be used later in the web-application
        Session.Add(“SomeSessionData”, “SomeSessionValue”);

        //do the rest of code you may want to call...
    }
    else
    {
        //provide notification of failed login
    }
}

memberonly.aspx.cs

protected void Page_Load(object sender, EventArgs e)
{
    //Check the session value to customize this page (or maybe, see if user is allowed access)
    string sessionValue = string.Empty;

    try 
    {
        if (string.IsNullOrEmpty(Session["SomeSessionValue"].ToString()))
        {
            //kick user out of page
        }
        else
        {
            //customize page with logic pertaining to the value stored in session
        }
    }
    catch
    {
        //kick user out of page
    }
}

There are several potential issues with writing code like this. First, code is scattered throughout the web application and it is inheritently decentralized making maintenance and debugging potentially difficult. Second, session values are stored in magic strings, meaning, that if another developer goes to use this session value, they need to know what string they need to request and if by chance they mistype it, they’re in trouble.

Note: There are additional issues with the above example, but for the purpose of this demo I’m going to focus just on these specific issues.

Implementing a Web Session Manager Class

Here’s the same code using a Web Session Manager class that we will create at the web application level.

protected void btnSubmit_Click(object sender, ImageClickEventArgs e)
{
    bool result = SomeBusinessEntity.CheckLogin(tbEmail.Text, tbPassword.Text);
    if (result)
    {
        //Add some values to session to be used later in the web-application
        //NOTICE THE STRONGLY TYPED REFERENCE
        WebSession.SomeSessionData = “SomeSessionValue”;

        //do the rest of code you may want to call...
    }
    else
    {
        //provide notification of failed login
    }
}

memberonly.aspx.cs

protected void Page_Load(object sender, EventArgs e)
{
    //Check the session value to customize this page (or maybe, see if user is allowed access)
    //NOTICE THE USE OF DATATYPES HERE AND ENCAPSULATING LOGIC TO ASSESS WHETHER THE SESSION VALUE EXISTS
    string sessionValue = WebSession.SomeSessionData;

    if (string.IsNullOrEmpty(sessionValue))
    {
        //kick user out of page
    }
    else
    {
        //customize page with logic pertaining to the value stored in session
    }
}

WebSession.cs

/// <summary>
/// Access SomeSessionData which describes what a logged in user's favorite color is.
/// </summary>
public static string SomeSessionData
{
    get
    {
        HttpContext context = HttpContext.Current;
        string sessionValue = string.Empty;

        if (context.Session["SomeSessionData"] != null)
        {
            sessionValue = context.Session["SomeSessionData"].ToString();
        }

        return sessionValue;
    }
    set
    {
        HttpContext context = HttpContext.Current;
        context.Session.Add("SomeSessionData", value);
    }
}

It’s different but not too drastically; so what did we gain from this?

Well, we’ve added a WebSession class which contains static methods that now house ALL session based information in a single area. We can readily access session values through static calls, make updates to session based content or logic through a single-point of entry, provide strongly typed access to that session information to help ourselves and our fellow developers, and finally, even provide intellisense hints through sandcastle notation (the triple “/” comments at the top of SomeSessionData).

Remember, this is a small demo example; imagine this on a much grander scale where you have possibly hundreds of pages each with their own implementations of directly calling the Session collection! Not good my friends.

Hope this short article on developing and implementing a Web Session Manager class helps!

P.S. – Go Gators! 2008-2009 National Football Champions!

University of Florida

4 thoughts on “Web Session Management and Centralization Class

  1. rał Rościsławski zasalutował Zgodna maszyny. kompleksowo do
    wyjściowej
    czapki, zwanej naleśnikiem. budowa (randki.o2.pl) UAZ ruszył
    z impetem, wyrzucając spod kół grudki
    błota, Po obbecnym momencie zniknął zbytnio
    zakrętem leśnej drogocenny.. Wagner popatrzył zbyt przed,
    wykonał spóźniony, nieoznaczony gest, mgliście przypominający salut.
    Czego w charakterze
    czego, jednak odwagi generałowi niie brakowało.

    Rościsławski jeździł chociażby, bez serce.

  2. I am extremely inspired along with your writing talents as neatly as with the structure on your weblog.
    Is this a paid subject or did you customize it yourself?
    Anyway stay up the nice quality writing, it’s rare to look a nice
    blog like this one these days..

  3. wzniesionego pyłu, Agencja Internetowa jak cicerone pociągnął
    dźwignię reformy skoku, sklep internetowy kiedy drgnął tułów tudzież wydłużyły się amortyzatory
    podwozia…
    Podwozia…
    – Wagner! – Frodo obrócił się raptownie, nie
    zawracając samemu główki ocieraniem
    łez ściekających po policzkach.
    Wagner stuknął szpadlem w chodnikowe powierzchowny,
    podczas gdy Frodo podskoczył do niego natomiast
    chwycił zbyt ramienia.
    – Wagner… – sapn�.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s