Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

No More Session Variable Misspellings

0.00/5 (No votes)
22 Jun 2011 1  
This can be automated and streamlined with generics. First, create a SessionVariable class:public class SessionVariable{ private string VariableName { get; set; } private System.Web.SessionState.HttpSessionState Session { get; set; } public T Value { get ...
This can be automated and streamlined with generics. First, create a SessionVariable class:
C#
public class SessionVariable<T>
{
    private string VariableName { get; set; }
    private System.Web.SessionState.HttpSessionState Session { get; set; }
    public T Value
    {
        get
        {
            object sessionValue = this.Session[this.VariableName];
            if (sessionValue == null)
            {
                sessionValue = default(T);
            }
            return (T)sessionValue;
        }
        set
        {
            this.Session[this.VariableName] = value;
        }
    }
    public SessionVariable(string variableName,
        System.Web.SessionState.HttpSessionState session)
    {
        this.VariableName = variableName;
        this.Session = session;
    }
}

Next, create a SessionHelper class:
C#
using System;
using System.Reflection;
public class SessionHelper
{
    public static void InitializeSessionVariables(object instance,
        System.Web.SessionState.HttpSessionState session, string prefix)
    {
        foreach (var property in instance.GetType().GetProperties(
            BindingFlags.Public | BindingFlags.Instance))
        {
            if (property.PropertyType.IsGenericType &&
                property.PropertyType.GetGenericTypeDefinition() ==
                typeof(SessionVariable<>))
            {
                property.SetValue(instance, Activator.CreateInstance(
                    property.PropertyType, prefix + property.Name, session),
                    new object[] { });
            }
        }
    }
}

You can then add properties to your page (or another suitable class) that act as a simple way to access session. Here is an example:
C#
public partial class Default : System.Web.UI.Page
{
    public SessionVariable<string> CompanyName { get; set; }
    public SessionVariable<int> EmployeeCount { get; set; }
    public SessionVariable<System.Text.StringBuilder> CompanyInformation { get; set; }
    protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);
        SessionHelper.InitializeSessionVariables(this, Session, "Default.aspx.");
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        CompanyName.Value = "Code Project";
        EmployeeCount.Value = 5;
        Response.Write(CompanyName.Value);
        Response.Write(EmployeeCount.Value.ToString());
        Response.Write((CompanyInformation.Value ??
            new System.Text.StringBuilder("Company information null")).ToString());
    }
}

That is my code behind for my Default.aspx page. Notice I added 3 generic properties of type SessionVariable. Next, I initialized those properties using my helper method, InitializeSessionVariables (note that I passed in a prefix to ensure the session variables would not conflict with those used on other pages). Finally, I demonstrated their use in the Page_Load method. This makes creating session variables type safe and prevents mistyping session variable names.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here