De-Sludging ASP.NET Pages with PageAdapter

Introduction

You know what VIEWSTATE is? It’s that encrypted gobbley-gook in a hidden field that makes stateless web pages (in ASP.NET) keep track of a page for each user between round trips to the server. VIEWSTATE is what keeps track of the text you put in a TextBox. VIEWSTATE is what keeps track of events that need to fire. And, VIEWSTATE is a lot of scrambled eggs that goes back and forth between each client and your server (or servers).

By now, you have probably heard that one should disable VIEWSTATE in ASP.NET applications for static content or when you know you don’t need it. This is a tip for improving performance. For static web sites, this is a good tip. For dynamic websites—applications—VIEWSTATE is pretty hard to do without. However, this doesn’t mean you have to card it around with each page.

In this article, I will show you how to use VIEWSTATE but leave it on the server. The technique was introduced in ASP.NET 2.0. It’s a great technique, will significantly reduce the size of the rendered HTML returned to clients, still permit VIEWSTATE dependent behaviors to work, and make your web pages a little snappier.

Implementing a Custom PageAdapter

The web scales because each client gets its data and disconnects. Things such as Session ID, cookies, and VIEWSTATE help web servers figure out what to do when a page is posted back. Content-only (or content-mostly) sites like http://www.softconcepts.com don’t really need a lot of state information, so it can be turned off to improve performance a bit. Further, sites like mine can use page caching to get a little better performance.

By implementing a custom PageAdapter, you can use VIEWSTATE but ASP.NET will use the Session ID and automatically keep and track VIEWSTATE on the server for each user. Complex web applications with a lot of viewstate will render a little faster and run a little snappier. To implement, simply add a class with the code in Listing 1 to your web application (and you will need a .Browser file, covered in the next section.)

Listing 1: To use VIEWSTATE but leave it on the server, add a class file with the following code.

Imports Microsoft.VisualBasic

Public Class MyPageAdapter
   Inherits System.Web.UI.Adapters.PageAdapter

   Public Overrides Function GetStatePersister() _
      As System.Web.UI.PageStatePersister
      Return New  SessionPageStatePersister(Me.Page)
   End Function

End Class

Visual Studio will add the code in Listing 1 to the App_Code folder.

Adding a .Browser File to Your Website

Next, you need to tell your web application that you have added a PageAdapter. Select your web project, choose Add New Item, and select the Browser File applet (see Figure 1). Listing 2 shows the default content and the <controlAdapters> tag for MyPageAdapter.

Figure 1: An easy item to miss, adding a Browser File lets you tell your web application about PageAdapters.

Listing 2: The .browser file—it can be named anything—containing default information added by the template and the tags added used to load myPageAdapter.

<!--
   You can find existing browser definitions at
   <windir>\Microsoft.NET\Framework\<ver>\CONFIG\Browsers
-->
<browsers>
   <browser id="NewBrowser" parentID="Mozilla">
      <identification>
         <userAgent match="Unique User Agent Regular Expression" />
      </identification>

      <capture>
         <userAgent match="NewBrowser (?'version'\d+\.\d+)" />
      </capture>

      <capabilities>
         <capability name="browser" value="My New Browser" />
         <capability name="version" value="${version}" />
      </capabilities>
   </browser>

   <browser refID="Mozilla">
      <capabilities>
         <capability name="xml" value="true" />
      </capabilities>
   </browser>

   <browser refID="Default">
      <controlAdapters>
         <adapter controlType="System.Web.UI.Page"
                  adapterType="MyPageAdapter" />
      </controlAdapters>
   </browser>
</browsers>

Listing 3 contains some simple sample code. Comment out the XML in bold for MyPageAdapter, run the code, and view source. You will see the fairly large VIEWSTATE. Uncomment the code—remove the <!–  –> comment characters—and run the code again. View the source. You will see that the VIEWSTATE is almost all gone. (See Listing 3 for some demo code.)

Listing 3: Some sample code you can use to test you PageAdapter.

Imports System.Collections.Generic

Partial Class _Default
   Inherits System.Web.UI.Page

   Protected Sub Page_Load(ByVal sender As Object, _
      ByVal e As System.EventArgs) Handles Me.Load

      If (Not IsPostBack) Then Return

      Dim customers As List(Of Customer) = New List(Of Customer)

      Dim I As Integer

      For I = 1 To 100
         customers.Add(New Customer(I, "Customer" + I.ToString()))
      Next

      GridView1.DataSource = customers
      GridView1.DataBind()


   End Sub
End Class


Public Class Customer
   Private _iD As Integer
   Public Property ID() As Integer
      Get
         Return _iD
      End Get
      Set(ByVal Value As Integer)
         _iD = Value
      End Set
   End Property

   Private _name As String
   Public Property Name() As String
      Get
         Return _name
      End Get
      Set(ByVal Value As String)
         _name = Value
      End Set
   End Property

   ''' <summary>
   ''' Initializes a new instance of the Customer class.
   ''' </summary>
   ''' <param name="iD"></param>
   ''' <param name="name"></param>
   Public Sub New(ByVal iD As Integer, ByVal name As String)
      _iD = iD
      _name = name
   End Sub
End Class

Right-click on your browser and select View Source. Search for VIEWSTATE to see the radical change in the amount of VIEWSTATE information with and without the PageAdapter.

Summary

I am a firm believer in user groups, TechEd, reading, and other such activities. Because I write, it’s a little harder for me to find new things for me, but I do find them. Jeff Prosise demonstrated an implementation a PageAdapter and .Browser for ASP.NET 2.0 at TechEd 2007 in Orlando. (Jeff is one smooth presenter; if you get a chance, see him.) I hope you got to go. If not, try to make it next year.

About the Author

Paul Kimmel is the VB Today columnist for www.codeguru.com and has written several books on object oriented programming and .NET. Check out his new book UML DeMystified from McGraw-Hill/Osborne. Paul is an architect for Tri-State Hospital Supply Corporation. You may contact him for technology questions at pkimmel@softconcepts.com.

If you are interested in joining or sponsoring a .NET Users Group, check out www.glugnet.org.

Written by Paul Kimmel. pkimmel@softconcepts.com
Copyright © 2007. All Rights Reserved.

More by Author

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Must Read