ASP.NET state management

Posted on Updated on

ASP.NET state management

·   Web pages rarely be stand alone. Web applications almost always need to track users who visit multiple pages, whether to provide personalization, store information about a user or to track usage for reporting purposes.

·   State management is the process by which you maintain state and page information over multiple requests for the same or different pages. 

·   Whenever any request is sent, the interaction between the client and server can be either stateless or stateful.

Types of State Management 
1) Client – Side State Management –view state, cookies, hidden fields, query string

2)  Server – Side State Management –session state, application state

 

Client side State management Options:
i) 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 to keep 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!”;

If you want to store client’s information use the below code

Response.Cookies[“UserId”].Value=username;

Advantages:

  • Simplicity

Disadvantages:

  • Cookies can be disabled on user browsers
  • Cookies are transmitted for each HTTP request/response causing overhead on bandwidth
  • Inappropriate for sensitive data

 

ii) 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. 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:

  • Simple to implement for a page specific data
  • Can store small amount of data so they take less size.

Disadvantages:

  • Inappropriate for sensitive data
  • Hidden field values can be intercepted(clearly visible) when passed over a network

iii)View State: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 addingEnableViewState=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.

// Add item to ViewState

ViewState[“myviewstate”]  = myValue;

 //Reading items from ViewState
Response.Write(ViewState[“myviewstate”]);
Advantages:

  • Simple for page level data
  • Encrypted 
  • Can be set at the control level

Disadvantages:

  • Overhead in encoding View State values
  • Makes a page heavy

iv)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, 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

 

Server Side State management:

As name implies, state information will be maintained on the server.

i)Application: Application State: ASP.NET allows you to save values using application state, a global storage mechanism that is accessible from all pages in the Web application. Application state is stored in the Application key/value dictionary. Once you add your application-specific information to application state, the server manages it, and it is never exposed to the client. Application state is a great place to store information that is not user-specific. By storing it 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. 

Application object is used to store data which is visible across entire application and shared across multiple user sessions. Data which needs to be persisted for entire life of application should be stored in application object.
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. 

 

·   Variables and objects added to the application state are global to an Asp.net application. For example, we can create a variable called appvar with the value Hello and store it in the application state. To create  appvar, we need to use the following statement:

Application [“appvar”]=”Hello”;

·   After the application in which you declared app var is executed, any page contained in the application can retrieve the value of the appvar. To read the value of the MyVariable, we need to use the following-

Response.Write(Application[“appvar”]);

Advantages:

·   Applications state is easy to use and is consistent with other .net framework classes.

·   Storing information in application state involves maintaining only a single copy of the information.

Disadvantages:

·   The data stored in application state is lost when the web server containing the application state fails due to server crash, upgrade or shut down.

·   It requires server memory and can affect the performance of the server and the scalability of the web application.

 

ii) Session: 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:
<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 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.You can disable session for a page using EnableSessionState attribute. You can set off session for entire application by setting mode=off in web.config file to reduce overhead for the entire application.

Configuration information:

<sessionState mode=”Inproc”

 sqlConnectionString=”data source=server;user id=freelance;password=freelance”

 cookieless=”false” timeout=”20″ />

Advantages:

  • Fastest mode 
  • Simple configuration

Disadvantages:

  • Session data will be lost if the worker process or application domain recycles
  • Not ideal for web gardens and web farms

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s