Wednesday, July 4, 2007

Generic StateManagedCollection

Do you have a custom control which exposes a collection property? E.g. DropDownList exposes a property called Items, GridView exposes a property called Columns etc.

Prior to ASP.Net 2.0, you had to write a custom collection which explicitly implemented IList interface and then you had to expose custom typed methods and properties (IList can deals with objects). You also had to implement IStateManager interface in this custom collection class so the items can be stored in view state.

Fortunately, ASP.Net 2.0 has a class collection class which serves this specific purpose i.e. creating a custom collection which can be stored in the view state. All you have to do is inherit from StateManagedCollection and add your custom typed properties e.g. Add(), Remove(), IndexOf() etc. The StateManagedCollection will automatically manage the items in the collection in ViewState. Please note that StateManagedCollection expects items stored inside it implement IStateManager interface.

Suppose, you need to have two collection properties viz. Holidays (which holds Holiday objects) and Leaves (which holds Leave objects). The code in both the collection classes will more or less same except for the custom typed properties e.g. Holidays.Add() would expect an object of Holiday class and Leaves.Add() will expect an object of a Leave class. The definitions of the functions would be as follows:

Holidays.Add(Holiday h) { // code to add holiday to collection }
Leaves.Add(Leave l) { // code to add leave to collection }

To tackle this problem I created a generic StateManagedCollection (called StateManagedCollection) class which can automatically expand and create custom typed properties for the passed type parameter.

For this, I first created an abstract class called StateManagedEntity which all the item classes (e.g. Holiday, Leave etc have to derive from). StateManagedEntity class creates a private StateBag and exposes a protected property called ViewState in which the derived classes can store their data etc. StateManagedEntity also takes care of implementing IStateManager interface.

The StateManagedCollection class has two constraints on it i.e. it can only accept types that are inherited from StateManagedEntity and the type should be a concrete type (non-abstract) i.e. it should be possible to create an object of the class.

Once the item class (Holiday, Leave etc) have inherited from StateManagedEntity, all it takes is to declare a property in the custom control like:

public StateManagedCollection Holidays
{
get { }
set { }
}

You don’t even have to declare a collection class inheriting from StateManagedCollection. Check out the sample and code. Issues and feedback is welcome.

The code can be download here.

1 comment:

DLarsen said...

Where can I download the code?