Automatic Logout when session is timeout in vb.net:
To do this I am use a user control and use the user control in master page.
<%@ Control Language="VB" AutoEventWireup="false" CodeFile="AutoLogout.ascx.vb" Inherits="UserControl_AutoLogout" %>
<script type="text/javascript">
var timeRefresh;
var timeInterval;
var currentTime;
var expressTime;
expressTime = "<%=ExpressDate %>";
currentTime = "<%=LoginDate %>";
setCookie("express", expressTime);
timeRefresh = setInterval("Refresh()", 30000);
// Refresh this page to check session is expire or timeout.
function Refresh() {
var current = getCookie("express");
var date = current.split(" ")[0];
var time = current.split(" ")[1];
var scriptDate = new Date();
var year = scriptDate.getFullYear();
var month = scriptDate.getMonth() + 1;
var day = scriptDate.getDate();
var hour = scriptDate.getHours();
var min = scriptDate.getMinutes();
var second = scriptDate.getSeconds();
if (Date.UTC(year, month, day, hour, min, second) >=
Date.UTC(date.split("-")[0], date.split("-")[1], date.split("-")[2],
time.split(":")[0], time.split(":")[1], time.split(":")[2])) {
clearInterval(timeRefresh);
Redirect();
}
}
function Redirect() {
window.location.replace("index.aspx?info=1");
}
// Retrieve cookie by name.
function getCookie(name) {
var arg = name + "=";
var aLen = arg.length;
var cLen = document.cookie.length;
var i = 0;
while (i < cLen) {
var j = i + aLen;
if (document.cookie.substring(i, j) == arg) {
return getCookieVal(j);
}
i = document.cookie.indexOf(" ", i) + 1;
if (i == 0) break;
}
return;
}
function getCookieVal(offSet) {
var endStr = document.cookie.indexOf(";", offSet);
if (endStr == -1) {
endStr = document.cookie.length;
}
return unescape(document.cookie.substring(offSet, endStr));
}
// Assign values to cookie variable.
function setCookie(name, value) {
document.cookie = name + "=" + escape(value);
}
</script>
--------------------
VB Code:
Imports System.Globalization
Partial Public Class UserControl_AutoLogout
Inherits System.Web.UI.UserControl
Public LoginDate As String
Public ExpressDate As String
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
If HttpContext.Current.Session("uname") = Nothing Then
Response.Redirect("index.aspx?info=0")
End If
' '''Get user login time or last activity time.
Dim date0 As DateTime = DateTime.Now
LoginDate = date0.ToString("u", DateTimeFormatInfo.InvariantInfo).Replace("Z", "")
Dim sessionTimeout As Integer = Session.Timeout
Dim dateExpress As DateTime = date0.AddMinutes(sessionTimeout)
ExpressDate = dateExpress.ToString("u", DateTimeFormatInfo.InvariantInfo).Replace("Z", "")
End Sub
End Class
------------------
In master page add this:
<%@ Register src="~/UserControl/AutoLogout.ascx" tagname="AutoRedirect" tagprefix="uc1" %>
Add this in from tag:
<uc1:AutoRedirect ID="AutoRedirect1" runat="server" />
Set session timeout in web.config file:
<sessionState timeout="30"/>