Click here to Skip to main content
15,881,882 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

 
GeneralMixed Opinion Pin
Blake Coverett18-Sep-03 8:18
Blake Coverett18-Sep-03 8:18 
GeneralRe: Mixed Opinion Pin
Nigel Shaw23-Sep-03 2:57
Nigel Shaw23-Sep-03 2:57 
GeneralRe: Mixed Opinion Pin
Randal Wilcox24-Sep-03 5:36
Randal Wilcox24-Sep-03 5:36 
GeneralRe: Mixed Opinion Pin
Blake Coverett24-Sep-03 12:50
Blake Coverett24-Sep-03 12:50 
GeneralRe: Mixed Opinion Pin
Chris Keeble24-Sep-03 23:23
Chris Keeble24-Sep-03 23:23 
GeneralRe: Mixed Opinion Pin
Blake Coverett25-Sep-03 11:43
Blake Coverett25-Sep-03 11:43 
GeneralRe: Mixed Opinion Pin
brzozow28-Sep-03 10:30
brzozow28-Sep-03 10:30 
GeneralRe: Mixed Opinion Pin
Blake Coverett28-Sep-03 10:45
Blake Coverett28-Sep-03 10:45 
You missed the point completely. The compression of the LosFormatter was only about the fact that you can't compare the size of the viewstate written to the page with the size of the corresponding objects in memory. The point is there's a _reason_ the whole idea of ViewState which is not stored in the Session was introduced with ASP.NET. It's because storing that information in the memory is a bad idea anyway.

Your particular implementation above even stores the blob back as wide char strings, resulting in most of the 'compression' being lost. Not to mention the flaw that ViewState is meant to be discarded after each page and now it's being kept around in the Session.

How many accounts do you have here, Marcyś?

--
-Blake (com/bcdev/blake)
GeneralRe: Mixed Opinion Pin
brzozow28-Sep-03 22:19
brzozow28-Sep-03 22:19 
GeneralRe: Mixed Opinion Pin
Blake Coverett28-Sep-03 22:34
Blake Coverett28-Sep-03 22:34 
GeneralRe: Mixed Opinion Pin
Nigel Shaw25-Sep-03 1:40
Nigel Shaw25-Sep-03 1:40 
GeneralRe: Mixed Opinion Pin
Blake Coverett25-Sep-03 11:57
Blake Coverett25-Sep-03 11:57 
GeneralRe: Mixed Opinion Pin
Nigel Shaw25-Sep-03 12:33
Nigel Shaw25-Sep-03 12:33 
GeneralRe: Mixed Opinion Pin
Blake Coverett25-Sep-03 14:12
Blake Coverett25-Sep-03 14:12 
GeneralRe: Mixed Opinion Pin
Nigel Shaw25-Sep-03 14:49
Nigel Shaw25-Sep-03 14:49 
GeneralRe: Mixed Opinion Pin
Anonymous29-Sep-03 21:02
Anonymous29-Sep-03 21:02 
GeneralRe: Mixed Opinion Pin
Blake Coverett5-Oct-03 10:37
Blake Coverett5-Oct-03 10:37 
GeneralRe: Mixed Opinion Pin
Anonymous6-Oct-03 6:38
Anonymous6-Oct-03 6:38 
GeneralRe: Mixed Opinion Pin
Owen Lloyd5-Oct-03 2:38
Owen Lloyd5-Oct-03 2:38 
GeneralRe: Mixed Opinion Pin
Blake Coverett5-Oct-03 10:39
Blake Coverett5-Oct-03 10:39 
GeneralRe: Mixed Opinion Pin
MarkC#15-Oct-03 6:38
MarkC#15-Oct-03 6:38 

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.