Review of the page state storage mechanism
As you probably know by default page state is saved in the hidden field named __VIEWSTATE. If page state is relatively large, it will cause slow response from application. So developers often think of keeping it outside the page. ASP.NET provides us with a possibility to do it without need to write a lot of code, using SessionPageStatePersister class. Both SessionPageStatePersister and HiddenFieldPageStatePesister which is used by default are derived from the PageStatePersister abstract class and have Load and Save methods, which do all the job for us. Adaptive rendering mechanism must be used with SessionPageStatePersister, and you can very easily save states of all pages of your site in the Session. Later in this article I will describe how it can be done. If you prefer keeping the page state in other storage but not the Session, you are still able to do it, but in this case you must write the whole code for saving and loading page state by yourself. For example, another class derived from PageStatePersister can be created for this purpose which can also be used in conjunction with adaptive rendering. But if you don't want to use Page Adapters and .browser files just for the sake of page state server side storage you can solve the task in other ways. Page class has protected virtual property - PageStatePersister:
protected virtual System.Web.UI.PageStatePersister PageStatePersister
{
get
{
if (this._persister == null)
{
System.Web.UI.Adapters.PageAdapter pageAdapter = this.PageAdapter;
if (pageAdapter != null)
{
this._persister = pageAdapter.GetStatePersister();
}
if (this._persister == null)
{
this._persister = new HiddenFieldPageStatePersister(this);
}
}
return this._persister;
}
}
Further, two virtual protected methods of the Page class: SavePageStateToPersistenceMedium and LoadPageStateFromPersistenceMedium use this property to get PageStatePersister object and call its Save and Load methods:
protected internal virtual void SavePageStateToPersistenceMedium(object state)
{
System.Web.UI.PageStatePersister pageStatePersister = this.PageStatePersister;
.
.
.
}
protected internal virtual object LoadPageStateFromPersistenceMedium()
{
System.Web.UI.PageStatePersister pageStatePersister = this.PageStatePersister;
.
.
.
}
So, without use of adaptive rendering we can override PageStatePersister property and it will return an object of our own class, derived from PageStatePersister, or we can directly override SavePageStateToPersistenceMedium and LoadPageStateFromPersistenceMedium without creating subclass of PageStatePersister.
We see several ways of changing default behavior and even one ready-made class SessionPageStatePersister by using which storing and retrieving of the page state outside the page can be achieved by writing just a few lines of code. But why page state default storage is a hidden field? Are there any drawbacks related to storing page state on the server? Why the only ready alternative to hidden field which exists in ASP.NET is intended to be used in the context of adaptive rendering? Let's try to find answers on these questions.
HistorySize
So, we choose to store pages' states on the server, now while saving current page's state, should we overwrite the previously saved data if it belongs to another page which was requested by the same user, or keep it together with the current state? Of course, we would prefer not to keep but replace previous page's state with the state of the current one. Otherwise, during user's navigation through our site we'll use more and more server resources.
But will our application work properly if we keep only one page data per user at a time? There are two rather typical scenarios below for which the answer is no.
Scenario A. User navigated through different pages of your application and the pages were kept in the browser's cache, and now the user returns to one of the previously requested pages by clicking Back button and submits the page.
Scenario B. User requested a page, then, while keeping it open, he requested another page in a new tab or window of the browser. He can do so several times. As in the first scenario after working with new pages user decides to return to one of the previous pages and submits it. (Though, if frames are used, the same effect can be achieved within one tab or window, I don't concentrate attention on this option, because it's up to you not to use frames, if you see some drawbacks.)
If you write an application for the corporate usage, you can try to persuade the client that your site should not be used in these ways. It will be good if he agrees. But if he doesn't or if you write public but not corporate web site which is intended to be used by anyone, you'll have to save the states of many or even all pages requested within the current session during the whole lifetime of the session, even if most of the data will never be used. And keep in mind that after the processing of the last request in the session is completed all the data will still be kept for some time (the minimum is HttpSessionState's Timeout - HttpServerUtility's ScriptTimeout, which is equal to 18 min. 10 sec. for their default values).
So you'll have to spend a lot of resources on the server. What you can do is to restrict number of pages for which you'll keep state data, supposing that in practice large number will hardly be needed. By the way, this is what is done in SessionPageStatePersister class. It reads SessionPageState section from the configuration file and uses the value of its HistorySize property.
<system.web>
<sessionPageState historySize ="7"/>
</system.web>
If you don't provide SessionPageState section in web.config, 9 will be applied as this limit.
If we keep page state in the Session, there will be additional drawback.
Let's return to the second scenario and consider its variation, when user makes another request while your server side code is still processing previous request(s) from this user. We'll have parallel access to the Session object from different threads. Http module, named SessionStateModule, which manages everything related to Session, takes into consideration such a possibility which may occur not only in the case described above. To avoid collisions SessionStateModule tries to apply writer lock on the session state and only then it creates the copy of session state for the current thread. If session state is already locked by another request, code of the SessionStateModule, working for the current thread, polls the session's data store to check whether or not it's still locked and also to check if the blocking thread exceeds request execution timeout (HttpServerUtility's ScriptTimeout, which is equivalent to ExecutionTimeout property of HttpRuntime configuration section). In this case it releases the lock applied by another thread. This locking mechanism obviously affects performance and also means that requests within the same session cannot be processed simultaneously, even if requests are handled on different processors of the same computer or different computers. We can optimize our application in cases where some of its pages only need to read data from Session, or even they need neither reading nor writing. There is EnableSessionState property in Pages section in configuration file and in Page directives of .aspx files.
<%@ Page Language="C#" EnableSessionState="ReadOnly" ...
Its default value is true and it causes the above situation. For pages which only read data from Session object we should set EnableSessionState="ReadOnly" in order SessionStateModule applies reader lock so other threads, which don't need to write in the Session, won't be blocked. For pages where we don't use Session object at all we can set EnableSessionState="False", so any other threads won't be blocked.
Now let's return to our main subject. If we save page state in the Session object, we have to always set EnableSessionState="true" ...
Let's consider alternative ways to keep page state in the server.
Besides Session there are several other built-in options to store it in the server memory: Cache, Application state or static data in the Global.asax (based on information from that file ASP.NET will generate a class derived from HttpApplication).
Also, we can store page state in files. Doing so, we won't spend server memory, which is more valuable resource than hard drive space. But I think you'll agree that working with files instead of memory we decrease performance.
Finally we can implement page state storage in a way which utilizes both memory and hard drive. For example, previous pages' states can be kept in files but the current state - in the memory. Indeed, with ASP.NET we do not write simply static pages with hyperlinks, instead each our page has a UI and if a user has requested the page we can expect that he will work with it for some time and we'll receive postbacks, so they will be processed faster if the page state is cached in memory buffer. But when a user requests another page we can suppose that the previous one won't be needed in the nearest future, so we can flush its data on the hard drive thus reducing memory usage.
There is an additional common task for all the methods which do not use Session.
Let's remember that after processing of the last request within the session is completed all the data will still be kept for some time. If it is kept in the session state, it will be automatically deleted with all other data in the session after its expiration. But when page state is kept outside the Session it is our responsibility to make a clean up, when a session is expired. Doing cleanup in the Session_OnEnd event handler can be a good solution, but unfortunately we are able to do it only when session state mode is "InProc". InProcSessionStateStore provider stores session state in Cache, and when adding item to Cache it is possible to specify CacheItemRemovedCallback method to be called when the item is removed. But if we use another SessionStateStore provider, Cache object and its possibilities won't be utilized, Session_End event won't be raised and we will have to implement a custom solution for our cleanup task.
In which situations shall we use not "InProc" session state mode but "StateServer" or "SqlServer" in spite of the fact that "InProc" mode has the best performance?
-
When we must be sure that data in the Session won't be lost whatever happens to ASP.Net process.
-
If we want to make web site more robust we can use Web-Garden mode in which multiple ASP.Net processes are assigned to your web site. So if there are problems with any of the ASP.Net processes, other processes will still keep your site in a working state. The drawback is because requests within the same session can be handled by different processes we can't use InProcSessionStateStore provider.
-
And, in my opinion most important case is creating an application which is able to work in Web Farm. It is a group of servers that act as a single web server. This mode gives us a lot of benefits but with some cost. Again we'll have several ASP.Net processes. Though it is possible to attach all requests within the session to the same computer (having configured single server affinity from the Network Load Balancing Manager) it can cause an overloading of some servers in the Farm. But if we don't use server affinity, we can't use "InProc" session state mode.
A more complicated cleanup task is not the main issue for Web Garden or Web Farm without server affinity. Where shall we keep page states? Only file system storage can be easily implemented among the mentioned alternatives to Session. Each ASP.Net process has its own instances of Cache, Application State and Application's static data. If for Session we can choose OutOfProcSessionStateStore or SqlSessionStateStore providers but for Cache, Application state and Application's static data ASP.Net doesn't give us a similar possibility. So if requests within the session are handled by different processors/computers and we want to keep page state not in files but in the memory we have to implement our custom solution or use Session in spite of locking. As we can see there is a reason for which the only ready alternative to HiddenFieldPageStatePesister is SessionPageStatePersister.
And locking is not the only thing which we must tolerate using Session in these scenarios.
If Session is stored inside the process we have no need to serialize/deserialize the data in the Session including page state. This is an advantage as compared with keeping page state in the hidden field where it must be serialized. But if we must configure Session state so that it will be stored outside the process all data in the Session including our page state will be serialized and deserialized.
As it was discussed earlier we must keep states of many pages, requested within the current session (9 by default). And as in case of Web Farm the Session state is located on another computer all this (probably redundant) data will be transferred across the network for each request during AcquireRequestState and ReleaseRequestState. And if Session is locked, polling mentioned above will also be done across the network.
SessionPageStatePersister
Now we can see that if we want to keep page state on the server, a lot of things must be taken into consideration, and making an efficient server side page state storage mechanism, suitable for many situations, is not a trivial task.
There is only one case, for which it is written in MSDN about changing default storage of the page state: "In scenarios where pages are served to small devices that have limited client-side resources or use a markup language that does not support a hidden field element, it is required to store view state on the server." That's why the only existing alternative to HiddenFieldPageStatePesister is designed to be used as a part of adaptive rendering. By the way, the quote above is taken from MSDN article, describing SessionPageStatePersister class: http://msdn.microsoft.com/en-us/library/system.web.ui.sessionpagestatepersister.aspx
Detailed discussion of adaptive behavior is beyond the scope of this article, I'll just write what must be done for our purpose.
-
Create class, derived from PageAdapter , and override its GetStatePersister property, to return an object of SessionPageStatePersister, instead of HiddenFieldPageStatePersister, used by default. Here is an example:
public class SessionPageStateAdapter : System.Web.UI.Adapters.PageAdapter
{
public override PageStatePersister GetStatePersister()
{
return new System.Web.UI.SessionPageStatePersister(this.Page);
}
}
<browsers>
<browser refID="Default">
<controlAdapters>
<adapter controlType="System.Web.UI.Page"
adapterType="<Your Namspace>.SessionPageStateAdapter" />
</controlAdapters>
<capabilities>
<capability name="RequiresControlStateInSession" value="true" />
</capabilities>
</browser>
</browsers>
That is all. Now states for all our pages will be kept in the Session instead of hidden fields.
One Notice. As you should know, begining from the second version of ASP.NET page state is divided into two parts which however are kept together. These parts are ViewState and ControlState. The first, as earlier, is a collection, where you can save data, second is used by controls. SessionPageStatePersister's Save method checks RequiresControlStateInSession property of HttpBrowserCapabilities or MobileCapabilities object, available from the Request's Browser property and only if it is true, save ControlState together with ViewState. Therefore it is needed to set RequiresControlStateInSession to true in the .browser file (<browsercaps> section in web.config also can be used but it is considered deprecated), otherwise only your ViewState collection will be saved, but controls on the page may not work properly. That's why adaptive rendering mechanism must be used together with SessionPageStatePersister. Or you can reverse engineer SessionPageStatePersister, change a small block of code, related to RequiresControlStateInSession, in the Save method and use the class in your projects. Below is the code, generated by Lutz Roeder's Reflector. Relevant part is marked red.
public override void Save()
{
bool x = false;
object y = null;
Triplet viewState = base.ViewState as Triplet;
if ((base.ControlState != null) || ((((viewState == null) || (viewState.Second != null)) ||
(viewState.Third != null)) && (base.ViewState != null)))
{
HttpSessionState session = base.Page.Session;
string str = Convert.ToString(DateTime.Now.Ticks, 0x10);
object obj3 = null;
x = base.Page.Request.Browser.RequiresControlStateInSession;
if (x)
{
obj3 = new Pair(base.ViewState, base.ControlState);
y = str;
}
else
{
obj3 = base.ViewState;
y = new Pair(str, base.ControlState);
}
string str2 = "__SESSIONVIEWSTATE" + str;
session[str2] = obj3;
Queue queue = session["__VIEWSTATEQUEUE"] as Queue;
if (queue == null)
{
queue = new Queue();
session["__VIEWSTATEQUEUE"] = queue;
}
queue.Enqueue(str2);
SessionPageStateSection sessionPageState =
RuntimeConfig.GetConfig(base.Page.Request.Context).SessionPageState;
int count = queue.Count;
if (((sessionPageState != null) && (count > sessionPageState.HistorySize)) ||
((sessionPageState == null) && (count > 9)))
{
string name = (string) queue.Dequeue();
session.Remove(name);
}
}
if (y != null)
{
base.Page.ClientState = Util.SerializeWithAssert(base.StateFormatter, new Pair(x, y));
}
}
Besides the scenario described in MSDN the case, when it is worth to keep page state on the server and it can be done without much effort, is the following:
- There are only a few pages with large state in our application and we implement server side page state storage only for these pages but not for all pages of the site. So the issue mentioned in HistorySize section won't have a big practical importance.
- All requests within a session are handled by the same ASP.Net process (no matter whether it is the only one or not). In this case we can use any in-memory alternative to Session listed above, for example Cache, and make cleanup in the Session_OnEnd event handler. By the way, sources of SessionPageStatePersister with small changes can be used and that will significantly ease solving our task.