Click here to Skip to main content
15,879,535 members
Articles / Web Development / ASP.NET
Article

State Management

Rate me:
Please Sign up or sign in to vote.
3.65/5 (20 votes)
23 Sep 20034 min read 491.3K   994   56   51
This article describes set of best practices in state management.

Introduction

How to persist objects in a web application between each request? How to send objects between pages? How to easily access the persisted objects? This article demonstrates a set of best practices and sample codes that I gained during web applications development.

I created a State class that is responsible for storage of persisted objects. The State object is implicitly stored in HttpSession, therefore can be treated as a wrapper of the Session. The State has two static methods: get and set which allows you to get and set an object from and to the State. The methods are intended to be used in property get and set methods therefore the names. Each of the persisted object is internally stored in a Hashtable under two parts key: class name and property name.

Here you can find few samples of how to use the State class.

Persisting objects between requests

There is very often a need to persist some object stored on page between requests. The object can be stored in viewstate, but I do not recommend it as it involves serialization of the object and sending it to the client.

Solution 1: Private property that stores value in State.

Such private property that stores its value in State allows you to retrieve a previously set value. There can be many of such properties on one page. Each of them is stored under different key in the State.

Here is a sample property used to store an object between requests:

C#
private string persistedText
{
    get { return (string)State.get(); }
    set { State.set(value); }
}

Solution 2: [Persist] attribute on a field that should be retained.

The Persist attribute is created to mark fields that should be saved and restored from State.

Here is a sample how to mark a field to be persisted between requests:

C#
[ Persist ]
private string previouslySent;

To make the attribute working, special code must be run on page init to restore the fields' values from State:

C#
private void Page_Init(object sender, System.EventArgs e)
{
    Persister.LoadState(this);
}

To store the fields' values in State, Persister should be also called in Page_Unload event:

C#
private void Page_Unload(object sender, System.EventArgs e)
{
    Persister.SaveState(this);
}

Sending objects between pages

The problem with sending objects between pages is that there is only one Page object available at a time. There is no way to get a page that will be displayed on the next request and change its properties.

Solution: a static property that stores value in State.

Such property is available from any place, and does not require object to be created at the time it is set. We are used to static properties that store application level objects, but thanks to using State, it is session level storage (two sessions can set the same property and each of them retrieves its own value).

Here is a sample property that can be used to pass string between pages:

C#
public class Addressee : System.Web.UI.Page
{
    public static string IncomingText
    {
        get { return (string)State.get(); }
        set { State.set(value); }
    }
}

And here is a sample code that sends some text to Addressee.aspx:

C#
Addressee.IncomingText = "the sent text";
Response.Redirect("~/Addressee.aspx");

Storing session level objects

By the session level object, I mean an object that is session specific and should be available from any place in the application, e.g. user name. I do not recommend storing the objects directly in session. It causes problems, as it does not give strongly typed access to the object and it is very similar to global variables in old, procedural programming (and involves the same difficulties).

Solution: one class that will give strongly typed access to all the session level objects and store them in State.

Such a class will contain one static property for each of the objects. The property will store and retrieve the object value from State.

Here is a sample class that gives access to session level objects:

C#
public class SessionContext
{
    public static string UserName
    {
        get { return (string)State.get(); }
        set { State.set(value); }
    }
}

Storing application level objects

The application level object is an object that can be implemented by Singleton Design Pattern. Simply speaking, it is application global variable. Such a variable can be stored in one of three places: static variable, Application object or Cache object. I do not recommend any of them as all the ways are quite similar.

Here you can find sample of how to store application level object in application state.

C#
public static object GlobalObject
{
    get { return HttpContext.Current.Application["some unique key"]; }
    set { HttpContext.Current.Application["some unique key"] = value; }
}

How to avoid sending ViewState to client

I found that in some cases serialized viewstate took half of the sent page.

Solution: store viewstate in State.

The Page object gives you two methods: SavePageStateToPersistenceMedium and LoadPageStateFromPersistenceMedium. When you override those methods on your page, you can store the viewstate wherever you need. The viewstate will not be serialized and sent to the client.

Here is sample code that should be added to Page class to store viewstate in State.

C#
private object __VIEWSTATE
{
    get { return State.get(); }
    set { State.set(value); }
}

override protected void SavePageStateToPersistenceMedium(object viewState)
{
    this.__VIEWSTATE = viewState;
}

override protected object LoadPageStateFromPersistenceMedium()
{
    return this.__VIEWSTATE;
}

Best practices summary

Remember: Always use strongly typed access to an object that you persist.

Remember: Create your own Page and UserControl base classes. Place the Persister call in there and add the viewstate storing.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Web Developer
Poland Poland
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
Question@class ? Pin
bachand20-Jun-06 8:03
bachand20-Jun-06 8:03 
AnswerRe: @class ? Pin
Marcin Celej20-Jun-06 10:01
Marcin Celej20-Jun-06 10:01 
Generalreuse component Pin
joachim stephan9-Nov-05 3:42
joachim stephan9-Nov-05 3:42 
Questionhelp! what's wrong with my code? Pin
Your details have been updated28-Aug-05 21:54
Your details have been updated28-Aug-05 21:54 
GeneralSession on new HTTPHandler Pin
Guillermo Jimenez28-May-05 17:27
Guillermo Jimenez28-May-05 17:27 
GeneralHttpContext Pin
skb33317-Mar-05 5:56
skb33317-Mar-05 5:56 
GeneralRe: HttpContext Pin
Guillermo Jimenez28-May-05 17:18
Guillermo Jimenez28-May-05 17:18 
GeneralWhy not use Cache object Pin
Anonymous1-Nov-04 7:08
Anonymous1-Nov-04 7:08 
GeneralRe: Why not use Cache object Pin
Marcin Celej1-Nov-04 8:00
Marcin Celej1-Nov-04 8:00 
GeneralRe: Why not use Cache object Pin
miltash24-Jul-07 4:32
miltash24-Jul-07 4:32 
QuestionAm I missing something? Pin
Mike Gilbert9-Jul-04 3:56
Mike Gilbert9-Jul-04 3:56 
AnswerRe: Am I missing something? Pin
Marcin Celej9-Jul-04 4:29
Marcin Celej9-Jul-04 4:29 
GeneralRe: Am I missing something? Pin
Mike Gilbert9-Jul-04 4:45
Mike Gilbert9-Jul-04 4:45 
GeneralDoes not work Pin
ballaln15-Jun-04 0:08
ballaln15-Jun-04 0:08 
AnswerRe: Only works in Debug builds ??? Pin
rjones060414-May-04 4:54
rjones060414-May-04 4:54 
GeneralRe: Only works in Debug builds ??? Pin
Mike Gilbert9-Jul-04 7:51
Mike Gilbert9-Jul-04 7:51 
GeneralRe: Only works in Debug builds ??? Pin
JoePaterno21-Sep-04 6:31
JoePaterno21-Sep-04 6:31 
QuestionOnly works in Debug builds ??? Pin
rfordvpi12-May-04 16:24
rfordvpi12-May-04 16:24 
AnswerRe: Only works in Debug builds ??? Pin
rjones060413-May-04 7:03
rjones060413-May-04 7:03 
QuestionWhy use a HashTable and not interact direct with session? Pin
Patrick Spieler26-Nov-03 1:48
Patrick Spieler26-Nov-03 1:48 
AnswerRe: Why use a HashTable and not interact direct with session? Pin
Marcin Celej27-Nov-03 22:01
Marcin Celej27-Nov-03 22:01 
GeneralSome questions to Marcy... Pin
r_storaa7-Oct-03 23:23
sussr_storaa7-Oct-03 23:23 
GeneralRe: Some questions to Marcy... Pin
Marcin Celej7-Oct-03 23:42
Marcin Celej7-Oct-03 23:42 
GeneralRe: Some questions to Marcy... Pin
Rannveig9-Oct-03 6:12
Rannveig9-Oct-03 6:12 
QuestionHow about web farms ? Pin
andrei alexe23-Sep-03 19:15
andrei alexe23-Sep-03 19:15 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.