Explain State Management (SM):

It is used for maintaining the state of the user. State Management can be achieved at three levels:
1) Session level
2) Application Level
3) Page Level

1) Session Level State Management: it is used to maintain the state of the user across multiple webforms present within the web application.
? To achieve session level state management, sessions and cookies are used.

Sessions: It is used to maintain the user information across the web forms present within the application by maintaining the data at the server side.

Enhancements of Sessions in ASP.NET:
? Session information can be enabled or can be disabled as per the requirement in any web form within the application.
? Sessions in ASP.NET can be either cookies based or cookieless.
? Session information can be stored within the web server as a Inprocess and also the session information can be maintained within the state server and also sql server database as a Outprocess.

To set:
? session [session Variable] = value;

?The value that can be assigned to a session variable can be either a string or an object.
? If string is passed as a value then the session information will be maintained within the contents collection and if any object is assigned as a value then the information will be maintained within the state objects collection.
? The default expiration time for the session information will be 20 minutes.

To read string information:
variable = Session [ sessionVariable].ToString();

To read object information:
objectname = (objecttype)Session [sessionVariable];

String database object information in the sessions

To disable the sessions for any specific webform:

In source of .aspx file:
%@page language = “C#" EnableSessionState = “false" ... %

? Whenever ‘enableSessionState' attribute has been set to false then the session object cannot be used within that web form and the resources required for maintaining the sessions will not be allocated for that page.
? If ‘enableSessionState' is set to false and if the session object is used within the form then the asp.net runtime environment will raise an error.

By default the sessions are always cookie based sessions.

? Browsers are having a capability to disable the cookies and if the browsers has been disabled with the cookies then the web application which uses cookie based sessions will not function properly.
? Inorder to identify the session id of the client session.SessionID should be used.

Cookieless Sessions: If used for maintaining the session information then the session id of the client will be appended for all the navigate url accessed within the web application. Where navigateurl is the url to which the user sending a requesting.

To set:
In web.config file:


? Whenever cookieless sessions are used then as the session id of the client will be appended on all the urls the application will function properly irrespective to cookies are enabled or disabled at the client system.

Client system maintains session id.
Server system maintains session info.

Cookieless sessions can be used if and if the web application does not use any confidential data.
By default the session information is maintained within the webserver as a InProcess.
Whenever the session information is stored as a InProcess within the webserver. If the webserver crashes then the total session information maintained within the webserver will be lost and hence if the same application is existing within other webserver, the data cannot be accessed.

Maintaining session information as a out process: (i.e. Sql server database, State server)

Maintaining session information within state server:
State server: It is a window service which is used to refer the address of a memory block at the webserver.

To store session information within state server

Performance: (Maintaining session information)
Webserver > State Server > Sql server DB
Faster Slow

Consistency: (of data)
Webserver < State Server < Sql server DB
Less secure More secure

Inorder to kill the session of the user explicitly:
Session. Abandon();

Cookies: It is used to maintain the server side information at client system.
Cookies is of 2 types:
1) In memory cookies or temporary cookies or non-persistent cookies
2) Permanent cookies or persistent cookies

1) In memory cookies: If used for maintaining the user information then the cookie details will be stored within the memory allocated by the web browser.
2) Permanent cookies: If persistent cookies are used for maintaining the user information then the cookie details will be maintained within the file at the client system.

To set the cookie:
1st method:
Response.Cookies[cookieName].Value = value;

2nd method:
HttpCookie cookieObject = new HttpCookie (“name", “value");
Response.Appendcookies(cookieObject);

Only string information can be maintained within the cookies.
The default expiration time for the cookie information will be 30 minutes.

To set the expiration time for the cookie information:
1st method:
Response.Cookies[cookieName].Expires = DataTime;

2nd method:
cookieObject.Expires = DateTime;

If a cookie has been defined without an expiration time then it is said to be an in memory cookie and if the cookie information has been defined with the expiration time then it is said to be persistent cookies.

To read the value from the cookie:
variable = Request .Cookies [cookieName].Value;

Cookies can store only string information and the information will always be maintained at the client system only.
Web browsers are having a capability to disable the cookies and if the browser disables the cookie then the web application which uses cookies will not function properly.

The information maintained within the cookie are not secure.

Sessions should be used whenever the data has to be maintained confidential and if any objects has to be passed across multiple webform and the data will be accessed by less users.
Cookies should be used if only string information has to be passed across multiple pages and if the data is not confident and if more number of users access the web application.

Application level state management: Whenever the information of all the users accessing the web application has to be maintained then application level state management should be used.
Assume that we have a web server within webserver we have web application and within application has ‘n' number of webforms.

To set:
Application[“variable"] = value; where the value can be either string or an object

If string information has been assigned to the application variable then the information will be maintained within the contents collection and if any objects are assigned to the application variable then the information will be maintained within the static objects collection.

Application variable will not have any expiration period but if the server has been restarted then the contents present within the application variable will be lost.
The information maintained within the application object will be shared for all the users accessing the web application.

To read the value from the application collection:
To read string information:
variable = Application[“variable"].ToString();

To read object information:
objectName = (objectType)Application[“variable"];

Application.Lock(): It is used to lock the application contents collection from accessing by other users variable, the application contents collection is used by one user.

Whenever an application has been locked then once a complete page has been processed then the application collection will be unlocked implicitly.

Application.Unlock(): It is used to release the lock defined on the application using the Application.Lock method.

Working with Global.asax file:

Global.asax: (Global ASP.Net Application file)
It is a collection of events which will be raised implicitly based on the actions performed by the user within the web application.

Events present within the Global.asax file:
1) Application_Start: The code written within this event will be executed only once whenever the web application is requested for the first time.
2) Application_BeginRequest: The code written within this event will be executed for all the web forms present within the web application before processing the code written within the page load event.
3) Application_EndRequest: The code written within this event will be executed for all the webforms present within the web application before the user navigates from one web form to the other.
4) Application_Authenticate: The code written within this event will be executed before the user credentials has been authenticated by the ASP.Net runtime.
5) Application_Error: The code written within this event will be executed implicitly whenever any exception is raised within any webform present within the application and if the exception is not handled within the form.
6) Application_End: The code written within this event will be executed only once whenever the website has been shutdown.
7) Session_Start: The code written within this event will be executed every time a new session has been created for a web application within the server.
8) Session_End: The code written within this event will be executed whenever the session of the user has been expired.

If the session information is maintained within the SQL server database or the state server and if the session of the user has been expired this event will not be raised.

3) Page level state management: It is used for maintaining the state of the controls after submitting the data to the server.

By default for all the web server controls page level state management will be enabled.
Inorder to achieve page level state management, view state will be used.

Viewstate is a class which maintains the state of the control by maintaining the information in a name value pair within the view state bag collection.

To set the view state explicitly:
ViewState[“control"] = value;

To read the value from the view state:
variable = ViewState[“control"];

whenever view state has been enabled for the control then the ASP.Net runtime environment will define a HTML hidden field with a name _ _ ViewState and the value will be encrypted.


Comments

Author: ChandraShekar Thota14 Jan 2009 Member Level: Gold   Points : 0

Good one keep it up..

Chandrashekar Thota(Editor, MVP)

Author: Gaurav Aroraa30 Jan 2009 Member Level: Gold   Points : 2

State Managment

The State or Cache Management is nothing but the way to storing the data in Client-Side and in Server-Side using preity small memory.

There are two major category of the above :

Server-Side State Management




Session State: Its nothing but defined as a period of time shared between the web application and user. Every user has individual session. Items/Objects can be placed into the Session which would only define these object for that user. Session contains key variables which help to identify the related values. This can be thought of as a hash table. Each user would represent a different key node in the hash identifying unique values. The Session variables will be clear by the application which can clear it, as well as through the timeout property in the web config file. Usually the timeout is 20 minutes by default.




Session Variables are stored on the server, can hold any type of data including references, they are similar to global variables in a windows application and use HTTP cookies to store a key with which to locate user's session variables.




The collection of session variables is indexed by the name of the variable or by an integer index. Session variables are created by referring to the session variable by name. You do not have to declare a session variable or explicitly add it to the collection.




Lets get it cleared from following example:




Session[“firstName"] = “Gaurav" //User's first name

Session[“lastName"] = “Arora" //User's last name




// Clear the session variable

Session[“FirstName"] = null;




//Clear all Session variables

Session.Abandon();







InProc—Stores Session state in the same process as the ASP.NET process [aspnet_wp.exe].




StateServer—Stores Session state in a Windows NT process, which is distinct from the ASP.NET process[aspnet_state.exe].




SQLServer—Stores Session state in a SQL Server database.




Both in StateServer and SQLServer options, we need to ensure that the objects we cache are serializable as data storages are out-of-process systems. Both these options have impact on the application performance as data retrieval and saving operations take more time when compared to the InProc option. So based on our application requirement we should choose the option that best suits our requirement.







Note:

By default, ASP.NET session state is enabled for all ASP.NET applications.

Author: Mrs. Meetu Choudhary Nanda11 Feb 2009 Member Level: Gold   Points : 2

State Management is defined as the management of the state of one or more user interface controls such as textboxes, buttons, etc in a Graphical User Interface. In UI programming technique, the state of UI control depends on the state of other UI controls. For example, a state managed UI control such as a command button will be in its enabled state when input fields or the text fields have valid values and the button will be in the disabled state if the input fields are empty or have invalid values.

In ASP.NET applications, hosted in a web server are accessed over the stateless HTTP protocol. As such, if the application uses state full interaction, it has to implement state management on its own. ASP.NET provides various functionality for state management in ASP.NET applications.

Some of them are


Application state

A collection of user-defined variables which are shared by an ASP.NET application are termed as Application state. When the Application_OnStart event fires at the time of loading of the first instance of the applications these variables are set and initialized and are available till the last instance of the application exits. To access the Application state variables the Applications collection is used, which provides a wrapper for the application state variables.

Session state

A collection of user-defined session variables are termed as Session state, which are persevered during a user session. These variables are accessed using a Session Collection. These variables have a unique instance to different instances of a user session for the application. Session variables can be set to automatically destroyed after a definite period of inactive time, irrespective of the session state whether session ends or not. At the client side, a user session is identified either by a cookie or by encoding the session ID in the URL.


ASP.NET supports three modes of persistence for session variables:


In Process Mode
These session variables are maintained within the process of ASP.NET Applications. This is the fastest way, however, in this mode the variables are destroyed when the process is recycled or shut down. This mode is not recommended for critical applications as the application is recycled from time to time.

ASPState Mode
In this mode, A separate Windows service is run by ASP.NET, Which maintains the state variables. This has a negative impact on performance as the state management happens outside the ASP.NET process,on the other hand it allows multiple ASP.NET instances to share the same server state, thus allowing an ASP.NET application to be load-balanced and scaled out on multiple servers.As state management service runs independent from ASP.NET, variables can persist across ASP.NET process shutdowns.

SqlServer Mode
In this mode, the state variables are stored in a database, which are accessible using SQL or SQL Queries. Variables can be persisted across ASP.NET process shutdowns. The advantage of SqlServer mode is it allows the application to balance load on a server cluster while sharing sessions between servers.

View state

Mechanism to manage the state at the page-level is refereed as View state, that is utilized by the HTML pages by ASP.NET applications to maintain the state of the web form controls. The encoded state of the controls are sent to the server at time of form submission in a hidden field known as __VIEWSTATE. The server returns the value back of the variable so that when the page is re-rendered, the controls render at their last state.

Other

Other means of state management that are supported by ASP.NET are cookies, caching, and using the query string.



  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: