Determining the ViewState Size

ViewState is one of the 3 way that used by ASP2.0 to retain state information about the web page. ViewState allows the state of objects (serializable) to be stored in a hidden field on the page. It is transported to the client and back to the server, and is not stored on the server or any other external source. I’m not going to go deep in to what is ViewState or how to use it. You can find more about ViewState here>>.

Since ViewState is kept in the webpage itself, it can become a performance bottleneck. If the ViewState is too large then the roundtrip delay for postback can increase significantly, especially if the user is having slow internet link. So it would be wonderful if we can find out the size of the ViewState during the testing phase of the application. So we can get relevant actions to improve the performance.

To do that create a class (I named it as MainPageBase) class that all the other pages in the application need to inherit. The code for the class is as shown below.

public class EmsBasePage : System.Web.UI.Page
{
/// <summary>
/// Get the page name of the current page.
/// </summary>
/// <returns></returns>
private string GetCurrentPageName()
{
string path = System.Web.HttpContext.Current.Request.Url.AbsolutePath;
if (!String.IsNullOrEmpty(path))
{
System.IO.FileInfo oInfo = new System.IO.FileInfo(path);
string name = oInfo.Name;
return name;
}
else
{
return "";
}

}

protected override void SavePageStateToPersistenceMedium(object state)
{
int viewStateSize = 0;

base.SavePageStateToPersistenceMedium(state);
LosFormatter format = new LosFormatter();
StringWriter writer = new StringWriter();
format.Serialize(writer, state);
viewStateSize = writer.ToString().Length;
string pageName = GetCurrentPageName();
HttpContext.Current.Trace.Warn(pageName + ": The ViewState Size is:", viewStateSize.ToString());
}
}

It writes the size of the ViewState to the Trace. To view the Trace you have to enable it first. To do that adds following line of code within the section in the web.config file.

<trace enabled="true" pageOutput="false" requestLimit="40" localOnly="false"/>

That’s all. Compile the code and do the testing of your application. Finally to view the results of what we did open the Trace viewer(Trace.axd page). For example http://yourApplicationroot/Trace.axd.

Technorati Tags: , ,
 

Reader Comments