State – Part 1 (View State)

September 23, 2010 § 1 Comment

So the web itself is, of course, stateless. What does this mean, exactly? It simply means that every request is independent of every other request. For instance, when you access a web page, your web browser asks the server for the page markup, and the server sends the page markup down. The browser reads the page markup, and then makes subsequent requests to the server (or another server) to download additional resources like images, javascript files, or CSS files. As far as the server is concerned, these are separate requests that aren’t really associated.

This obviously yields huge advantages to scalability. The resources to serve a single web page can be spread out to multiple machines to distribute the load, and subsequent request can hit separate servers without any issues. However, with this scalability come some challenges. In fact, Google’s new experimental protocol – SPDY is designed to get around some of these challenges.

You need to have state to write a web application. You have to know which user is requesting a page, and you have to know what they did with the last page you gave them. Back in the classic ASP days, before we had automagical ASP.NET, one method for keeping track of who a user was or what data he had entered in a previous page, was to create a hidden field on the page to hold that information. This works – Microsoft even describes how you ought to do it. However, there are some pretty serious security issues with storing data in hidden form fields – namely, that it’s plainly visible to the user on the other end. This article goes into some detail about it.

ASP.NET View State took this same approach to storing data, but it encrypted the data to close the security hole and prevent the user on the other end from seeing or modifying the data. (This, by the way, is the problem with the ASP.NET padding oracle attack – it allows the end user to break that encryption and read/modify the data in View State.)

So, logically, this makes sense. If you want to store some data, in your code-behind file, write some data to View State (which is actually going to be an encrypted, hidden form field on your page), then serve the page up to the client. The page (with the included View State) goes across whatever the network connection is to the client’s web browser. They get to have the page for a little while, make whatever edits that are appropriate, then post the form back to your server. Your server (ASP.NET) pulls the View State out of the posted form, and you now are able to figure out who they are and what they were doing – it gives you state.

This is great in some ways. It makes your application much more scalable. Any request can go to any server, because all the information necessary to process the request is in the http request itself. This is also bad in that anything that you put in View State is transmitted to the client and back to the server. The network connection will almost certainly be the bottleneck for your application’s performance. The more data you send across the wire, the slower your application will be. It affects performance much more severely than processors, memory, or hard drive speed.

There are other mechanisms for storing state, of course, and I’ll be discussing those more in an upcoming post. The thing to consider here is that View State is very good for scalability, and very poor for performance. Since we want our applications to be both performant and scalable, how do we use View State? The answer, like many things in life, is to use moderation. Store small things in View State.

Consider a web page or control that has a customer property on it for a Customer object. I have seen too many times code like the following:

public partial class Example : System.Web.UI.Page
{
    public Customer CurrentCustomer
    {
        get
        {
            return ViewState["Customer"];
        }
        set
        {
            ViewState["Customer"] = value;
        }
    }
 
    protected void Page_Load(object sender, EventArgs e)
    {
        // ...
    }
}

If you’ve seen this code (or worse, written this code) and didn’t cringe, stop for a moment and think about what’s happening. That entire customer object is being serialized, encrypted, stored in a hidden field, transmitted to the client browser, transmitted back to the server, decrypted, and deserialized. Much better to see something like this:

public partial class Example : System.Web.UI.Page
{
    public Customer CurrentCustomer
    {
        get
        {
            int customerId;
            if (int.TryParse(Convert.ToString(ViewState["CustomerId"]), out customerId))
            {
                return ServiceProvider.GetCustomerFromDatabase(customerId);
            }
            return null;
        }
        set
        {
            ServiceProvider.SetCustomerInDatabase(value);
            ViewState["CustomerId"] = value.CustomerId;
        }
    }
 
    protected void Page_Load(object sender, EventArgs e)
    {
        // ...
    }
}

Only the id is stored in ViewState, and those 4 bytes don’t take much time to transmit back and forth. Hitting the database is infinitely preferable to transmitting that object to the client and back, besides the obvious ability to cache objects, which is a discussion for another post.

So when you have some data that you will need to access when the page posts back, View State can be an excellent, viable choice. Simply stop to consider the underpinnings of what you are doing. Just because something is done under the covers doesn’t mean it isn’t done, and just because it’s being done for you doesn’t mean you shouldn’t understand what’s it’s doing.

In part 2, we discuss Session State.

Advertisements

Tagged: , , , , ,

§ One Response to State – Part 1 (View State)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

What’s this?

You are currently reading State – Part 1 (View State) at Mike Vallotton's Blog.

meta

%d bloggers like this: