Thursday, April 14, 2011

Session - State Management in ASP.net


To manage information at server side Session is best method. It Provides
* Security
* Reliability
* it can store any type of data
How Session works and it created on Server
When Browser send request to your website then server generates a UID called sessionid and
this 'Sessionid' is managed in Session Table. A table is created on the server for managing the
session id for various web clients( Browsers).
This session id is sent to the client. after this session is also sent to the server after first request.
Figure 1
When Server assign session id then event iss also fired called 'Session_Start'.
The generated session id is stored in the cooked. server send session id to client and client send
this session id every time and this cookie  mechanism based on cookies working.Cookie is created
at client side with then name 'aspnet_sessionid'. It is a Non-persistent cookies.
A simple program that demonstrate the working of Session Management.
1. create a empty web application
2. Add a webpage and name them a.aspx
3. Add Global.asax- Global Application Class
4. add a button on a.aspx
and write code this code.
protected void Page_Load(object sender, EventArgs e)
   {
       Response.Write("No of cookies: " + Request.Cookies.Count.ToString());
   }
   protected void btnSend_Click(object sender, EventArgs e)
   {
       Response.Write("No of cookies: " + Request.Cookies.Count.ToString());
   }
when you first time run it will show no of cookies =0 , but when you click on button then
it will show count =1. session id is sent by server after the first request and when you click on button
then it have cookies that store the information of the session id.
Transferring on page information to another page:
1. add a text box on a.aspx and add a new page named b.aspx
2. write below code at button's click event.
Figure 2 Form a.aspx

protected void btnSend_Click(object sender, EventArgs e)
   {
      Session.Add("msg",txtMessage.Text);
       Response.Redirect("b.aspx");
   }
3.  now write following code at b.aspx Page_Load event.
protected void Page_Load(object sender, EventArgs e)
   {
       Response.Write("Message From A:- " +Session["msg"].ToString());
       Response.Write("<br/>Cookie Name:- "+Request.Cookies[0].Name);
       Response.Write("<br/>Session Id:- "+Request.Cookies[0].Value);
   }
output will be after clicking on send button with a message in textbox.

Figure 3 Output on another page

Case
if someone directly access the b.aspx, what will happen.

Figure 4 Error Message: if some one access b.aspx directly

it will give error because we have not assed value to the msg in session. To avoid this set any
default value to the msg at the start of the Session as:
Go to Global.asax and find event named Session_Start and here you should initialize the session
using add method.
as:
Session.Add("msg", "null");
and at the click of the button you just update the value of the session except adding value to the
session as:
Session[]=txtMessage.Text;
Response.Redirect("b.aspx");
Some Session Methods and Properties :
Abandon()- Used to kill the session by force as Session.Abandon();
CookieMode –Property have two options Cookie or CookieLess
IsCookieLess- check the client that cookie is supported or not.
IsNewSessoin- checks that is it your first request to the server from client.
Mode- InProc and OutProc
           Inproc – at server cookies etc.
           outproc- information saved in external application like state server, SQL server db.
SessionId- returns SessionId
timeout – Specifies the number of minutes that a session can remain idle before the server terminates it
automatically. The default is 10 minutes. Session.Timeout has no hard-coded limit. It should not be set
higher than 20 minutes (except in special cases) because every open session is holding onto memory. It
should also not be set lower than 4 minutes because clients rarely respond within that time resulting in a
loss of session state. Most of the books tell this 20 minutes. according to me it depends upon IIS.

IIS 6.0: The minimum allowed value is 1 minute and the maximum is 1440 minutes.
Changing Session Related Information
if you want to change the session related information then go to Web.config and use following Session
tag to specify Session values as in the <System.Web> section.
<sessionState timeout="1" cookieName="Niranjan" regenerateExpiredSessionId ="true"  />
if you want to regenerate new session id if your session expire after 20 minutes or fix time. it will not work
on local machine if you request from remote then it will work.
To Implement CookieLess
use cookieless attribute in SessionState for implementing this.
it have 5 options:
1. AutoDetect- Detech first that Browser support cookie then cookie else cookieless
2. Use Cookies- Use cookies
3. UseDeviceProfile- Use Device Information
4. UseUri- session id is managed in url not good, if you use this url in another browser then it will get same
    value. it is not good in case of online transactions.
Session Mode -
InProc
OutProc
If you want that info is save either sever close or anything happen with the web application then
use the OutProc Mode of Session State.
you can store information in two external application
1. StateServer
To use State Server do the following:
<sessionState timeout="1" cookieName="Niranjan" regenerateExpiredSessionId ="true"  mode=
"StateServer" stateConnectionString ="tcpip=localhost:42424" stateNetworkTimeout="5"/>


if you running a web application just restart your IIS. your session information will be lost. if you have done
done above settings then it will not loose your session values either your app reset or anything happen.
one thing if you run your website after doing these setting and you have already restarted the IIS just now.
then it will give error. because we have not started the state server. To start state server go to control panel
and open services then start the ASP.NET State  Service.
Figure 5- Enabling ASP.NET State Service
now it will work fine.
2. SQLServer
To use State Server do the following:
<sessionState  mode="SQLServer" sqlConnectionString="datasource=.; integrated security=true"
sqlCommandTimeout="5"/>
To manage session information in SQL Server, you have to create some Database, table in the SQL Server.
If you want to use temporary storage in  tempdb to provide tables for storing information, then you have to
create table there
using .net framework specified SQL Script.
these scripts are stored in the  directory C:\Windows\Microsoft.NET\Framework\v2.0.50727.
to create table in the tempdb, the script file name is InstallSqlState.sql.
If you want to save State Information Permanently then use another Script InstallPersistSqlState.sql.
it will crate a  new database with the required table to store the state information.
open query Analyzer and run these script in the database.
Remember:
if tempdb files are installed then iwill not save to the ASPState_db (permanent Storage database that
will be create after running the InstallPersistSqlState.sql.
*first it check tempdb data table then your permanent storage database.
*your connection string dost not specify db name because .net know the DB name.
 

No comments :

Post a Comment