Click here to Skip to main content
13,349,539 members (47,903 online)
Click here to Skip to main content
Add your own
alternative version


27 bookmarked
Posted 27 Jun 2007

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.


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.


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


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 :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
            Dim viewState As String = Request.Form("__VSTATE")
            Return SerialX.DeSerialize(viewState)
            Return Nothing
        End Try

    End Function

    Protected Overrides Sub SavePageStateToPersistenceMedium(ByVal viewState As Object)
            RegisterHiddenField("__VSTATE", SerialX.Serialize(viewState))
            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 useSecurity Indicated to:
ViewState normal: GoodBad (binary) NoneUse low Data LowForms with low controls, Grids with paging
Serializer normal: GoodBad (binary)Good Mid proposes Moderate Grids with Viewstate turned On Without paging
Serializer optimized: RegularRegularRegularGrand 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.


  • 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


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


About the Author

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

You may also be interested in...

Comments and Discussions

QuestionProblem with GridView inside FormView Pin
sv20083-Feb-08 6:52
membersv20083-Feb-08 6:52 
GeneralRe: Problem with GridView inside FormView Pin
Manuel Soler (ModMa)4-Feb-08 4:53
memberManuel Soler (ModMa)4-Feb-08 4:53 
GeneralRe: Problem with GridView inside FormView Pin
sv200810-Feb-08 12:04
membersv200810-Feb-08 12:04 
GeneralRe: Problem with GridView inside FormView Pin
Manuel Soler (ModMa)22-Feb-08 14:10
memberManuel Soler (ModMa)22-Feb-08 14:10 
Newsnext version soon... Pin
Manuel Soler (ModMa)18-Jul-08 1:12
memberManuel Soler (ModMa)18-Jul-08 1:12 
GeneralRe: next version soon... Pin
alhambra-eidos26-May-09 4:14
memberalhambra-eidos26-May-09 4:14 
GeneralRe: next version soon... Pin
ModMa26-May-09 8:21
memberModMa26-May-09 8:21 
GeneralRe: next version soon... Pin
ModMa27-Sep-09 1:01
memberModMa27-Sep-09 1:01 
GeneralThanks !!! Pin
alhambra-eidos27-Sep-09 21:01
memberalhambra-eidos27-Sep-09 21:01 

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

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

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