Blogs

This Blog

Subscribe (RSS, Email)

Mehul Harry's DevExpress Blog

JavaScript, HTML 5, ASP.NET, DevExpress, ASP.NET MVC & WebForms, and News - Mehul Harry's DevExpress blog

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

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

Published Jun 15 2011, 12:45 PM by
Bookmark and Share

Comments

Jens Havelberg

in XAF integrated?

June 15, 2011 4:11 PM

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.

June 15, 2011 4:30 PM

Brendon Muck [DevExpress MVP]

Very helpful. Thanks, Mehul!

June 15, 2011 4:31 PM

Dennis (DevExpress Support)

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.

June 16, 2011 4:56 AM

Fırat Esmer

I liked it :)

June 17, 2011 7:35 AM

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 !

June 21, 2011 3:58 AM

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.

June 21, 2011 4:41 AM

Yves Lessard

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

June 21, 2011 8:47 AM

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

June 21, 2011 12:26 PM

Mehul Harry (DevExpress)

Yves,

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

Thanks.

June 21, 2011 3:33 PM

Mehul Harry (DevExpress)

Huu,

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

June 21, 2011 3:36 PM

Mehul Harry (DevExpress)

Huu,

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

July 11, 2011 6:19 PM

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.

August 12, 2011 3:23 PM

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.

August 12, 2011 3:33 PM

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

March 1, 2012 6:45 AM

Mehul Harry (DevExpress)

Sagar,

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

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

March 1, 2012 12:55 PM

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.

October 15, 2012 11:36 AM

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.

October 15, 2012 1:36 PM

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

December 3, 2012 4:20 AM

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.

December 6, 2012 8:34 AM

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

February 26, 2013 8:55 AM

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.

March 1, 2013 5:49 PM

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')

April 19, 2013 7:48 PM

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

May 22, 2013 3:36 AM

Mehul Harry (DevExpress)

Thanks Ilayaraja for sharing.

May 22, 2013 2:17 PM

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.

May 25, 2013 4:56 AM

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

June 17, 2013 11:38 AM

Mehul Harry (DevExpress)

Yilmaz,

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

June 18, 2013 1:16 PM

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.

July 1, 2013 7:58 AM

About Mehul Harry (DevExpress)

Mehul Harry is an ASP.NET technical evangelist at Developer Express. You can reach him directly at mharry@DevExpress.com. You can also follow him on Twitter: http://twitter.com/mehulharry
LIVE CHAT

Chat is one of the many ways you can contact members of the DevExpress Team.
We are available Monday-Friday between 7:30am and 4:30pm Pacific Time.

If you need additional product information, write to us at info@devexpress.com or call us at +1 (818) 844-3383

FOLLOW US

DevExpress engineers feature-complete Presentation Controls, IDE Productivity Tools, Business Application Frameworks, and Reporting Systems for Visual Studio, along with high-performance HTML JS Mobile Frameworks for developers targeting iOS, Android and Windows Phone. Whether using WPF, Silverlight, ASP.NET, WinForms, HTML5 or Windows 8, DevExpress tools help you build and deliver your best in the shortest time possible.

Copyright © 1998-2014 Developer Express Inc.
All trademarks or registered trademarks are property of their respective owners