Home .NET Goodbye, ViewState – 2, or Put it in the Base!

Goodbye, ViewState – 2, or Put it in the Base!

by admin

Another round. the hard confrontation with ViewState. This time, let’s try saving it in the SQL Server database.Let’s reiterate the theory a little bit. We have a class PageAdapter , the use of which can "adapt" the aspx page to a certain browser(in our case, to all browsers).With this adapteryou can overridethe functionality for loading and saving the ViewState (using the method GetStatePersister ).
So, order of action :
– Create a simple structure in the databaseto store the ViewState:
Goodbye, ViewState - 2, or Put it in the Base!

We also create stored procedures to retrieve, save, and clear the (deprecated) ViewState;
– inherit class PageStatePersister , overriding the Load and Save methods to implement loading and saving the ViewState respectively :

namespace SqlStatePersister
{
public class SqlPageStatePersister:PageStatePersister
{
private Page Page;
public SqlPageStatePersister( Page page)
: base (page)
{
_page = page;
}
public override void Load()
{
// function to load and deserialize ViewState
}
public override void Save()
{
// function of ViewState serialization and saving
}
}
}
* This source code was highlighted with Source Code Highlighter

– we inherit the PageAdapter class, override the GetStatePersister method in it, so that it returns an instance of the classdefined in the first step :

namespace SqlStatePersister
{
public class SqlPageAdapter: PageAdapter
{
public override PageStatePersister GetStatePersister()
{
return new SqlPageStatePersister( Page );
}
}
}
* This source code was highlighted with Source Code Highlighter

– Using the .browserfile we "adapt" the page :

< browsers >
< browser refID ="Default" >
< controlAdapters >
< adapter controlType ="System.Web.UI.Page" adapterType ="SqlStatePersister.SqlPageAdapter" />
</ controlAdapters >
</ browser >
</ browsers >
* This source code was highlighted with Source Code Highlighter

– If you want, we can add some extra features, such as gzip-compression before saving to the database;
– Create a shell (for example, SQL Server Job), which will clean the table from obsolete ViewState;
– PROFIT!
In example (VS 2010 solution, .NET 4) uses the database AdventureWorks which replaced Northwind as an example. The app requires the ViewStateCompress setting in appSettings, which is set to 1 if gzip compression is needed, or 0 if not. In the section connectionStrings you also need a connection string to the database where ViewState will be stored (in my example it is a separate database, created by executing the install.sql script from the solushen).
Thank you for your attention! If you need more detailed comments on the project, I’m at your service 😉
P.S.Based on Store ViewState in the Database instead of Hidden Form Field and ViewState Compression

You may also like