The jury is still out on if the class should be stored in the session in the first place. With the app I asked the question for, I opted on NOT stuffing the class into session, it really wasn't necessary, I was being lazy. Working out this method to manage the session was worth all the time, as it's something that has bothered me for some time in web development.
What came out of my research is writing a static class to manage my session variables. This class handles all reads and writes to the session and keeps them all strongly typed for me to boot. It has always bothered me using repeated code all over the place for session crap. Keeps typos way down too.
There are two articles I like which I found on this, I can only locate one of them now and will include the other when I locate it.
The first was at Code Project
This may be the second link
The pattern is easy and straight forward. I have also built a class for requests for grabbing parameters from url query strings. I see no reason not to extend it to cookies too.
This was my first use of the pattern, I only used strings so the private method is a bit limited, but this can easily be changed to use any class or primitive type.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Configuration;
namespace BDZipper.Site
{
/// <summary>
/// This class maintains all session variables for us instead of handeling them
/// individually in the session. They are also strongly typed.
/// </summary>
public static class SessionManager
{
# region Private Constants
// Define string constant for each property. We use the constant to call the session variable
// easier not to make mistakes this way.
// I think for simplicity, we will use the same key string in the web.config AppSettings as
// we do for the session variable. This way we can use the same constant for both!
private const string startDirectory = "StartDirectory";
private const string currentDirectory = "CurrentDirectory";
# endregion
/// <summary>
/// The starting directory for the application
/// </summary>
public static string StartDirectory
{
get
{
return GetSessionValue(startDirectory, true);
}
//set
//{
// HttpContext.Current.Session[startDirectory] = value;
//}
}
public static string CurrentDirectory
{
get
{
return GetSessionValue(currentDirectory, false);
}
set
{
HttpContext.Current.Session[currentDirectory] = value;
}
}
//TODO: Update to use any class or type
/// <summary>
/// Handles routine of getting values out of session and or AppSettings
/// </summary>
/// <param name="SessionVar"></param>
/// <param name="IsAppSetting"></param>
/// <returns></returns>
private static string GetSessionValue(string SessionVar, bool IsAppSetting)
{
if (null != HttpContext.Current.Session[SessionVar])
return (string)HttpContext.Current.Session[SessionVar];
else if (IsAppSetting) // Session null with appSetting value
return ConfigurationManager.AppSettings[SessionVar];
else
return "";
}
}
}