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.