State
management
State management
is the process by which you maintain state and page information over multiple
requests for the same or different pages.
Types of State
Management
1.
Client
– Side State Management
This stores
information on the client's computer by embedding the information into a Web
page, a uniform resource locator(url), or a cookie. The techniques available to
store the state information at the client end are listed down below:
a. View
State – Asp.Net uses View State
to track the values in the Controls. You can add custom values to the view
state. It is used by the Asp.net page framework to automatically save the
values of the page and of each control just prior to rendering to the page.
When the page is posted, one of the first tasks performed by page processing is
to restore view state.
// Check if View State
object exists, and display it if it does
If (ViewState
["lastVisit"]!= null)
Label1.Text =
(string)ViewState["lastVisit"]; else
Label1.Text =
"lastVisit ViewState not defined.";
// Define the
ViewState object for the next page view ViewState.Add("lastVisit",
DateTime.Now.ToString());
B . Hidden fields – Like view state, hidden fields store data in an HTML
form without displaying it in the user's browser. The data is available only
when the form is processed.
C. Cookies –
Cookies store a value in the user's browser that the browser sends with every
page request to the same server. Cookies are the best way to store state data
that must be available for multiple Web pages on a web site.
Though it depends
on the browser, you typically can’t store more than 20 cookies per site, and
each cookie can be a maximum of 4 KB in length.
<body
runat="server" id="BodyTag">
<form id="form1"
runat="server">
<asp:DropDownList runat="server"
id="ColorSelector" autopostback="true" onselectedindexchanged="ColorSelector_IndexChanged">
<asp:ListItem
value="White" selected="True">Select
color...</asp:ListItem>
<asp:ListItem value="Red">Red</asp:ListItem>
<asp:ListItem value="Green">Green</asp:ListItem>
<asp:ListItem
value="Blue">Blue</asp:ListItem>
</asp:DropDownList>
</form>
</body>
protected void
Page_Load(object sender, EventArgs e)
{
if
(Request.Cookies["BackgroundColor"] != null)
{
ColorSelector.SelectedValue =
Request.Cookies["BackgroundColor"].Value;
BodyTag.Style["background-color"] =
ColorSelector.SelectedValue;
}
}
protected void
ColorSelector_IndexChanged(object sender, EventArgs e)
{
BodyTag.Style["background-color"]
= ColorSelector.SelectedValue;
HttpCookie cookie = new
HttpCookie("BackgroundColor");
cookie.Value =
ColorSelector.SelectedValue;
cookie.Expires =
DateTime.Now.AddHours(1);
Response.SetCookie(cookie);
}
D . Query Strings - Query strings store values in the URL that
are visible to the user. Use query strings when you want a user to be able to
e-mail or instant message state data with a URL.
http://support.microsoft.com/Default.aspx?kbid=315233
Limitations for
Query Strings:
1. Some Browsers and client devices
impose a 2083 – character limit on the length of the URL.
2. You must submit the page using an
HTTP GET command in order for query string values to be available
during page
processing. Therefore, you shouldn’t add query strings to button targets in
forms.
3. You must manually add query string
values to every hyperlink that the user might click.
int ID = 10;
string name =
"SHASHI";
Response.Redirect("Default1.aspx?id="+ID+"&name="+name);
f
(Request.QueryString[0] != null && Request.QueryString[1] != null)
{
/* string id =
Request.QueryString[0].ToString();
string name =
Request.QueryString[1].ToString();
*/
string id =
Request.QueryString["id"].ToString();
string name =
Request.QueryString["name"].ToString();
}
2. Server – Side State
Management
a. Application State
- Application State
information is available to all pages, regardless of which user requests a
page.
a global storage
mechanism that is accessible from all pages in the Web application.
By storing data in the application state, all
pages can access data from a single location in memory, rather than keeping
separate copies of the data. Data stored in the Application object is not
permanent and is lost any time the application is restarted.
ASP.NET provides
three events that enable you to initialize Application variables (free
resources when the application shuts down) and respond to Application errors:
a. Application_Start: Raised when the
application starts. This is the perfect place to initialize Application
variables.
b. Application_End: Raised when an
application shuts down. Use this to free application resources and perform
logging.
c. Application_Error: Raised when an
unhandled error occurs. Use this to perform error logging.
Both application
state and session state information is lost when the application restarts. To
persist user data between application restarts, you can store it using profile
properties.
void Application_Start(object sender, EventArgs e)
{
// Code that runs on
application startup
Application["LoginID"] = "annathurai";
Application["DomainName"] = "www.annathurai.com";
}
Example 2: Inside the
.aspx page
protected void Page_Load(object sender, EventArgs e)
{
// Code that runs
on page load
Application["LoginID"] = "annathurai";
Application["DomainName"] = "www.annathurai.com";
}
How to retrieve application state?
It's very easy to retrieve application state in the ASP.NET
application. I am going to take you to write simple application state program
now.
string loginID=string.Empty;
loginID = Application["LoginID"].ToString();
string loginID = string.Empty;
loginID
= Application.GetKey(0);
How to remove application variable?
We have three methods to remove application variable from the
ASP.NET application.
Application.Remove("LoginID");
Application.RemoveAt(0);
Application.RemoveAll();
How to implement Synchronization in application state?
We can avoid deadlock occurrence while we updating application
variable by multiple users with help of Lock(),and,UnLock().
Application.Lock();
Application["LoginID"]= "annathurai";
Application["Domain"]= "www.annathurai.com";
Application.UnLock();
Application.Lock();
Application["LoginID"]= "annathurai";
Application["Domain"]= "www.annathurai.com";
Application.UnLock();
Advantages of application state:
·
Application object memory
relased when we removed.
·
Multi user can able to access
application variable.
·
To avoid deadlock or conflict
we should use Lock and Unlock when we use write or update in the application
object.
·
Other application can't access
this application values.
Disadvantages of application state:
·
Application variable will
exists until exit our application.
·
If we do not have Lock() and
Unlock, deadlock will occur.
·
Its gloable variable so anyone
can access within this application.
b.Session State
– Session State
information is available to all pages opened by a user during a single visit.
Web is Stateless,
which means a new instance of the web page class is re-created each time the
page is posted to the server. As we all know HTTP is a stateless protocol, it
can't hold the client information on page. If user inserts some information,
and move to the next page, that data will be lost and user would not able to
retrieve the information. So what we need? we need to store information.
Session provides that facility to store information on server memory. It can
support any type of object to store along with our custom object. For every
client Session data store separately, means session data is stored as per
client basis.

This Session TimeOut Setting keeps session alive for 30 minute.
It is really a great work and the way in which u r sharing the knowledge is excellent.
ReplyDeleteThanks for helping me to understand basic concepts. As a beginner in Dot Net programming your post help me a lot.Thanks for your informative article. dot net training institute in velachery | top10 dot net training institutes in chennai