Wednesday, 25 September 2013

State Management Techniques - Part 1

Hyper Text Transfer Protocol (HTTP) is a request/response style communication protocol which is implemented in the "World Wide Web(WWW)". Clients (browsers, spider, etc) will request to a server (web server) and the server responds to these requests. It connects to a specific port (default is 80) to the server and communicates via that port. Once the response is received completely, client programs will be disconnected from the server

HTTP is a stateless protocol and the server will abandon the connection once the request is served. Therefore managing state in web applications is challenging. State management techniques are used to maintain user state throughout the application.
  • QueryString
  • Cookies
  • Cache
  • View State
  • Session state
  • Application state

Understanding the state management techniques play a major role in creating efficient web applications. The following are the commonly used state management techniques.

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
https://accounts.google.com/ServiceLogin.aspx?service=mail

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, service is the key and mail is its value. You can send multiple values through querystring, separated by the & symbol. The following code shows sending multiple values to the

https://accounts.google.com/ServiceLogin.aspx page.
https://accounts.google.com/ServiceLogin.aspx?service=mail&User=1

The following code shows reading the QueryString values in ServiceLogin.aspx
String strService= Request.QueryString[“service”];
String struser= Request.QueryString[“user”];

Pros and Cons

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. However, it has many disadvantages.
  • You can pass information only as a string. If you need to pass objects in any case through QueryString, it involves more effort.
  • URL length has limitations. So you can't send much information through URL.
  • 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 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.

The location where the cookie is stored is completely controlled by the browser. Sometimes it may keep the cookie in its memory instead of creating a file. 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 and retrieved using Request.

Response.Cookies["UserRole"].Value = "admin";Response.Cookies["UserRole"].Expires = DateTime.Now.AddDays(1);

Once you set the cookie, the browser will include it for every request. You read the cookie from the Request.Cookies collection by specifying cookie name. Consider the following code.

if (Request.Cookies["UserRole"] != null){string strUserRole = Request.Cookies["UserRole "].Value;Response.Write("User Role is" + UserRole);}

Cookies are managed by the browser and will take care about removing expired cookies. If you need to remove a cookie before the expiry period, you have to create a cookie with the same name and with an expiry date that is already passed. This will make browser think that the cookie is expired and will be removed immediately.

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

Multi-valued Cookies

RFC states that a browser should not store more than 20 cookies from a domain. Multi-Valued cookie is very handy when you have more items to keep in cookie. To create a multi-valued cookie, you instantiate the HttpCookie instance and set it's values. Consider the following code.

HttpCookie cookie = new HttpCookie("user");cookie["UserName"] = "Raj";cookie["UserRole"] = "Admin";cookie["UserId"] = "22";cookie.Expires = DateTime.Now.AddDays(1);Response.Cookies.Add(cookie);
Here is how you read it
HttpCookie cookie = Request.Cookies["user"];
if (cookie != null){
string strUserName = cookie["UserName"];
string strUserRole = cookie["UserRole "];
string strUserId = cookie["UserId "];
}

Pros and Cons

A cookie is a very handy and easily usable state management technique. It is useful when you want to keep small information that is needed for long periods of time. The processing overhead of cookies is much less compared to sessions. However, it has the following 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.

Some Useful Properties you Must Know Before Using Cookies

Property Name
Description
Domain
Specifies which domain is associated with this cookie. Default is the current domain. See security constraints later in this article
Expires
DateTime value specifies the expiry time of the cookie
HttpOnly
Cookies can be accessed using java script. Setting this property prevents cookies being accessed from java script
Secure
Set this if cookies are transmitted over SSL
Name
Cookie name
Value
Cookie value (string)


About Author:
Amit Salunkhe is budding technology geek, who actively contributes to Systems Plus with his creativity and research on technology. He can be contacted at amit.salunkhe@spluspl.com

No comments:

Post a Comment