Best Practices for Renew Session

  1. #1

    Best Practices for Renew Session

    Hi, I need to have a code for renewing the session timeout. I wish to :

    - call a window for session renewal each time my app detects the timeout in the server.
    or
    - renew the session automatically each time a session timeout

    I have an app like the examples explorer of ext.net. So for a better user experience, I dont want to redirect to a login.aspx and the user looses all his job.

    So I want to know the best practices for renewing and detect the session timeout when you call to:

    - directevent and directmethods inside a webform.aspx
    - ashx handler for loading data to stores

    So, In which event is the best place for detecting the session timeout in the latter scenarios?
    Do I need to check the timeout in each webform I load?
    How can I detect the session timeout in an ashx handler?

    Can you share a working sample for the above scenarios?

    Thanks in advance.
    Last edited by iomega55; Oct 29, 2014 at 4:57 AM.
  2. #2
    Hi @iomega55,

    I would recommend you to read this thread.
    http://forums.ext.net/showthread.php?18578
  3. #3

    Using a window popup for requesting credentials

    Thanks Daniil, I used the code from the post you recommended. (Thanks to Equiman)

    I made some small changes for having a winpopup requesting your credentials instead of redirecting to a login.aspx webform each time you have a timeout.

    Also in the original code, in my case, I needed to use Ext.getCmp('frmTimeOut') for getting the popup window, and use window.hide and window.show instead window.SetVisible.

    // URL Redirection
    var timeOutSession = function () {
        top.location.replace(GetNewPath('/KA.aspx'));
    };
    
    // Add this into Master Page (TabPanelContain):
    // <DocumentReady Handler="masterTimeOut();stopCount();" />
    var masterTimeOut = function () {
        //Convert minutes value indicated in TimeOut del Web.Config to seconds
        var min = 0;
        var sec = 0;
        var timer = null;
        var vis = false;
        var server = new Date().getTime() / 1000;
    
        doTimer = function () {
            var wnd = Ext.getCmp('frmTimeOut');
            // At least 1 min, show the countdown window
            if ((min - sec) < 60) {
    
                updateTime();
    
                if (wnd.hidden) {
                    vis = true;
                    wnd.show();
                }
            }
            else {
                if (!wnd.hidden) {
                    vis = false;
                    wnd.hide();
                }
            }
    
            // Check the countdown counter
            if ((min - sec) > 0) {
                sec++;
                // Repeat the process each minute
                timer = setTimeout('doTimer()', 1000);
            }
            else {
                // When countdown is finish, redirect to Login page
                //timeOutSession();
                var wnd = Ext.getCmp('frmTimeOut'); vis = false; wnd.hide();
                clearTimeout(timer);
                wnd = Ext.getCmp('wndL'); wnd.show();
            }
        };
    
        stopCount = function () {
             if (vis === true) {
                //2 seconds Idle (no detect events, because showing alert window is detected as mousemove)
                if ((min - sec) < 58) {
                    vis = false;
                }
            }
             else {
                // Convert minutes to second
                min = (document.getElementById('txtMinTimeOut').value * 60);
                sec = 0;
                clearTimeout(timer);
    
                // Get actual time
                keepaliveServer((new Date().getTime() / 1000));
                doTimer();
            }
        };
    
        keepaliveServer = function (time) {
            // Validating not saturation of the server with sending Keep Alive request
            if ((time - server) > (min - 10)) {
    
                var pageToCall = GetNewPath('/KA.aspx');
    
                var requestParms = new Sys.Net.WebRequest();
                requestParms.set_url(pageToCall);
                requestParms.set_httpVerb("POST");
                var message = "I'm keeping you alive!";
                requestParms.set_body(message);
                requestParms.get_headers()["Content-Length"] = message.length;
                requestParms.add_completed(doNothing);
                requestParms.invoke();
    
                // Set new actual time
                server = time;
            }
        };
        doNothing = function (executor, eventArgs) { };
    
        updateTime = function () {
            var message = 'Inactividad detectada. Tu sesi?n caducar? en';
            var time = (min - sec);
            var unity = 'segundos.';
            Ext.getCmp('lblText').setText(message + ' ' + time + ' ' + unity);
        };
    
        // Start counter on Load
        document.onload = function () {
            stopCount();
            //return false;
        };
        // Star counter when mouse move
        document.onmousemove = function () {
            stopCount();
            //return false;
        };
        // Star counter when key is pressed
        document.onkeypress = function () {
            stopCount();
            //return false;
        };
    
        // Read and event when is send from an iFrame
        function displayMessage(e) {
            if ((e.origin.split(":", 2)[0] + ":" + e.origin.split(":", 2)[1]) === (GetNewPath("/").split(":", 2)[0] + ":" + GetNewPath("/").split(":", 2)[1])) {
                // If the iFrame send any of this events start counter
                switch (e.data) {
                    case "onload":
                    case "onmousemove":
                    case "onkeypress":
                    case "simulated":
                        stopCount();
                }
            }
        };
    
        if (window.addEventListener) {
            // For standards-compliant web browsers
            window.addEventListener("message", displayMessage, false);
        }
        else {
            window.attachEvent("onmessage", displayMessage);
        };
    };
    
    
    // Add this into any iFrame Page:
    // <DocumentReady Handler="detailTimeOut();" />
    var detailTimeOut = function () {
        // Start counter on Load
        document.onload = function () {
            top.postMessage("onload", GetNewPath("/"));
            return false;
        };
        // Star counter when mouse move
        document.onmousemove = function () {
            top.postMessage("onmousemove", GetNewPath("/"));
            //return false;
        };
        // Star counter when key is pressed
        document.onkeypress = function () {
            top.postMessage("onkeypress", GetNewPath("/"));
            //return false;
        };
        // Simulated Event
        simulatedEvent = function () {
            top.postMessage("simulated", GetNewPath("/"));
            //return false;
        };
    };
    
    // Get the Path when use VirtualPath in .Net or IIS
    var GetNewPath = function (relative_path) {
        var url = window.location.href;
    
        if (url.substring(url.length - 1, url.length) == '/') {
            url = url.substring(0, url.length - 1);
        }
    
        var url_parts = url.split('/');
    
        if (relative_path.substring(0, 1) != '/') {
            url_parts[url_parts.length - 2] = relative_path;
            url_parts[url_parts.length - 1] = '';
        }
        else {
            url_parts[url_parts.length - 2] = relative_path.substring(1);
            url_parts[url_parts.length - 1] = '';
        }
    
        var new_page_absolute_path = url_parts.join('/');
    
        if (new_page_absolute_path.substring(new_page_absolute_path.length - 1, new_page_absolute_path.length) == '/') {
            new_page_absolute_path = new_page_absolute_path.substring(0, new_page_absolute_path.length - 1);
        }
        return new_page_absolute_path;
    };
    In the masterpage, the one used for the content pages:

       <form runat="server">
        <asp:ScriptManager ID="smDetail" EnableScriptLocalization="true" runat="server">
            <Scripts>
                <asp:ScriptReference Path="~/resources/js/timeout.js" />
            </Scripts>
        </asp:ScriptManager>
        <ext:ResourceManager ID="rsManager01" runat="server" Theme="Gray" IDMode="Static">
            <Listeners>
                <DocumentReady Handler="detailTimeOut();" />
            </Listeners>
        </ext:ResourceManager>
        <asp:ContentPlaceHolder ID="cpContent01" runat="server">
            
        </asp:ContentPlaceHolder>
        </form>
    In the parent webform, so where I have a the main viewport and tabpanel (as in the examples.ext.net). Just need a stopCount(); in the success handler of the window where you request the credentials. In the frmTimeOut window I removed the HideLabel="true" tag, and add the FocusOnToFront="false" property (in november of the last year Equiman added it).

    http://forums.ext.net/showthread.php...ible%28true%29

       <form runat="server">
        <asp:ScriptManager ID="smmaster" EnableScriptLocalization="true" runat="server">
            <Scripts>
                 <asp:ScriptReference Path="~/resources/js/timeout.js" />
            </Scripts>
        </asp:ScriptManager>
        <ext:ResourceManager ID="ResourceManager1" runat="server" >
            <Listeners>
                <DocumentReady Handler="masterTimeOut();stopCount();" />
            </Listeners>
        </ext:ResourceManager>
        <ext:Viewport runat="server" Layout="BorderLayout">
        .....
       </ext:Viewport>
    
    //This is the window for requesting again the credentials
     <ext:Window 
                ID="wndL" 
                runat="server" 
                Closable="false"
                Resizable="false"
                Height="150" 
                Icon="Lock" 
                Title="Tu Sesion Caduco. Reingresa al Portal"
                Draggable="false"
                Width="400" Hidden="true"        
                Modal="true"
                BodyPadding="5"
                Layout="FormLayout" DefaultButton="btnLogin">
                <Items>
                    <ext:TextField 
                        ID="txtUser" 
                        Name="txtUser"
                        runat="server"                     
                        FieldLabel="Usuario" 
                        AllowBlank="false"
                        BlankText="Usuario" />
                    <ext:TextField 
                        ID="txtPass" 
                        Name="txtPass"
                        runat="server" 
                        InputType="Password" 
                        FieldLabel="Password" 
                        AllowBlank="false" 
                        BlankText="Password" />
                </Items>
                <Buttons>
                    <ext:Button ID="btnLogin" runat="server" Text="Login" Icon="Accept" Cls="default">
                        <Listeners>
                            <Click Handler="
                                if (!#{txtUser}.validate() || !#{txtPass}.validate()) {
                                    Ext.Msg.alert('Error','Usuario y Password son requeridos');
                                    // return false to prevent the btnLoginW_Click Ajax Click event from firing.
                                    return false; 
                                }" />
                        </Listeners>
                        <DirectEvents>
                            <Click OnEvent="btnLClick" Success="stopCount();">
                                <EventMask ShowMask="true" Msg="Verificando..." MinDelay="500" />
                            </Click>
                        </DirectEvents>
                    </ext:Button>
                    <ext:Button runat="server" Text="Logout" Icon="Cancel" Cls="default">
                        <DirectEvents>
                            <Click OnEvent="btnLOClick">
                                <EventMask ShowMask="true" Msg="Desconectado..." MinDelay="500" />
                            </Click>
                        </DirectEvents>
                    </ext:Button>
                </Buttons>
            </ext:Window>
    //This is the window popup for timeout session reminder
          <ext:Window
                ID="frmTimeOut"
                runat="server"
                Width="350"
                Height="50"
                Modal="false"
                Resizable="False"
                Hidden="false"
                Closable="false"
                Layout="FormLayout" BodyStyle = "background-color: yellow;"
                Draggable="false" FocusOnToFront="false"
                Padding="12">
                <Items>
                    <ext:Label ID="lblText" runat="server" Text="" AutoWidth="true" />
                </Items>
            </ext:Window>
        </form>
    My final question is: Why do we need to use this scriptmanager, does it exist a solution using just ext.net code? Using the asp:scriptmanager is mandatory to have a form runat="server" tag even if you dont need it:

     <asp:ScriptManager ID="smmaster" EnableScriptLocalization="true" runat="server">
            <Scripts>
                 <asp:ScriptReference Path="~/resources/js/timeout.js" />
            </Scripts>
        </asp:ScriptManager>
    Last edited by iomega55; Nov 01, 2014 at 2:44 PM.
  4. #4
    I guess a ScriptManager should not be required.
  5. #5
    Script manager is no need ... just is another way to add script reference dynamically.

    You can use tradicional HTML
    <script src="../resources/js/timeout.js">
    But with this method you need to deal with paths. With Script Manager you don't need to deal with virtual directories (IIS).

    Dynamically Assigning Script References:
    http://msdn.microsoft.com/en-us/libr...v=vs.100).aspx
    Last edited by equiman; Nov 03, 2014 at 6:01 AM.
  6. #6
    Also you can use
    <ext:ResourceManager runat="server">
        <ResourceItems>
            <ext:ClientResourceItem Path="~/resources/js/timeout.js" />
        </ResourceItems>
    </ext:ResourceManager>
  7. #7
    Ext Resource Manager is fine, but if you are planing use Localization, is better Script Manager

    <asp:ScriptManager ID="ScriptManager1" EnableScriptLocalization="true" runat="server">
           <Scripts>
                 <asp:ScriptReference Path="../../Scripts/AllItemJS.js" ResourceUICultures="it-IT,fr-FR"  />
           </Scripts>
    </asp:ScriptManager>

Similar Threads

  1. Renew premium support or bundle
    By aguidali in forum Licensing
    Replies: 2
    Last Post: Sep 12, 2014, 6:23 AM
  2. [CLOSED] Best practices to Ext Resources Size
    By advBackOffice in forum 2.x Legacy Premium Help
    Replies: 6
    Last Post: Jan 24, 2013, 12:12 AM
  3. Tablelayout & colspan- best practices
    By springrider in forum 1.x Help
    Replies: 0
    Last Post: Aug 18, 2011, 10:35 PM
  4. Window management best practices
    By dbassett74 in forum 1.x Help
    Replies: 1
    Last Post: Apr 20, 2009, 8:24 PM
  5. Best Practices for WebService CRUD operations
    By pkellner in forum Open Discussions
    Replies: 1
    Last Post: Dec 22, 2008, 4:55 PM

Tags for this Thread

Posting Permissions