Click here to Skip to main content
Click here to Skip to main content

ViewState Serializer, Compressor & Encrypter

, 26 Sep 2009
Rate this:
Please Sign up or sign in to vote.
It's a very complete and robust processor of ViewState, it allows: to select the way of serialization, compression and encryption optionally.

Introduction

People get frustrated when they see that in their forms, the ViewState is enormous and consumes a bandwidth of madness when being filled with styles, controls, Grids, which results in  very long post time at the client. There are many solutions here, from a simple compressor to a storage in Session/Cache.

This code makes work easy, but it is a unique one for a special form: it uses a special serializer to work with binary data.

A point that will interest you is the deficient scope security system of the ViewState. If it is possible to encrypt using a server key, but there are documents that say in a same server with 2 stores online, encrypted ViewStates can be used to cause frauds in the sale of products, the special method with easy code can make a unique key by session difficult to break.

Background

The lite portion of code is based on a simple ViewState compressor: ViewStateCompression.

The compression engine uses the ICSharpCode SharpZipLib.

This code has only been tested in VB 7.1 (VS2003) not in VS2005 platform.

Using the Code

I will not be centered in the class due to lack of time (I will do it), but will explain its conditions of use: (a wonderful way to learn how the code works is by taking a look at the demo;) )

The class can be used in 2 modes: inheritance and a class declaration. I recommend using the inheritance mode, as it is the easiest way.

The inheritance mode is simple, replace:

Public Class formTest1
    Inherits System.Web.UI.Page
    ... 

with:

Public Class formTest1
    Inherits ViewStateSerializer 
    ...

and simply configure in Page_Load:

SetViewStateValues(EnCrypt As Boolean, Optimize As Boolean)
  • EnCrypt: If is True, turns on the Encryption algorithms, a random seed & key for each session will be created.
  • Optimize: If is True, turns on the algorithm of Binary Serialization, larger than the other option, but you can add a large DataTable for example in ViewState. The standard deserializer of .NET hands up the server in large DataTables, not this Big Grin | :-D
    Private Sub Page_Load(ByVal sender As System.Object, _
	ByVal e As System.EventArgs) Handles MyBase.Load

        Response.Expires = -1 'important ?!

        If Not IsPostBack Then
             SetViewStateValues(True, False) 'Configuration HERE ! 
         ...
        End If 
    ...
    End Sub 

The second way is to simply place the code in any location of the Form class. The constructor format is the same as SetViewStateValues:

#Region "Overrides Page: Compression / ViewState Cryptography"

    Dim SerialX As New TurboSerializer(True, False)

    Protected Overrides Function LoadPageStateFromPersistenceMedium() As Object
        Try
            Dim viewState As String = Request.Form("__VSTATE")
            Return SerialX.DeSerialize(viewState)
        Catch
            ...
            Return Nothing
        End Try

    End Function

    Protected Overrides Sub SavePageStateToPersistenceMedium(ByVal viewState As Object)
        Try
            RegisterHiddenField("__VSTATE", SerialX.Serialize(viewState))
        Catch
            ...
            RegisterHiddenField("__VSTATE", String.Empty)
        End Try
    End Sub

#End Region

Points of Interest

You can use deferent configurations in forms but, please use in the Init configuration constant parameters in the same form to prevent browser cache failures (Response.Expires = -1).

Now I write a table to help you to select a ViewState mode that you can use according to your necessities:

Serialization Deserialization Compression Amount of Data to use Security Indicated to:
ViewState normal: Good Bad (binary) None Use low Data Low Forms with low controls, Grids with paging
Serializer normal: Good Bad (binary) Good Mid proposes Moderate Grids with Viewstate turned On Without paging
Serializer optimized: Regular Regular Regular Grand Data (DataTable) Moderate ViewState with DataTables & Grids with paging or without the ViewState turned off

Notes About the Sharp VS2005 Version

This version uses the native compression of VS2005 (no need for SharpZipLib).

The encryption now uses two levels of security, that generate two types of keys (the low mode uses a pseudo-random 3 times at day for updatable keys for all sessions, the high one is the old mode).

V1.1 of this version is compatible with Microsoft Ajax & Microsoft Ajax Control Toolkit (the only one?).

NOTE: This uses a lot of hacks to do it. To do work, see how calls to the code in the overrides section are totally different from the VB 7.x version.

The Optimized mode is hardly tested. I don't check if it works correctly in all cases.

About Version 1.3

This new version uses a new option to select the MachineKey encryption. No need anymore to set ViewStateEncryptionMode="Never"; CompressPage() now works in Ajax and more optimized De/Serialization.

About Version 1.2

This new version uses a new API to manage the load & save of ViewState. Now it is more compatible with FW 2.0 & Ajax; please see the annotation code of V1.2 for more information & usage!

Remember that in this version, you must check if ViewStateEncryptionMode="Never" is set to the engine that can compress the ViewState data (encrypting makes a aleatory data that the engine can't compress it!)
If you use the code to compress all pages, you're warned that in Microsoft Ajax, the method response.filter (Async Postback) does not work.

History

  • 09/26/2009: Posted the v1.3 Public Sharp VS2005 version (now uses a new option to select the MachineKey encryption; uses more Reflection to access in .NET Serialization API, this point is more optimized than the older version)
  • 07/28/2008: Posted the v1.2 Public Sharp VS2005 version (now uses PageStatePersister: more easy, compatible & can use a PageAdapter)
  • 01-12-2008: Posted the v1.1 Public Sharp VS2005 version (Microsoft Ajax support)
  • 08-30-2007: Posted the v1.0 Public Sharp VS2005 version
  • 06-27-2007: Posted the v1.0 Public version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

ModMa
Architect Sermicro
Spain Spain
My life in programming has been long, begins from the 6 years of age with Basic, I have knowledge of C++, Javascript, ASP .NET, Cisco CCNA, among others.
 
One of my pastimes in the programming, is cryptology and systems security
 
One of my recognized works is P2PFire, other smaller projects like utilities for Chats
Follow on   LinkedIn

Comments and Discussions

 
QuestionProblem with GridView inside FormView Pinmembersv20083-Feb-08 5:52 
GeneralRe: Problem with GridView inside FormView PinmemberManuel Soler (ModMa)4-Feb-08 3:53 
GeneralRe: Problem with GridView inside FormView Pinmembersv200810-Feb-08 11:04 
GeneralRe: Problem with GridView inside FormView PinmemberManuel Soler (ModMa)22-Feb-08 13:10 
Newsnext version soon... PinmemberManuel Soler (ModMa)18-Jul-08 0:12 
GeneralRe: next version soon... Pinmemberalhambra-eidos26-May-09 3:14 
GeneralRe: next version soon... PinmemberModMa26-May-09 7:21 
GeneralRe: next version soon... PinmemberModMa27-Sep-09 0:01 
GeneralThanks !!! Pinmemberalhambra-eidos27-Sep-09 20:01 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web03 | 2.8.140902.1 | Last Updated 26 Sep 2009
Article Copyright 2007 by ModMa
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid