Sunday, January 18, 2009

Different implementation of StateBag

I am going to show some different implementations of StateBag... many times while developing .Net Application, you need to pass some data from one function to another for eg:

A() -> B() --> C()
OR

you want to keep data in some collection and spit it out during page rendering.


Instead of moving the data domain data from function to function, it is a good idea to put the data in the Application Context or in the StateBag.


StateBag -- This is implentation is not a session implentation but its global becuase I am making the stateBag a static variable.



PS:Click on the image to enlarge

StateBag1 implementation:

StateBag1 is a good implementation which exposes a property which will return the StateBag.. The StateBag is stored in the HttpContext. HttpContext provides a items collection where you can dump all your StateBag.This implementation will only work in web centric senario as HttpContext is not available in non web centric application.




StateBag2 implementation:

This implementation is similar to StateBag1 but can be used in non web-centric as it uses the CallContext object if HttpContext is not available.



Creating your ApplicationContext:

This is bascially a wrapper class around the HttpContext. You can store this AppContext object in the CallContext, this way only one instance is created per thread.I like this implementation a lot.




You need to searlize this StateBag before the page renders as a hidden string. When postBack happens that time you need to desearlize the StateBag to get the parameters back.

If you want to download the SourceCode ---> http://DotNetDevBlog.googlepages.com/WebApplication1.Zip

I hope you like the implentations :)

Happy Coding!!
Yash