Navigation

Thursday 26 January 2017

How to stop session expiry by using ICallbackEventHandler Interface

I have done this by using following code. In this code I used one user control file and other one is JQuery(.js) file.

To use this functionality you have to drag and drop this UserControl page to your .aspx page. e.g. at default.aspx page or for whole project u have to drag and drop to Master page. I use master page. to call this session expire code.
Logic behind this code is that, we just use timer which will call popup when page is not use by user and we reset the timer when user perform any activation on page.


STEP 1: Create one .ascx file with any name in my case the name is "SessionExpired.ascx"


<%@ Control Language="C#" AutoEventWireup="true" CodeFile="SessionExpired.ascx.cs"
    Inherits="Control_SessionExpired" %>
<style>
    .ModalPopupBG
    {
        background-color: #666699;
        filter: alpha(opacity=50);
        opacity: 0.7;
    }
    .HellowWorldPopup
    {
        min-width: 200px;
        min-height: 150px;
        background: white;
        margin: == "20px";
    }
</style>

<script type="text/javascript">

    function clientReceiveServerData(returnValue) {

        fnTimeextendOrExpired();
        fnTimeextendOrExpiredOnUI();
    }

</script>

<input id="Button3" type="button" value="button" onclick="TimeextendOrExpired('SESSION');" />
<asp:HiddenField ID="hfTimeOut" runat="server" />
<asp:Button ID="Button1" runat="server" Text="Button" Style="display: none;" />
<cc1:ModalPopupExtender ID="ModalPopupExtender1" runat="server" CancelControlID="btnTimeExpired"
    OkControlID="btnTimeextend" BehaviorID="modalpopup" TargetControlID="Button1"
    PopupControlID="Panel1" PopupDragHandleControlID="PopupHeader" Drag="true" BackgroundCssClass="modalBackground">
</cc1:ModalPopupExtender>
<asp:Panel ID="Panel1" Style="display: none" runat="server">
    <div class="ui-widget-content ui-corner-all timeout-dialog">
        <span id="spSessionExpired" style="color: White; display: none;">The session is expired.</span>
        <div id="DivUI">
            <div class="ui-dialog-titlebar ui-widget-header ui-corner-all ui-helper-clearfix"
                style="width: 405px">
                <span class="ui-dialog-title" id="Span1">Your session is about to expire!</span><a
                    href="#" class="ui-dialog-titlebar-close ui-corner-all" role="button"><span class="ui-icon ui-icon-closethick">close</span></a></div>
            <div id="timeout-dialog" class="ui-dialog-content ui-widget-content" style="width: auto;
                min-height: 0px; height: auto;">
                <p id="timeout-message" style="margin-top: 15px;">
                    <span>Your session will be expired after <span id="timeout-countdown"></span> seconds,
                </p>
                <p id="timeout-question">
                    Do you want to stay signed in?</p>
            </div>
            <div class="ui-dialog-buttonpane ui-widget-content ui-helper-clearfix">
                <div class="ui-dialog-buttonset">
                    <button type="button" id="btnTimeextend" class="ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only"
                        role="button" onclick="SetTimeextend();">
                        <span class="ui-button-text">Yes, Keep me signed in</span></button>
                    <button type="button" id="btnTimeExpired" class="ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only"
                        role="button" onclick="SetTimeExpired();">
                        <span class="ui-button-text">No, Sign me out</span></button></div>
            </div>
        </div>
        <div id="DivSession">
            <div class="ui-dialog-titlebar ui-widget-header ui-corner-all ui-helper-clearfix"
                style="width: 405px">
                <span class="ui-dialog-title" id="Span2">Your session is about to expire!</span><a
                    href="#" class="ui-dialog-titlebar-close ui-corner-all" role="button"><span class="ui-icon ui-icon-closethick">close</span></a></div>
            <div id="timeout-dialog1" class="ui-dialog-content ui-widget-content" style="width: auto;
                min-height: 50px; height: auto;">
                <p id="timeout-message1" style="margin-left: 15%;margin-top: 15px;">
                    <span>Please save your changes.
                    <br/>Your session will be expired after <span id="timeout-countdown1"></span> seconds.
                </p>
            </div>
            <div class="ui-dialog-buttonpane ui-widget-content ui-helper-clearfix">
                <div class="ui-dialog-buttonset">
                    <button type="button" id="Button2"
                     class="ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only"
                     style="margin-left: 45%"
                        role="button" onclick="SetTimeextend();">
                        <span class="ui-button-text">OK</span></button>
                </div>
            </div>
        </div>
        <span style="clear: both;"></span>
    </div>
</asp:Panel>

<script type="text/javascript">
    var L = 120;
    var M = 30;
    function SetTime() {
        $("#timeout-countdown").html(L.toString());
        if (L > 0) {
            L--;
        }
        else if (L == 0 && isextend == false) {
            window.location.href = "../Default.aspx";
        }

    }
    function SetTime1() {
        $("#timeout-countdown1").html(M.toString());
        if (M > 0) {
            M--;
        }
        else if (M == 0 && isextend == false) {
            window.location.href = "../Default.aspx";
        }

    }
</script>

<script type="text/javascript">
    $(document).ready(function() {
        fnTimeextendOrExpired();
        fnTimeextendOrExpiredOnUI();
        $("input").keypress(function() {
            clearInterval(MyExpiredTimerUI);
            clearInterval(counter);
            clearInterval(counter1);
            fnTimeextendOrExpiredOnUI();
        });
        $('select').change(function() {
            clearInterval(MyExpiredTimerUI);
            clearInterval(counter);
            clearInterval(counter1);
            fnTimeextendOrExpiredOnUI();
        });

    });
    function fnTimeextendOrExpired() {
        var timeOut = $("input:hidden[id*='hfTimeOut']").val();
        MyExpiredTimer = setInterval("TimeextendOrExpired('SESSION')", (timeOut - 2) * 60 * 1000);
    }
    function fnTimeextendOrExpiredOnUI() {
        MyExpiredTimerUI = setInterval("TimeextendOrExpired('UI')", 33 * 1000);
    }
</script>


STEP 2: Past following code to SessionExpired.ascx.cs.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 Control_SessionExpired : System.Web.UI.UserControl, ICallbackEventHandler
{
 
    protected void Page_Load(object sender, EventArgs e)
    {
       

        // Set the client method "client_ReceiveServerData" to receive the value
        // from the server.
        string reference = Page.ClientScript.GetCallbackEventReference(this, "", "clientReceiveServerData", "");

        // Register a client method "CallServer" to request the server for async.
        string callbackScript = "function clientCallServer()" +
            "{" + reference + ";}";
        Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "clientCallServer", callbackScript, true);

        // Set the Session's timeout value to the client side. It will be assign to a HiddenField that
        // it will not affect user use.
        //hfTimeOut.Value = Session.Timeout.ToString();
 
        //we fixed the session time to 35 min
        hfTimeOut.Value = "40";
    }
    #region The Callbackhandler

    /// <summary>
    /// You do not need to get any value from the server side.
    /// </summary>
    /// <returns></returns>
    public string GetCallbackResult()
    {
        return string.Empty;
    }
    /// <summary>
    /// Do not add any code for you just need to interactive with the server.
    /// </summary>
    /// <param name="eventArgument"></param>
    public void RaiseCallbackEvent(string eventArgument)    {
     
    }
    #endregion

}


STEP 2: following is the code of SessionExpired.js file, cal this .js file to your aspx page along with user control file i.e name SessionExpired.ascx page.

var isextend = false;
var counter;
var counter1;
function TableHidden() {
    $find('modalpopup').hide();
}

function TableShow() {

    $find('modalpopup').show();
}

function SetTimeextend() {
    isextend = true;
    clientCallServer();
    TableHidden();
    clearInterval(counter);
    clearInterval(counter1);
    clearInterval(MyExpiredTimer);
    clearInterval(MyExpiredTimerUI);
    L = 120;
    M = 30;
}

function SetTimeExpired() {
    if (!isextend) {
        TableHidden();
        window.location.href = "../Default.aspx";
    }
}
function TimeextendOrExpired(id) {
    isextend = false;
    if (id == "SESSION") {      
        $("#DivSession").show();
        $("#DivUI").hide();
        counter1 = setInterval("SetTime1()", 1000);
    }
    else {
        counter = setInterval("SetTime()", 1000);
        $("#DivSession").hide();
        $("#DivUI").show();
    }
    TableShow();
    L = 120;
    M = 30;
}  




No comments:

Post a Comment