Thursday 16 March 2017

Show Alert before session expire in asp.net web application using c#.


<style type="text/css">
        .modalBackground {
            background-color: Black;
            filter: alpha(opacity=60);
            opacity: 0.6;
        }

        .modalPopup {
            background-color: #FFFFFF;
            width: 300px;
            border: 3px solid #006990;
            border-radius: 12px;
            padding: 0;
        }

            .modalPopup .header {
                background-color: #006990;
                height: 30px;
                color: White;
                line-height: 30px;
                text-align: center;
                font-weight: bold;
                border-top-left-radius: 6px;
                border-top-right-radius: 6px;
            }

            .modalPopup .body {
                padding: 10px;
                min-height: 50px;
                text-align: center;
                font-weight: bold;
            }

            .modalPopup .btnSection {
                padding: 6px;
            }

            .modalPopup .yes, .modalPopup .no {
                height: 23px;
                color: White;
                line-height: 23px;
                text-align: center;
                font-weight: bold;
                cursor: pointer;
                border-radius: 4px;
            }

            .modalPopup .yes {
                background-color: #006990;
                border: 1px solid #006990;
            }

            .modalPopup .no {
                background-color: #9F9F9F;
                border: 1px solid #5C5C5C;
            }
    </style>

 <asp:LinkButton ID="lnkFake" runat="server" />
                        <asp:ModalPopupExtender ID="mpeTimeout" BehaviorID="mpeTimeout" runat="server" PopupControlID="pnlPopup"
                            TargetControlID="lnkFake" OkControlID="btnYes" CancelControlID="btnNo" BackgroundCssClass="modalBackground"
                            OnOkScript="ResetSession()">
                        </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 />
                                Do you want to reset?
                            </div>
                            <div class="btnSection" align="right">
                                <asp:Button ID="btnYes" runat="server" Text="OK" CssClass="yes" />
                               <%-- <asp:Button ID="btnNo" runat="server" Text="No" CssClass="no" />--%>
                            </div>
                        </asp:Panel>
                        <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 - 60 * 1000);
                                setTimeout(function () {
                                    //alert(" Your Session has expired.");
                                    window.location = window.location.href;
                                   // window.location = "Expired.aspx";
                                }, timeout);
                            };
                            function ResetSession() {
                                //Redirect to refresh Session.
                                //window.location = window.location.href;
                                $.ajax({
                                    type: "POST",
                                    contentType: "application/json; charset=utf-8",
                                    url: '<%=ResolveUrl("~/area/login.aspx/ResetSession") %>',
                                    dataType: "json",
                                    success: function (data) {
                                        SessionExpireAlert(data.d);
                                    },
                                    error: function (result) {
                                        alert("Error");
                                    }
                                });
                            }
                        </script>

 protected void Page_Load(object sender, EventArgs e)
    {
 Response.Cache.SetCacheability(HttpCacheability.NoCache);
                if (!Page.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;
                    ScriptManager.RegisterStartupScript(this, typeof(string), "SessionAlert", "SessionExpireAlert(" + timeout + ");", true);
                }
}

Use of Web Method to avoid reload page and maintain  page data

[WebMethod]
    public static string ResetSession()
    {
        int TimeOut = 0;
        try
        {
            HttpContext.Current.Session["Reset"] = true;
            Configuration config = WebConfigurationManager.OpenWebConfiguration("~/Web.Config");
            SessionStateSection section = (SessionStateSection)config.GetSection("system.web/sessionState");
            TimeOut = (int)section.Timeout.TotalMinutes * 1000 * 60;
            //ScriptManager.RegisterStartupScript(this, typeof(string), "SessionAlert", "SessionExpireAlert(" + timeout + ");", true);
        }
        catch (Exception ex)
        {

        }
        return TimeOut.ToString();
    }


IN WEB CONFIG-

 <sessionState timeout="2"/>

Sql query to convert rows into column using Piovt or CTE.



create table #companyvalues
(
companyid           varchar(5),
paramkey            varchar(30),
paramvalue          integer
);

INSERT #companyvalues ([CompanyId], [ParamKey], [ParamValue]) VALUES (N'ABC', N'MinLength', 8)
INSERT #companyvalues ([CompanyId], [ParamKey], [ParamValue]) VALUES (N'ABC', N'MaxLength', 0)
INSERT #companyvalues ([CompanyId], [ParamKey], [ParamValue]) VALUES (N'ABC', N'IsAlphanumeric', 1)
INSERT #companyvalues ([CompanyId], [ParamKey], [ParamValue]) VALUES (N'ABC', N'IsCaseSensitive', 0)
INSERT #companyvalues ([CompanyId], [ParamKey], [ParamValue]) VALUES (N'ABC', N'IsSpecialChars', 0)
INSERT #companyvalues ([CompanyId], [ParamKey], [ParamValue]) VALUES (N'ABC', N'PasswordExpiryDays', 80)
INSERT #companyvalues ([CompanyId], [ParamKey], [ParamValue]) VALUES (N'ABC', N'AlertDays', 10)
INSERT #companyvalues ([CompanyId], [ParamKey], [ParamValue]) VALUES (N'XYZ', N'MinLength', 7)
INSERT #companyvalues ([CompanyId], [ParamKey], [ParamValue]) VALUES (N'XYZ', N'MaxLength', 1)
INSERT #companyvalues ([CompanyId], [ParamKey], [ParamValue]) VALUES (N'XYZ', N'IsAlphanumeric', 3)
INSERT #companyvalues ([CompanyId], [ParamKey], [ParamValue]) VALUES (N'XYZ', N'IsCaseSensitive', 1)
INSERT #companyvalues ([CompanyId], [ParamKey], [ParamValue]) VALUES (N'XYZ', N'IsSpecialChars', 1)
INSERT #companyvalues ([CompanyId], [ParamKey], [ParamValue]) VALUES (N'XYZ', N'PasswordExpiryDays', 90)
INSERT #companyvalues ([CompanyId], [ParamKey], [ParamValue]) VALUES (N'XYZ', N'AlertDays', 5)


;with companynames as
(
select distinct companyid compid
from #companyvalues
) ,
details as
(
select * from #companyvalues
)
select compid, max(MinLength) MinLength, max(MaxLength) MaxLength, max(IsAlphanumeric) IsAlphanumeric,
max(IsCaseSensitive) IsCaseSensitive, max(IsSpecialChars) IsSpecialChars, max(PasswordExpiryDays) PasswordExpiryDays,
max(AlertDays) AlertDays
from
(
select compid
, case when  paramkey = 'MinLength'          then paramvalue else -1 end  MinLength        
, case when  paramkey = 'MaxLength'          then paramvalue else -1 end  MaxLength        
, case when  paramkey = 'IsAlphanumeric'     then paramvalue else -1 end  IsAlphanumeric  
, case when  paramkey = 'IsCaseSensitive'    then paramvalue else -1 end  IsCaseSensitive  
, case when  paramkey = 'IsSpecialChars'     then paramvalue else -1 end  IsSpecialChars  
, case when  paramkey = 'PasswordExpiryDays' then paramvalue else -1 end  PasswordExpiryDays
, case when  paramkey = 'AlertDays'          then paramvalue else -1 end  AlertDays        
from companynames, details
where compid = companyid
) finalresult
group by compid
order by 1



select * from
(
select companyid,paramkey,paramvalue from #companyvalues
 )X
 PIVOT
 (
 MAX(paramvalue)
  FOR paramkey IN ([MinLength], [MaxLength],  [IsAlphanumeric],     [IsCaseSensitive],    [IsSpecialChars],  [PasswordExpiryDays],[AlertDays])  
 )Y