Click here to Skip to main content
15,884,237 members
Articles / Web Development / ASP.NET
Alternative
Tip/Trick

No More Session Variable Misspellings

Rate me:
Please Sign up or sign in to vote.
4.83/5 (10 votes)
22 Jun 2011CPOL 11.4K   3   4
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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Web Developer
United States United States

  • Managing Your JavaScript Library in ASP.NET (if you work with ASP.net and you don't read that, you are dead to me).
  • Graduated summa cum laude with a BS in Computer Science.
  • Wrote some articles and some tips.
  • DDR ("New high score? What does that mean? Did I break it?"), ping pong, and volleyball enthusiast.
  • Software I have donated to (you should too):

Comments and Discussions

 
GeneralReason for my vote of 5 Clean and simple Pin
dieguzzo18-Sep-11 11:22
dieguzzo18-Sep-11 11:22 
GeneralReason for my vote of 5 Nice Pin
Espen Harlinn17-Jul-11 13:26
professionalEspen Harlinn17-Jul-11 13:26 
GeneralI did something like that a few minutes ago, but my version ... Pin
#realJSOP23-Jun-11 3:21
mve#realJSOP23-Jun-11 3:21 
GeneralReason for my vote of 5 nice one Pin
pankajupadhyay2923-Jun-11 0:59
professionalpankajupadhyay2923-Jun-11 0:59 

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.