RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX


ASP.NET Simplifies State Management in Web Applications : Page 2

If you're tired of writing state management code in your Web applications, you'll be happy to know that ASP.NET not only greatly simplifies the process, but also solves some of the classic ASP Session object's problems, such as using Sessions with Web farms, and persisting state data.

Examining Viewstate
If you look at the Viewstate hidden field, it looks like the information has been encrypted; but it isn't. Viewstate is simply a string in Base64 encoding. To see what the Viewstate string contains, you need to decode it:

I have modified a simple routine (from MSDN help) to convert the Base64 encoding into a string value and write it into a text file as shown in the following code snippet.

   Dim str As String = 
      "dDwxNTgwOTQ2NjA3O3Q8O2w8aTwxPjs+O2" &  
     _"w8dDw7bDxpPDM+Oz47bDx0PHA8cDxsPFRleHQ7" & _
      "PjtsPFlvdSBoYXZlIGNob3NlbiBDIywgVkIuTk" & _
   Dim binaryData() As Byte
   binaryData = System.Convert.FromBase64String(str)
   Dim outFile As System.IO.FileStream
      outFile = New System.IO.FileStream("c:\output", _
      outFile.Write(binaryData, 0, binaryData.Length - 1)
   Catch exp As System.Exception
      System.Console.WriteLine("{0}", exp.Message)
   End Try
After the conversion, the string represented by Viewstate appears as:

      <Text;>;l<You have chosen C#, VB.NET;>>;>;;>;>>;>>;
Although the decoded string isn't in plain English, it's not too difficult to see the text contained in the Label control. This might pose a security risk as these values can be spoofed and modified. To prevent that, you can detect whether the user has modified the Viewstate value by forcing the ASP.NET framework to run a Machine Authentication Check (MAC) when the client posts the Viewstate back to the server. To do so, add an EnableViewStateMac attribute to the @Page directive in your aspx file.

   <%@ Page EnableViewStateMac="true" Language="vb" %>
Programming Viewstate
Most ASP.NET developers are aware of the existence of the Viewstate hidden field. But most are not aware that it is possible to programmatically manipulate the field, adding any values that you wish. For example, suppose you want to know the last time the Listbox item was selected. You can use the code similar to the following to save the current date and time to the Viewstate:

   Private Sub lstLanguages_SelectedIndexChanged( _
      ByVal sender As System.Object, ByVal e As _
      System.EventArgs) Handles 
      ViewState("lastChanged") = DateTime.Now
   End Sub
You can retrieve values you add to Viewstate, with code similar to the following:

   Response.Write("The Listbox was last changed at " & _

Close Icon
Thanks for your registration, follow us on our social networks to keep up-to-date