Vous êtes sur la page 1sur 36

HTTP Protocol and the Need for State Management Techniques

Hyper Text Transfer Protocol (HTTP) is a communication protocol which is implemented in the "World Wide Web(WWW)".

It is a request/response style protocol. (Client-Server)


HTTP uses TCP protocol for communication. It connects to a specific port to the server and communicates via that port.

Once the response is received completely, client programs will be disconnected from the
server. For each request, client programs have to acquire a connection with servers and do all the request cycles again.

State Management..
ASP.NET files are just text files which will be placed in the server and served upon the request. When a request comes for a page, the server will locate the requested file and ask

the ASP.NET engine to serve the request.


TheASP.NET engine will process the server tags and generate HTML for it and return back to the client.

HTTP is a stateless protocol and the server will abandon the connection once the request is
served. Since HTTP is stateless, managing state in web applications is challenging. State management techniques are used to maintain user state throughout the application. Information you want to maintain over the lifetime of a web applications depends on your context. It can be from simple numbers to very complex objects.

This is a concept of Web Server, which remembers the user's information or it holds the information about multiple user requests. Options or Types:

1. Client Side State Management Techniques. 2 Server Side State Management Techniques.

Commonly used state management Techniques


QueryString Cookies ViewState Session state

Client Side

Application state
Static variables Profiles
Server Side

QueryString
This is the most simple and efficient way of maintaining information across requests. The information you want to maintain will be sent along with the URL. A typical URL with a query string looks like www.somewebsite.com/search.aspx?query=foo The URL part which comes after the ? symbol is called a QueryString. QueryString has two parts, a key and a value. In the above example, query is the key and foo is its value. You can send multiple values through querystring, separated by the & symbol.

Example
The following code shows sending multiple values to the foo.aspx page. Response.Redirect("foo.aspx ?id=1&name=foo"); The following code shows reading the QueryString values

in foo.aspx
string id = Request.QueryString["id"]; string name = Request.QueryString["name"];

Query string is lightweight and will not consume any server resources. It is very easy to use and it is the most efficient state

management technique.
Disadvantages. You can pass information only as a string

URL length has limitations. So you can't send much information


through URL.(Client browser limit on URL length) Information passed is clearly visible to everyone and can be easily altered.

Cookies
A cookie is a small file which is stored in the visitor's hard disk drive. This is helpful for storing small and trivial information. A cookie can have a maximum size of 4KB. The web server creates a cookie, attaches an additional HTTP header to the response, and

sends it to the browser.


The browser will then create this cookie in a visitor's computer and includes this cookie for all further requests made to the same domain. Servers can read the cookie value from the request and retain

the state.

Creating and using a cookie


The HttpCookie class is a key/value collection which allows storing string values.

The following code shows how to create a cookie and send it to the client.
Cookies are added using Response property(storing the client information) and retrieved using Request.

Response.Cookies["id"].Value = "10";

COOKIES
Since no expiry time specified, a cookie added like the above method will be cleared by the browser immediately when it is closed. If you would like to keep the cookie for a long time, you have to use the HttpCookie.Expiresproperty set with an expiration date. The following code shows how to do that. // this cookie expires after one day from the date it is set // browser will take care about removing the cookies after the expiry time Response.Cookies["id"].Value = "10";

Response.Cookies["id"].Expires = DateTime.Now.AddDays(1);

Ex.
// for safety, always check for NULL as cookie may not exist if (Request.Cookies["id"] != null) {

string userId = Request.Cookies["id"].Value;

Response.Write("User Id value" + userId);


}

COOKIES
Advantages: Simplicity Disadvantages: Cookies have a size limitation of 4KB. Storing huge information is not possible. Cookies can be easily tampered as they are kept in the client's machine. So additional security checking has to be done when using them. The user can disable cookies.

Hidden Fields
ASP.NET allows you to store information in a Hidden Field control, which renders

as a standard HTML hidden field.


A hidden field does not render visibly in the browser, but you can set its properties just as you can with a standard control.

When a page is submitted to the server, the content of a hidden field is sent in
the HTTP form collection along with the values of other controls.

A hidden field acts as a repository for any page-specific information that you

want to store directly in the page.


It is rendered as an <input type= "hidden"/> element. This control was introduced by ASP.NET 2.0.

Ex..
<script runat="server"> protected void Page_Load(object sender, EventArgs e) <html > <head > { if (!IsPostBack) </head> <body> <form id="form1" runat="server"> <div> count += i; <asp:HiddenField ID="HiddenField1" runat="server" />

int count = 0;
for (int i = 0; i < 10; i++) {

}
HiddenField1.Value = count.ToString(); Response.Write(count); }

<asp:Button ID="Button1" runat="server" Text="Button" </div> </form> </body> </html>

if (IsPostBack)
{ Response.Write(HiddenField1.Value); } } </script>

Cookies vs. Session


Cookie can store only primitive types (int,string...), we cannot store complex types(ie.,Dataset,...) Session memory can store Objects Cookies does not provide security for data(because it will store at client side) Session memory provides security for data(because it will store at server side) Processing cookies will be faster compare to session memory. Cookie max size is 4kb but session memory doesn't have any limitation(as long as server is supported that much of memory it will take) Number of cookies are limited(20 cookies) No limit for number of sessions.

Session
When client makes the first request to the application Asp.Net worker process will create a block of memory unique to client, this is called "Session Memory This session memory will be maintained with the timeout of 20 mins by default. To access this session memory from asp.net webpage, Microsoft is provided Session

object.
Session.Add("Varname",value) for eg:Session.Add("Uname","ramesh"); (or) Session["Uname"] = "ramesh"; Session.Remove("Varname");-->It will remove variable from session memory. Session.RemoveAll();-->Removes all keys and values from session-state collection. Session.Clear();-->Removes all keys and values from session-state collection. Session.Abandon(); -->It will kills the Session.

Storing Session State


ASP.NET provides five ways of storing the session state on the server-side.
InProc - Stores session states in memory on the web server. This is the default mode. StateServer
Stores session in a service called the ASP.NET State Service. This ensures that session state is preserved if the web application is restarted and also makes session state available to multiple servers in a web farm.

SQLServer -

Stores session state in a SQL Server database. This ensures that session state is preserved if the web application is restarted and also makes session state available to multiple servers in a web farm. Custom Enables you to specify a custom session stage storage provider. You also need to implement the custom storage provider. Off -Disables session state.

What is the difference between Session.Abandon() and Session.Clear()?


Session.Abandon() destroys the session and the Session_OnEnd event is triggered. Session.Clear() just removes all values (content) from the Object. The session with the same key is still alive. If you use Session.Abandon(), you lose that specific session and the user will get a new session key. You could use it for example when the user logs out. Use Session.Clear(), if you want that the user remaining in the same session (if you don't want him to relogin for example) and reset all his session specific data.

Example

When first client first request comes to the application asp.net worker process will allocate a block of memory common to all clients this is called "Application Memory

This application memory doesn't have any timeout, it will be maintained till the application
is running under worker process. To access this application memory from asp.net webpage, Microsoft is provided Application object. Application.Add("Varname",value) for eg:Application.Add("Uname","ramesh"); Application["Uname"] = "ramesh"; Application.Remove("Varname"); Lock() Unlock() (or)

Each client request to the webserver is considered as one thread. Webserver will provide equal processor time to all threads.

In this case there is a possibility of more than one thread manipulating


same data ie., application memory data, this will provide improper results

can be avoided with synchronization of threads this can be implemented using lock() and unlock() methods.

protected void lnkbtnWriteMsg_Click(object sender, EventArgs e) { Application.Lock(); Application["FlashNews"] = ".Net 5.0 is going to come"; Application.UnLock(); } protected void lnkbtnReadMsg_Click(object sender, EventArgs e) { Application.Lock(); Response.Write(Application["FlashNews"]); Application.UnLock(); }

Example

1)Session events

a)Onstart-->It will be executed when session is created b)Onend -->It will be executed when session is closed

2)Application events
a)Onstart-->It will be executed when website is started b)Onend -->It will be executed when website is stopped

c)BeginRequest-->This event occurs when a client makes a request to any pages of the
application. It can be useful to open connection to database for all requests. d)EndRequest-->After a request for a page has been made, this is the last event that is called. e)Error-->This event is used to handle all unhandled exceptions in the application. It's the best place to put your error tracking mechanism.etc., -->This events should be placed with in a special file called "Global.asax

Global.asax
-->It is an application file, used to handle application and session level events. -->Website supports only one global.asax file.

void Application_Start(object sender, EventArgs e) { // Code that runs on application startup Application.Lock(); Application["OnlineUsers"] = 0; Application["HitCount"] = 0; Application.UnLock(); } void Session_Start(object sender, EventArgs e) { // Code that runs when a new session is started Application.Lock(); Application["OnlineUsers"] = Convert.ToInt32(Application["OnlineUsers"]) + 1; Application["HitCount"] = Convert.ToInt32(Application["HitCount"]) + 1; Application.UnLock(); }

void Session_End(object sender, EventArgs e) { Application.Lock(); Application["OnlineUsers"] = Convert.ToInt32(Application["OnlineUsers"]) - 1; Application.UnLock(); // Code that runs when a session ends. // Note: The Session_End event is raised only when the sessionstate mode // is set to InProc in the Web.config file. If session mode is set to StateServer // or SQLServer, the event is not raised. }

Page submission:
Client submitting data to webserver is called "Page submission". for eg:- login parameters,......... 2 Types 1)Postback submission: Page submitting to itself is called "Postback submission". 2)Crosspage submission: One webpage submitting to another webpage is called "Cross page submission". Note:- Crosspage Submission will be implemented based on PostBackUrl property.

e)Profile
Profile Properties allows you to store user-specific data. This feature is similar to session state,except that the profile data is not lost when a user's session expires. The profile-properties feature uses an ASP.NET profile, which is stored in a persistent format and associated with an individual user. To use profile properties, you must configure a profile provider. ASP.NET includes a SqlProfileProvider class that allows you to store profile

data in a SQL database.

Purpose: Used to store user specific information.

ASP.NET profile
ASP.NET profile feature allows you to store simple (scalar) values, collections and other complex types, and user-defined types. EG:

When it comes to profile implementation the communication with database takes place
two times for request processing 1)When the webpage is accessing profile properties, the total data will be retrieved from database 2)when the modifications takes place to profile data, it will be updated to database after complete processing is finished. The client profile data will be stored into DB, by providing a unique identification based on authentication mode. Profile implementation is recommended, when the amount of data is small and required for less no. of pages.

Pros
1)Since the state management information is placed in profile properties, no data is lost and is preserved even when the IIS and the application worker-process is restarted. 2)Profile properties can be used both in multi-computer and multi-process configurations. Therefore, they optimize the scalability of a Web application.

Cons
If it is more amount of Profile data and used in more no. of pages then performance will be degraded.(because For all client requests,It is going to retrieve entire profile data, even if it is not required.) Differences between Session and Profile objects The major difference between Profile and Session objects are 1. Profile object is persistent(ie., It doen't have any timeout) whereas Session object is non-persistant. 2. Profile object uses the provider model to store information whereas Session object uses the In Proc, Out Of Process or SQL Server Mode to store information. 3. Profile object is strongly typed whereas Session object is not strongly typed. The similarity between them is that Each user will automatically have a profile of his own

similar to Sessions where each user will have his own Session State.

Session data is lost when the visitor leaves the webpage. What if you need to persist all the user information for a long time? ASP.NET Profile is the answer. It provides a neat way to persist information for a long time. You only need a few entries in the web.config file as seen below <profile> <properties> <add name="Id" type="Int32"/> <add name="Name"/> <add name="Age" type="Int32"/> </properties>

ASP.NET generates a strongly typed class for accessing profile data. Data type for the properties are chosen depending upon the type value. Default type is string if no type is specified. Following code shows setting values and reading back from profile. Profile.Name = txtName.Text; Profile.Id = int.Parse(txtPersonId.Text); Profile.Age = int.Parse(txtAge.Text); / / to read profile value, use int age = Profile.Age; string name = Profile.Name; int id = Profile.Id; ASP.NET keeps the profile data in SQLServer database. If no databases are available in the project, it creates a database file in the app_data directory when it is used for the first time.

It allows to keep only serializable types Reading data from profile requires database access which can potentially make your application less performant. If your website uses profiles heavily, you have to cache the results to avoid unncessary database calls.

Vous aimerez peut-être aussi