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

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

Kill a remote user session remotely

When trying to connect to your Windows 2000/2003 server remotely, you may receive the following error. "The terminal server has exceeded the maximum number of allowed connections." You could kill one or more of those connections by using PsExec tool that can be downloaded from the following link. This tool and a bunch of others were developed by SysInternals which was bought by Microsoft. http://www.microsoft.com/technet/sysinternals/utilities/pstools.mspx Open your command prompt and from the directory that contains the psexec utility, do the following 1) psexec \\x.x.x.x -u user -p password cmd (this will give you access to the cmd prompt on the server) Example: psexec \\127.0.0.1 -u admin -p password cmd 2) once you get the command prompt run the command qwinsta to get a list of all Terminal Services connections. Each connection has an Id Number. 3) Run the command logoff [id# of session to quit] /v (this will kill the connection with that id #) Example: logoff 2 /v Once ...

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...