The other day I was checking out the Microsoft Web Client Software Factory, but I wasn’t very impressed. Too complicated, too “heavy”, too …
Anyway, I did stumble upon something interesting: it includes a class that allows you to define a class member that will survive page requests (in other words, it is stored in the session). Of course, the class can’t be used without implementing the whole framework. Too bad. But then I thought: hey, this shouldn’t be too hard to implement as a standalone class… and it isn’t. Fifty lines of code to be precise (and it takes the concept a little further than the original)
Imagine you are writing a web application, and imagine you could have a (typed) property in your class that, whenever you access it, you are actually writing to the session? Not too hard, but it requires some code:
public int CustomerID
{
get
{
if (HttpContext.Current.Session["CustomerID"] == null)
return -1;
else
return (int) HttpContext.Current.Session["CustomerID"];
}
set
{
HttpContext.Current.Session["CustomerID"] = value;
}
}
Not too bad, I know, but we can do better
How about this:
private SessionProperty<int> _customerID = new SessionProperty<int>("CustomerID",-1);
public int CustomerID
{
get { return _customerID.Value; }
set { _customerID.Value; }
}
The number of lines of code isn't that much lower, but it is a lot cleaner.
You can even do this:
private SessionProperty<Customer> _customer
= new SessionProperty<Customer>("CurrentCustomer",
delegate { return new Customer() });
public Customer CurrentCustomer
{
get { return _customer.Value; }
set { _customer.Value; }
}
In the example above, if there is nothing in the session when you first access the property, it will create a new instance of the Customer and store it in the session. No more fear for NullReferenceExceptions. Isn’t this cool?
Did I forget something? ... Yes! The code!
public delegate T Creator<T>();
public class SessionProperty<T>
{
private readonly string _sessionKey;
private readonly T _defaultValue;
private readonly Creator<T> _defaultValueCreator;
public SessionProperty(string sessionKey)
{
_sessionKey = sessionKey;
_defaultValue = default(T);
}
public SessionProperty(string sessionKey, T defaultValue)
{
_sessionKey = sessionKey;
_defaultValue = defaultValue;
}
public SessionProperty(string sessionKey, Creator<T> defaultValueCreator)
{
_sessionKey = sessionKey;
_defaultValueCreator = defaultValueCreator;
}
public T Value
{
get
{
if (ProMeshHttpContext.Current.Session[_sessionKey] == null)
{
if (_defaultValueCreator != null)
{
T value = _defaultValueCreator();
Value = value;
return value;
}
else
return _defaultValue;
}
else
return (T) HttpContext.Current.Session[_sessionKey];
}
set
{
HttpContext.Current.Session[_sessionKey] = value;
}
}

•