Click here to Skip to main content
6,595,854 members and growing! (19,636 online)
Email Password   helpLost your password?
Web Development » ASP.NET » General     Advanced License: The Code Project Open License (CPOL)

ViewState Serializer, Compressor & Encrypter

By ModMa

It's a very complete and robust processor of ViewState, it allows: to select the way of serialization, compression and encryption optionally.
C# (C# 2.0), VB (VB 7.x), Windows, .NET (.NET 1.1, .NET 2.0), ASP.NET, Ajax, IIS 5.1, IIS 6, VS.NET2003, VS2005, Dev
Version:4 (See All)
Posted:27 Jun 2007
Updated:26 Sep 2009
Views:12,144
Bookmarked:20 times
Announcements
Loading...
 
Search    
Advanced Search
Add to IE Search
printPrint   add Share
      Discuss Discuss   Broken Article?Report  
8 votes for this article.
Popularity: 2.38 Rating: 2.63 out of 5
2 votes, 25.0%
1
2 votes, 25.0%
2

3
1 vote, 12.5%
4
3 votes, 37.5%
5

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 :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)

About the Author

ModMa


Member
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

In this moments I work in the projects Ficres Netherlands & Ficres France
Occupation: Web Developer
Company: TecnoConsulting
Location: Spain Spain

Other popular ASP.NET articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 9 of 9 (Total in Forum: 9) (Refresh)FirstPrevNext
QuestionProblem with GridView inside FormView Pinmembersv20086:52 3 Feb '08  
GeneralRe: Problem with GridView inside FormView PinmemberManuel Soler (ModMa)4:53 4 Feb '08  
GeneralRe: Problem with GridView inside FormView Pinmembersv200812:04 10 Feb '08  
GeneralRe: Problem with GridView inside FormView PinmemberManuel Soler (ModMa)14:10 22 Feb '08  
Newsnext version soon... PinmemberManuel Soler (ModMa)1:12 18 Jul '08  
GeneralRe: next version soon... Pinmemberalhambra-eidos4:14 26 May '09  
GeneralRe: next version soon... PinmemberModMa8:21 26 May '09  
GeneralRe: next version soon... PinmemberModMa1:01 27 Sep '09  
GeneralThanks !!! Pinmemberalhambra-eidos21:01 27 Sep '09  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 26 Sep 2009
Editor: Deeksha Shenoy
Copyright 2007 by ModMa
Everything else Copyright © CodeProject, 1999-2009
Web13 | Advertise on the Code Project