Pages

Saturday 12 January 2013

State Management in ASP.Net

In general, Webapplications are stateless i.e. the objects wont persist its state accross request to the web application. In other words, the State or Cache Management is nothing but the way to storing the data in Client-Side and in Server-Side using pretty small memory to maintain its state.
There are two major categories of the above :
1.Server-Side State Management
2.Client-Side State Management
Moving forward, we will see how State Management is done in ASP.Net application.


Server-Side State Management
  1. Session State
  2. Application State


Client-Side State Management
  1. Cookies
  2. ViewState
  3. Hidden fields
  4. Query Strings
View State:
The View State is the state of the page and all its controls. It is automatically maintained across posts by the ASP.Net framework.
When a page is sent back to the client, the changes in the properties of the page and its controls are determined and stored in the value of a hidden input field named _VIEWSTATE. When the page is again post back the _VIEWSTATE field is sent to the server with the HTTP request.
The view state could be enabled or disabled for:
  • The entire application - by setting the EnableViewState property in the <pages> section of web.config file
  • A page - by setting the EnableViewState attribute of the Page directive, as <%@ Page Language="C#" EnableViewState="false" %>
  • A control - by setting the Control.EnableViewState property. 

    Advantages:
     
  • Can be set at the control level
Disadvantages:
  • Overhead in encoding View State values
  • Makes a page heavy
Session State:

When a user connects to an ASP.Net website, a new session object is created.
When session state is turned on, a new session state object is created for each new request.
This session state object becomes part of the context and it is available through the page.
Session state is generally used for storing application data like inventory or supplier list, or a customer record or shopping cart.
It can also keep information about the user and his preference and keep track of pending operations. Sessions are identified and tracked with a 120-bit SessionID, which is passed from client to server and back as cookie or a modified URL.
The SessionID is globally unique and random.
The session state object is created from the HttpSessionState class, which defines a collection of session state items. 

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.
Session state in ASP.NET can be configured in different ways based on various parameters including scalability, maintainability and availability
  • In process mode (in-memory)- State information is stored in memory of web server
  • Out-of-process mode- session state is held in a process called aspnet_state.exe that runs as a windows service.
  • Database mode รข€“ session state is maintained on a SQL Server database.

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:
  • Session data will be lost if the worker process or application domain recycles
  • 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. 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.
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:
  • Supports web farm and web garden configuration
  • Session data is persisted across application domain recycles. This is achieved by using separate worker process for maintaining state
Disadvantages:
  • Out-of-process mode provides slower access compared to In process
  • Requires serializing data  
SQL-Backed Session state:
ASP.NET sessions can also be stored in a SQL Server database. Storing sessions in SQL Server offers resilience that can serve sessions to a large web farm that persists across IIS restarts.

SQL based Session state is configured with aspnet_regsql.exe. This utility is located in .NET Framework's installed directory
 C:\<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:
  • Supports web farm and web garden configuration
  • Session state is persisted across application domain recycles and even IIS restarts    when session is maintained on different server.
Disadvantages:
  • Requires serialization of objects
ASP.NET session state supports several different storage options for session data:
a. InProc Stores session state in memory on the Web server. This is the default, and it offers much better performance than using the ASP.NET state service or storing state information in a database server. InProc is fine for simple applications, but robust applications that use multiple Web servers or must persist session data between application restarts should use State Server or SQLServer.
b. StateServer Stores session state in a service called the ASP.NET State Service. This ensures that session state is preserved if the Web application is restarted and also makes session state available to multiple Web servers in a Web farm. ASP.NET State Service is included with any computer set up to run ASP.NET Web applications; however, the service is set up to start manually by default. Therefore, when configuring the ASP.NET State Service, you must set the startup type to Automatic.
c. SQLServer Stores session state in a SQL Server database. This ensures that session state is preserved if the Web application is restarted and also makes session state available to multiple Web servers in a Web farm. On the same hardware, the ASP.NET State Service outperforms SQLServer. However, a SQL Server database offers more robust data integrity and reporting capabilities.
d. Custom Enables you to specify a custom storage provider. You also need to implement the custom storage provider.
e. Off Disables session state. You should disable session state if you are not using it to improve performance.
 

void StoreSessionInfo()
{
 String fromuser = TextBox1.Text;
 Session["fromuser"] = fromuser;
}
void RetrieveSessionInfo()
{
 String fromuser = Session["fromuser"];
 Label1.Text = fromuser;
}

Application State

An ASP.Net application is the collection of all web pages, code and other files within a single virtual directory on a web server. When information is stored in application state, it is available to all the users.
To provide for the use of application state, ASP.Net creates an application state object for each application from the HTTPApplicationState class and stores this object in server memory. This object is represented by class file global.asax.
Application State is mostly used to store hit counters and other statistical data, global application data like tax rate, discount rate etc and to keep track of users visiting the site.

Application state data is generally maintained by writing handlers for the events:
  • Application_Start
  • Application_End
  • Application_Error
  • Session_Start
  • Session_End
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. 


  The following code snippet shows the basic syntax for storing application state information:


Void Application_Start(object sender, EventArgs e)  {    Application["startMessage"] = "The application has started.";  }  Void Application_End(object sender, EventArgs e)  {    Application["endtMessage"] = "The application has ended.";  } 
 
Query Strings
 
Query strings provide a simple but limited way of maintaining some state information.You can easily pass information from one page to another, But most browsers and client devices impose a 255-character limit on the length of the URL. In addition, the query values are exposed to the Internet via the URL so in some cases security may be an issue.
http://www.CodeDigest.com/?authorid=4
Example
string authorid;
authorid=Request.Params[“authorid”];



Advantages:
  • Simple to Implement

Disadvantages:

  • Human Readable 
  • Client browser limit on URL length
  • Cross paging functionality makes it redundant 
  • Easily modified by end user

Hidden fields

Hidden fields are very popular among VB-ASP web developers. Hidden field is similar to any other control in a page but the visible state of this control is always false. Like ViewState we should not use it for storing large amounts of data.
Note:Similarly hidden frames can be used to cache data in the client side. But please note that hidden frames are not supported by all Internet browsers.

<!--In ASP.NET-->
<asp:HiddenField ID="myHiddenField" Value="Shuby"  runat="server" />                                    
<!--In HTML-->
<input id="myHiddenField" type="hidden" value="Shuby" />



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


Cookies

Cookie is a very familiar term in web development environment. Cookie is a client-side storage that is sent to the server for each request and also received as response back from the server. Because of its size limitation (4096 bytes) it should be used for storing small amount of data. Expiration policies can be set for cookies to invalidate the items after a certain period of time. The following example shows how Cookie can be used in an ASP.NET application:

if (this.Request.Cookies["MY_NAME"] == null) {
    this.Response.Cookies.Add(new HttpCookie("MY_NAME",
                                       "Shubhabrata Mohanty"));
}
else
{
    this.Response.Write(this.Request.Cookies["MY_NAME"].Value);
}



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


    Advantages of Client – Side State Management:

    1. Better Scalability: With server-side state management, each client that connects to the Web server consumes memory on the Web server. If a Web site has hundreds or thousands of simultaneous users, the memory consumed by storing state management information can become a limiting factor. Pushing this burden to the clients removes that potential bottleneck.

    2. Supports multiple Web servers: With client-side state management, you can distribute incoming requests across multiple Web servers with no changes to your application because the client provides all the information the Web server needs to process the request. With server-side state management, if a client switches servers in the middle of the session, the new server does not necessarily have access to the client’s state information. You can use multiple servers with server-side state management, but you need either intelligent load-balancing (to always forward requests from a client to the same server) or centralized state management (where state is stored in a central database that all Web servers access).

    Advantages of Server – Side State Management:

    1. Better security: Client-side state management information can be captured (either in transit or while it is stored on the client) or maliciously modified. Therefore, you should never use client-side state management to store confidential information, such as a password, authorization level, or authentication status.

    2. Reduced bandwidth: If you store large amounts of state management information, sending that information back and forth to the client can increase bandwidth utilization and page load times, potentially increasing your costs and reducing scalability. The increased bandwidth usage affects mobile clients most of all, because they often have very slow connections. Instead, you should store large amounts of state management data (say, more than 1 KB) on the server. 

No comments:

Post a Comment