Click here to Skip to main content
Click here to Skip to main content

No More Session Variable Misspellings

By , 22 Jun 2011
 
This can be automated and streamlined with generics. First, create a SessionVariable class:
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:
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:
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)

About the Author

AspDotNetDev
Web Developer
United States United States
Member
  • 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):

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
Hint: For improved responsiveness ensure Javascript is enabled and choose 'Normal' from the Layout dropdown and hit 'Update'.
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralReason for my vote of 5 Clean and simplememberdieguzzo18 Sep '11 - 11:22 
GeneralReason for my vote of 5 NicemvpEspen Harlinn17 Jul '11 - 13:26 
GeneralI did something like that a few minutes ago, but my version ...mvpJohn Simmons / outlaw programmer23 Jun '11 - 3:21 
GeneralReason for my vote of 5 nice onemembercode in play23 Jun '11 - 0:59 

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

Permalink | Advertise | Privacy | Mobile
Web03 | 2.6.130516.1 | Last Updated 22 Jun 2011
Article Copyright 2011 by AspDotNetDev
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid