There seems to have been a lack of .NET-related stuff on this blog recently, so let me show you something I cobbled together for work purposes last Wednesday:
A common requirement we have in our ASP.NET applications is how to reliably persist object instances for a lengthy period of time. End users shouldn't have to concern themselves with the concept of Session expiry, and it's unacceptable for them to return to their PC after nipping off for a coffee to be confronted with the dreaded "Object reference not set to an instance of an object" when they try to continue editing their basket / sales order / timesheet / whatever.
One pattern to solve this, detailed by Martin Fowler in Patterns of Enterprise Application Architecture, is the Serialized LOB (Large Object), which works by serializing the object in question into binary or text which is then stored in a single database field.
An excellent example of how to achieve this using SQL Server and .NET is given by Peter A Bromberg in this Egghead Cafe article.
Building on this example, I've put together a generic assembly for persisting and retrieving serializable classes into SQL Server, referenced by a combination of two strings (a username and a key). It is essentially an alternative to storing objects in Session or ViewState. As an additional benefit, it allows you to "lock" objects based on the key, so that only one user can store the same object at a given point in time.
The zip file below includes the source and a SQL script for setting up the required database table and four stored procedures, as well as some unit tests (yes, I am sticking to my New Year's Resolution!).
The DataStore class contains the various static methods necessary to add, retrieve and delete objects from the store. For example, to save an object you can simply make a call along the lines of:
DataStore.Add("joebloggs","order1234",objOrder);
DataStore.Add("joebloggs","order1234",objOrder,true);
SalesOrder objOrder = DataStore.Get("joebloggs","order1234").StoredObject as SalesOrder;
Updated 30 October 2005:
- Download .NET 2.0 version (86 Kb)
- Download .NET 1.1 version (116 Kb)
