About viewstate, session... In Asp.net .... Summary

Source: Internet
Author: User
1. Mutual conversion between sessions and Dataset (not recommended)

Operation Method:
Session ["Sss"] = Ds; // Save the DataSet object to the session

Dataset DS = (Dataset) session ["Sss"]; // After forced type conversion, the saved dataset is obtained.

2. Comparison of session and viewstate
Session Viewstate
Occupy server resources True False
Time out True False
Store any. Net Type True Flase (only supports strings, integers, booleans, arrays,
Arraylist, hashtable, customtypeconverters)
Increase HTML Load False True

The session is valid for the entire application, while the viewstate is equivalent to the session of a page.
Define viewstate

// Save in viewstate
Viewstate ["sortorder"] = "DESC ";

// Read from viewstate
String sortorder = (string) viewstate ["sortorder"];

Session
In ASP. NET, there is a stateapplication to manage sessions. In fact, it is a helper process that processes session expiration and creation special requests.
When receiving each request, the auxiliary process will call the status server (you can set different status servers through web. config) to obtain the session.
Session of sessionid, a new session will be created, and then bound to the context (httpcontext); unlike ASP, there are many session Status servers
Currently, three methods are implemented in ASP. NET:
1) inprocstateclientmanager: this is a traditional session storage method, but there are still some nuances.
2) sqlstateclientmanager: saves the session to the database.
3) outofprocstateclientmanager: saves the session outside the process.
The session mechanism of ASP. Net has a feature that the auxiliary process for processing the session is separated from the State server for storing the session. According to msdn, the following benefits are provided:
"Because the memory used for session status is not in the ASP. NET auxiliary process, you can recover from application faults ."
"Because all statuses are not stored together with the secondary process, you can partition the application across multiple processes cleanly. This partition can significantly improve the availability and scalability of applications on computers with multiple processes ."
"Because all statuses are not stored together with the secondary processes, You can partition applications across multiple secondary processes running on multiple computers ."
ASP. in my opinion, the session mechanism of net is flexible, and the internal implementation is also clever. But in fact, because there is not much test done, will the application be as beautiful as it said, do not dare to pack tickets.

3. Application

Application
This is the global storage area in the life cycle of Web applications, and the data stored in the application is globally valid. In ASP. NET, there is an application pool where several
(Or dozens of) application instances, each request will take an instance from the pool to process the request. Before the request is completed, the instance will not accept other requests; this leads to a problem that may exist at the same time.
Multiple applications, that is, multiple threads, all of which may access the application. Therefore, when processing objects in the application, you must consider the same thread
In fact, the application object implements a thread lock. When calling its own add, remove, and other methods, the lock and unlock operations are automatically called.
For performance considerations, the application does not automatically process thread synchronization for obtaining and operating the objects directly through the indexer or other methods, and the following similar code must be used
Reason:
Application. Lock ();
(INT) application ["count"]) ++;
Application. Unlock ();
It is worth noting that after the lock is called, if unlock is not displayed, the application object will be automatically unlocked at the end of the request, which prevents deadlock, however, to ensure code robustness, the unlock method should be called immediately after the lock is called and the modification is completed.
Application
An object is essentially a hash table, which stores objects according to the key value. Because the objects are global and stored on the server, and multiple threads are simultaneously accessed
It should be the data that is frequently accessed, rarely modified, and at least used by most global functions, such as counters or database connection strings.

In ASP. NET, the application usage is the same as that in ASP, and there is almost nothing to say, but it has two more useful events,
Application_onbeginrequest and application_onendrequest. Their and their original
Application_onstart and application_onend are stored in the Global File (note that the file name in ASP is
Global. Asa, which is global. asax in ASP. NET ).

Note: This event is the same if you do not write on. For example, application_end and application_onend are the same.

Application_onstart is the first event triggered by the entire ASP. NET application, that is, when the first ASP. Net program is executed in a virtual directory
For triggering, application_onend is the opposite. It is triggered when the entire application is stopped (usually when the server is restarted/shut down ).
Application_onrequeststart and application_onrequestend are sent when each ASP. NET program is requested.
That is to say, when the customer accesses an ASP. NET program once, these two events will be triggered. We can see his application from the following program. We should first create a global. asax
The content is as follows:

<Script language = "C #" runat = "server">

Void application_onbeginrequest (Object sender, eventargs E)
{
Response. Write ("request is starting... <br> ");
}

Void application_onendrequest (Object sender, eventargs E)
{
Response. Write ("request is ending... <br> ");
}

</SCRIPT>

Put it in the root directory of the local virtual directory, and then we can open any aspx file.
We are at Global. request is starting... and request is ending... this is not the one we add in this file. We will add another ASP. net file.
.

Viewstate

Viewstate
This is what we will focus on today. In fact, viewstate is not mysterious. It is a hidden field, but it is the basis for saving the status of the server control. unfamiliar friends can use IE to view
HTML source code, find a hidden field named "_ viewstate", which contains a lot of messy characters, which is the viewstate of the page.


People who have done web programs may have this kind of painful experience. Sometimes, in order to handle complicated functions on the page, many den operations are often added, and then a lot of judgments are used on the server side to analyze the current
Status, which is annoying to write, and even more difficult to read after writing the Code. In fact, viewstate helps our system to save the control status. The server-side control can also save the status between multiple requests.
All depends on it.
Well, the introduction is here. Today we are not discussing the use of viewstate, but exploring the essence of this thing from the inside.
First, create a test page:
<% @ Page Language = "C #" codebehind = "viewstatetest. aspx. cs" autoeventwireup = "false" inherits = "csdntest. viewstatetest" %>
<! Doctype HTML public "-// W3C // dtd html 4.0 transitional // en">
<HTML>
<Head>
<Title> viewstatetest </title>
<Meta name = "generator" content = "Microsoft Visual Studio 7.0">
<Meta name = "code_language" content = "C #">
<Meta name = "vs_defaultclientscript" content = "JavaScript">
<Meta name = "vs_targetschema" content = "http://schemas.microsoft.com/intellisense/ie5">
</Head>
<Body>
<Form ID = "viewstatetest" method = "Post" runat = "server">
<Asp: button id = "btnpostback" runat = "server" text = "post back" width = "85px"> </ASP: button>
<Br/>
<Asp: checkbox id = "chktest" runat = "server" text = "This is a check box"> </ASP: checkbox>
</Form>
</Body>
</Html>

This is a simple page designed with vs. net. It contains a server-side button and a checkbox, And then we respond to the button event on the server side:

Private void btnpostback_click (Object sender, system. eventargs E)
{
[1] response. Write ("viewstate:" + request. Params ["_ viewstate"] + "<br/> ");

[2] string decodevalue = encoding. utf8.getstring (convert. frombase64string (request. Params ["_ viewstate"]);

[3] response. Write ("viewstate Decode:" + decodevalue + "<br/> ");

[4] object viewstate = (New losformatter (). deserialize (request. Params ["_ viewstate"]);
 
[5] response. Write ("viewstate object:" + viewstate. GetType (). Name );
}


For convenience, I added a row number. In the first line, we typed out the value of viewstate. What is the second line? In fact, a string stored in viewstate on the client is internal
Viewstate is encoded by base64 after being serialized in some way, so we can re-encode the base64 encoded string. For the fourth line, I will not
First, let's look at the execution results:
After running, there is nothing on the page, except the button and checkbox (nonsense :), we click the button and the result is as follows:

[A] viewstate: ddwxmju2mdi5mta3oztspgnoa1rlc3q7pj6gg0qzm + 7gacywcy0hnrct9tooda =
[B] viewstate Decode: T <1256029107; L> d3i S -! T
[C] viewstate object: triplet

Then let's analyze this result. The value displayed in a is the value uploaded from viewstate to the client. The value displayed in B is the value after base64 anti-encoding. It seems that nothing can be seen from this, in C, A: triplet? What is this? Let's go back to the above Code:
Object viewstate = (New losformatter (). deserialize (request. Params ["_ viewstate"]);


Note that we use a losformatter class. In fact, this class is the class that provides serialization for viewstate in ASP. NET. It has two methods, one is
Serialize is to serialize an object. One is deserialize and the other is deserialization. Here we use the deserialization method to directly deserialize viewstate.
The object is a triplet type. In fact, the viewstate stored on the page in ASP. NET is of this type. First
Analyze losformater.
Let's look back at the result B: T <1256029107; L> d3i S -!
T,
In fact, by viewing the losformatter decompiled code, we can see that the serialization method is very simple, that is, to judge the type of the object to be serialized, if it is not a directly serialized class
Type, record its type, and recursively serialize its attributes. We can see that "T" in B Indicates the triplet type, which has three attributes, these three attributes are included in
"<" And ">", separated by ";", and the last d3i S -!
T according to my analysis, it should be a hash value that prevents viewstate changes. This is not very definite, because the decompilation code is really ugly. I just did not read it carefully after learning it.


We just analyzed that the viewstate deserialization in the page is the triplet type. In fact, this class is found in msdn, and it is
Object. To put it simple, it is a big box that can put three boxes (it seems to be confused, haha). It has three attributes: first, second, thrid
:), Representing three objects respectively.

In the corresponding page, first is the return value of page. gettypehashcode (). This method is a protection defined by system. Web. UI. Page.
The virtual method of protection, returns an integer, implemented by the class generated by the aspx file, because this class has ASP. net is responsible for generating and compiling the source code at runtime. It calculates a large constant as a return
Return value, which is unique among all pages of the web application. (Aside from a question, the source code automatically generated by ASP. NET can be
System Disk: \ windows \ Microsoft. NET \ framework \ v1.0.3705 \ temporary ASP. NET
Files). The unique hash value is used to generate a tag in viewstate so that this viewstate applies only to the corresponding page.
Second recursively saves the object returned by viewstate of the page Control tree through the control. saveviewstaterecursive method, that is, the real viewstate data.
Third stores the list of control names on the current page that require PostBack.


After analyzing the composition of the viewstate of the page, let's look at the implementation of the viewstate of control. Viewstate is
An Attribute implemented by the system. Web. UI. control class. The attribute type is system. Web. UI. statebag. This class contains
The implementation of viewstate data structure is actually an internal hash table, which stores and retrieves data through key values.
How does the Server Control Save the status?
We know that all server controls are derived from system. Web. UI. Control, so they all have the viewstate attribute. Within control, two protected virtual methods are defined:
Protected virtual object saveviewstate ()
And
Protected virtual void loadviewstate (Object savedstate)

These two methods are used to derive the child control to save and read its own viewstate. For example, we have a self-written control that saves a string to viewstate, then our method is roughly like this:
Protected virtual object saveviewstate ()
{
Object [] States = new object [2];
States [0] = base. saveviewstate (); // remember to save the viewstate of the parent Control
States [1] = "Hello, I'm tietong! "; // Save your own

Return states; // return the repackaged object
}
When obtaining:
Protected override void loadviewstate (Object savedstate) // The savedstate here is the object array returned when we save
{
Object [] States = (object []) savedstate;
Base. loadviewstate (States [0]); // parse the data of the parent class for himself.
String mydata = (string) States [1]; // obtain our own data
}
We can save it in our own way. We don't have to use arrays like above. In fact, we can use any object that supports serialization. The parent class doesn't care about how to save subclass, we only need to use the same method when saving and load, and pass the correct data to the parent class method.

Another problem is that the viewstate of the control we use is a key-Value Pair such as key-value. How does it save it?
In fact, it is very simple. There is a class named pair under system. UI. Web. It is similar to Triplet, but it only contains two objects. When statebag is saved, first stores the array of all key values, and second stores the array of all values.

Now, we have learned how viewstate is serialized and saved to the client, and how controls save their own viewstate. How are these two combined?

That is, how does the viewstate of the Control tree of the entire page be saved and read?

There are two internal methods in control:
Internal object saveviewstaterecursive ();
Internal void loadrecursive ();

These two methods are called by system. Web. UI. Page. After the render ends, the page calls the savepageviewstate method,
The savepageviewstate method calls the saveviewstaterecursive () method of control. This method is to call every
The saveviewstaterecursive method of control. Controls is used to save the viewstate of all controls in the control tree. Here, it may be smart.
My friend asked, since saveviewstaterecursive is a recursive call to save the method, what is the use of the saveviewstate () method we wrote above?
What about it?

We know that control. Controls may have many, and our saveviewstate () only saves the data of the current control, but does not record the knot of the Control tree.
Structure, if we use the recursive saveviewstate () method to save data, the structure of the Control tree will be lost, so the structure of the Control tree cannot be restored during load.
The code in the saveviewstaterecursive method is as follows:
[1] obtain the viewstate of the control (call the saveviewstate method)
[2] loop child Control
{
Define two dynamic arrays, one for storing the control index, and one for storing the values returned by recursively calling the saveviewstaterecursive method of the child control.
}
[3] define a triplet (haha, this thing appears again)
[4] first save the viewstate of this control
[5] Second: Save the sub-Control Index
[6] third: Save the return value of the saveviewstaterecursive method of the recursive subcontrol
[7] returns triplet
In this way, the viewstate of the entire control tree and the structure of the Control tree are saved.

The load method is similar to the Save method, but the load method retrieves the index of the sub-control from the savedstate to recursively recursive the loadrecursive () method of the sub-control, this ensures that the stored data is correctly transmitted to the Child control.

Here, we have a general understanding of the implementation of viewstate, and finally come to some conclusions:
1. viewstate is stored on the client, which reduces the burden on the server and is a better way to save data.
2. Because of the limitations of viewstate, only serializable objects can be saved, and it is best not to put too many things, saving the province, so as not to slow down the transmission speed and increase the load on Server Resolution.

3. We can obtain the value in viewstate in a simple way. We have discussed some of the above. Although we did not write the parsed code, we use
Losformatter can get the object after viewstate deserialization, so it is easy to parse it. Therefore, viewstate is still relatively poor in terms of security,
Not recommended
Stores confidential and sensitive information. Although viewstate can be encrypted, because viewstate is stored on the client, security risks are inherent.
4. From the technical point of view, viewstate has no new ideas, but the design of server controls is clever.

Finally, from my personal point of view, I think the appearance of viewstate has greatly reduced the burden on programmers, but what we need to see is the nature of viewstate and the rational application of it.

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.