Click here to Skip to main content
15,890,579 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.7K   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

 
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 
I enjoyed your article Marcys, good job! I look forward to your future posts. I hope you don’t let the know-it-alls drag you down; they’ve got their own issues to deal with.

Blake, I'd simply like to mention that I think you should have a look at learning some self control – get your negative opinions under control and keep the offensive words to yourself. Instead of tearing down everyone else and being pompous because they don't share your sentiments, how about doing something positive and post an actual article to help everyone with a concept instead? I notice you have over 150 comments throughout the site - yet not even one article. That says a lot. Oh I'm sure you've got lots of reasons. Who cares.

For some reason you must think you are here to tell everyone how it is and act like some kind of "expert". The only thing you have been an "expert" at in this discussion, is your belittling of others and putting on a fine show of how ignorant and stubborn you can be in your quest to be right(eous). How about get off your high horse for a minute and try acting like a human being for a minute or two while you prepare to post - you can still do that without sacrificing the knowledge that you feel is so important to share. Apply some tact, there's no need for this kind of negative bs.

Let me tell you something - if you had not said a word - and I think I speak for the majority of us when I tell you this - the lack of your "insight" would have been of no loss to us. To be clear - we wouldn't have missed your comments one little bit. I mean, what did you manage to accomplish here other than frustrating and belittling everyone who didn't agree with your sentiments?

Perhaps you should consider taking your version of "help" somewhere else if you insist on continuing with your behavior - we don't need this kind of negativity - and it most definately is negative, to say the least. What a horrible, appalling spew of nonsense. Please think about that before you speak up and try to justify it next time, so we don't all have to look at the disgusting mess.

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.