View state persistence mechanism for ASP.net 2.0

Source: Internet
Author: User
Tags abstract base64 datetime tostring root directory
Asp.net| View

Objective

As long as you have a little understanding of viewstate, you will know that the ASP.net page viewstate is generally stored in a hidden field of the page:

When we look at the source of the page, we see a lot of clutter (especially when the page has a DataGrid with a lot of data, or a GridView in the asp.net2.0), that's viewstate.

Basic knowledge

Because of the new changes in the ViewState persistence storage mechanism in asp.net2.0, it's a simple introduction to the relevant things.

In the asp.net1.1, only provides the persistence mechanism of the page hidden field, so that in some cases you have to give up using ViewState, imagine if you have tens of thousands of records in your DataGrid (do not think that this kind of abnormal need is not, someone has met), if you enable ViewState, you feel sure you Can the IIS server withstand, the network to withstand the winner? Of course you can change your storage mechanism by rewriting the Page.savepagestatetopersistencemedium () method, but don't forget to rewrite Page.loadpagestatefrompersistencemedium (), They're a couple.

The default view state persistence mechanism in asp.net2.0 remains the state information as a BASE64 encoded string in a hidden HTML element on the page (an element with a Type property set to "hidden"). The ASP.net page performs this work using a Hiddenfieldpagestatepersister object and serializes and deserializes the object state information using a Istateformatter instance. Alternatively, for mobile clients with limited bandwidth and resources, you can also use the SessionPageStatePersister class to store the view state of the page in the session object on the server, but there is also a session persistence mechanism. Let's keep the page state in session, not in the page, which is a savings on bandwidth.

But if you want to delve into the ViewState persistence mechanism, the abstract class pagestatepersister you should know, to preserve view state on clients that cannot support existing view state persistence mechanisms, you can extend the PageStatePersister class, Introduce your own view state persistence method, and you can use the page adapter to configure the ASP.net application to use a different view state persistence mechanism depending on the type of client for which the page is provided. Classes derived from the PageStatePersister class must override the Save abstract method to store view state and control state in persistent media, while overriding the Load method to extract state information. If you need to serialize view state and control state to a string, you can use the Istateformatter object that is accessed through the Stateformatter property. It can efficiently serialize and deserialize object state information into BASE64 encoded strings. You can also rewrite the Stateformatter property to provide your own object state serialization mechanism, as described in my code, simple enough to see.

Persistence mechanism of ViewState

Hidden fields

This is not introduced, the default is this. As in the preface.

Session

In asp.net2.0, just rewrite the PageStatePersister property.

protected override PageStatePersister PageStatePersister
{
Get
{
return new SessionPageStatePersister (Page);
}
}

If you need to rewrite the loadpagestatefrompersistencemedium in asp.net1.1, the two methods are:

protected override Object LoadPageStateFromPersistenceMedium ()
{
return session["ViewState"];
}

protected override void Savepagestatetopersistencemedium (object viewState)
{
session["ViewState"] = ViewState;
RegisterHiddenField ("__viewstate", "");
}

Database (my example is SQL Server2000)

In the ASP1.1, please pay attention to the Purple Line below, I do not know what the use of it, it let me depressed for several days, and so you will understand my depressed. And the following code is just a copy of my source, you can not write, in addition to the necessary outside.

protected override void Savepagestatetopersistencemedium (object state)
{
String ViewStateID = "viewstate#" + Session.SessionID.ToString () + "#" + DateTime.Now.Ticks.ToString ();
Clientscript.registerhiddenfield ("__viewstate_key", ViewStateID);
Clientscript.registerhiddenfield ("__viewstate", "");//Please note

Try
{
if (LosFormatter = null)
{
LosFormatter = new LosFormatter ();
}
StringWriter SW = new StringWriter ();
Losformatter.serialize (SW, state);
Common.viewstatedata VSD = new Viewstatedata ();
Vsd. ViewStateID = ViewStateID;
Vsd. ViewState = SW. ToString ();
da = new DataAccess ();
String error = Da. SaveViewState (VSD);
Response.Write (Error);
}
catch (Exception ex)
{
Response.Write (ex. message);
}
}

protected override Object LoadPageStateFromPersistenceMedium ()
{
String viewState = String. Empty;
Try
{
if (LosFormatter = null)
{
LosFormatter = new LosFormatter ();
}
String Stateid = page.request["__viewstate_key"]. ToString ();
da = new DataAccess ();
ViewState = da. LoadViewState (Stateid);
}
Catch
{}

Return Losformatter.deserialize (viewState);
}

In the ASP2.0 this line of code is basically OK, why is basic, because is above that line Clientscript.registerhiddenfield ("__viewstate", "");

There is no this line, in the asp.net1.1 is feasible, I also refer to someone else's code, this line has joined, added this line, just in the page more than a

That is, there are two such things in the source file of the running page. Remove that line can also, so I do not understand the statement is used for what, please tell me. But not in the asp.net2.0, there are the following errors:

The state information was invalid for this page and might to be corrupted.

Anyway, it was a halo, and I've never met as a mistake before, go to Google also have no income, yes, kill me also don't know is that sentence wrong ah, so depressed for two days, the problem can not be solved, I was born dull, I tracked the view state of the database and from the database read the whole process, Can't find the wrong, I think about the code, but the line, I was a bit confused, why the page to register a "__viewstate" hidden field, so I commented out this line, incredibly can run, so I still do not understand what the purpose of the line.

Of course, we can also do this by writing a pagestatepersister new subclass, which is added by asp.net2.0:

Namespace PageAdapter
{
Using System;
Using System.IO;
Using System.Security.Permissions;
Using System.Web;
Using System.Web.UI;

[AspNetHostingPermission (SecurityAction.Demand, level = Aspnethostingpermissionlevel.minimal)]

public class Databasepagestatepersister:pagestatepersister
{
Public databasepagestatepersister (Page page): Base (page)
{}
//
Load ViewState and ControlState.
//
public override void Load ()
{
String viewState;
Istateformatter formatter = this. Stateformatter;
DataAccess da = new DataAccess ();
String Stateid = base. page.request["__viewstate_key"]. ToString ();
ViewState = da. LoadViewState (Stateid);
Pair Statepair = (Pair) formatter. Deserialize (viewState);
ViewState = Statepair.first;
ControlState = Statepair.second;
}
//
Persist any ViewState and controlstate.
//
public override void Save ()
{
if (ViewState!= null | | ControlState!= null)
{
if (page.session!= null)
{
String ViewStateID = "viewstate#" + base. Page.Session.SessionID.ToString () + "#" + DateTime.Now.Ticks.ToString ();
Base. Page.ClientScript.RegisterHiddenField ("__viewstate_key", ViewStateID);
Pair Statepair = new Pair (ViewState, controlstate);
Istateformatter formatter = this. Stateformatter;
Serialize the Statepair object to a string.

String serializedstate = Formatter. Serialize (Statepair);
Viewstatedata VSD = new Viewstatedata ();
Vsd. ViewStateID = ViewStateID;
Vsd. ViewState = serializedstate;
DataAccess da = new DataAccess ();
String error = Da. SaveViewState (VSD);
}
Else
throw new InvalidOperationException ("Session needed for streampagestatepersister.");
}
}
}

}

Then there is the rewrite PageStatePersister property:

protected override PageStatePersister PageStatePersister
{
Get
{
return new Databasepagestatepersister (Page);
}
File

This is not really the same as the database, I only speak asp.net2.0, in the asp.net1.1 should be similar, but I did not write code debugging:

Or the way to write PageStatePersister new subclasses:

Namespace Streampageadapter
{
Using System;
Using System.IO;
Using System.Security.Permissions;
Using System.Web;
Using System.Web.UI;

//
The StreamPageStatePersister is a example view state
Persistence mechanism that persists view and control
State on the WEB server.
//

[AspNetHostingPermission (SecurityAction.Demand, level = Aspnethostingpermissionlevel.minimal)]

public class Streampagestatepersister:pagestatepersister
{
Public streampagestatepersister (Page page): Base (page)
{}
//
Load ViewState and ControlState.
//

public override void Load ()
{
Stream statestream = Getsecurestream ();
Read the state string, using the Stateformatter.
StreamReader reader = new StreamReader (statestream);
Istateformatter formatter = this. Stateformatter;
String filecontents = reader. ReadToEnd ();   
//Deserilize Returns the Pair object is serialized in
//The Save method.
Pair Statepair = (Pair) formatter. Deserialize (filecontents);
ViewState = Statepair.first;
ControlState = Statepair.second;
Reader. Close ();
Statestream.close ();  
}
//
//Persist any ViewState and controlstate.
//

public override void Save ()
{
if (ViewState!= null | | ControlState!= null)
{
if (page.session!= null)
{
Stream Statestream = Getsecurestream ();
StreamWriter writer = new StreamWriter (Statestream);
Istateformatter formatter = this. Stateformatter;
Pair Statepair = new Pair (ViewState, controlstate);

Serialize the Statepair object to a string.
String serializedstate = Formatter. Serialize (Statepair);
Writer. Write (serializedstate);
Writer. Close ();
Statestream.close ();
}
Else
throw new InvalidOperationException ("Session needed for streampagestatepersister.");
}
}

Return a secure Stream for your environment.

Private Stream Getsecurestream ()
{
string path = @ "D:\a.txt";
FileStream fs = new FileStream (path, FileMode.Open, FileAccess.ReadWrite);
return FS;
}
}
}

Then rewrite the PageStatePersister property to:

protected override PageStatePersister PageStatePersister
{
Get
{
return new StreamPageStatePersister (Page);

}

Through the simple introduction above, we should have some understanding, just want to understand is: in asp.net1.1 we can only by rewriting Age.savepagestatetopersistencemedium () and Page.loadpagestatefrompersistencemedium () to complete the above functions And in asp.net2.0, in addition to this, and by writing PageStatePersister new subclasses and rewriting the PageStatePersister property to complete, I did not find anything different, of course if you understand in the following content, write PageStatePersister new The real use of subclasses.

Using the page adapter

Because the state persistence mechanism is related to adaptive rendering and client functionality, it provides the databasepagestatepersister of the mypageadapter activation asp.net application. Finally, a browser function (. browser) file is provided to enable the MyPageAdapter for a specific category of clients (in this case, the default Web browser).

Please refer to the PageAdapter project in the source code I provided. Read it and understand it.

Using System.Security.Permissions;
Using System.Web;
Using System.Web.UI;

Namespace PageAdapter
{
[AspNetHostingPermission (SecurityAction.Demand, level = Aspnethostingpermissionlevel.minimal)]
public class MyPageAdapter:System.Web.UI.Adapters.PageAdapter
{
public override PageStatePersister Getstatepersister ()
{
return new Pageadapter.databasepagestatepersister (Page);
}
}
}

Finally, in order to enable the MyPageAdapter adapter, you must create a directory named App_Browsers under the root directory of the ASP.net application and include a. Browser that contains configuration information. Files (In fact, these are all vs2005 to you when you add a. browser file to your project.) The




Controltype= "System.Web.UI.Page"
Adaptertype= "Pageadapter.mypageadapter"/>



This can be seen in the source code of the Testpageadapter project. This project is used to demonstrate the page adapter.

Conclusion

Said relatively simple, may not be very clear, as for the pros and cons of a variety of durable mechanisms, I have not specifically tested, and the last "use page adapter" is not a permanent mechanism, but also with the adapter, we do not rewrite

PageStatePersister properties, I don't seem to be very useful, because we can put the rewrite PageStatePersister action in the base class of the page, all the other pages inherit the base class, which is what I do in my Code, With this page adapter is also troublesome, of course, I also too know the page adapter this dongdong.

In addition, to my source to make a simple description:

1. PageAdapter Project

Subclasses of the DatabasePageStatePersister.cs:PageStatePersister class
MyPageAdapter.cs: Page Adapters
DataAccess.cs and ViewSate.cs database access, belong to the auxiliary class.

2. Streampageadapter Project

This is similar to the above, not much said

3. Savestatetodatabase Project

Stateinhiddenfield.aspx: Testing The default storage mechanism is to see a lot of clutter when looking at the page source file.

Stateinsession.aspx: storage mechanism for session

Stateindatabase.aspx: Storage mechanism database, is the kind of rewrite method, asp.net1.1,2.0 can be used.

Stateindatabase2.aspx: Write PageStatePersister The new subclass and write the PageStatePersister attribute

Stateinfile.aspx: Save the ViewState to a folder in the server.

4. Testpageadater Project.

Used to test also the adapter.



Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.