You are on page 1of 16

State Management Phase II

Rakesh Singh
NARESH I TECHNOLOGIES Hyderabad
0

ASP.NET State Management Server Side State Management:


It is another way which ASP.NET provides to store the user's specific information or the state of the application on the
server machine. It completely makes use of server resources (the server's memory) to store information.
Server-side options for storing page information typically have higher security than client-side options, but they can use
more Web server resources, which can lead to scalability issues when the size of the information store is large.
Or you can say:
ASP.NET offers you a variety of ways to maintain state information on the server, rather than persisting information on the
client. With server-based state management, you can decrease the amount of information sent to the client in order to
preserve state, however it can use costly resources on the server.
ASP.NET provides several options to implement server-side state management.
The following are the server-side state management options that ASP.NET supports:
1. Application State
2. Session State

1. Application State:
Application state is a server side state management technique. The date stored in application state is common for all users
of that particular ASP.NET application and can be accessed anywhere in the application. It is also called application level
state management.
ASP.NET provides application state via the HttpApplicationState class as a method of storing global application-specific
information that is visible to the entire application. Application-state variables are, in effect, global variables for an ASP.NET
application.
You can store your application-specific values in application state, which is then managed by the server.
Data that is shared by multiple sessions and does not change often is the ideal type of data to insert into application-state
variables.
Application state is a data repository available to all classes in an ASP.NET application. Application state is stored in memory
on the server and is faster than storing and retrieving information in a database. Unlike session state, which is specific to
a single user session, application state applies to all users and sessions. Therefore, application state is a useful place to
store small amounts of often-used data that does not change from one user to another.
Application State is used to store information which is shared among users of the ASP.Net web application. Application
state is stored in the memory of the windows process which is processing user requests on the web server. Application
state is useful in storing a small amount of often-used data. If application state is used for such data instead of frequent
trips to the database, then it increases the response time/performance of 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.
If the information that you want to be accessed or stored globally throughout the application, even if multiple users access
the site or application at the same time, then you can use an Application Object for such purposes.
A global storage mechanism that is accessible from all pages in the Web application. Application state is stored in the
Application key/value dictionary. This information will also be available to all the users of the website.

Copyright 2015 - 2016 https://www.facebook.com/rakeshdotnet All Rights Reserved.


Page |1

Advantages of using application state are:

Simple implementation: Application state is easy to use, familiar to ASP developers, and consistent with other
.NET Framework classes.

Application scope: Because application state is accessible to all pages in an application, storing information in
application state can mean keeping only a single copy of the information (for instance, as opposed to keeping
copies of information in session state or in individual pages).

Disadvantages of using application state are:

Application scope: The scope of application state can also be a disadvantage. Variables stored in application
state are global only to the particular process the application is running in, and each application process can have
different values. Therefore, you cannot rely on application state to store unique values or update global counters
in Web-garden and Web-farm server configurations.

Limited durability of data: Because global data that is stored in application state is volatile, it will be lost if the
Web server process containing it is destroyed, such as from a server crash, upgrade, or shutdown.

Resource requirements: Application state requires server memory, which can affect the performance of the
server as well as the scalability of the application.

Careful design and implementation of application state can increase Web application performance. For example, placing a
commonly used, relatively static dataset in application state can increase site performance by reducing the overall number
of data requests to a database. However, there is a performance trade-off. Application state variables containing large
blocks of information reduce Web server performance as server load increases. The memory occupied by a variable stored
in application state is not released until the value is either removed or replaced. Therefore, it is best to use applicationstate variables only with small, infrequently changed datasets.
There are three types of events in ASP.NET. Application event is written in a special file called Global.asax. This file is not
created by default, it is created explicitly by the developer in the root directory.

Application_Start: Raised when the application starts. This is the perfect place to initialize Application
variables.

Application_End: Raised when an application shuts down. Use this to free application resources and perform
logging.

Application_Error: Raised when an unhandled error occurs. Use this to perform error logging.

Application State Considerations:


When using application state, you must be aware of the following important considerations:
Resources: Because it is stored in memory, application state is very fast compared to saving data to disk or a database.
However, storing large blocks of data in application state can fill up server memory, causing the server to page memory
to disk. As an alternative to using application state, you can use the ASP.NET cache mechanism for storing large
amounts of application data. The ASP.NET cache also stores data in memory and is therefore very fast; however,
ASP.NET actively manages the cache and will remove items when memory becomes scarce.

Volatility: Because application state is stored in server memory, it is lost whenever the application is stopped or
restarted. For example, if the Web.config file is changed, the application is restarted and all application state is lost
unless application state values have been written to a non-volatile storage medium such as a database.

Scalability: Application state is not shared among multiple servers serving the same application, as in a Web farm,
or among multiple worker processes serving the same application on the same server, as in a Web garden. Your
application therefore cannot rely on application state containing the same data for application state across different
servers or processes. If your application will run in multi-processor or multi-server environments, consider using a more
scalable option, such as a database, for data that must preserve fidelity across the application.

Copyright 2015 - 2016 https://www.facebook.com/rakeshdotnet All Rights Reserved.


Page |2

Concurrency:
Application state is free-threaded, which means that application state data can be accessed
simultaneously by many threads. Therefore, it is important to ensure that when you update application state data, you
do so in a thread-safe manner by including built-in synchronization support. You can use the Lock and UnLock
methods to ensure data integrity by locking the data for writing by only one source at a time. You can also reduce the
likelihood of concurrency problems by initializing application state values in the Application_Start method in the
Global.asax file.

How to: Save Values in Application State


Application state is stored in an instance of the HttpApplicationState class. This class exposes a key-value dictionary of
objects.
The HttpApplicationState instance is created the first time a user accesses any URL resource in an application. The
HttpApplicationState class is most often accessed through the Application property of the HttpContext class.
Application state stores data as Object data types. Therefore, you must convert the data back to the appropriate type
when retrieving it.
The HttpApplicationState class can be accessed at any time during the life of an application. However, it is often useful
to load application state data when the application starts. To do so, you can put code to load application state into the
Application_Start method in the Global.asax file.
To write a value to application state:
In your application, set the value of the variable in the HttpApplicationState class.
The following code example shows how you can set the application variable Message to a string.
Application["Message"] = "Welcome to the RakeshDotNet.com Web Site.";
To write a value to application state when the application starts
In Application_Start handler of your application's Global.asax file, set the value of the application state variable. Just as
in a regular .aspx page, the HttpApplicationState class is exposed through the Application object.
The following code example shows how you can set the application variable Message to a string and initialize the variable
PageRequestCount to 0.
Application["Message"] = "Welcome to the RakeshDotNet.com Web Site.";
Application["PageRequestCount"] = 0;

We can also save object of some Class in Application variable. Let's say we have a class as:
/// <summary>
/// Summary description for Employee
/// </summary>
public class Employee
{
private string name;
public string Name {
get
{
return this.name;
}
set
{
this.name = value;
}
}
private decimal annualSalary;
public decimal AnnualSalary
{
get

Copyright 2015 - 2016 https://www.facebook.com/rakeshdotnet All Rights Reserved.


Page |3

{
return this.annualSalary;
}
set
{
this.annualSalary = value;
}

}
public Employee()
{
//
// TODO: Add constructor logic here
//
}
}

Put this class file in App_Code folder. Now class will be available throughout the application so also in Global.asax. Now to
save it in Application_Start as:
void Application_Start(object sender, EventArgs e)
{
Employee objEmployee = new Employee();
objEmployee.Name = "Albert";
objEmployee.AnnualSalary = 1000000;
Application["EmployeeObject"] = objEmployee;
}
Note: Here one thing I would like to mention is that we don't require to serialize the object to store in Application state as
we need to keep in mind in case of ViewState, etc. So there is no need of serialization here.
Writing a Value to Application State with Locking:
Application state variables can be accessed by multiple threads at the same time. Therefore, to prevent invalid data, you
must lock application state for writing by only one thread before setting values.
Or in other words we can say:
Application state is not thread safe so it can be accessed by multiple threads at the same time, i.e., if we have stored
some value in Application state say some counter and we increase it whenever a particular page is accessed. So at a single
point of time, two instances of page of a different session can read the same value and update it. So we'll not get the
desired result. So here we need some synchronisation mechanism so that at a single point of time only, one can update its
value. Here we can call the System.Web.HttpApplicationState.Lock method, set the application state value, and then
call the System.Web.HttpApplicationState.UnLock method to unlock the application state, freeing it for other write
or update it.
Note:
You should always modify application state data within a lock statement unless you have set some other type of lock.
To write a value to application state with locking:
In the code where you set the application variable, call the HttpApplicationState.Lock method, set the application state
value, and then call the HttpApplicationState.UnLock method to unlock the application state, freeing it for other write
requests.
The following code example shows how you can lock and unlock application state. The code increases the
PageRequestCount variable by 1 and then unlocks application state.
//Global.asax

Copyright 2015 - 2016 https://www.facebook.com/rakeshdotnet All Rights Reserved.


Page |4

void Application_Start(object sender, EventArgs e)


{
Application["PageRequestCount"] = 0;
}
//In web pages
if (Application["PageRequestCount"]!=null)
{
Application.Lock();
Application["PageRequestCount"] = ((int)Application["PageRequestCount"]) + 1;
Application.UnLock();
}
Response.Write(Application["PageRequestCount"].ToString());

So by this way, we can avoid writing the same value from multiple Threads at the same time.
When we run the page and hit the button to do a postback or page gets refreshed by making request to same page, the
web will show us the postbacks or requests being done so far which is being stored in ApplicationState. We can use this
object to keep track of clicks or requests by all users on the entire website.

How to: Read Values from Application State


Application state stores data typed as Object. Therefore, even though you do not have to serialize the data when storing
it in application state, you must cast the data to the appropriate type when retrieving it. Although you can cast a null object,
if you attempt to use a non-existent application-state entry, a NullReferenceException exception is thrown.
To read a value from application state
Determine whether the application variable exists, and then convert the variable to the appropriate type when
you access it.
The following code example retrieves the application state AppStartTime value and converts it to a variable
named myAppStateTime of type DateTime.
if (Application["AppStartTime"] != null)
{

DateTime myAppStartTime = (DateTime)Application["AppStartTime"];

}
Or in other words we can say:
So to read from Application state is fairly simple. We should just have a safety check to see whether the value we are
accessing is null, if the data will not be in Application state is not there then it will return null and if we'll try to cast it in
any different type, it'll throw an exception. As I already discussed, Application state stores the data in object form so we
need to typecast after reading it. So we can read the value as:
if (Application["Message"] != null)
{

String message = Application["Message"] as String;

Copyright 2015 - 2016 https://www.facebook.com/rakeshdotnet All Rights Reserved.


Page |5

A Classic Example of Application State:


A classic example of Application variable can be to show the number of online user in a website. This can be done in the
following steps:

Add an online counter variable ApplicationStart method of Global.asax file as:


Application["OnlineCounter"] = 0;

So in this, a variable will be added when the application first starts and will be initialized to 0 as there
will be no logged in user at that point of time.

Now as we know whenever a new user opens the website, a new session is created and Session_Start method
of Global.asax is called. So we can increase the counter in this method as:
void Session_Start(object sender, EventArgs e)
{
// Code that runs when a new session is started
if (Application["OnlineCounter"] != null)
{
Application.Lock();
Application["OnlineCounter"] =
((int)Application["OnlineCounter"]) + 1;
Application.UnLock();
}
}

We should use the Locks, else we may get the wrong result because this may be updated at the same time
and updated data is not correct. How: Let's say we currently have Application["OnlineCounter"] is
5 and at the same time, two sessions read the value 5 and make an increment to 6 and updated it.
Application state as 6. So although two users are logged in, the counter is increased by one only. So to
avoid this, we should use the locks.

So also at the time session ends, we should decrease it by one. As I already discussed, an event Session_End is
fired whenever a session ends. So it can be done as:
void Session_End(object sender, EventArgs e)
{
// Code that runs when a new session is started
if (Application["OnlineCounter"] != null)
{
Application.Lock();
Application["OnlineCounter"] =
((int)Application["OnlineCounter"]) - 1;
Application.UnLock();
}
}

And this value can be accessed throughout the application at any point of time in the application as:
if (Application["OnlineCounter"] != null)
{
int OnlineUsers = ((int)Application["OnlineCounter"]);
}

And this value can be used anywhere in the application.

Copyright 2015 - 2016 https://www.facebook.com/rakeshdotnet All Rights Reserved.


Page |6

Application State: Points to Think About Before Using

Application state is stored in memory of webserver, so huge amount of data can cause severe performance
overhead. Also keep in mind that these variables will be stored in memory till the application ends whether we
need the entire time or not. So use it carefully.

If the application goes down or is restarted, then all the data stored in Application state is lost.

Also Application data is not shared between multiple servers in webfarm scenario.

Application also doesn't work in case of Webgarden. Variables stored in application state in either of those
scenarios are global only to the particular process in which the application is running. Each application process
can have different values.

Application state is not thread safe, so we must keep the synchronisation in mind as discussed above.

2. Session State:
ASP.NET provides a session state, which is available as the HttpSessionState class, as a method of storing sessionspecific information that is visible only within the session. ASP.NET session state identifies requests from the same browser
during a limited time window as a session, and provides the ability to persist variable values for the duration of that session.
You can store your session-specific values and objects in session state, which is then managed by the server and available
to the browser or client device. The ideal data to store in session-state variables is short-lived, sensitive data that is specific
to an individual session.
OR
ASP.NET session state enables you to store and retrieve values for a user as the user navigates ASP.NET pages in a Web
application. HTTP is a stateless protocol. This means that a Web server treats each HTTP request for a page as an
independent request. The server retains no knowledge of variable values that were used during previous requests. ASP.NET
session state identifies requests from the same browser during a limited time window as a session, and provides a way to
persist variable values for the duration of that session. By default, ASP.NET session state is enabled for all ASP.NET
applications.
OR
ASP.NET Session state provides a place to store values that will persist across page requests. Values stored in Session are
stored on the server and will remain in memory until they are explicitly removed or until the Session expires. It is defined
as the period of time that a unique user interacts with a Web application. Session state is a collection of objects, tied to a
session stored on a server.
OR
ASP.NET allows you to save values using session state, a storage mechanism that is accessible from all pages requested
by a single Web browser session. Therefore, you can use session state to store user-specific information. Session state is
similar to application state, except that it is scoped to the current browser session. If different users are using your
application, each user session has a different session state. In addition, if a user leaves your application and then returns
later after the session timeout period, session state information is lost and a new session is created for the user. Session
state is stored in the Session key/value dictionary.
OR
Session management is a very strong server-side technique to maintain state. Generally session is used to store user's
information and/or uniquely identify a user (or say browser). The server maintains the state of user information by using
a session ID. When users makes a request without a session ID, ASP.NET creates a session ID and sends it with every
request and response to the same user.
OR

Copyright 2015 - 2016 https://www.facebook.com/rakeshdotnet All Rights Reserved.


Page |7

Session is one of the most common way which is being used by developers to maintain the state of the application. The
Session basically stores the values as a dictionary collection in key/value pairs. It completely utilizes server resources to store
the data. It is a secure way of storing data, since the data will never be passed to the client.
For each and every user, a separate Session is created, and each and every Session has its Unique ID. This ID is being stored
in the client's machine using cookies. If there are multiple users who are accessing a web application, then for each user a
separate Session is created. If a single user logs in and logs out the Session is killed, then if the same user again logs into
the application, then a new Session ID is being created for the same user.
The Session has a default timeout value (20 minutes). We can also set the timeout value for a session in the web.config file.
Alternatives to session state include the following:

Application state, which stores variables that can be accessed by all users of an ASP.NET application.

Profile properties, which persists user values in a data store without expiring them.

ASP.NET caching, which stores values in memory that is available to all ASP.NET applications.

View state, which persists values in a page.

Cookies.

The query string and fields on an HTML form that are available from an HTTP request.

Session Variables:
Session variables are stored in a SessionStateItemCollection object that is exposed through the HttpContext.Session
property. In an ASP.NET page, the current session variables are exposed through the Session property of the Page object.
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. The following example shows how to create session variables in an ASP.NET page for the first and last name of a
user, and set them to values retrieved from TextBox controls.
Session["FirstName"] = txtFirstName.Text;
Session["LastName"] = txtLastName.Text;
Note:
When you use a session-state mode other than InProc, the session-variable type must be either a primitive .NET type or
serializable. This is because the session-variable value is stored in an external data store.

Session Identifiers:
Sessions are identified by a unique identifier that can be read by using the SessionID property. When session state is
enabled for an ASP.NET application, each request for a page in the application is examined for a SessionID value sent from
the browser. If no SessionID value is supplied, ASP.NET starts a new session and the SessionID value for that session is sent
to the browser with the response.
By default, SessionID values are stored in a cookie. However, you can also configure the application to store SessionID
values in the URL for a "cookieless" session.
A session is considered active as long as requests continue to be made with the same SessionID value. If the time between
requests for a particular session exceeds the specified time-out value in minutes, the session is considered expired. Requests
made with an expired SessionID value result in a new session.

Copyright 2015 - 2016 https://www.facebook.com/rakeshdotnet All Rights Reserved.


Page |8

Security Note:
SessionID values are sent in clear text, whether as a cookie or as part of the URL. A malicious user could get access to the
session of another user by obtaining the SessionID value and including it in requests to the server. If you are storing sensitive
information in session state, it is recommended that you use SSL to encrypt any communication between the browser and
server that includes the SessionID value.

Cookieless SessionIDs:
By default, the SessionID value is stored in a non-expiring session cookie in the browser. However, you can specify that
session identifiers should not be stored in a cookie by setting the cookieless attribute to true in the <sessionState> section
of the Web.config file.
The following example shows a Web.config file that configures an ASP.NET application to use cookieless session identifiers.
<configuration>
<system.web>
<sessionState mode="InProc" cookieless="true" regenerateExpiredSessionId="true" />
</system.web>
</configuration>
ASP.NET maintains cookieless session state by automatically inserting a unique session ID into the page's URL. For example,
the following URL has been modified by ASP.NET to include the unique session ID

u1daopo5vmuwl55yenibg1zl:

http://localhost/WebSiteHttp1/(S(u1daopo5vmuwl55yenibg1zl))/ViewEmp.aspx
When ASP.NET sends a page to the browser, it modifies any links in the page that use an application-relative path by
embedding a session ID value in the links. (Links with absolute paths are not modified.) Session state is maintained as long
as the user clicks links that have been modified in this manner. However, if the client rewrites a URL that is supplied by the
application, ASP.NET may not be able to resolve the session ID and associate the request with an existing session. In that
case, a new session is started for the request.
The session ID is embedded in the URL after the slash that follows the application name and before any remaining file or
virtual directory identifier. This enables ASP.NET to resolve the application name before involving the SessionStateModule
in the request.
Note:
To improve the security of your application, you should allow users to log out of your application, at which point the
application should call the Abandon() method. This reduces the potential for a malicious user to get the unique identifier
in the URL and use it to retrieve private user data stored in the session.
Regenerating Expired Session Identifiers:
By default, the session ID values that are used in cookieless sessions are recycled. That is, if a request is made with a session
ID that has expired, a new session is started by using the SessionID value that is supplied with the request. This can result
in a session unintentionally being shared when a link that contains a cookieless SessionID value is used by multiple
browsers. (This can occur if the link is passed through a search engine, through an e-mail message, or through another
program.) You can reduce the chance of session data being shared by configuring the application not to recycle session
identifiers. To do this, set the regenerateExpiredSessionId attribute of the <sessionState> configuration element to true.
This generates a new session ID when a cookieless session request is made with an expired session ID.
Note:
If the request that is made with the expired session ID is made by using the HTTP POST method, any posted data will be
lost when regenerateExpiredSessionId is true. This is because ASP.NET performs a redirect to make sure that the browser
has the new session identifier in the URL.

Copyright 2015 - 2016 https://www.facebook.com/rakeshdotnet All Rights Reserved.


Page |9

Session-State Modes:
ASP.NET session state supports several storage options for session variables. Each option is identified by a value in the
SessionStateMode enumeration. The default behaviour is to store session variables in the memory space of the ASP.NET
worker process. However, you can also specify that session state should be stored in a separate process, in a SQL Server
database, or in a custom data source. If you do not want session state enabled for your application, you can set the
session mode to Off.
There are four session storage mechanisms provided by ASP.NET:

InProc mode, which stores session state in memory on the Web server. This is the default. 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 StateServer or SQLServer.

StateServer mode, which stores session state in a separate process 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 start-up type to Automatic.

SQLServer mode 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.

Custom mode, which enables you to specify a custom storage provider. You also need to implement the custom

storage provider.

Off mode, which disables session state. You should disable session state if you are not using it to improve

performance.

Configuring Session State:


Session state is configured by using the <sessionState> element of the <system.web> configuration section. You can also
configure session state by using the EnableSessionState value in the @ Page directive.
The <sessionState> element enables you to specify the following options:

The mode in which the session will store data.

The way in which session identifier values are sent between the client and the server.

The session Timeout value.

Supporting values that are based on the session Mode setting.

The following example shows a sessionState element that configures an application for any of the session mode:
<configuration>
<system.web>
<sessionState mode = "InProc" | "SqlServer" | "StateServer" | "Custom" | "Off"
cookieless = "true" | "false"
timeout = "positive integer indicating the session timeout in minutes"
sqlConnectionString = "SQL connection string that is only used in the SQLServer mode"
stateConnectionString="State connection string that is only required when the mode is StateServer"
</sessionState>
</system.web>
</configuration>

Copyright 2015 - 2016 https://www.facebook.com/rakeshdotnet All Rights Reserved.


P a g e | 10

You can disable session state for an application by setting the session-state mode to Off. If you want to disable session
state for only a particular page of an application, you can set the EnableSessionState value in the @ Page directive to
false. The EnableSessionState value can also be set to ReadOnly to provide read-only access to session variables.
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 as session state is maintained on a SQL Server database.

InProc session state mode:


InProc mode is the default mode provided by ASP.NET. In this mode, session values are stored in the web server's memory
inside the asp.net worker process. If there are more than one IIS servers then session values are stored in each server
separately on which request has been made. Since the session values are stored in server, whenever server (asp.net worker
process) is restarted the session values will be lost. It is the only mode that supports the Session_End event.
Web.config:
<configuration>
<system.web>
<sessionstate mode="InProc" cookieless="false" timeout="20" />
</system.web>
</configuration>
Advantages of InProc session state mode:
1. Very easy to implement. All that is required is, to set, the session state mode=InProc in web.config file.
2. Will perform best because the session state memory is kept on the webserver, within the ASP.NET worker process
(aspnet_wp.exe).
3. Suitable for web applications hosted on a single server.
4. Objects can be added without serialization
Dis-advantages of InProc session state mode:
1. Session state data is lost, when the worker process or application pool is recycled.
2. Not suitable for web farms and web gardens.
3. Scalability could be an issue.

StateServer session state mode:


The session state variables are stored in a process, called as asp.net state service. This process is different from the asp.net
worker process. The asp.net state service can be present on a web server or a dedicated machine.
This mode could store session in the web server but out of the application pool. But usually if this mode is used there will
be a separate server for storing sessions, i.e., stateServer. The benefit is that when IIS restarts the session is available.
It stores session in a separate Windows service. For State server session mode, we have to configure it explicitly in the
web.config file and start the aspnet_state service.
To use StateServer mode, you must first be sure the ASP.NET state service is running on the server used for the session
store. The ASP.NET state service is installed as a service when ASP.NET and the .NET Framework are installed. The
ASP.Net state service is installed at the following location:
SystemRoot\Microsoft.NET\Framework\VersionNumber\aspnet_state.exe
Example:
C:\Windows\Microsoft.NET\Framework\v4.0.30319\ aspnet_state.exe

Copyright 2015 - 2016 https://www.facebook.com/rakeshdotnet All Rights Reserved.


P a g e | 11

To configure an ASP.NET application to use StateServer mode, in the application's Web.config file do the following:
1. Start the ASP.NET state Service. To start the asp.net state service
a) Click Start > Type Run > Press Enter
b) In the run window, type services.msc and click OK.
c) In the services window, right click on ASP.NET State Service and select Start.
2. Set the mode attribute of the sessionState element to StateServer.
3. Set the stateConnectionString attribute to tcpip=serverName:42424.
The following example shows a configuration setting for StateServer mode where session state is stored on a local
computer named localhost (127.0.0.1):
Web.config:
<configuration>
<system.web>
<sessionState mode="StateServer"
stateConnectionString="tcpip=127.0.0.1:42424"
cookieless="false"
timeout="20"/>
</system.web>
</configuration>
Advantages of using StateServer session state mode:
1. ASP.NET worker process independent. Survives worker process restart.
2. Can be used with web farms and web gardens.
3. State server offers more scalability than InProc.
Dis-advantages of using StateServer session state mode:
1. StateServer is slower than InProc
2. Complex objects, need to be serialized and deserialized
3. If the StateServer, is on a dedicated machine, and if the server goes down all the sessions are lost.

SqlServer session state mode:


SQLServer mode stores session state in a SQL Server database. Using this mode 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.
Session is stored in a SQL Server database. This kind of session mode is also separate from IIS, i.e., session is available
even after restarting the IIS server. This mode is highly secure and reliable but also has a disadvantage that there is
overhead from serialization and deserialization of session data. This mode should be used when reliability is more
important than performance.

To use SQLServer mode, you must first be sure the ASP.NET session state database is installed on SQL Server.
You can install the ASP.NET session state database using the aspnet_regsql.exe tool.
Steps to follow, to configure asp.net web application to use SQLServer:
1. Create the ASPState database using aspnet_regsql.exe tool. There are several versions of this tool. I am running .NET
version 4.0, on a 64 bit operating system. So I will use the version that is present in
C:\Windows\Microsoft.NET\Framework64\v4.0.30319.
a) Click Start -> Type Run -> Press Enter
b) Type cmd -> Press Enter
c) In the command prompt type - cd C:\Windows\Microsoft.NET\Framework64\v4.0.30319
d) Press Enter
e) Type - aspnet_regsql.exe -S SQLServerMachineName -E -ssadd -sstype p
f) Press Enter. At this point you should have ASPState Database added.
g) For help running this tool, please refer to the following MSDN article

http://msdn.microsoft.com/en-us/library/ms229862(v=vs.100).aspx
Copyright 2015 - 2016 https://www.facebook.com/rakeshdotnet All Rights Reserved.
P a g e | 12

2. Set the mode attribute of the sessionState element to SQLServer and set the sqlConnectionString attribute to a
connection string for your SQL Server database.

If you want to use Windows Authentication


<sessionState mode="SQLServer" sqlConnectionString="Data Source=SQLServerMachineName; integrated
security=SSPI" timeout="20"></sessionState>

If you want to use Sql Serevr Authentication


<sessionState mode="SQLServer" sqlConnectionString="Data Source=SQLServerMachineName; user id=sa;
password=123" timeout="20"></sessionState>

Example:
Web.config:
<configuration>
<system.web>
<sessionState mode="SqlServer"
sqlConnectionString="Data Source=(local); user id=sa; password=123" cookieless="false" timeout="20" />
</system.web>
</configuration>
Note: If you use integrated security (windows authentication), you might get an error stating "Failed to login to
session state SQL server for user 'IIS APPPOOL\ASP.NET v4.0'.". To resolve this error
a)
b)
c)
d)
e)

Click Start -> Type Run -> Press Enter


Type inetmgr -> Press Enter
Expand IIIS and Click on Application Pools.
Right click on ASP.NET v4.0 and select Advanced settings
Change Process Model -> Identity to LocalSystem and Click OK

Advantages of using SQLServer session state mode:


1. SQLServer is the most reliable option. Survives worker process recycling and SQL Server restarts.
2. Can be used with web farms and web gardens.
3. More scalable than State server and InProc session state modes.
Dis-advantages of using StateServer session state mode:
1. Slower than StateServer and InProc session state modes
2. Complex objects, need to be serialized and deserialized

Custom Session mode:


Generally we should prefer InProc state server mode or SQL Server mode but if you need to store session data using other
than these techniques then ASP.NET provides a custom session mode. This way we have to maintain everything customized
even generating session ID, data store, and also security.
Attributes

Description

Indicates that the session is used with or without cookie. cookieless set to true indicates sessions
Cookieless true/false without cookies is used and cookieless set to false indicates sessions with cookies is used. cookieless
set to false is the default set.
timeout

Indicates the session will abound if it is idle before session is abounded explicitly (the default time
is 20 min).

StateConnectionString

Indicates the session state is stored on the remote computer (server). This attribute is required
when session mode is StateServer

SqlConnectionString

Indicates the session state is stored in the database. This attribute is required when session mode
is SqlServer.

Copyright 2015 - 2016 https://www.facebook.com/rakeshdotnet All Rights Reserved.


P a g e | 13

Session Events in ASP.NET:


To manage a session, ASP.NET provides two events: session_start and
called Global.asax in the root directory of the project.

session_end that is written in a special file

Session_Start: The Session_start event is raised every time a new user makes a request without a session ID, i.e.,
new browser accesses the application, then a session_start event raised. Let's see the Global.asax file.
void Session_Start(object sender, EventArgs e)
{
Session["Count"] = 0; // Code that runs when a new session is started
}
Session_End: The Session_End event is raised when session ends either because of a time out expiry or explicitly by
using Session.Abandon().The Session_End event is raised only when the sessionstate mode is set to InProc in the
Web.config file. If session mode is set to StateServer or SQLServer, the event is not raised.

Example: Storing & Retrieving Session Objects Data:

Code to write values into a Session:


Session["KeyName"] = Value;
OR Using Add() Method

Session.Add("KeyName", Value);

Code to read values from Session:


Type VariableName = (TypeCast) Session[index];
OR
Type VariableName = (TypeCast) Session["KeyName"];
Advantages of using session state are:

Copyright 2015 - 2016 https://www.facebook.com/rakeshdotnet All Rights Reserved.


P a g e | 14

Simple implementation: The session-state facility is easy to use, familiar to ASP developers, and consistent with
other .NET Framework classes.

Session-specific events: Session management events can be raised and used by your application.

Data persistence: Data placed in session-state variables can be preserved through Internet Information Services
(IIS) restarts and worker-process restarts without losing session data because the data is stored in another process
space. Additionally, session-state data can be persisted across multiple processes, such as in a Web farm or a Web
garden.

Platform scalability: Session state can be used in both multi-computer and multi-process configurations,
therefore optimizing scalability scenarios.

Cookieless support: Session state works with browsers that do not support HTTP cookies, although session state
is most commonly used with cookies to provide user identification facilities to a Web application. Using session
state without cookies, however, requires that the session identifier be placed in the query string, which is subject
to the security issues stated in the query string section of this topic.

Extensibility: You can customize and extend session state by writing your own session-state provider. Session
state data can then be stored in a custom data format in a variety of data storage mechanisms, such as a database,
an XML file, or even to a Web service.

Disadvantage of using session state are:

Performance considerations: Session-state variables stay in memory until they are either removed or replaced,
and therefore can degrade server performance. Session-state variables that contain blocks of information, such as
large datasets, can adversely affect Web-server performance as server load increases.

Copyright 2015 - 2016 https://www.facebook.com/rakeshdotnet All Rights Reserved.


P a g e | 15

You might also like