Developer is forced to implement various state management techniques when developing applications which provide customized content and which "remembers" the user.
We can classify state management techniques as client side state management and server side state management. Each technique has its own pros and cons.
Client side State management Options:
ASP.NET provides various client side state management options like Cookies, Query Strings (URL), Hidden fields, View State and Control state.
Cookie:
A cookie is a small piece of text stored on user's computer. Usually, information is stored as name-value pairs. Cookies are used by websites to keep track of visitors. Every time a user visits a website, cookies are retrieved from user machine and help identify the user.
Advantages:
• Simplicity
Disadvantages:
• Cookies can be disabled on user browsers
• Cookies are transmitted for each HTTP request/response causing overhead on bandwidth
Hidden fields:
Hidden fields are used to store data at the page level. As its name says, these fields are not rendered by the browser. It's just like a standard control for which you can set its properties. Whenever a page is submitted to server, hidden fields values are also posted to server along with other controls on the page. We can still use it to store insignificant data. We can use hidden fields in ASP.NET pages using following syntax
Advantages:
• Simple to implement for a page specific data
• Can store small amount of data so they take less size.
Disadvantages:
• Hidden field values can be clearly visible when passed over a network
View State:
View State can be used to store state information for a single user. View State is a built in feature in web controls to persist data between page post backs. You can set View State on/off for each control using EnableViewState property. By default, EnableViewState property will be set to true.
View state information of all the controls on the page will be submitted to server on each post back. To reduce performance penalty, disable View State for all the controls for which you don't need state. (Data grid usually doesn't need to maintain state).
You can also disable View State for the entire page by adding EnableViewState=false to @page directive.
View state data is encoded as binary Base64
- encoded which add approximately 30% overhead. Care must be taken to ensure view state for a page is smaller in size.
Advantages:
• Simple for page level data
• Encrypted
• Can be set at the control level
Disadvantages:
• Overhead in encoding View State values
• Makes a page heavy
Query strings:
Query strings are usually used to send information from one page to another page. They are passed along with URL in clear text
Query strings seem to be redundant.
Most browsers impose a limit of 255 characters on URL length. We can only pass smaller amounts of data using query strings.
Since Query strings are sent in clear text, we can also encrypt query values. Also, keep in mind that characters that are not valid in a URL must be encoded using Server.UrlEncode.
Advantages:
• Simple to Implement
Disadvantages:
• Human Readable
• Client browser limit on URL length
• Easily modified by end user
Control State:
Control State is new mechanism in ASP.NET 2.0 which addresses some of the shortcomings of View State. Control state can be used to store critical, private information across post backs.
Control state is another type of state container reserved for controls to maintain their core behavioral functionality whereas View State only contains state to maintain control's contents (UI).
Control State shares same memory data structures with View State. Control State can be propagated even though the View State for the control is disabled.
Server Side State management:
As name implies, state information will be maintained on the server. Application, Session, Cache and Database are different mechanisms for storing state on the server.
Application object:
Application object is used to store data which is visible across entire application and shared across multiple user sessions. Data which needs to be persisted for entire life of application should be stored in application object.
We should write to application variable only in application_Onstart event (global.asax)
Below code sample gives idea
Application.Lock();
Application["mydata"]="mydata";
Application.UnLock();
Session object:
Session object is used to store state specific information per client basis. It is specific to particular user. Session data persists for the duration of user session you can store session's data on web server in different ways. Session state can be configured using the
Configuration information:
cookieless = <"true" "false">
timeout =
sqlconnectionstring =
server =
port =
Mode:
This setting supports three options. They are InProc, SQLServer, and State Server
Timeout:
This indicates the Session timeout vale in minutes. This is the duration for which a user's session is active. Note that the session timeout is a sliding value; Default session timeout value is 20 minutes
Caching
It is a way to store the frequently used data into the server memory which can be retrieved very quickly. And so provides both scalability and performance. For example if user is required to fetch the same data from database frequently then the resultant data can be stored into the server memory and later retrieved in very less time (better performance). And the same time the application can serve more page request in the same time (scalability).
Drawback: Suppose the server memory is filled with the data then the remaining part of the data is stored into the disk which slower the complete system performance. That's why self limiting caching techniques are best; where once the server memory gets filled the data has been selectively removed from the server memory to ensure that the application performance is not degraded.
Caching Types: Basically, caching is of two types:
1. Output caching - The rendered html page is stored into the cache before sending it to the client. Now, if the same page is requested by some other client the already rendered htm page is retrieved from the server memory and sent to the client, which saves the time requires rendering and processing the complete page.
Note: The page is automatically removed when the application is recompiled.
<@ OutputCache Duration="20" VaryByParam="None">
2. Data Caching - The important pieces of information, that are time consuming and frequently requested, are stored into the cache. For example a data set retrieved from the database. It is very similar to application state but it is more server friendly as the data gets removed once the cache is filled.
Profiles
if you remember that when we used the Session variables in Asp.net a unique Session ID was generated for every user. This ID was generated automatically. if you tried printing out the Session ID code is below it will be different for each computer and each session that's why its unique.
Response.Write(Session.SessionID); // This will print roahoq55lpkgn055qwcwod45
Let's see some examples that how we can use profile object in our Asp.net web applications
First in order to create unique id for the anonymous users we need to add a tag in the web.config file.
This tag means that we will create a Profile ID for the anonymous users.
New thing to note about the Profile tag is that you cannot make the variables on the fly. I mean you cannot do something like this:
Sample2.aspx: We just simply put the Name from the TextBox in the profile object
Profile["Name"] = txtName.Text;
Response.Redirect("Sample2_1.aspx");
Sample2_1.aspx: This page recieved the Name from the Sample2.aspx page and prints the result
if (!Page.IsPostBack)
{
if (Profile["Name"] != null)
{
string name = Profile["Name"].ToString();
Response.Write(name);
}
}
This will result in an error saying that it was not able to recognize the Name variable. For this to work
we need to define the Profile variables and what better place to do this than in the web.config file.
Let's see how we can pass values from one page to another using the Profile object.
As we see that we have introduced some new tags in the profile class. All the tags are placed inside the profile tag which also contains the properties tag. You can define any number of profile variables in the add tag. In this example we are just using the "Name" tag. Now let's see how we can access the values of the Profile variables that we have just set in the web.config file.
Our "Sample2.aspx" page contains a simple TextBox and the button. When the button is clicked the values are transferred to another page Sample2_1.aspx page.
Now let's see the button click code:
void Button1_Click(object sender, EventArgs e)
{
Profile["Name"] = txtName.Text;
Response.Redirect("Sample2_1.aspx");
}
We simply assigns the value of the TextBox to the Profile variable called "Name" and than redirected the page to the Sample2_1.aspx page where we can now display the value.
Sample2_1.aspx:
if (!Page.IsPostBack)
{
if (Profile["FirstName"] != null)
{
string name = Profile["FirstName"].ToString();
Response.Write(name);
}
}
On this page we simply retrieve the value from the Profile object and prints out the value.
Let's see if we can transfer an arrayList from one page to another by putting it in the profile object.
Sample3.aspx
void Button1_Click(object sender, EventArgs e)
{
System.Collections.ArrayList aList = new System.Collections.ArrayList();
aList.Add("Azam");
aList.Add("John");
aList.Add("Saif");
Profile["Name"] = (object) aList; // You may not need the (object) conversion since this is an implicit conversion
Response.Redirect("Sample3_1.aspx");
}
In the above code we just added few items in the arrayList object and than put that arrayList in the Profile object. And finally we redirected the to Sample3_1.aspx page.
Sample3_1.aspx
if (!Page.IsPostBack)
{
if (Profile["Name"] != null)
{
System.Collections.ArrayList myList = (System.Collections.ArrayList)Profile["Name"];
for (int i = 0; i < myList.Count; i++)
{
Response.Write(myList[i].ToString());
}
}
}
In this code sample we just iterate through the list and print all the values contained in the arrayList.
If you run this code you will get an error saying that the Profile object is not compatible with the type. For this to work you need to make a small change in the web.config file.
Now if you see the web.config file above you can see that I have defined a type attribute which has the "System.Collections.ArrayList" type.
Now if you run your page it will work fine and display the results on the Sample3_1.aspx page.
There is much more you can do with profiles like sending classes information by serializing them and inheriting from profiles and using role based profiles.
POST && GET
The difference between METHOD="GET" (the default) and METHOD="POST" is primarily defined in terms of form data encoding. The official recommendations say that "GET" should be used if and only if the form processing is idempotent, which typically means a pure query form. Generally it is advisable to do so. There are, however, problems related to long URLs and non-ASCII character repertoires which can make it necessary to use "POST" even for idempotent processing. As a simplification, we might say that "GET" is basically for just getting (retrieving) data whereas "POST" may involve anything, like storing or updating data, or ordering a product, or sending E-mail.
when u r using get method u can see the data in URL even if u r using any king of state management technique.
there no relation between query string and Get method both are different concepts.
the only similarity is viewing data in URL.
Request, Response Objects
Request and Response objects represent information coming into the Web server from the browser and information going out from the server to the browser. The Request object is called the input object and the Response object is called the output object.
Response Object
As mentioned above, the Response object represents a valid HTTP response that was received from the server. The response header properties are read-only. Notable properties of the object are as follows:
Body: Gets the body of the HTTP response. Only the portion of the body stored in the response buffer is returned
BytesRecv: Gets the number of bytes the client received in the response
BytesSent: Gets the number of bytes sends in the HTTP request
CodePage: Gets or sets the code page used for setting the body of the HTTP response
ContentLength: Gets the size, in bytes, of the response body
Headers: Gets a collection of headers in the response
HeaderSize: Gets the combined size, in bytes, of all the response headers
HTTPVersion: Gets the HTTP version used by the server for this response
Path: Gets the path that was requested
Port: Gets the server port used for the request
ResultCode: Gets the server's response status code
Server: Gets the name of the server that sent the response
TTFB: Gets the number of milliseconds that have passed before the first byte of the response was received
TTLB: Gets the number of milliseconds that passed before the last byte of the response was received
UseSSL: Checks whether the server and client used an SSL connection for the request and response
Request Object
As mentioned above, the Request object represents an HTTP request before it has been sent to the server. Notable properties of this object are as follows:
Body: Gets/Sets the HTTP request body
CodePage: Gets/Sets the code page for the request body
EncodeBody: Gets/Sets whether URL ACT automatically encodes the request body
EncodeQueryAsUTF8: Gets/Sets whether UTF-8 ACT automatically encodes the request's query string
Headers: Gets the HTTP Headers collection object
HTTPVersion: Gets/Sets the HTTP version
Path: Gets/Sets the HTTP path
ResponseBufferSize: Gets/Sets the size of the buffer used to store the response body
Verb: Gets/Sets the HTTP method verb
No comments:
Post a Comment