Wednesday, March 26, 2008

A Generic Session Wrapper for 2.0/3.5

Just something I use quite often for my Web applications and decided to throw out there.

I often write a Facade class that exposes Session Variables using properties, but under the covers, this class is called.

It could use a little updating, but it works. *shrug*

public static partial class SessionHelper
{
static SessionHelper()
{
}

static public T Read(string name)
{
if (string.IsNullOrEmpty(name))
{
throw new ArgumentNullException("name");
}
if (HttpContext.Current == null) return default(T);
if (HttpContext.Current.Session[name] != null)
{
return (T)HttpContext.Current.Session[name];
}
return default(T);
}
static public T Read(int index)
{
if (HttpContext.Current == null) return default(T);
if (HttpContext.Current.Session[index] != null)
{
return (T)HttpContext.Current.Session[index];
}
return default(T);

}

static public void Remove(string name)
{
if (HttpContext.Current == null) return;
if (string.IsNullOrEmpty(name))
{
throw new ArgumentNullException("name");
}
HttpContext.Current.Session.Remove(name);
}

static public void Store(string name, object item)
{
if (string.IsNullOrEmpty(name))
{
throw new ArgumentNullException("name");
}
HttpContext.Current.Session.Add(name, item);
}

}