Click here to Skip to main content
12,500,818 members (47,187 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as

Stats

5.7K views
3 bookmarked
Posted

No More Session Variable Misspellings

, 22 Jun 2011 CPOL
Rate this:
Please Sign up or sign in to vote.
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:
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)

Share

About the Author

AspDotNetDev
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):

You may also be interested in...

Pro
Pro

Comments and Discussions

 
GeneralReason for my vote of 5 Clean and simple Pin
dieguzzo18-Sep-11 11:22
memberdieguzzo18-Sep-11 11:22 
GeneralReason for my vote of 5 Nice Pin
Espen Harlinn17-Jul-11 13:26
mvpEspen Harlinn17-Jul-11 13:26 
GeneralI did something like that a few minutes ago, but my version ... Pin
John Simmons / outlaw programmer23-Jun-11 3:21
mvpJohn Simmons / outlaw programmer23-Jun-11 3:21 
GeneralReason for my vote of 5 nice one Pin
code in play23-Jun-11 0:59
membercode in play23-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.

| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.160919.1 | Last Updated 22 Jun 2011
Article Copyright 2011 by AspDotNetDev
Everything else Copyright © CodeProject, 1999-2016
Layout: fixed | fluid