asp state management
TRANSCRIPT
![Page 1: ASP State Management](https://reader031.vdocuments.net/reader031/viewer/2022022215/577d35b71a28ab3a6b91363b/html5/thumbnails/1.jpg)
8/8/2019 ASP State Management
http://slidepdf.com/reader/full/asp-state-management 1/16
ASP.Net State Management Techniques
State Management Techniques in ASP.NET
This article discusses various options for state management for web
applications developed using ASP.NET. Generally, web applications are basedon stateless HTTP protocol which does not retain any information about userrequests. In typical client and server communication using HTTP protocol,page is created each time the page is requested.
Developer is forced to implement various state management techniqueswhen developing applications which provide customized content and which"remembers" the user.
Here we are here with various options for ASP.NET developer to implement
state management techniques in their applications. Broadly, we can classifystate management techniques as client side state management or serverside state management. Each technique has its own pros and cons. Let'sstart with exploring client side state management options.
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.NET2.0). Let's discuss each of client side state management options.
Bandwidth should be considered while implementing client side statemanagement options because they involve in each roundtrip to server.Example: Cookies are exchanged between client and server for each page
request.
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 tokeep track of visitors. Every time a user visits a website, cookies are
retrieved from user machine and help identify the user.
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!";
![Page 2: ASP State Management](https://reader031.vdocuments.net/reader031/viewer/2022022215/577d35b71a28ab3a6b91363b/html5/thumbnails/2.jpg)
8/8/2019 ASP State Management
http://slidepdf.com/reader/full/asp-state-management 2/16
If you want to store client's information use the below code
Response.Cookies["UserId"].Value=username; Advantages:
y Simplicity
Disadvantages:
y Cookies can be disabled on user browsersy Cookies are transmitted for each HTTP request/response causing
overhead on bandwidthy Inappropriate for sensitive data
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 controlfor which you can set its properties. Whenever a page is submitted toserver, hidden fields values are also posted to server along with othercontrols on the page. Now that all the asp.net web controls have built instate management in the form of view state and new feature in asp.net 2.0control state, hidden fields functionality seems to be redundant. We can stilluse it to store insignificant data. We can use hidden fields in ASP.NET pagesusing 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:
y Simple to implement for a page specific datay Can store small amount of data so they take less size.
Disadvantages:
y Inappropriate for sensitive datay Hidden field values can be intercepted(clearly visible) when passed
over a network
![Page 3: ASP State Management](https://reader031.vdocuments.net/reader031/viewer/2022022215/577d35b71a28ab3a6b91363b/html5/thumbnails/3.jpg)
8/8/2019 ASP State Management
http://slidepdf.com/reader/full/asp-state-management 3/16
View State:
View State can be used to store state information for a single user. ViewState is a built in feature in web controls to persist data between page postbacks. You can set View State on/off for each control
using EnableViewState property. By default, EnableViewState propertywill be set to true. View state mechanism poses performance overhead. Viewstate information of all the controls on the page will be submitted to serveron each post back. To reduce performance penalty, disable View State for allthe controls for which you don't need state. (Data grid usually doesn't needto maintain state). You can also disable View State for the entire page byadding EnableViewState=false to @page directive. View state data isencoded as binary Base64 - encoded which add approximately 30%overhead. Care must be taken to ensure view state for a page is smaller insize. View State can be used using following syntax in an ASP.NET webpage.
// Add item to ViewState ViewState["myviewstate"] = myValue; //Reading items from ViewStateResponse.Write(ViewState["myviewstate"]);
Advantages: y Simple for page level datay Encrypted
y Can be set at the control level
Disadvantages:
y Overhead in encoding View State valuesy Makes a page heavy
Query strings:
Query strings are usually used to send information from one page to anotherpage. 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 onlypass smaller amounts of data using query strings. Since Query strings aresent in clear text, we can also encrypt query values. Also, keep in mind thatcharacters that are not valid in a URL must be encodedusing Server.UrlEncode.
![Page 4: ASP State Management](https://reader031.vdocuments.net/reader031/viewer/2022022215/577d35b71a28ab3a6b91363b/html5/thumbnails/4.jpg)
8/8/2019 ASP State Management
http://slidepdf.com/reader/full/asp-state-management 4/16
Let's assume that we have a Data Grid with a list of products, and ahyperlink in the grid that goes to a product detail page, it would be an idealuse of the Query String to include the product ID in the Query String of thelink to the product details page (for example,productdetails.aspx?productid=4).
When product details page is being requested, the product information canbe obtained by using the following codes:
string productid;productid=Request.Params["productid"]; Advantages:
y Simple to Implement
Disadvantages:
y Human Readabley Client browser limit on URL lengthy Cross paging functionality makes it redundanty 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 statecontainer reserved for controls to maintain their core behavioral functionalitywhereas View State only contains state to maintain control's contents (UI).Control State shares same memory data structures with View State. ControlState can be propagated even though the View State for the control isdisabled. For example, new control Grid View in ASP.NET 2.0 makes effectiveuse of control state to maintain the state needed for its core behavior acrosspost backs. Grid View is in no way affected when we disable View State forthe Grid View or entire page
Server Side State management:
As name implies, state information will be maintained on the server.Application, Session, Cache and Database are different mechanisms forstoring state on the server.
Care must be taken to conserve server resources. For a high traffic web sitewith large number of concurrent users, usage
![Page 5: ASP State Management](https://reader031.vdocuments.net/reader031/viewer/2022022215/577d35b71a28ab3a6b91363b/html5/thumbnails/5.jpg)
8/8/2019 ASP State Management
http://slidepdf.com/reader/full/asp-state-management 5/16
of sessions object for state management can create load on server causing
performance degradation
Application object:
Application object is used to store data which is visible across entireapplication and shared across multiple user sessions. Data which needs to bepersisted for entire life of application should be stored in application object.
In classic ASP, application object is used to store connection strings. It's agreat place to store data which changes infrequently. We should write toapplication variable only in application_Onstart event (global.asax) orapplication.lock event to avoid data conflicts. 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. Itis specific to particular user. Session data persists for the duration of usersession you can store session's data on web server in different ways.Session state can be configured using the <session State> section in theapplication's web.config file.
Configuration information:
<sessionState mode = <"inproc" | "sqlserver" | "stateserver">cookieless = <"true" | "false">timeout = <positive integer indicating the session timeout in minutes>sqlconnectionstring = <SQL connection string that is only used in the SQLServer mode>server = <The server name that is only required when the mode is State Server>
port = <The port number that is only required when the mode is State Server>
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 whetherthe Session is a cookie less one.
Timeout:
![Page 6: ASP State Management](https://reader031.vdocuments.net/reader031/viewer/2022022215/577d35b71a28ab3a6b91363b/html5/thumbnails/6.jpg)
8/8/2019 ASP State Management
http://slidepdf.com/reader/full/asp-state-management 6/16
This indicates the Session timeout vale in minutes. This is the duration forwhich a user's session is active. Note that the session timeout is a slidingvalue; Default session timeout value is 20 minutes
SqlConnectionString:
This identifies the database connection string that names the database usedfor mode SQLServer.
Server:
In the out-of-process mode State Server, it names the server that is runningthe required Windows NT service: aspnet_state.
Port:
This identifies the port number that corresponds to the server setting formode State Server. Note that a port is an unsigned integer that uniquelyidentifies a process running over a network.
Y ou can disable session for a page using EnableSessionState attribute. Y ou
can set off session for entire application by setting mode=off in web.config
file to reduce overhead for the entire application.
Session state in ASP.NET can be configured in different ways based onvarious parameters including scalability, maintainability and availability
y In process mode (in-memory)- State information is stored in memoryof web server
y Out-of-process mode- session state is held in a process calledaspnet_state.exe that runs as a windows service.
y Database mode â¼³ session state is maintained on a SQL Serverdatabase.
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 sessionspecific 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" />
![Page 7: ASP State Management](https://reader031.vdocuments.net/reader031/viewer/2022022215/577d35b71a28ab3a6b91363b/html5/thumbnails/7.jpg)
8/8/2019 ASP State Management
http://slidepdf.com/reader/full/asp-state-management 7/16
Advantages:
y Fastest modey Simple configuration
Disadvantages:
y Session data will be lost if the worker process or application domainrecycles
y Not ideal for web gardens and web farms
Out-of-process Session mode (state server mode):
This mode is ideal for scalable and highly available applications. Sessionstate is held in a process called aspnet_state.exe that runs as a windowsservice which listens on TCP port 42424 by default. You can invoke stateservice using services MMC snap-in or by running following net commandfrom command line.
Net start aspnet_state
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:
y Supports web farm and web garden configurationy Session data is persisted across application domain recycles. This is
achieved by using separate worker process for maintaining state
Disadvantages:
y Out-of-process mode provides slower access compared to In processy
Requires serializing data
SQL-Backed Session state:
ASP.NET sessions can also be stored in a SQL Server database. Storingsessions in SQL Server offers resilience that can serve sessions to a largeweb farm that persists across IIS restarts.
![Page 8: ASP State Management](https://reader031.vdocuments.net/reader031/viewer/2022022215/577d35b71a28ab3a6b91363b/html5/thumbnails/8.jpg)
8/8/2019 ASP State Management
http://slidepdf.com/reader/full/asp-state-management 8/16
SQL based Session state is configured with aspnet_regsql.exe. This utility islocated in .NET Framework's installed directoryC:\<windows>\microsoft.net\framework\<version>. Running this utility will
create a database which will manage the session state.
Configuration Information:
<sessionState mode="SQLServer" sqlConnectionString="data source=server;user id=freelance;password=freelance" cookieless="false" timeout="20" />
Advantages:
y Supports web farm and web garden configurationy Session state is persisted across application domain recycles and even
IIS restarts when session is maintained on different server.
Disadvantages:
y Requires serialization of objects
Choosing between client side and Server side management techniques isdriven by various factors including available server resources, scalability andperformance. We have to leverage both client side and server side statemanagement options to build scalable applications.
When leveraging client side state options, ensure that little amount of
insignificant information is exchanged between page requests.
Various parameters should be evaluated when leveraging server side stateoptions including size of application, reliability and robustness. Smaller theapplication, In process is the better choice. We should account in theoverheads involved in serializing and deserializing objects when using StateServer and Database based session state. Application state should be usedreligiously.
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.
![Page 9: ASP State Management](https://reader031.vdocuments.net/reader031/viewer/2022022215/577d35b71a28ab3a6b91363b/html5/thumbnails/9.jpg)
8/8/2019 ASP State Management
http://slidepdf.com/reader/full/asp-state-management 9/16
In simple term, cookie is a small text file sent by web server and saved by web browser on
client machine.
Some point to understand cookies
It is a server side object.
Cookies are used in state management.
HttpCookie class is there for cookie by .NET
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 -> ASP.NET_SessionID
Value -> will be alphanumeric value.
Name and value will be sent to client as session cookie (which is stored in cookie header).
ASP.NET 2.0 it is also used for mobile development.
Session timeout is 20 minutes by default (it depends on sliding time request).
In mobile development each request is treated as new request.
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).
If the browser doesn't support cookie or cookies are off in browser,
Cookie less session is maintained.
Cookies can only store string type of data.
You can only store 4kb (4096 bytes) of data in cookie.
When browser goes out of scope cookies are expired.
Cookies can be stored in persist and non persist manner. By default cookies are non
persistent.
![Page 10: ASP State Management](https://reader031.vdocuments.net/reader031/viewer/2022022215/577d35b71a28ab3a6b91363b/html5/thumbnails/10.jpg)
8/8/2019 ASP State Management
http://slidepdf.com/reader/full/asp-state-management 10/16
Persistent cookies are sorted on client browser.
Cookies data is not secured.
Cookies are identified on basis of there name.
Single and multiple value cookies (on basis of key).
Cookies are domain specific also.
IE support more than 100 cookies.
Cookies were introduced from Netscape 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.
Code for Default.aspx design page
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="
_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>
![Page 11: ASP State Management](https://reader031.vdocuments.net/reader031/viewer/2022022215/577d35b71a28ab3a6b91363b/html5/thumbnails/11.jpg)
8/8/2019 ASP State Management
http://slidepdf.com/reader/full/asp-state-management 11/16
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";
![Page 12: ASP State Management](https://reader031.vdocuments.net/reader031/viewer/2022022215/577d35b71a28ab3a6b91363b/html5/thumbnails/12.jpg)
8/8/2019 ASP State Management
http://slidepdf.com/reader/full/asp-state-management 12/16
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:
Code for Default2.aspx design page
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits=
"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
![Page 13: ASP State Management](https://reader031.vdocuments.net/reader031/viewer/2022022215/577d35b71a28ab3a6b91363b/html5/thumbnails/13.jpg)
8/8/2019 ASP State Management
http://slidepdf.com/reader/full/asp-state-management 13/16
![Page 14: ASP State Management](https://reader031.vdocuments.net/reader031/viewer/2022022215/577d35b71a28ab3a6b91363b/html5/thumbnails/14.jpg)
8/8/2019 ASP State Management
http://slidepdf.com/reader/full/asp-state-management 14/16
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:
![Page 15: ASP State Management](https://reader031.vdocuments.net/reader031/viewer/2022022215/577d35b71a28ab3a6b91363b/html5/thumbnails/15.jpg)
8/8/2019 ASP State Management
http://slidepdf.com/reader/full/asp-state-management 15/16
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
Security problem as they are stored on client.
Client can delete cookie any time.
Browsers also impose limitations on how many cookies your site can store on the user's
computer.
Cookie can only store 4kb of data.
Data is not authenticated i.e. client can delete the cookie.
Conclusion
I hope that this article would have helped you in understanding Cookies in ASP.NET. How
![Page 16: ASP State Management](https://reader031.vdocuments.net/reader031/viewer/2022022215/577d35b71a28ab3a6b91363b/html5/thumbnails/16.jpg)
8/8/2019 ASP State Management
http://slidepdf.com/reader/full/asp-state-management 16/16
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.