Skip to main content

How to use ASP.net AJAX timer control to alert user when session times out.

Recently I needed a way to redirect the user to the login page after a certain time of inactivity. I found a neat way to do this using ASP.net AJAX timer control.

Following is the approach I took. I put the code in my master page as it can be shared by all the content pages.

1) Drag and drop the script manager control.
2) Drag and drop an update panel.
3) Set the updatepanel's UpdateMode property to Conditional.
4) Drag and drop a Timer control inside the update panel. Set the Interval property to the session time out time.
5) Set the timer control as a trigger to the update panel which causes it to postback on some event (Tick) .
Following is the code after the first 5 steps.

<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePartialRendering="true">
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanelMaster" UpdateMode="Conditional" runat="server">
<ContentTemplate>
<asp:Timer ID="Timer1" runat="server" Interval="500000"> </asp:Timer>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="Timer1" EventName="Tick" />
</Triggers>
</asp:UpdatePanel>
6) Now we need to sprinkle some javascript to go about our business. The basic idea is we need handle PageRequestManager's begin Request and end request events.

7)In the following code, we got hold of the instance of the PageRequestManager and handled its beginRequest and endRequests event by passing our function name as the parameter.
<script type="text/javascript">
var mgr = Sys.WebForms.PageRequestManager.getInstance();
mgr.add_beginRequest(BeforeAjaxRequest);
mgr.add_endRequest(AfterAjaxRequest);

//This function is called before each AJAX request
function BeforeAjaxRequest(sender, args)
{
var eventTarget=$get('__EVENTTARGET').value;
if(eventTarget=='<%=Timer1.UniqueID%>') //if timer triggered the postback..
{
alert('Your session has expired.');
window.location.href='login.aspx';
return false;
}
else
{
//if the post back is not triggered by the timer, stop the timer
//so that it doesn't time out when the post back is in process.
var timer = $find('<%= Timer1.ClientID %>');
if(timer!=undefined)
{
timer._stopTimer();
}
}
}

//This event is called after each request
function AfterAjaxRequest(sender,args)
{
var timer = $find('<%= Timer1.ClientID %>');
if(timer!=undefined)
{
var interval=timer.get_interval();
timer.set_interval(interval);
timer._startTimer(); //Restart the timer..
}

}

</script>
8) Every time there is a AJAX request, BeforeAJAXRequest method gets called. In that, I'm inspecting the event target to figure out who initiated the AJAX request.

9) If the request is initiated by our timer control, that means the user hasn't done anything for the specified interval. If that is the case alert the user and redirect to the login page. If it is not initiated by the timer, then stop the timer so that it doesn't time out during the postback.

10)In the event handler for endRequest event, restart the timer. Since the timer will be sitting in the master page and each content page can have their own update panels, the timer will not be reset on each postback automatically. So the timer might time out after the specified interval even though post backs happened during that interval. So to avoid that, we are stopping and starting the timer.

Comments

Popular posts from this blog

Clear Validation Errors and Validation Summary messages

ASP.net built in validation does not provide us a straight forward to clear all the validation errors. This would be really helpful while resetting a form. The reset html button would simply reset the form values but will not clear the validation errors. The following javascript code snippet can be used to clear the validation error messages. Have a reset button on your form and call the following js function onclick. <input type="reset" onclick="HideValidationErrors();" /> function HideValidationErrors() { //Hide all validation errors if (window.Page_Validators) for (var vI = 0; vI < Page_Validators.length; vI++) { var vValidator = Page_Validators[vI]; vValidator.isvalid = true; ValidatorUpdateDisplay(vValidator); } //Hide all validaiton summaries if (typeof (Page_ValidationSummaries) != "undefined") { //hide the validation summaries ...

Find the cause of poor performance in Sql Server

I found the following two part article by Gail Shaw on Simple-Talk really helpful in trouble shooting poorly performing queries in Sql Server. The articles talks about spotting poorly performing queries with the help of the Profiler, understand Sql Server Query plans and fine tune the peformance using proper indexes. Part 1: http://tinyurl.com/ccl6gj Part 2: http://tinyurl.com/okcuqg

SharePoint: Comparing dates in XSLT

In one of my sharePoint projects, I had to compare a date with the current date in XSLT. As it turned out, there is no support for date comparision in XSLT. This is how I went about doing it. The trick involves converting the date string into a number Say the date is in ISO format YYYY-MM-DDTHH:MM:SSZ (for example, 2001-01-21T22:54:47Z). Say we have a variable DueDate <xsl:variable name="DueDate" select="'2001-01-21T22:54:47Z'"> Replace the dashes in the string with empty string Take the first 10 character in the date sring convert the string to number number(translate(substring(@DueDate,1,10),'-','')) On doing the above we get: 20010121 We can do the same thing with the date to compare. We can compare the duedate with the current date in SharePoint as follows number(translate(substring(@DueDate,1,10),'-','')) & lt; number(translate(substring(ddwrt:TodayIso(),1,10),'-','')) You can apply the same log...