ASP.NET - How To Show A Popup Warning Before Session Timeout

ASP.NET Team Blog
15 June 2011

Check out this useful Code Central ASP.NET sample that shows you how to use the DevExpress ASP.NET PopupControl to:

  1. Display a warning message before a user's session times out and
  2. Allow the end-user to continue the session or log them out automatically

E3302

Session Timeout

Session Timeout is a property that you can set in your web.config file to control when a user session should expire.

Unfortunately, your end-users don't know when their session will expire unless you notify them somehow.

Popup Warning

One one of the best way to notify them is using a popup warning dialog. You may have seen these types of popups on your bank's website.

Say you're checking your bank balance online and need to answer a phone call elsewhere. You've just left the browser open at your bank account details which creates a potential security issue. To put it mildly.

If the ASP.NET Session timeout has been set then it will expire the session but it may not give any useful hints to the end-user. Most banking websites will display a client-side popup dialog to warn and ask the end-users if they would like to continue the session.

The popup could have a one minute timer and an OK button. If the end-user is still there and wants to continue the session then they'll click the 'Ok' button. But if the timer on the popup runs out then they'll automatically be logged out.

ASPxPopupControl To The Rescue

Now you can have this wonderful feature in your websites using the ASPxPopupControl! We've put together a Code Central sample that contains a ready-to-use UserControl that has our ASPxPopupControl embedded within it:

How to control state when the Session is being expired and prolong it on demand

To learn how Code Central works, watch this short video.

Note: You can't run this demo online, even though it's an ASP.NET project, because it uses the session state. However, you can easily download and run it locally.

Break It Down

The slick Code Central sample contains 4 files:

  • TimeoutControl.ascx - User Control that contains the Popup warning dialog
  • TimeOutPage.aspx - Simple page to redirect to when session has timed out
  • Default.aspx - Default page that calls the UserControl
  • Default.aspx.cs - Code behind page that sets the TimeOutUrl to point to TimeOutPage.aspx

All the Java Script magic happens in the Timeoutcontrol.ascx UserControl:

<script type="text/javascript">

    window.SessionTimeout = (function() {
        var _timeLeft, _popupTimer, _countDownTimer;

        var stopTimers = function() {
            window.clearTimeout(_popupTimer);
            window.clearTimeout(_countDownTimer);
        };

        var updateCountDown = function() {
            var min = Math.floor(_timeLeft / 60);
            var sec = _timeLeft % 60;
            if(sec < 10)
                sec = "0" + sec;

            document.getElementById("CountDownHolder").innerHTML = min + ":" + sec;

            if(_timeLeft > 0) {
                _timeLeft--;
                _countDownTimer = window.setTimeout(updateCountDown, 1000);
            } else  {
                window.location = <%= QuotedTimeOutUrl %>;
            }            
        };

        var showPopup = function() {
            _timeLeft = 60;
            updateCountDown();
            ClientTimeoutPopup.Show();
        };

        var schedulePopup = function() {       
            stopTimers();
            _popupTimer = window.setTimeout(showPopup, <%= PopupShowDelay %>);
        };

        var sendKeepAlive = function() {
            stopTimers();
            ClientTimeoutPopup.Hide();
            ClientKeepAliveHelper.PerformCallback();
        };

        return {
            schedulePopup: schedulePopup,
            sendKeepAlive: sendKeepAlive
        };

    })();    

</script>

Download the sample and integrate into your websites to give your end-users a friendly reminder that their session is expiring soon and would they like to keep it running. Smile

Thanks!

DXperience? What's That?

DXperience is the .NET developer's secret weapon. Get full access to a complete suite of professional components that let you instantly drop in new features, designer styles and fast performance for your applications. Try a fully-functional version of DXperience for free now: http://www.devexpress.com/Downloads/NET/

Follow MehulHarry on Twitter

Free DevExpress Products – Get Your Copy Today

The following free DevExpress product offers remain available. Should you have any questions about the free offers below, please submit a ticket via the DevExpress Support Center at your convenience. We’ll be happy to follow-up.
Jens Havelberg
Jens Havelberg

in XAF integrated?

15 June 2011
Mehul Harry (DevExpress)
Mehul Harry (DevExpress)

Jens,

This is a code central sample so I don't believe it's integrated directly into XAF. I've asked the XAF team to look into it for you and they'll comment soon about it.

Thanks.

15 June 2011
Brendon Muck [DevExpress MVP]
Brendon Muck [DevExpress MVP]

Very helpful. Thanks, Mehul!

15 June 2011
Dennis (DevExpress)
Dennis Garavsky (DevExpress)

As Mehul mentioned above, it is not integrated in XAF. Furthermore, in XAF we have our own mechanism that automatically prolongs the session. If you are interested to learn more about it, please notice the SessionKeepAliveReconnect.aspx page in the root folder of your website. And if you have access to XAF sources, check out the SessionKeepAliveReconnect method in the CommonFunctions.js file as well as the use of the SessionKeepAliveControl class.

However, you can implement the solution demonstrated in this blog in XAF Web applications because XAF produces regular ASP.NET applications where the same customization techniques can be used.

16 June 2011
Fırat Esmer
Fırat Esmer

I liked it :)

17 June 2011
Jean Pierre RAVEZ
Jean Pierre RAVEZ

This solution assumes that each user will use only one client window at a time on the web application , no ? Do you think it's possible to implement a "simple" solution that would work with several windows opened at the same time (sharing the same session) by a single user ? Thanks !

21 June 2011
Mehul Harry (DevExpress)
Mehul Harry (DevExpress)

Jean,

The approach from the example will prolong the session for all browser windows, but other windows cannot know about it and will be redirected to the timeout page, so the user will have to use the “Back” button to continue their work.

Unfortunately, there isn't a simple solution here. To solve it, there should be some kind of opened window tracking and cross-window communication. And this cannot be simple and universal, sorry.

21 June 2011
Yves Lessard
Yves Lessard

In a Master Page project ... would it be wyse to instantiate the TimeoutControl.ascx in the master page ?

21 June 2011
Huu Huyen 1
Huu Huyen 1

Is there equivalent code as Razor partial page? And can this be incorporated in common view layout page (similar to above question into master page).

21 June 2011
Mehul Harry (DevExpress)
Mehul Harry (DevExpress)

Yves,

Yes, you can put the usercontrol on the master page. :)

Thanks.

21 June 2011
Mehul Harry (DevExpress)
Mehul Harry (DevExpress)

Huu,

There isn't an MVC version of this. I'll look into it and get back to you.

21 June 2011
Mehul Harry (DevExpress)
Mehul Harry (DevExpress)

Huu,

Here a version of this sample for ASP.NET MVC that uses DevExpress MVC Popupcontrol extension: http://dxpr.es/pNGAJ3

11 July 2011
Huu Huyen
Huu Huyen

Mehul, thanks for providing example in MVC. I tried to incorporate your example into my project but the popup control does not display correctly. My DevExpress version is 10.2 and your example is DevExpress version 11.1. Do I need to upgrade DevExpress version again? It looks like Popup Control support has changed.

Also can I incorporate this feature into _Layout.cshtml so it will apply to all pages and only render TimeoutPartial when request is authenticated as it only makes sense to show timeout if user has logged in.

12 August 2011
Mehul Harry (DevExpress)
Mehul Harry (DevExpress)

Huu,

No problem and yes, I recommend upgrading to the latest version because we've added some great improvements that you'll want to take advantage of:

community.devexpress.com/.../asp-net-popup-control-lightweight-rendering-scroll-bars-css3-and-more-coming-soon-in-v2011-vol-1.aspx

Thanks.

12 August 2011
sagar metkar 1
sagar metkar 1

this Code is good.

but when i use UserControl  popup control and timeout popup is display same time, if i want session live then i click ok button then previous popup control client side validation create static to increment session how can solve this problem..

1 March 2012
Mehul Harry (DevExpress)
Mehul Harry (DevExpress)

Sagar,

Thanks, I recommend that you contact our support team and they can help you:

www.devexpress.com/.../CreateIssue.aspx

1 March 2012
Ryan Bromm
Ryan Bromm

When several window is opened at same time I use the array to store the handle to opened windows.

Now what to do so that popup appears on top most window.

15 October 2012
Mehul Harry (DevExpress)
Mehul Harry (DevExpress)

Ryan,

Can you please upload a small sample to our support team so they can have a closer look?

www.devexpress.com/.../Create

Thanks.

15 October 2012
Glen Harvy
Glen Harvy

Hi Mehul,

This won't work in a Web Application as I can now fully attest to. After several  hours trying I found this posting:

In the How to control state when the Session is being expired and prolong it on demand example the solution is posted in the "Web Site project" format, but you are using the "Web Application Project". Web Site projects support the placing of the server-side code in the page markup, but the Web Application project does not support this. Please refer to the Web Application Projects versus Web Site Projects in Visual Studio article for more information regarding this.

To make your application work correctly move all server-side code from your control's markup to the code behind file (TimeOutControl.aspx.vb).

I've asked if they can provide a sample for Web Applications in C# - perhaps a link on this post might be a good idea as well.

Merry Christmas ...

3 December 2012
Mike (DevExpress Support)
Mike (DevExpress Support)

Hello Glen,

Thank you for your feedback. I agree with your point of view so it will be useful to provide solutions for both project types (ASP.NET WebSite and WebApplication) because there are some structure differences between these two kinds of VS projects.

I have updated the E3302 Code Central example accordingly.

This example contains two solutions:

The solution for v2010 vol 2.8+ versions - is an ASP.NET WebSite project.

The solution for v2011 vol 1.12+ versions - is an ASP.NET WebApplication project.

6 December 2012
Richard Benetseder
Richard Benetseder

Hi!

I've integrated this pop into my MasterPage project and it works fine, except that the countdown isn't shown. But the redirect is done as expected.

Any idea?

Thx,

Rich

26 February 2013
Mehul Harry (DevExpress)
Mehul Harry (DevExpress)

Rich,

Not sure, could be a popup blocker? Contact our support team and they can help you:

www.devexpress.com/.../CreateIssue.aspx

Thanks.

1 March 2013
Hector Badillo
Hector Badillo

Hi Im trying to implement this solution to my aplication but when I test the project I get multiple javascript messages from VS2012

for example:

0x800a1391 - Runtime Error in Microsoft BLOCKED SCRIPT 'aspxAddHoverItems' is undefined

in line 201 aspxAddHoverItems('TimeoutControl_TimeoutPop......etc')

19 April 2013
Ilayaraja Periasamy
Ilayaraja Periasamy

Hi all,

I have found a workaround to implement this solutions to work for multiple tabs (sharing the same session) by a single user.

Only thing we need to do is, create a Cookie while the user logs in and check that Cookie in the following places,

var showPopup = function() {            

_timeLeft = 60;            

var userid=ASPxClientUtils.GetCookie("LoggedInUser");

if(userid == null)

{

updateCountDown();            

ClientTimeoutPopup.Show();        

}

};

var updateCountDown = function() {

          var min = Math.floor(_timeLeft / 60);

           var sec = _timeLeft % 60;

           if(sec < 10)

               sec = "0" + sec;

           document.getElementById("CountDownHolder").innerHTML = min + ":" + sec;

           if(_timeLeft > 0) {

               _timeLeft--;

               _countDownTimer = window.setTimeout(updateCountDown, 1000);

           } else  {  

               //ASPxClientUtils.SetCookie("userid",null,new Date());  

               //ASPxClientUtils.DeleteCookie("userid");  

               var userid=ASPxClientUtils.GetCookie("LoggedInUser");

               if(userid == null)

               {

                   document.getElementById("<%=btnlogout.ClientID %>").click();

               }

               else

               {

                   sendKeepAlive();

               }

           }            

       };

As per my example I have created a cookie with name "LoggedInUser".

Also we need to do another thing to make the above code work, created a class (.cs) file which inherits the System.Web.UI.Page class and implement the following code in it.

public partial class BasePage : System.Web.UI.Page

{

   protected void Page_PreInit(object sender, EventArgs e)

   {

        if (Session["userid"] != null)

       {

             if (Request.Cookies["LoggedInUser"] != null)

           {

               HttpCookie LoggedInUser = Request.Cookies["LoggedInUser"];

               LoggedInUser.Value = Convert.ToString(Session["userid"]);

               LoggedInUser.Expires = sessionTimeout;

               Response.AppendCookie(LoggedInUser);

           }

           else

           {

               HttpCookie LoggedInUser = new HttpCookie("LoggedInUser");

               LoggedInUser.Value = Convert.ToString(Session["userid"]);

               LoggedInUser.Expires = sessionTimeout;

               Response.AppendCookie(LoggedInUser);

           }

       }

   }

}

So finally we need to inherit this BasePage class in all the .aspx pages in your web application.

I hope this solution will be helpful to you all. At once I found the solution I have posted this is comment and happy it would help someone.

Happy programming..

22 May 2013
Mehul Harry (DevExpress)
Mehul Harry (DevExpress)

Thanks Ilayaraja for sharing.

22 May 2013
Ilayaraja Periasamy
Ilayaraja Periasamy

Hi Mehul,

You are welcome, everything is working fine except one thing. What will happen if session timeout value is less than the PopupShowDelay, the popup is not at all showing but the session got timedout.

For example I have ket the PopupShowDelay=50 mintues and the session timeout is default ie. 20 minutes. What is happening is the session got timedout in 20 minutes and popup never pops up.

So for this shall i set the PopupShowDelay and the Session timeout to same value?

Please help me with a suggestion.

25 May 2013
Yilmaz Uksal
Yilmaz Uksal

Using document.location is problematic. Use window.location instead. When browser is minimized and not in focus, usage of document.location doesn't render the page. Check out my ticket to DevEx. www.devexpress.com/.../focus-answer-a29bf533-d2a5-11e2-9b11-005056c00008

17 June 2013
Mehul Harry (DevExpress)
Mehul Harry (DevExpress)

Yilmaz,

Thanks, I've updated the post to reflect the window.location.

18 June 2013
Martijn van IJperen
Martijn van IJperen

Nice article.

There is one thing to keep in mind when you work with FormsAuthentication

(SlidingExpiration resets the expiration time for a valid authentication cookie

if a request is made and more than half of the timeout interval has elapsed)

Example:

a) Session timeout 5 minutes

b) FormsAuthentication timeout 5 minutes ( With SlidingExpiration)

Say you load a page on 12:00 and decide to navigate to another page on 12:01 the Session.Timeout will state 5 minutes but the FormsAuthenticationTicket.Expiration will state 4 minutes

because the ticket is not renewed due to the fact that more than the half of the timeout is still available.

If you would do nothing on the page and rely on the Session.Timeout the popup will shown to late and continue the session will not work because you are not authorized anymore. So

it's better to use the FormsAuthentication.Expiration.

There you could do FormsAuthentication.Expiration - DateTime.Now from that you can return the TotalMilliseconds - 60000 ( one minute ). In some cases more time could be required for session end processing.

1 July 2013
Guillermo Villasana
Guillermo Villasana

How can I make a timeout notification like this using the Identity Framework that uses OWIN cookie authentication??

30 June 2016

Please login or register to post comments.