ramlicious Blogs by Tina & Prabhu

November 10, 2011

Notifying and Renewing Web sessions using AJAX

Filed under: .NET,C#,Programming — Prabhuram @ 4:07 pm

This article demonstrates a simple technique to notify a session expiry and renew session.

  1.   Session is renewed when the user responds to the alert message before the session expiry time
  2.   Session is renewed when the user type in the web form before the session expiry time
  3.   Session expires when user does not respond to the alert message before the session expiry time

My .aspx page’s <body> tag will be something like this:

<body onload="loadForm(event)" onkeydown="keyDown(event)">
    <form id="form1" runat="server">
    <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true">
    </asp:ScriptManager>

    <!-- script added to implement session timeout logic
    Logic:  1.  If no keys were pressed by the user for (session time out period - 1) minutes, an alert will be
                shown one minute before the session time out, if the user responds to the message, the session
                refreshes, else the session expires eventually
            2.  If keys were pressed by the user before (session time out period - 1) minutes, then the session
                automatically refreshes.
        -->
    <script type="text/javascript" >
        var actionFlag; //flag to monitor user key actions
        var timeoutPeriod; //holder for the server session timeout period (in minutes)
        var int; //variable for Interval
        var seconds = 60 //constant
        var nanoseconds = 1000 //constant

        //Uses the PageMethods to get the session timeout from the server
        function GetSessionTimeout() {
            //PageMethods.GetTimeoutPeriod(function (result) { timeoutPeriod = result; }); //todo: make it synchronous instead of async
            timeoutPeriod = parseInt(document.forms[0].inttop.value);  //session time out is available in a hidden field

        }

        //Calculates the retrigger time
        function getRetriggerTime() {
            if (timeoutPeriod == 1) return timeoutPeriod;
            return timeoutPeriod - 1;
        }

        //function handler for form's load event
        function loadForm(oEvent) {
            actionFlag = false; //reset the flag
            GetSessionTimeout(); //get the session timeout
            int = setInterval("notifyTimeOut()", getRetriggerTime() * seconds * nanoseconds); //renew the interval
        }

        //function that resets the actionFlag
        function keyDown(oEvent) {
            if (actionFlag) return; //skip if the flag is already true
            switch (oEvent.keyCode) {
                case 17: //skip if key is ctrl
                case 18: //skip if key is alt
                    return;
                    break;
            }
            //else
            actionFlag = true;
        }

        //function that refreshes the session without an alert
        function autoRefreshSession() {
            PageMethods.RefreshSession(); //make the server call
            int = clearInterval(int); //clear the interval, todo: check if this line is required
            int = setInterval("notifyTimeOut()", getRetriggerTime() * seconds * nanoseconds);  //renew the interval
        }

        //function that executes when the user triggers to refresh the session
        function manualRefreshSession() {
            PageMethods.RefreshSession(); //make the server call
            int = setInterval("notifyTimeOut()", getRetriggerTime() * seconds * nanoseconds); //renew the interval
        }

        //function thats executed at the scheduled time interval
        function notifyTimeOut() {
            int = clearInterval(int); //clear the interval, todo: check if this line is required
            if (actionFlag == true) autoRefreshSession(); //if action was taken, perform auto refresh
            else {
                alert('Your Session is about to expire! Click OK to refresh your session!'); //show alert to the user
                manualRefreshSession(); //if control returns refresh session, if the session has already expired a new session will start
            }
            actionFlag = false; //reset the flag
        }

    </script>
    </form>
</body>

and the code behind .aspx.cs’ class will be something like this:

        protected void Page_Load(object sender, EventArgs e)
        {
            Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "sessiontimeout", string.Format(@"<input type=""hidden"" id=""inttop"" value=""{0}"" />", Session.Timeout));
        }
        [WebMethod]
        public static void RefreshSession() { System.Diagnostics.Debug.WriteLine(DateTime.Now.ToString() +  "Session refreshed"); }

No Comments

No comments yet.

RSS feed for comments on this post.

Sorry, the comment form is closed at this time.

Powered by WordPress