Link to home
Start Free TrialLog in
Avatar of Saroj13
Saroj13

asked on

Display Session Timeout message before Session expires in ASP.Net having masterpage and iframes?

Hi,

I am having masterpage and using iframes. Everything is working fine except if submit activity happens on iframes, its not reseting the session timeout?

Open in new window

Masterpage.aspx
<%@ Master Language="C#" AutoEventWireup="true" CodeBehind="AdminMasterPage.master.cs" Inherits="CoreTeamFeedback.Administration.MasterPage" %>
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp"%>
<!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">

   <asp:ContentPlaceHolder id="head" runat="server">
   </asp:ContentPlaceHolder>
 
 </head>
<body>
    <form id="form1" runat="server">
     
                 <asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server"></asp:ToolkitScriptManager>
       <span style="visibility:hidden">Session Idle:</span><span id="secondsIdle" style="visibility:hidden">&nbsp;seconds.</span>
           <asp:LinkButton ID="lnkSession" runat="server" />
<asp:ModalPopupExtender ID="mpeTimeout" BehaviorID ="mpeSessionTimeout" runat="server" PopupControlID="pnlPopup" TargetControlID="lnkSession"
   OkControlID="btnOK"  BackgroundCssClass="modalBackground"  >
</asp:ModalPopupExtender>

<asp:Panel ID="pnlPopup" runat="server" CssClass="modalPopup" Style="display: none" >
        <div class="footer" align="right">
     
        <asp:Button ID="btnOK" runat="server" Text="OK" CssClass="Savebutton" CausesValidation="false" />
             
    </div>
</asp:Panel>
     
       <div id="mainContent">
        <asp:ContentPlaceHolder id="MainContent" runat="server"  >      
        </asp:ContentPlaceHolder>
    </div>
       
    </form>
</body>
</html>

---------------------
.cs
protected void Page_Load(object sender, EventArgs e)
{
    Response.Cache.SetCacheability(HttpCacheability.NoCache);
    if (!this.IsPostBack)
    {
        Session["Reset"] = true;
        Configuration config = WebConfigurationManager.OpenWebConfiguration("~/Web.Config");
        SessionStateSection section = (SessionStateSection)config.GetSection("system.web/sessionState");
        int timeout = (int)section.Timeout.TotalMinutes * 1000 * 60;
        ClientScript.RegisterStartupScript(this.GetType(), "SessionAlert", "SessionExpireAlert(" + timeout + ");", true);
    }
}
----------

default.aspx
Default.aspx   main page
              <frameset rows="20%,80%" frameborder="0"  >
            <frame name="topFrame" scrolling="no" frameborder="0" src="top.aspx">
            <frame name="mainFrame" scrolling="yes" src="bottom.aspx" DESIGNTIMEDRAGDROP="7">
      </frameset>

-----------------

<script type="text/javascript">
function SessionExpireAlert(timeout) {
    var seconds = timeout / 1000;
    document.getElementsByName("secondsIdle").innerHTML = seconds;
    document.getElementsByName("seconds").innerHTML = seconds;
    setInterval(function () {
        seconds--;
        document.getElementById("seconds").innerHTML = seconds;
        document.getElementById("secondsIdle").innerHTML = seconds;
    }, 1000);
    setTimeout(function () {
        //Show Popup before 20 seconds of timeout.
        $find("mpeTimeout").show();
    }, timeout - 20 * 1000);
    setTimeout(function () {
        window.location = "Expired.aspx";
    }, timeout);
};

</script>

Question:
What to do if there is any activity in top and right frame, it will reset the session timeout without refreshing the full page? If parent page refreshes, everything is working fine?
Avatar of Ryan Chong
Ryan Chong
Flag of Singapore image

What to do if there is any activity in top and right frame, it will reset the session timeout without refreshing the full page?

If parent page refreshes, everything is working fine?

it depends, probably 2 ways you can think off:

1. Save the "last activity date time" at server end, for your web page (probably using AJAX so your whole page is not refreshing) do a query to server side like every min (configurable) to determine whether your page:

a) is going to expire.
If yes, like within 2 mins of expiration, prompt user to refresh or retain the session

b) is expired
if yes, reset session and then redirect user to default page

2. similar to method 1, but you can keep the "last activity date time" at client end (like localstorage or cookies), if your web application is not required to be protected securely.
Avatar of Saroj13
Saroj13

ASKER

Please find my proper code here. i am not sure how this can be done. Plz provide me the code snippets..


Mastepage.aspx

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
 
   <asp:ContentPlaceHolder id="head" runat="server">
   </asp:ContentPlaceHolder>
</head>
<body>
    <form id="form1" runat="server">
  
       <div id="mainContent" >
        <asp:ContentPlaceHolder id="MainContent" runat="server"   >      
        </asp:ContentPlaceHolder>
    </div>
  <asp:ScriptManager ID="sm" runat="server" EnablePartialRendering="true" />
       <span style="visibility:hidden">Session Idle:</span><span id="secondsIdle" style="visibility:hidden">&nbsp;seconds.</span>
           <asp:LinkButton ID="lnkSession" runat="server" />
<asp:ModalPopupExtender ID="mpeTimeout" BehaviorID ="mpeSessionTimeout" runat="server" PopupControlID="pnlPopup" TargetControlID="lnkSession"
   OkControlID="btnOK"  BackgroundCssClass="modalBackground" >
</asp:ModalPopupExtender>
 
<asp:Panel ID="pnlPopup" runat="server" CssClass="modalPopup" Style="display: none">
     <div class="header"> Session Expiring!
      </div>
 
    <div class="body">
        Your session will expire in&nbsp;<span id="seconds"></span>&nbsp;seconds.<br />
        Please submit/update your changes or you will loose your data.
    </div>
 
    <div class="footer" align="right">
    
        <asp:Button ID="btnOK" runat="server" Text="OK" CssClass="Savebutton" CausesValidation="false" />
             
    </div>
</asp:Panel>     
    </form>
</body>
</html>

 

Masterpage.aspx.cs

        protected void Page_Load(object sender, EventArgs e)
        {
            //Session Timeout Warning Dialog
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            if (!this.IsPostBack)
 
            {
                Session["Reset"] = true;
                Configuration config = WebConfigurationManager.OpenWebConfiguration("~/Web.Config");
                SessionStateSection section = (SessionStateSection)config.GetSection("system.web/sessionState");
                int timeout = (int)section.Timeout.TotalMinutes * 1000 * 60;
                Page.ClientScript.RegisterStartupScript(this.GetType(), "SessionAlert", "AdminSessionTimeoutAlert(" + timeout + ");", true);
            }
        }

 

 

Javascript

function AdminSessionTimeoutAlert(timeout) {
   var seconds = timeout / 1000;
   document.getElementsByName("seconds").innerHTML = seconds;
    setInterval(function () {
        seconds--;
        document.getElementById("seconds").innerHTML = seconds;
       }, 1000);
 
    setTimeout(function () {
        $find("mpeSessionTimeout").show();
    }, timeout - 120 * 1000);
 
 
    setTimeout(function () {
        window.top.location.href = "AdminSessionExpired.aspx";
    }, timeout);
 
};
 

--------------------------------------------------

Web.config

    <sessionState timeout="15"/>
 
Default.aspx (Main Page)
 
 
<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" Runat="Server">
 
    <div class="container">
   
      <iframe id="leftframeName1" name="leftframeName1" src="leftframename1.aspx" frameborder="0" class="indexframe" ></iframe>
        </div>
 
<div class="container1">
     <iframe id="rightframeName2" src="right.htm" frameborder="0" class="blankframe"  ></iframe>
</div> 
    
  </asp:Content>
 
 
leftframename1.aspx

is having tree control which opens different pages in rightframe for adding/editing/deleting nodes.

Working:

Everything is working fine. Session timeout dialog appears at 13 minutes and default.aspx will redirect to session timeout page at 15 minute.

Problem: Need solution if in right frame if user clicks on Add/edit/delete button, it will update the information in the left frame/right frame, but it will not reset the session timeout. I don’t want whole page to be reloaded. How to reset session timeout in case of form submit activities…..

 

Open in new window


thanks
Sorry as don't have time in verify your issue in depth.

but it seems that what you need to do is to call the javascript function: AdminSessionTimeoutAlert again after the user clicked on Add/edit/delete button in the Right frame.

you can do that by calling Page.ClientScript.RegisterStartupScript after the button was clicked at server end, but this time you need to make sure you able to call that javascript function: AdminSessionTimeoutAlert as it's not within the frame codes.
Avatar of Saroj13

ASKER

Its calling the javascript. But my Session Timeout popup code is in the masterpage. i need to display always on parent page 'default.aspx'. how to call parent page modalpopup window from iframe (rightframe). Please help me...
how to call parent page modalpopup window from iframe (rightframe)
considering to put the popup window scripts into a function in your parent's page, then you could try like:

Parent page (WebForm1.aspx):

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication_C.WebForm1" %>

<!DOCTYPE html>
<html>
<body>
<iframe id="myframe" src="WebForm2.aspx" width="100%" height="500" style="background:#f1f1f1;">
  <p>Your browser does not support iframes.</p>
</iframe>
<p>Click the button inside the iframe to call parent page's function.</p>
</body>
</html>

<script type="text/javascript">
    function ParentFunction(v) {
        alert("Now is = " + v);
    }
</script>

Open in new window


Iframe page (WebForm2.aspx):

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm2.aspx.cs" Inherits="WebApplication_C.basePage" %>
<html>
<body>
<p>Click the button.</p>
<button onclick="window.parent.ParentFunction(new Date())">Try it</button>
</body>
</html>

Open in new window


looking for window.parent.functionname() from the iframe.
Avatar of Saroj13

ASKER

i tried this its not working.
Parentpage is default.aspx which uses masterpage. masterpage is having session timeout code. below javascript is used. its perfecty working fine. showing warning 13 minute and 15 minute redirect page.

javascript
<asp:ScriptManager ID="sm" runat="server" EnablePartialRendering="true" />
       <span style="visibility:hidden">Session Idle:</span><span id="secondsIdle" style="visibility:hidden">&nbsp;seconds.</span>
           <asp:LinkButton ID="lnkSession" runat="server" />
<asp:ModalPopupExtender ID="mpeTimeout" BehaviorID ="mpeSessionTimeout" runat="server" PopupControlID="pnlPopup" TargetControlID="lnkSession"
   OkControlID="btnOK"  BackgroundCssClass="modalBackground" >
</asp:ModalPopupExtender>
 
<asp:Panel ID="pnlPopup" runat="server" CssClass="modalPopup" Style="display: none">
     <div class="header"> Session Expiring!
      </div>
 
    <div class="body">
        Your session will expire in&nbsp;<span id="seconds"></span>&nbsp;seconds.<br />
        Please submit/update your changes or you will loose your data.
    </div>
 

Open in new window


Problem:
in the right frame, i have add event

<input type=submit name=submit value="Submit" ID="btnSubmit" runat="server">
When we click on the above text, it will add a node in the left frame without refreshing. I want at this time session will again reset to 15 minutes. how this cab accomplished?

thanks
Parentpage is default.aspx which uses masterpage. masterpage is having session timeout code. below javascript is used. its perfecty working fine.
if you're doing the session timeout checking from code behind (in master page), in order to reset the counter, you would need to execute that piece of code at server end as well.

you may want to think of a way to do that if you don't want to refresh that whole page (master page), as already mentioned, try a AJAX approach should be good enough to send a request to server end to tell the server to reset the counter.
Avatar of Saroj13

ASKER

Hi Ryan,

Please find my below code.. Please try to fix my code... Its really important. I tried everything, but its not working...

Problems. When I open the default.aspx, Session Timeout dialog appears 2 minutes before the session timeout. In the dialog seconds are changing like 132 103 91 88 84 96 90 78 85 83 seconds. I am not sure why seconds are changing like that . It should show 120,119, 118, 117...


Problem2. Default.aspx is having frames. Index frame is having tree control . clicking on any node will open page in details.aspx. Button click will again reset the session  and should display the session timeout dialog having 120 seconds left..... Its not working like that.

Code

MasterPage.aspx

<%@ Master Language="C#" AutoEventWireup="true" CodeBehind="Masterpage.master.cs" Inherits="Masterpage" %>
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp"%>
<%@ Register Src="~/SessionTimeout.ascx" TagPrefix="uc1" TagName="SessionTimeout" %>
 
<!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">
   <asp:ContentPlaceHolder id="head" runat="server">
   </asp:ContentPlaceHolder>
</head>
<body>
    <form id="form1" runat="server">
  
       <div id="mainContent" >
        <asp:ContentPlaceHolder id="MainContent" runat="server"   >      
        </asp:ContentPlaceHolder>
    </div>
     <uc1:SessionTimeout id="SessionTimeout" runat="server"></uc1:SessionTimeout>
     
    </form>
</body>
</html>
 
SessionTimeout.ascx
 
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="SessionTimeout.ascx.cs" Inherits="SessionTimeout" %>
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp"%>
<script src="scripts/jquery-1.12.4.js" type="text/javascript"></script>
<script type="text/javascript" src="scripts/Functions.js"></script>
 
 
      <asp:ScriptManager ID="sm" runat="server" EnablePageMethods="true" />
                  <asp:LinkButton ID="lnkSession" runat="server" />
<asp:ModalPopupExtender ID="mpeTimeout" BehaviorID ="mpeSessionTimeout" runat="server" PopupControlID="pnlPopup" TargetControlID="lnkSession"
   OkControlID="btnOK"  BackgroundCssClass="modalBackground" >
</asp:ModalPopupExtender>
 
<asp:Panel ID="pnlPopup" runat="server" CssClass="modalPopup" Style="display: none">
     <div class="header"> Session Expiring!
      </div>
 
    <div class="body">
        Your session will expire in&nbsp;<span id="seconds"></span>&nbsp;seconds.<br />
     </div>
 
    <div class="footer" align="right">
    
        <asp:Button ID="btnOK" runat="server" Text="OK" CssClass="Savebutton" CausesValidation="false" />
             
    </div>
</asp:Panel>
 

SessionTimeout.ascx.cs

using System.Configuration;
using System.Web.Configuration;
using System.Web.Services;
 
    public partial class SessionTimeout : System.Web.UI.UserControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            //Session Timeout Warning Dialog
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            if (!this.IsPostBack)
 
            {
                Session["Reset"] = true;
                int timeout = GetSessionTimeout();
                Page.ClientScript.RegisterStartupScript(this.GetType(), "SessionAlert", "AdminSessionTimeoutAlert(" + timeout + ");", true);
            }
        }
 
 
        [WebMethod(EnableSession = true)]
        public static int ResetSession()
        {
            HttpContext.Current.Session["Reset"] = true;
            int timeout = GetSessionTimeout();
            return timeout;
        }
 
 
        private static int GetSessionTimeout()
        {
            Configuration config = WebConfigurationManager.OpenWebConfiguration("~/Web.Config");
            SessionStateSection section = (SessionStateSection)config.GetSection("system.web/sessionState");
            return Convert.ToInt32(section.Timeout.TotalMinutes * 1000 * 60);
        }
 
 
    }
 

Web.config

<sessionState timeout="3"/>

Javascript  Functions.js

function AdminSessionTimeoutAlert(timeout) {
   var seconds = timeout / 1000;
 
     window.parent.document.getElementsByName("seconds").innerHTML = seconds;
 
    setInterval(function () {
 
        seconds--;
 
        window.parent.document.getElementById("seconds").innerHTML = seconds;
 
      }, 1000);
 
    setTimeout(function () {
       window.parent.$find("mpeSessionTimeout").show();
 
    }, timeout - 120 * 1000);
 
 
    setTimeout(function () {
 
        window.top.location.href = "SessionExpired.aspx";
 
    }, timeout);
 
};
 
function ResetSession() {
    PageMethods.ResetSession(OnSuccess);
    return false;
}
function OnSuccess(response, userContext, methodName) {
    AdminSessionTimeoutAlert(response);
}
 
 

Parent Page default.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="default.aspx.cs" Inherits="default" MasterPageFile="~/Masterpage.Master"%>
 
<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" Runat="Server">
    <div class="container">
      <iframe id="frameName1" name="frameName1" src="index.aspx" frameborder="0"></iframe>
        </div>
 
<div class="container1">
     <iframe id="frameName2" src=" details.aspx" frameborder="0"></iframe>
</div> 
</asp:Content>
 
Details.aspx
 
<%@ Page language="c#" Inherits="Details" Codebehind="DEtails.aspx.cs" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
  <HEAD>
      <script type="text/javascript" src="scripts/Functions.js"></script>
      <script src="scripts/jquery-1.12.4.js" type="text/javascript"></script>
 
 
  </HEAD>
  <body>
      
    <form id="Form1" method="post" runat="server">
              <asp:ScriptManager ID="sm" runat="server" EnablePageMethods="true" />
              <INPUT type="text" name="txtCategoryName"  size="20" maxlength="50" ID="txtCategoryName" runat="server">
 
<asp:Button text="Submit" ID="btnSubmit1" runat="server"  OnClientClick="ResetSession();"/>
     </form>
      
  </body>
</HTML>
 
Details.aspx
 
using System.Web.Services;
using System.Configuration;
using System.Web.Configuration;
 
       public partial class Details: System.Web.UI.Page
       {
              protected void Page_Load(object sender, System.EventArgs e)
              {
 
            if (!IsPostBack)
            {
                Session["Reset"] = true;
                int timeout = GetSessionTimeout();
                Page.ClientScript.RegisterStartupScript(this.GetType(), "SessionAlert", "AdminSessionTimeoutAlert(" + timeout + ");", true);
            }
        }
 
        [WebMethod(EnableSession = true)]
        public static int ResetSession()
        {
            HttpContext.Current.Session["Reset"] = true;
            int timeout = GetSessionTimeout();
            return timeout;
       }
 
 
        private static int GetSessionTimeout()
        {
            Configuration config = WebConfigurationManager.OpenWebConfiguration("~/Web.Config");
            SessionStateSection section = (SessionStateSection)config.GetSection("system.web/sessionState");
            return Convert.ToInt32(section.Timeout.TotalMinutes * 1000 * 60);
        }
 

Open in new window



Problems. When I open the default.aspx, Session Timeout dialog appears 2 minutes before the session timeout. In the dialog seconds are changing like 132 103 91 88 84 96 90 78 85 83 seconds. I am not sure why seconds are changing like that . It should show 120,119, 118, 117...


Problem2. Default.aspx is having frames. Index frame is having tree control . clicking on any node will open page in details.aspx. Button click will again reset the session  and should display the session timeout dialog having 120 seconds left..... Its not working like that.

I am not sure how to fix these issues. Please fix my code. Its urgent.

Thanks
why you're calling function AdminSessionTimeoutAlert twice,

once in Default.aspx and once in SessionTimeout.ascx?

Page.ClientScript.RegisterStartupScript(this.GetType(), "SessionAlert", "AdminSessionTimeoutAlert(" + timeout + ");", true);

Open in new window


I think you should include it once but not more than once
Avatar of Saroj13

ASKER

I am not sure what needs to be done. I want  AdminSessionTimeout Alert dialog will appear on the default.aspx before 2 minutes left in session timeout. If user is in any of the iframe, click any submit button will reset the session without page refresh and adminsessiontimeout alert dialog will appear again.

thanks
Avatar of Saroj13

ASKER

Hi Ryan,

Please see my below code in the attachment. Ajaxcontroltoolkit dll is not included.

1. please test addcategory link and Submit button. Submit button needs to reset the session timeout.

thanks
WebSite.zip
i got an JavaScript error when clicked on the Add Category link using FF:

parent.frameName2.location is undefined

Open in new window


anyway, the counter looks ok for me in which the numbers are not jumping around, instead it's counting down in proper sequence.
to resolve error above, you should put a name attribute when you define your frameName2:

<iframe id="frameName2" name="frameName2" src="blank.html" frameborder="0" class="blankframe"  ></iframe>
In the dialog seconds are changing like 132 103 91 88 84 96 90 78 85 83 seconds. I am not sure why seconds are changing like that . It should show 120,119, 118, 117...
i guess reason being there are more than 1 timer is running, that's why you saw the effect of jumping numbers
ASKER CERTIFIED SOLUTION
Avatar of Ryan Chong
Ryan Chong
Flag of Singapore image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
have you tried out what i posted above?

do you need further assistance here?
testing working using localstorage  method.