ISessionStateItemCollection interface

Summary

In previous programming projects, I have used the ISessionStateItemCollection object to override the session state collection object built into HttpContext.Current.  In this blog post I’m going to demo a bug in Microsoft’s sample code used to show how to create a custom SessionStateItemCollection.

Where to Find the Sample Code

Microsoft provides a lot of sample code for objects that you can customize.  The session state collection is one example.  The ISessionStateItemCollection interface is detailed on this webpage:  IsessionStateItemCollection Interface.  Each property and method is described in detail to make it easy to design a custom object.  If you scroll down the page, you’ll see a sample custom interface that uses the SortedList object to contain the item collection.  If you copy the code and paste it into Visual Studio, it will run as advertised.  Here’s a sample of some code you can execute in a console application:

var sessionTest = new MySessionStateItemCollection();

sessionTest["test"] = "test data";

Console.WriteLine(sessionTest["test"]);
Console.ReadKey();

Unfortunately, there is a problem with the key collection cast.  If you attempt to run this code, you’ll see the run-time casting error:

var sessionTest = new MySessionStateItemCollection();

sessionTest["test"] = "test data";

Console.WriteLine(sessionTest.Keys.Count);
Console.ReadKey();

 The error message looks like this:

If you’re like me, you’ll copy the error message and paste it into Google and attempt to find a solution.  That solution normally shows up on Stack Overflow, but sometimes if it’s not on that website you’ll stumble across it someplace else.  The solution to this error, is nowhere to be found.  I suspect that very few programmers write a custom session state item collection and those who do, have found a work-around.  So I’m posting a work-around to this issue that is not fantastic, but it works.

First, remove the line of code containing the SortedList.  Then add a base class to the object like this:

public class MySessionStateItemCollection : NameObjectCollectionBase, ISessionStateItemCollection

Next, you’ll need to alter all the method calls that used the SortedList (pItems).  You can use base.BaseGet(index) and base.BaseSet(index), etc.  You can override the Keys property and it will cast correctly, or you can just remove it since the base class implements that property already.  You’ll have to perform some fancy footwork for the CopyTo() method, since it is not implemented in the base class.

A second solution to this problem is to implement your own NameObjectCollectionBase type.  You could technically, implement a custom collection that mirrors the built-in methods of the NameObjectCollectionBase class.  This object also has sample code from Microsoft and this code works as advertised (see NameObjectCollectionBase Class).

Leave a Reply