Dec 4, 2009

Session Timeout Notification


Sometimes you may need to get notification if session of an Asp.net application get expired. For the basics of session management you can find my post here.

In all of the above cases, the session supposed to be timeout. It will handle by the asp.net runtime, which we can set in the web.config <sessionState timeout="1" />. Default timeout is 20 mins. Which means after 20 min session will become abandon and if you are not correctly handle it will leads to system crash. What general recommendation is, always check null of the session item that you’re going to refer. But in most user oriented application, we should notify the user that ,"Hello your current session has expired, what do you want to do?"
 
How to achieve this?
 

If use In-Proc, it will automatically fire up session_end event which you can handle in Global.asax file. In rest of techniques this event will be ignored.
 
There are some workarounds to overcome this, but I’ll illustrate a simple trick, a pattern called “heartbeat”, that I’ve used in couple of my projects (especially in non AJAX applications).

In a nutshell, application will poll elapse time from the last post back and when it reaches to the time setup for session timeout, it will redirect to a page in which completely destroy the session.
  1. By considering the session time out ,we will generate a javascript and register to the page. As you can see in the following code snippet, I’ve attached logout() to the windows.onload event. (In non AJAX case this is always true. ) After time has expired it will redirect to the Timeout.aspx page, where user can retry the application.

    ClientScriptManager cm = Page.ClientScript;
    if(!cm.IsClientScriptBlockRegistered(Page.GetType(),"session_timout"))
    {
        StringBuilder sb = new StringBuilder();
        
        sb.Append("function logout(){");
        sb.Append("alert('Session has expired');");
        sb.Append("window.location.href='/Timeout.aspx';");
        sb.Append("}");
        sb.Append("window.onload = function(){var t=setTimeout(\"logout()\",");
        // We have to convert into millisec.
        sb.Append(Session.Timeout * 1000*60);
        sb.Append(");}");
        cm.RegisterStartupScript(Page.GetType(), "session_timout", sb.ToString(), true);
    }
    




Download Sample
File Size: 11.6K

No comments:

MEC: How to Set Message Counter for EDI Message

When you sending/creating EDI messages it is necessary to include unique message interchange number. This is to ensure each message that we ...