Tales from the trenches: ASP.Net ViewState bug


This post is part of a series of actual problems or bad practices I encountered working on existing C# code bases.

The names of all identifiers, the exact functionalities of the programs and the code samples have all been altered for confidentiality reasons.

While looking into a slow ASP.Net page I noticed that the page was making a lot more service calls than it should have. Visually I could see superfluous calls that should have been merged together.

I profiled the page with the Performance Tools in Visual Studio and also put breakpoints on all service calls and ran it in Debug mode.

One thing that stood out was one property that was supposed to be using ViewState to prevent calls to the service layer but actually wasn’t.

It went something like this :

public int Somevalue 
{
    get 
    {
        if (ViewState["SomeValue"] == null)
        {
            var foo =
            ValueService.GetSomeValue(Convert.ToInt32
                (Request["SomeValue"]));

            ViewState["SomeValue"] = foo;
        }
        
        return (int)ViewState["SomeValue"];
    }
    set 
    {
        ViewState["SomeValue"] = value;
    }
}

// ...

protected override void OnInit(EventArgs e)
{
    int x = SomeValue;	// contrived example
}

I noticed that ValueService.GetSomeValue was getting called on PostBacks. Looking at where it was used, I saw it was being called in the OnInit method. It just so happens that during the OnInit phase of the ASP.Net page life cycle, the ViewState hasn’t be loaded with it’s values. This effectively means that SomeValue will always be null in the OnInit phase and it will have to make a service call every time.

The solution in this case was simply to move the call to a later stage of the page life cycle, in this case the PageLoad event.

The take away from this is to be mindful of the ASP.Net page life cycle events. Also putting breakpoints on service calls while loading the page and submitting the form is a quick way to see if something is amiss with your service calls.

2 thoughts on “Tales from the trenches: ASP.Net ViewState bug

    1. I would prefer to be doing React, Angular or MVC but it’s still a very nice project on an excellet contract.

      Besides, as I grow older, I’m beginning to get less fussy about what technology is used on a project.

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