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

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

Creating a Windows Task Scheduler Service

Recently, one of my friends asked me for help in creating a windows service for scheduling some tasks. He said that he could not use the task scheduler that comes with Windows as the Task Scheduler expects each task to be a stand alone executable file. All his tasks were in a single class library and it would be a lot of work to separate each task into its own executable. Also he said that that the schedule for the tasks could change from time to time and it would be nice if he could configure the tasks in an XML file. To Recap, the requirements for the windows service are 1) The tasks should be loaded from a class library 2) The schedule information for the tasks should be configurable in an XML file. We googled (binged :)) for the solution and found an excellent article by Ajit Kumar Application Scheduler Service Using C#.Net And XML to base our solution upon. We took some good points like configuring the task information from the above mentioned article. This is how we to