ASP State Management
ASP State Management
This article discusses various options for state management for web
applications developed using ASP.NET. Generally, web applications are based
on stateless HTTP protocol which does not retain any information about user
requests. In typical client and server communication using HTTP protocol,
page is created each time the page is requested.
Here we are here with various options for ASP.NET developer to implement
state management techniques in their applications. Broadly, we can classify
state management techniques as client side state management or server
side state management. Each technique has its own pros and cons. Let's
start with exploring client side state management options.
ASP.NET provides various client side state management options like Cookies,
QueryStrings (URL), Hidden fields, View State and Control state (ASP.NET
2.0). Let's discuss each of client side state management options.
Cookie:
Let's see an example which makes use of cookies to customize web page.
if (Request.Cookies["UserId"] != null)
lbMessage.text = "Dear" + Request.Cookies["UserId"].Value + ", Welcome to our
website!";
else
lbMessage.text = "Guest,welcome to our website!";
If you want to store client's information use the below code
Response.Cookies["UserId"].Value=username;
Advantages:
Simplicity
Disadvantages:
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. Now that all the asp.net web controls have built in
state management in the form of view state and new feature in asp.net 2.0
control state, hidden fields functionality seems to be redundant. We can still
use it to store insignificant data. We can use hidden fields in ASP.NET pages
using following syntax
protected System.Web.UI.HtmlControls.HtmlInputHidden Hidden1;
//to assign a value to Hidden field
Hidden1.Value="Create hidden fields";
//to retrieve a value
string str=Hidden1.Value;
Advantages:
Disadvantages:
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 mechanism poses performance overhead. 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. View State can be used using following syntax in an ASP.NET web
page.
Advantages:
Disadvantages:
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. Now that cross page
posting feature is back in asp.net 2.0, 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.
Let's assume that we have a Data Grid with a list of products, and a
hyperlink in the grid that goes to a product detail page, it would be an ideal
use of the Query String to include the product ID in the Query String of the
link to the product details page (for example, productdetails.aspx?
productid=4).
When product details page is being requested, the product information can
be obtained by using the following codes:
string productid;
productid=Request.Params["productid"];
Advantages:
Simple to Implement
Disadvantages:
Human Readable
Client browser limit on URL length
Cross paging functionality makes it redundant
Easily modified by end user
Control State:
Care must be taken to conserve server resources. For a high traffic web site
with large number of concurrent users, usage
of sessions object for state management can create load on server causing
performance degradation
Application object:
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 <session State> section in the
application's web.config file.
Configuration information:
Mode:
This setting supports three options. They are InProc, SQLServer, and State
Server
Cookie less:
This setting takes a Boolean value of either true or false to indicate whether
the Session is a cookie less one.
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
SqlConnectionString:
This identifies the database connection string that names the database used
for mode SQLServer.
Server:
In the out-of-process mode State Server, it names the server that is running
the required Windows NT service: aspnet_state.
Port:
This identifies the port number that corresponds to the server setting for
mode State Server. Note that a port is an unsigned integer that uniquely
identifies a process running over a network.
In process mode:
This mode is useful for small applications which can be hosted on a single
server. This model is most common and default method to store session
specific information. Session data is stored in memory of local web server
Configuration information:
<sessionState mode="Inproc"
sqlConnectionString="data source=server;user id=freelance;password=freelance"
cookieless="false" timeout="20" />
Advantages:
Fastest mode
Simple configuration
Disadvantages:
This mode is ideal for scalable and highly available applications. Session
state is held in a process called aspnet_state.exe that runs as a windows
service which listens on TCP port 42424 by default. You can invoke state
service using services MMC snap-in or by running following net command
from command line.
Configuration information:
<sessionState mode="StateServer"
StateConnectionString="tcpip=127.0.0.1:42424"
sqlConnectionString="data source=127.0.0.1;user id=freelance; password=freelance"
cookieless="false" timeout="20"/>
Advantages:
Disadvantages:
Configuration Information:
<sessionState mode="SQLServer"
sqlConnectionString="data source=server;user id=freelance;password=freelance"
cookieless="false" timeout="20" />
Advantages:
Disadvantages:
When leveraging client side state options, ensure that little amount of
insignificant information is exchanged between page requests.
Cookies in ASP.NET
What is a cookie?
A cookie is a small bit of text that accompanies requests and pages as they go between the
Web server and browser. The cookie contains information the Web application can read
whenever the user visits the site.
In simple term, cookie is a small text file sent by web server and saved by web browser on
client machine.
Class-> httpSessionState
SessionID is send to the client in the form of cookie by server if the request is generated for
the first time.
Session Cookie
Name and value will be sent to client as session cookie (which is stored in cookie header).
Earlier to 2.0 session was maintained but 2.0 onwards we have to explicitly maintain
session (so we can use web and mobile development).
Cookies can be stored in persist and non persist manner. By default cookies are non
persistent.
Persistent cookies are sorted on client browser.
You can set the expiration date of the cookie for some day in the future it will remain their
until that day unless manually deleted by the user
I will explain you with the help of a program how to store cookies and how to retrieve the
cookies.
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherit
s="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0
Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="Button1" runat="server" Text="Store
Cookies" OnClick="Button1_Click" />
</div>
</form>
</body>
</html>
Code for Default.aspx.cs page
using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
HttpCookie myCookie;
protected void Button1_Click(object sender, EventArgs e)
{
myCookie = new HttpCookie("test");
myCookie.Values["name"] = "Puran Singh Mehra";
myCookie.Values["age"] = "30+";
myCookie.Values["Profession"] = "Software";
myCookie.Values["Address"] = "India";
myCookie.Expires = DateTime.Now.AddHours(1);
Response.Cookies.Add(myCookie);
Response.Redirect("Default2.aspx");
}
}
Output 1:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherit
s="Default2" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0
Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Style="top: 231p
x;
left: 476px; position: absolute; height: 26px; width: 116px" Text="Show
Cookie" />
</div>
</form>
</body>
</html>
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
public partial class Default2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
foreach (string str in Request.Headers)
{
Response.Write(str + "=" + Request.Headers[str] + "<br>");
}
Response.Write("________________________________________________" + "<br>");
}
protected void Button1_Click(object sender, EventArgs e)
{
foreach (string str in Request.Cookies["test"].Values)
{
Response.Write(str + "=" + Request.Cookies["test"].Values[str] + "<br>");
}
}
}
Output 2:
Output 3:
Cookies Merits
Data is stored on client side, so it is faster. Cookies are best used to store small amounts of
data, for example it can store User ID and Password. This UserID and Password can then be
used to identify the user and read user information from a database or other data store. It
is recommended to encrypt a password before it is stored in a cookie as cookies are not
secured.
Cookies Demerits
Conclusion
I hope that this article would have helped you in understanding Cookies in ASP.NET. How
you can use them to save state management. Please share it if you know more about this
attribute. Your feedback and constructive contributions are welcome.