Click here to Skip to main content
16,021,169 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 498K   995   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
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 
Hello Blake,

I think its unfortunate that you chose to focus on the Anonymous signature instead of the words behind it. Seeing your reaction makes me wonder what would happen if you had a suggestion box handed to you packed full of entries to deal with - but with no signatures attached.

My opinion stays the same whether I reveal my name or not. Simply because I have chosen not to reveal it, does not make any of my words any less valid. You can make whatever snide remarks you want about Anonymous signatures, but (in my opinion) it seems clear that you're only succeeding in repressing yourself by disclaiming opinions simply because they don't have a personalized name attached to them.

I choose not to announce/post my name on the Internet unless I think there is a good reason to (and to me, this is not one of them). In fact, I don't think you should do it either - but that's your choice to make so don't worry; if you want to continue to post your name then please go right ahead - I won't belittle you for doing it, criticize your reasonings behind it, or be pompous about it - even though it is abundantly clear that I do not subscribe to your views regarding anonymity whatsoever. Please note that although I don't share your sentiments around the subject, I do comprehend your concept of "anti-anonymity" and I realize that you have your own beliefs around it - as I do.

A point to consider - when you choose to ignore or justify issues that others are simply trying to bring to your attention, isn't it quite easy sometimes to see afterwards how it might have been you that was actually acting ignorantly (or naïve) all along? I have personally found that some of the most important tidbits of information come from what others express (and sometimes I don’t even know their names!) so I try to remain as open minded as possible, and encourage others to share their ideas, perspectives, and constructive criticism. I find that listening to their words regardless of whether I think they're "right" or not at the time (there’s more than one way to look at a given situation, remember?) quite often ends up being a great natural catalyst for change and a chance to self improve - if I am able to successfully keep my barriers out of the way of progress that is.

Notice that I said "constructive criticism"? It's definitely a fine line sometimes. Perhaps we have both crossed that line at some point during this? I think so.

I personally believe that there must always be room for reflection and self improvement. In fact, I have even managed to learn some good things through this, and I hope that some good things have been learned by you as well.

I apologize if I have managed to offend you with my previous post; I realize that I didn't handle the situation at hand as well as I could have.

Take care,

Anonymous
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.