Wednesday, November 14, 2012

Asp.Net Warning Message Before Session TimeOut

Web.Config
--------------
<configuration>
<appSettings>
    <add key ="SessionWarning" value ="1"/>
  </appSettings>    
</configuration>


-------------------------------------------------
SimpleAlert.aspx
-------------------
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="SimpleAlert.aspx.cs" Inherits="SimpleAlert" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="../Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
    <script language="javascript" type="text/javascript">
        var sessionTimeoutWarning = "<%= System.Configuration.ConfigurationSettings.AppSettings["SessionWarning"].ToString()%>";
        var sessionTimeout = "<%= Session.Timeout %>";
        var sTimeout = parseInt(sessionTimeoutWarning) * 60 * 1000;
        setTimeout('SessionWarning()', sTimeout);

        function SessionWarning() {
            var message = "Your session will expire in another " + (parseInt(sessionTimeout) - parseInt(sessionTimeoutWarning)) + " mins! Please Save the data before the session expires";
            alert(message);
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Button ID="Button1" runat="server" Text="Post Back" 
            onclick="Button1_Click" />
    </div>
    </form>
</body>
</html>


---------------------------------------------------
SimpleAlert.aspx.cs
------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace ASPNET_jQueryUI_Dialog_Timeout
{
    public partial class _Default : System.Web.UI.Page
    {
        public bool TimeoutControlEnabled
        {
            get { return Timeout1.Enabled; }
            set { Timeout1.Enabled = value; }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            Timeout1.TimeoutMinutes = HttpContext.Current.Session.Timeout;
            Timeout1.AboutToTimeoutMinutes = HttpContext.Current.Session.Timeout - 1;
        }
    }
}



-----------------------------------------------------------------------------------------
SimpleAlertAndRedirect.aspx
--------------------------------

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="SimpleAlertAndRedirect.aspx.cs" Inherits="SimpleAlertAndRedirect" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="../Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
     <script language="javascript" type="text/javascript">
        var sessionTimeoutWarning = "<%= System.Configuration.ConfigurationSettings.AppSettings["SessionWarning"].ToString()%>";
        var sessionTimeout = "<%= Session.Timeout %>";
        var timeOnPageLoad = new Date();
 
        //For warning
        setTimeout('SessionWarning()', parseInt(sessionTimeoutWarning) * 60 * 1000);
        //To redirect to the welcome page
        setTimeout('RedirectToWelcomePage()',parseInt(sessionTimeout) * 60 * 1000);

        //Session Warning
        function SessionWarning() {
            //minutes left for expiry
            var minutesForExpiry =  (parseInt(sessionTimeout) - parseInt(sessionTimeoutWarning));
            var message = "Your session will expire in another " + minutesForExpiry + " mins! Please Save the data before the session expires";
            alert(message);
            var currentTime = new Date();
            //time for expiry
            var timeForExpiry = timeOnPageLoad.setMinutes(timeOnPageLoad.getMinutes() + parseInt(sessionTimeout)); 

            //Current time is greater than the expiry time
            if(Date.parse(currentTime) > timeForExpiry)
            {
                alert("Session expired. You will be redirected to welcome page");
                window.location = "../Welcome.aspx";
            }
        }

        //Session timeout
        function RedirectToWelcomePage(){
            alert("Session expired. You will be redirected to welcome page");
            window.location = "../Welcome.aspx";
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
    </div>
    </form>
</body>
</html>


-------------------------------------------------------------------------
SimpleAlertAndRedirect.aspx.cs
--------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class SimpleAlertAndRedirect : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        Response.Write(Session.IsNewSession.ToString());
        if (!IsPostBack)
        {
            Session["Test"] = "Some Value";
        }
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        Response.Write(Session["Test"].ToString());
    }
}


-----------------------------------------------------------------------
ExtendSession.aspx
---------------------

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ExtendSession.aspx.cs" Inherits="ExtendSession" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="../Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
    <script language="javascript" type="text/javascript">
        var sessionTimeoutWarning = "<%= System.Configuration.ConfigurationSettings.AppSettings["SessionWarning"].ToString()%>";
        var sessionTimeout = "<%= Session.Timeout %>";
        var timeOnPageLoad = new Date();
        var sessionWarningTimer = null;
        var redirectToWelcomePageTimer = null;
        //For warning
        var sessionWarningTimer = setTimeout('SessionWarning()', parseInt(sessionTimeoutWarning) * 60 * 1000);
        //To redirect to the welcome page
        var redirectToWelcomePageTimer = setTimeout('RedirectToWelcomePage()',parseInt(sessionTimeout) * 60 * 1000);

        //Session Warning
        function SessionWarning() {
            //minutes left for expiry
            var minutesForExpiry =  (parseInt(sessionTimeout) - parseInt(sessionTimeoutWarning));
            var message = "Your session will expire in another " + minutesForExpiry + " mins. Do you want to extend the session?";

            //Confirm the user if he wants to extend the session
            answer = confirm(message);

            //if yes, extend the session.
            if(answer)
            {
                var img = new Image(1, 1);
                img.src = 'KeepAlive.aspx?date=' + escape(new Date());

                //Clear the RedirectToWelcomePage method
                if (redirectToWelcomePageTimer != null) {
                    clearTimeout(redirectToWelcomePageTimer);
                }
                timeOnPageLoad =  new Date();
                sessionWarningTimer = setTimeout('SessionWarning()', parseInt(sessionTimeoutWarning) * 60 * 1000);
                //To redirect to the welcome page
                redirectToWelcomePageTimer = setTimeout('RedirectToWelcomePage()',parseInt(sessionTimeout) * 60 * 1000);
            }

            //*************************
            //Even after clicking ok(extending session) or cancel button, if the session time is over. Then exit the session.
            var currentTime = new Date();
            //time for expiry
            var timeForExpiry = timeOnPageLoad.setMinutes(timeOnPageLoad.getMinutes() + parseInt(sessionTimeout)); 

            //Current time is greater than the expiry time
            if(Date.parse(currentTime) > timeForExpiry)
            {
                alert("Session expired. You will be redirected to welcome page");
                window.location = "../Welcome.aspx";
            }
            //**************************
        }

        //Session timeout
        function RedirectToWelcomePage(){
            alert("Session expired. You will be redirected to welcome page");
            window.location = "../Welcome.aspx";
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
    </div>
    </form>
</body>
</html>

------------------------------------------------------------------------
ExtendSession.aspx.cs
-------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class ExtendSession : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        Response.Write(Session.IsNewSession.ToString());
        if (!IsPostBack)
        {
            Session["Test"] = "Some Value";
        }
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        Response.Write(Session["Test"].ToString());
    }
}

0 comments:

Post a Comment