Store View State in a Persistent Medium, the Proper Way
page 1 of 6
Published: 26 Jun 2006
Unedited - Community Contributed
Abstract
In this article Bilal Haidar shows you how to properly store ASP.NET page's View State into a persistent medium, as an improvement to Scott Micthell's article on MSDN, Understanding ASP.NET View State.
by Bilal Haidar
Feedback
Average Rating: This article has not yet been rated.
Views (Total / Last 10 Days): 66431/ 570

Introduction

In his article, Understanding ASP.NET View State, Scott presented a section about storing the ASP.NET view state into a persistent medium, instead of storing it in the page itself.  He used the system file system, mainly a simple text file to store the page’s view state.  However, Scott did mention a few weaknesses in his approach and proposed some ideas on how to improve his method.

The following is quoted from Scott Mitchell’s article.

"There are two main challenges with this approach:

1.      Coming up with an acceptable file naming scheme.  Since the view state for a page will likely vary based on the user's interactions with the page, the stored view state must be unique for each user and for each page.

2.      Removing the view state files from the file system when they are no longer needed."

To tackle the first challenge, we will name the persisted view state file based on the user's SessionID and the page's URL.  This approach will work beautifully for all users whose browsers accept session-level cookies.  Those that do not accept cookies, however, will have a unique session ID generated for them on each page visit, thereby making this naming technique unworkable for them.  For this article I am just going to demonstrate using the SessionID / URL file name scheme, although it will not work for those whose browsers are configured not to accept cookies.  Also, it will not work for a Web farm unless all servers store the view state files to a centralized location.

Note: One workaround would be to use a globally unique identifier (GUID) as the file name for the persisted view state, saving this GUID in a hidden form field on the ASP.NET Web page.  This approach, unfortunately, would take quite a bit more effort than using the SessionID / URL scheme, since it involves injecting a hidden form field into the Web Form.  For that reason, I will stick to illustrating the simpler approach for this article.

The second challenge arises because each time a user visits a different page, a new file holding that page's view state will be created.  Over time this will lead to thousands of files.  Some sort of automated task would be needed to periodically clean out the view state files older than a certain date.  I leave this as an exercise for the reader.

In this article we are going to improve the method presented by Scott.  The improvement will include the following two sections.

First, we will use a GUID to name the text file used to store the view state.  This GUID will be generated per page and stored in a hidden field inside the page.

Second, we will be adding a semi-scheduler for deleting the view state files based on a certain threshold that we can control by having a key inside the Web.config.


View Entire Article

User Comments

Title: Great Article   
Name: Clever Name
Date: 3/30/2012 12:33:16 PM
Comment:
I used your method and it worked great. About a month later someone told me about Page Adapters. Instead of using the default HiddenFieldPageStatePersister you can use a SessionPageStatePersister or develop your own Persister.
While the way listed in the article works using this way probably is better.

http://msdn.microsoft.com/en-us/library/system.web.ui.sessionpagestatepersister.aspx
Title: Cleanup Viewstate Files on Session End   
Name: Mariner
Date: 10/14/2010 12:14:38 PM
Comment:
I like the cleanup file method that you are doing, however, I am not looking for a cleanup method that deletes the files based on a timestamp, but rather on a session end.
The reason for this is there are thousands of users accessing the site daily and there will be many viewstate files as a result. It is time and memory consuming to keep the files around based on DateTime methods.

Thank you very much for your time.

Mariner
Title: HiddenField not populated on postback   
Name: M
Date: 10/5/2010 11:20:57 AM
Comment:
Hi I am trying to implement your idea in my project. However I have a problem whereby the HiddenField (vsKey) loses its value (the key GUID) when the page is posted back. Because of this the LoadPageStateFromPersistenceMedium function fails as it is returned a blank value from the vsKey HiddenField. Any ideas on this?

Your time is much appreciated. M.
Title: Re: Rudolf   
Name: Bilal Haidar
Date: 6/11/2008 3:15:17 PM
Comment:
Hi Rudolf,
I am glad you liked my article!

Check the following links for compressing VS:
1. http://www.techtoolblog.com/archives/compressing-aspnet-20-viewstate

2. http://www.hanselman.com/blog/ZippingCompressingViewStateInASPNET.aspx

3. http://www.dotnetcurry.com/ShowArticle.aspx?ID=67&AspxAutoDetectCookieSupport=1


Hope they help!
Regards
Title: Viewstate with compresseion   
Name: Rudolf terppe
Date: 6/11/2008 2:59:47 PM
Comment:
Hi Bilal

A perfect articel
I installedand works well.
Do you have an Idea to include compression of Viewstate?

Rudolf terppe from Germany
Title: * shudder *   
Name: foobar
Date: 7/29/2006 11:17:25 PM
Comment:
There are far better ways to do this.

Go here: http://msdn2.microsoft.com/en-us/library/system.web.ui.pagestatepersister.aspx
Title: Checking for the deletion of files on every postback is bad   
Name: Shoaib
Date: 7/29/2006 10:31:46 AM
Comment:
I completely agree with Kevin.

Looping through the files for deletion on every postback is bad idea. I suggest you to create a separate service for that purpose and if you have any problem working with the services, then u should use some folder hierarchy to store files like:

Year/Month/Day

so that u can delete all the folders except the one created today.
Title: Feedback on Above article   
Name: Kishore
Date: 7/22/2006 8:14:20 AM
Comment:
The technique used in above article is very good but clean up files procedure is calling whenever request comes from client. I think to suggest/adopt other way around.
Title: Re:   
Name: Bilal Haidar
Date: 7/19/2006 10:04:14 AM
Comment:
Keven : Marco:
Looks you two new ways which are nice too, in addition to this one.
Why don't I have a look at them both? bilal@bhaidar.net

Thanks.
Title: Don't rely on session or page to clean up files   
Name: Kevin
Date: 7/19/2006 10:00:35 AM
Comment:
I think it's a very bad idea to have the page look for files to clean up and then cross its fingers and start deleting.

I also think that relying on session events at all for this is a bad idea since part of the value of ViewState is not having to rely on session at all.

Instead, you should use an HTTPModule with a Threading Timer to look for files to delete every now and again. This way, you get great reliability and you don't loop through every freakin' persisted viewstate file on every page postback.
Title: Performance Improvement   
Name: Marco Dissel
Date: 7/19/2006 9:58:22 AM
Comment:
i've created i slightly different implementation:

- create GUID and store it in hidden field
- add viewstate to Cache with timespan of x minutes (no LosFormatter)
- setup delegate to cache deletion of the Cache item
- in delegate store viewstate from cache in file

on retrieval first check if viewstate still in Cache, if so return the viewstate and clear the cache for that item. If not fount load the viewstate form the file and delete the file..

Cleanup process can be done with some timer in another (new) thread..

What do you think of my approach?
Title: Atlas Ajax   
Name: dadvav
Date: 7/19/2006 2:53:53 AM
Comment:
Hi, I have problem with with Atlas toolkit. I think better solution to save Viewstate ID is to use original hidden field and not own vsKey
Title: Re:   
Name: Bilal Haidar
Date: 7/6/2006 12:33:07 PM
Comment:
I had several incidents where the Session_End was not fired on my machine, maybe because of VS or so, have no idea.

Thanks
Title: SessionEnd not fired   
Name: Alain
Date: 7/6/2006 10:58:19 AM
Comment:
The sessionEnd event is only fired if the sessions are managed "in process" (InProc param), but not if the sessions are manages out of process (ASP.NET State Service or SQL database)
Title: Re:   
Name: Bilal Haidar
Date: 6/29/2006 6:04:06 AM
Comment:
Hello:
I do use sometimes that method of having the CleanupFiles in the SessionEnd(). But sometimes it doesn't work!! Something goes wrong and the session end doesn't get fired!
That is why, to be on the safe side, I decided to place it there!

Thanks.
Title: Performance improvment   
Name: Pravin Singh
Date: 6/29/2006 5:52:39 AM
Comment:
I think it is better to move the function CleanupFiles() from LoadPageStateFromPersistenceMedium() to Session_End(). In Session_End() we can find all the files with file names having the Session ID assigned to the user whose session just ended and delete them all. Because right now CleanUp() function gets called on page load of all the web forms.
Title: New Approach in ASP .NET 2.0   
Name: Juan
Date: 6/27/2006 10:30:49 AM
Comment:
Check out a new article on MSDN at http://msdn.microsoft.com/msdnmag/issues/06/07/WebAppFollies/default.aspx#S4

.NET 2.0 offers an out-of-the-box way to save viewstate to session, then you could persist it in a database or in session server if you want to or just use the inproc session provider. Either way it manages the viewstate on the server for you.

Product Spotlight
Product Spotlight 





Community Advice: ASP | SQL | XML | Regular Expressions | Windows


©Copyright 1998-2014 ASPAlliance.com  |  Page Processed at 10/24/2014 2:58:11 AM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search