Tuesday, May 13, 2008

Session Managment in Asp.net

Session management in asp.net means how and where session information is saved.
There are three types of session management in Asp.net

1-In process
3- State Server

By default all the applications are configured to in process it means that session information is being saved in the same process that application is running. So far so good you do not need change this however you can apply some session configuration like sessiontimeout which is an indicator for asp.net to know howlong should keep a session for user. For example if a user does not send any request to server for longer time than sessiontimeout (which is minutes) then asp.net will kill that session. Or you can make it cookiless it means that it will use query string to notify each session. All of these configuration can be done in web.config with sessionstate tag :

sessionState mode="InProc" cookieless="false" timeout="20"

You do not need to change the mode as long as you have just one server. If you have more than one server to serve your application then you need to use other session management (2 or 3). When your application is big enough and you have a lot of users you need to deploy your application in different servers (it is called webFarme). If you use InProcess approach, you cannot trust on session information the reason is that InProcess means each server has its own session information so imagine a user come to your site the first request goes to one server and second request of the same user will go another server so your session id will be different and second server has no idea about session information in first server. To solve this issue we need save session information in somewhere else rather than in each server. (I am sure everybody knows that to have multiple servers for one application we need load balancing service be installed between those servers).


Saving session information in one server and let other servers use that information from that server to do this you need ASP.NET State Service to be up and running (this service is installed when you install the .NET runtime). By default the service listens over port 42424. To see this service you can go to control panel\ Administrative tools \ services you should be able to find ASP.NET State Service. Using the State Service option is useful when you want out-of-process session state management but do not want to have to install SQL Server on the machine hosting the state. See this sample:

sessionState mode="StateServer" stateConnectionString=""

SqlServer :

Before using this mode, you must run the InstallSqlState.sql script on the database server where session state will be stored. This script can be found in :


(if you have another version you can try those ones)
The primary purpose of this script is to create some tables that can store client-specific state indexed by session ID in those tables. After running that script in your database (you do not need specify any specific database just run the query in query analyser in sqlserver)
See this sample:

sessionState mode="SQLServer" sqlConnectionString= "data source=;user id=sa;password="

Microsoft suggest the sql server approach.


CsPrince said...

Just now i try to run the InstallSqlState. but when i execute the file. there will appear this error >>
"Msg 14261, Level 16, State 1, Procedure sp_add_category, Line 32
The specified @name ('[Uncategorized (Local)]') already exists."
I'm not familiar with Sql server. can you help me?
And inside the InstallSqlState, it ask me to use the "aspnet_regsql.exe" to install and uninstall SQL session state. After run the installer. it also failed and display this error>>
"Setup failed.

Unable to connect to SQL Server database.

Details of failure

System.Web.HttpException: Unable to connect to SQL Server database. ---> System.Data.SqlClient.SqlException: An error has occurred while establishing a connection to the server. When connecting to SQL Server 2005, this failure may be caused by the fact that under the default settings SQL Server does not allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)
at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection)
at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj)
at System.Data.SqlClient.TdsParser.Connect(ServerInfo serverInfo, SqlInternalConnectionTds connHandler, Boolean ignoreSniOpenTimeout, Int64 timerExpire, Boolean encrypt, Boolean trustServerCert, Boolean integratedSecurity, SqlConnection owningObject)
at System.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword, Boolean ignoreSniOpenTimeout, Int64 timerExpire, SqlConnection owningObject)
at System.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(String host, String newPassword, Boolean redirectedUserInstance, SqlConnection owningObject, SqlConnectionString connectionOptions, Int64 timerStart)
at System.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(SqlConnection owningObject, SqlConnectionString connectionOptions, String newPassword, Boolean redirectedUserInstance)
at System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, Object providerInfo, String newPassword, SqlConnection owningObject, Boolean redirectedUserInstance)
at System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection)
at System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnection owningConnection, DbConnectionPool pool, DbConnectionOptions options)
at System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject)
at System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject)
at System.Data.ProviderBase.DbConnectionPool.GetConnection(DbConnection owningObject)
at System.Data.ProviderBase.DbConnectionFactory.GetConnection(DbConnection owningConnection)
at System.Data.ProviderBase.DbConnectionClosed.OpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory)
at System.Data.SqlClient.SqlConnection.Open()
at System.Web.Management.SqlServices.GetSqlConnection(String server, String user, String password, Boolean trusted, String connectionString)
--- End of inner exception stack trace ---
at System.Web.Management.SqlServices.GetSqlConnection(String server, String user, String password, Boolean trusted, String connectionString)
at System.Web.Management.SqlServices.SetupApplicationServices(String server, String user, String password, Boolean trusted, String connectionString, String database, String dbFileName, SqlFeatures features, Boolean install)
at System.Web.Management.SqlServices.Install(String database, SqlFeatures features, String connectionString)
at System.Web.Management.ConfirmPanel.Execute()"
can you explain me why? sorry and thank you..

Emad Yazdan said...

when you run that Installsqlstate and show you error there are some possible issues
1-it means that it is installed somehow to check that you can see the data base in your sql server data base you should have ASPState Database Also in Tempdb database you should have two more tables 1-ASPStateTempApplications 2-ASPStateTempSessions (However I do not think this is in your case)

2- running that script is ok in sqlserver 2000 however, for sql server 2005 you should run InstallSqlState.exe should be run which is in this folder:C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727

so you need run cmd then in cmd you have to go to that folder then you can run this (Case sensetive):
aspnet_regsql.exe -S localhost -E -ssadd

the best way is that running this code in server itself so it will not block you because of remote connection.


Anonymous said...

Hi Emad,
That will be great if you can explain pros and cons of each one, comparing from different angles, especially StateServer and SqlServer. Thanks

Emad Yazdan said...

Hi shahram,
In Process is always good as long as you are not dealing with multiple servers.
State server performance is not as good as sql server because it is using a file system at end to save information if you do not have sql server you may use this approach. Microsoft recommand Sqlserver approach. since it has a very good performance. if you look closely to the tables you will see that tables are created in Tempdb that has no logging so it is even faster compare to other databases in sqlserver.