Showing posts with label Session. Show all posts
Showing posts with label Session. Show all posts

Automatically redirect user when session timout

You can create a BasePae class which inherits System.Web.UI.Page. Override the OnInit method and write appropriate code in that which will redirect to default page.
public class BasePage : System.Web.UI.Page
{
    protected override void OnInit(EventArgs e)
    {
        if (Session["UserName"] == null)
        {
            Response.Redirect("~/Login.aspx");
        }
    }
}

And inherit all your ASPX pages from BasePage class, instead of System.Web.UI.Page like this:-
public partial class HomePage : BasePage
{
    protected void Page_Load(object sender, EventArgs e)
    {
    }
}

And finally in your login page, simply set Session["UserName"] with user's name. Feel free to share your comments. Happy Coding !!!

How to implement Cookieless Session in ASP. Net

By default ASP.Net relies on cookies to store session id. Cookies are actually a text data which is stored in browser. Generally cookies are not considered a safe way to store information. Also there is a chance that browser have disabled the cookies and in that case our application wont work on that browser.

To avoid such situation, we can use Cookieless session. To implement that you just need to set cookieless attribute to true in your session tag. Here is how you can do this:-
<system.web>
  <sessionState mode="InProc" cookieless="true" timeout="120" />
</system.web>

Once you have done that your URL will contain the session id, here is the snapshot of URL before and after implementing cookieless=true:-
As you can see that in the URL session id is visible.

Feel free to share your comments, Happy Codding !!!

How to end session when browser is closed

In high traffic sites sessions are very costly and they use lots of server's memory. Generally session timeout is 20 min (by default) and even if user closes the browser. Values in session still exist until session get expired after timeout. We can save lots of server memory if we destroy session as user closes the browser.

Here is how you can do it:-

1)First create a page AutoLogOut.aspx and in Page_Load event write this code:-
protected void Page_Load(object sender, EventArgs e)
{
    Session.Abandon();
}

2- Then add following javascript code in your page or Master Page:-
<script type="text/javascript">
     var clicked = false;
    function CheckBrowser()
    {
        if (clicked == false)
        {
            //Browser closed
        }
        else
        {
            //redirected 
            clicked = false;
        }
    }
 
    function bodyUnload()
    {
        if (clicked == false)//browser is closed
        {
            var request = GetRequest();
            
            request.open("GET""AutoLogOut.aspx"true);
            request.send();
        }
    }
 
    function GetRequest()
    {
        var request = null;
        if (window.XMLHttpRequest)
        {
            //incase of IE7,FF, Opera and Safari browser
            request = new XMLHttpRequest();
        }
        else
        {
            //for old browser like IE 6.x and IE 5.x
            request = new ActiveXObject('MSXML2.XMLHTTP.3.0');
        }
        return request;
    } 

3- Finally on your body tag add these event handlers:-
<body onunload="bodyUnload();" onclick ="clicked=true;>

Now when user closes the browser, it will close session on server. However I just like to highlight that this solution might not work 100% time as there are chances that when user close the browser, he is not connected to internet.

Feel free to share your comments on my post.

ASP.Net State Server

Introduction

In the world of web applications Sessions are commonly used to keep key information about users. Before going into the details of State Server lets have a quick look over different session management solutions provided by ASP.Net. Here are the different modes for storing session in ASP.net:-

InProc
This is the default mode. In this session data is stored in web server's (IIS) memory space. In case IIS is restarted all sessions data will be loss when this mode is configured.

StateServer
This is the out of the process way of storing session. In this mode session data is stored in a separate process (ASP.Net State Service). Incase IIS is restated then session data will not be effected when this mode is configured.

SQLServer
In this mode session's data is stored in SQL server. Incase IIS or SQL Server is restarted session will not loss. But is slower than State Server.

Custom
In this mode we can specify any custom provider.

Off
In this mode sessions are disabled.

Now if your application is hosted on a web farm/garden then users will claim that their sessions is getting loss too frequently. Consider a scenario when there are two servers hosting an application. Now if one request goes to server 'A', its session will be created on that particular server and in case other request from same user goes to server 'B' then on that server session will not exist so user have to log in again. Also if you are using Inproc mode and your IIS is restarted due to recycling or application deployment then all of your session will lost. In such scenarios we can configure seperate state server to avoid such problems.

How to configure State Server in ASP.Net

There are three steps to configure state server:-
  1. State Server Service Configuration
  2. Session State Section Configuration
  3. Machine Key Configuration

1- State Server Service Configuration
First go to Windows Control Panel -> Administrative Tools and Open Services. Now search for 'ASP.NET State Service'. Now set service start-up type to Automatic. Generally we configure a separate server as a state server but by default it is disabled. To enable saving state for remote machines, we have to configure some registry settings. So open registry editor and navigate to following location:-

HKLM\SYSTEM\CurrentControlSet\Services\aspnet_state\Parameters\

Now you have to set two parameters here:-
AllowRemoteConnections: It will allow other computers to use this computer as state server. Set it to 1. Default value is 0.
Port: Specify the port on which state service will run. By Default it is 42424. Keep it same unless you have some specific reason.

2- Session State Section Configuration
After that you have to modify your application's web.config file and set Here is a sample:-
<?xml version="1.0"?>
<configuration>
    <system.web>
        <sessionState mode="StateServer" stateConnectionString="tcpip=Type_State_Server_IP_Here:42424"
                                    cookieless="false" timeout="20" />
    </system.web>
</configuration>

3- Machine Key Configuration
Now we are almost done with state server configuration. One last thing is to set machineKey in our application's web.config. Here is a sample web.config file with machine key.
<?xml version="1.0"?>
<configuration>
    <system.web>
        <machineKey validationKey="21F090935F6E49C2C797F69BBAAD8402ABD2EE0B667A8B44EA7DD4374267A75D7AD972A119482D15A4127461DB1DC347C1A63AE5F1CCFAACFF1B72A7F0A281B"    decryptionKey="ABAA84D7EC4BB56D75D217CECFFB9628809BDB8BF91CFCD64568A145BE59719F" validation="SHA1" decryption="AES"/>
    </system.web>
</configuration>

You can generate a machine key from Pete's Nifty Machine Key Generator

Advantage and Disadvantage of State Server
Here are few things which you should keep in mind before going for state server:-

Advantages
  • Since session data is stored in a separate location so any issue with IIS will not affect sessions.
  • User will not face session loss in case of web farm or web garden.
Disadvantages
  • This approach is slower than InProc because of object serialization/de-serialization.
  • State server must be running otherwise application will not work.
  • In InProc mode any object can be stored in session but in state server case objects should be serializable.

Conclusion
State Server is a must have when you are using session and working web farm or web garden. Feel free to post comments.

Why .Net sessions are terminated/loss unexpectedly

There are many cases when ASP.Net website works great in development environment but as we migrate our website to production server, it starts giving unexpected session timeouts. This article discuss those problems and provide solutions to resolve them.

Here are some of the reasons why this happens:- 

Cause 1: IIS Settings:
1- Application Pool is recycled. - We will know this looking at the system logs
2- IIS/worker process is restarted. - System logs will tell this as well
3- Application Domain is restarted. - We need to monitor for application restarts for the ASP.NET counter in perform to check this.
4- IIS worker process can get recycled depending on the configuration, low on virtual memory, crash due to unhanded exception etc.

Resolution:
1- Goto Start->run->inetmgr->Application pools.
2- Select your application pool and right click -> properties.
3- And see the settings for Recycle worker process (in minutes), set an appropriate value there.
4- Alternatively you can recycle your process when your site generally stays idle i.e. you can select 'You can set values in Recycle worker process at time' and give appropriate time to recycle process.

Cause 2: Modifications in Application Contents:
1- Bin folder of the application is modified.
2- Web.config or the machine.config is modified.
3- Global.asax file is modified.
4- Something in the code is causing session loss, it can be anything like you are adding/removing files in your application folder through code e.g. uploading images. You will need to look into the code to have a fix on this. Like Session.Abandon() or Session.Clear();

Resolution:
Try stopping anti virus software on server and see that session as loosing frequently or not. If problem solves after that then Exclude the anti virus scanning from the IIS/ASP.NET default folders and your application folders.
a- <drive>:\WINDOWS\system32\inetsrv
b- <drive>:\WINDOWS\assembly\GAC_32
c- <drive>:\WINDOWS\Microsoft.NET\Framework\
d- Any application directory containing web.config files, global.asa or global.asax, .net assemblies, and/or other web content which your web apps use.

Check your code, that if your application looses session after a particular operation i.e. you might be changing the contents of your Bin folder or modifying web.config file through your code.

Cause 3: Application is hosted in Shared Server or in Web Farm/Garden:
If your application is hosted on a shared server where other applications are also running on the same server then it might be chances that due to other applications IIS is restarted and causing frequent session loss in your application.

Also if your application is hosted in a Web Garden or Web Farm, then you will also notice frequent session loss. E.g. if first request from user is process by server/process 1 and second request is processed by server/process 2, then session will also appear blank.

In both the cases you can go for a seperate state managment.

Resolution:
You can configure a seperate state server, in which session will not lost due to IIS restarts or server/process switching. First configure state server in your machine. For details and configuration of state server see How to Configure Asp.Net State Server.

Also change your web.config file like this:-
<configuration>
  <system.web>
    <sessionState mode="StateServer" cookieless="true" timeout="30"/>
    </sessionState>
  </system.web>
</configuration>

How to set Session Timeout in ASP.Net

Here are different places from where you can set timeouts. Check all these settings in your application:-

1- Web Config
You can define session time out in sessionstate tag of web.config file. Also if you are using forms authentication then also define session timeout in forms as mentioned below:-
<forms loginurl="sampleloginpage.aspx" name="samplecookie" timeout="45" path="/" requiressl="true" protection="All">
</forms>
<sessionstate mode="InProc" stateconnectionstring="tcpip=127.0.0.1:42424" cookieless="false" timeout="45">

2-Global.asax Session_Start Event
You can also set this in global.asax file as mentioned here:-
Session.Timeout = 60 ; // in Session.Start() event

3-sessionState
To set session timeout to 45 minutes write this in the web.config file :
<sessionstate mode="InProc" stateconnectionstring="tcpip=127.0.0.1:42424"
 sqlconnectionstring="data source=127.0.0.1;Trusted_Connection=yes" cookieless="false" timeout="20">

The maximum limit for session timeout is 525,600 minutes(1 year) - (365 days x 24 hours x 60 min)

If all mentioned above did not help you then it might be due to anti virus software. Software scans the files in application folder and updates their date/time. Which causes IIS to restart. There fore i uninstalled the anti virus from server. However, if you exclude the application folder from virus scan that will also do the job. Also you need to remove .config,.aspx,.ascs and other extensions specific to your application for further security.