Question : Detect Session State TimeOut

Dear Experts,

I have a aspx web application that requires to run more than 8 hours without refresh or logout.  Please no links but I would like to know some VB.NET code  or JavaScript Session timeout warning popup script  that says: “There has been no activity for some time. Click 'OK' if you wish to continue your session, or click 'Cancel' to log out. For your security if you are unable to respond to this message within 2 minutes you will be logged out automatically” and redirects to  login.aspx after timeout expires .

I have been doing this for 2 days without any success, also I would like you could see my code below:  web.config, global.asax, login.vb for your review and your help is really much appreciative.  Thanks.

WEB.CONFIG

<?xml version="1.0" encoding="UTF-8"?>
<!--
    Note: As an alternative to hand editing this file you can use the
    web admin tool to configure settings for your application. Use
    the Website->Asp.Net Configuration option in Visual Studio.
    A full list of settings and comments can be found in
    machine.config.comments usually located in
    \Windows\Microsoft.Net\Framework\v2.x\Config
-->
<configuration>
      <configSections>
            <sectionGroup name="system.web.extensions" type="System.Web.Configuration.SystemWebExtensionsSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
                  <sectionGroup name="scripting" type="System.Web.Configuration.ScriptingSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
                        <section name="scriptResourceHandler" type="System.Web.Configuration.ScriptingScriptResourceHandlerSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication" />
                        <sectionGroup name="webServices" type="System.Web.Configuration.ScriptingWebServicesSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
                              <section name="jsonSerialization" type="System.Web.Configuration.ScriptingJsonSerializationSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="Everywhere" />
                              <section name="profileService" type="System.Web.Configuration.ScriptingProfileServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication" />
                              <section name="authenticationService" type="System.Web.Configuration.ScriptingAuthenticationServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication" />
                              <section name="roleService" type="System.Web.Configuration.ScriptingRoleServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication" />
                        </sectionGroup>
                  </sectionGroup>
            </sectionGroup>
      </configSections>
      <!--<appSettings/>
    <connectionStrings/>-->
      <system.web>
            <!--<customErrors mode="Off"/>-->
            <!--
            Set compilation debug="true" to insert debugging
            symbols into the compiled page. Because this
            affects performance, set this value to true only
            during development.

            Visual Basic options:
            Set strict="true" to disallow all data type conversions
            where data loss can occur.
            Set explicit="true" to force declaration of all variables.
        -->
            <compilation batchTimeout="43200" debug="true" defaultLanguage="VB" explicit="true" numRecompilesBeforeAppRestart="15" strict="false">
     
                  <assemblies>
                        <add assembly="System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089" />
                        <add assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
                        <add assembly="System.Data.DataSetExtensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089" />
                        <add assembly="System.Web.Extensions.Design, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
                        <add assembly="System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A" />
                        <add assembly="System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089" />
                        <add assembly="System.Drawing.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A" />
                        <add assembly="Microsoft.Office.Interop.Excel, Version=11.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" />
                  
                        <add assembly="System.Xml, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
                        <add assembly="System.DirectoryServices, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A" />
                        <add assembly="System.DirectoryServices.Protocols, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A" />
                        
                        <add assembly="System.ServiceProcess, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A" />
                        
                        <add assembly="System.Web.RegularExpressions, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A" />
                        <add assembly="Office, Version=11.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" />
                        <add assembly="Accessibility, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A" />
                        <add assembly="CrystalDecisions.CrystalReports.Engine, Version=10.5.3700.0, Culture=neutral, PublicKeyToken=692fbea5521e1304" />
                        <add assembly="CrystalDecisions.Enterprise.Framework, Version=10.5.3700.0, Culture=neutral, PublicKeyToken=692fbea5521e1304" />
                        <add assembly="CrystalDecisions.ReportAppServer.ClientDoc, Version=10.5.3700.0, Culture=neutral, PublicKeyToken=692fbea5521e1304" />
                        <add assembly="CrystalDecisions.Shared, Version=10.5.3700.0, Culture=neutral, PublicKeyToken=692fbea5521e1304" />
                        <add assembly="CrystalDecisions.Enterprise.InfoStore, Version=10.5.3700.0, Culture=neutral, PublicKeyToken=692fbea5521e1304" />
                        <add assembly="CrystalDecisions.Web, Version=10.5.3700.0, Culture=neutral, PublicKeyToken=692fbea5521e1304" />
                        <add assembly="CrystalDecisions.ReportSource, Version=10.5.3700.0, Culture=neutral, PublicKeyToken=692fbea5521e1304" />
                        <add assembly="Microsoft.Office.Tools.Excel.v9.0, Version=9.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A" /></assemblies>
            </compilation>
            <pages>
                  <namespaces>
                        <clear />
                        <add namespace="System" />
                        <add namespace="System.Collections" />
                        <add namespace="System.Collections.Generic" />
                        <add namespace="System.Collections.Specialized" />
                        <add namespace="System.Configuration" />
                        <add namespace="System.Text" />
                        <add namespace="System.Text.RegularExpressions" />
                        <add namespace="System.Linq" />
                        <add namespace="System.Xml.Linq" />
        <add namespace="System.Xml" />
                        <add namespace="System.Web" />
                        <add namespace="System.Web.Caching" />
                        <add namespace="System.Web.SessionState" />
                        <add namespace="System.Web.Security" />
                        <add namespace="System.Web.Profile" />
                        <add namespace="System.Web.UI" />
                        <add namespace="System.Web.UI.WebControls" />
                        <add namespace="System.Web.UI.WebControls.WebParts" />
                        <add namespace="System.Web.UI.HtmlControls" />
                        <add namespace="System.DirectoryServices" />
                                          </namespaces>
                  <controls>
                        <add tagPrefix="asp" namespace="System.Web.UI" assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
                        <add tagPrefix="asp" namespace="System.Web.UI.WebControls" assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
                        <add namespace="AjaxControlToolkit" assembly="AjaxControlToolkit" tagPrefix="ajaxToolkit" />
                  </controls>
            </pages>
            <!--
            The <authentication> section enables configuration
            of the security authentication mode used by
            ASP.NET to identify an incoming user. timeout="480"
        -->
            <roleManager enabled="true"></roleManager>
            <authentication mode="Forms">
     
                  <forms loginUrl="login.aspx" timeout="540" name=".authCookie" protection="All" path="/" slidingExpiration="true" cookieless="UseCookies" />

    </authentication>

    <sessionState timeout="540"  />

    <authorization>
                  <allow users="*" />
                  <deny users="?" />
                  <!-- necessary with forms authentication to force redirect to login page -->
                  <!--  <allow users="[comma separated list of users]"/>
             <allow roles="[comma separated list of roles]"/>
             <deny users="[comma separated list of users]"/>
             <deny roles="[comma separated list of roles]"/> -->
            </authorization>
            
            <customErrors mode="RemoteOnly" defaultRedirect="GenericErrorPage.htm">
                  <error statusCode="403" redirect="NoAccess.htm" />
                  <error statusCode="404" redirect="FileNotFound.htm" />
            </customErrors>
            <httpHandlers>
                  <remove verb="*" path="*.asmx" />
                  <add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
                  <add verb="*" path="*_AppService.axd" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
                  <add verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" validate="false" />
            </httpHandlers>
            <httpModules>
                  <add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
            </httpModules>
            <siteMap defaultProvider="MyXmlSiteMapProvider" enabled="true">
                  <providers>
                        <add name="MyXmlSiteMapProvider" description="SiteMap provider that reads in .sitemap files." type="System.Web.XmlSiteMapProvider, System.Web, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" siteMapFile="Web.sitemap" />
                  </providers>
            </siteMap>
      </system.web>
      <system.codedom>
            <compilers>
                  <compiler language="c#;cs;csharp" extension=".cs" warningLevel="4" type="Microsoft.CSharp.CSharpCodeProvider, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
                        <providerOption name="CompilerVersion" value="v3.5" />
                        <providerOption name="WarnAsError" value="false" />
                  </compiler>
                  <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" warningLevel="4" type="Microsoft.VisualBasic.VBCodeProvider, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
                        <providerOption name="CompilerVersion" value="v3.5" />
                        <providerOption name="OptionInfer" value="true" />
                        <providerOption name="WarnAsError" value="false" />
                  </compiler>
            </compilers>
      </system.codedom>
      <!--
        The system.webServer section is required for running ASP.NET AJAX under Internet
        Information Services 7.0.  It is not necessary for previous version of IIS.
    -->
      <system.webServer>
            <validation validateIntegratedModeConfiguration="false" />
            <modules>
                  <remove name="ScriptModule" />
                  <add name="ScriptModule" preCondition="managedHandler" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
            </modules>
            <handlers>
                  <remove name="WebServiceHandlerFactory-Integrated" />
                  <remove name="ScriptHandlerFactory" />
                  <remove name="ScriptHandlerFactoryAppServices" />
                  <remove name="ScriptResource" />
                  <add name="ScriptHandlerFactory" verb="*" path="*.asmx" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
                  <add name="ScriptHandlerFactoryAppServices" verb="*" path="*_AppService.axd" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
                  <add name="ScriptResource" preCondition="integratedMode" verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
            </handlers>
      </system.webServer>
      <runtime>
            <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
                  <dependentAssembly>
                        <assemblyIdentity name="System.Web.Extensions" publicKeyToken="31bf3856ad364e35" />
                        <bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="3.5.0.0" />
                  </dependentAssembly>
                  <dependentAssembly>
                        <assemblyIdentity name="System.Web.Extensions.Design" publicKeyToken="31bf3856ad364e35" />
                        <bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="3.5.0.0" />
                  </dependentAssembly>
            </assemblyBinding>
      </runtime>
      <location allowOverride="true">
            <appSettings>
      <add key="ConnectionString" value="server=AVC;database=NNN;uid=User;pwd=user" />

<add key="ActiveDirectoryConn" value="LDAP://DC=cool,DC=net" />
            </appSettings>
      </location>
      <connectionStrings>
  <add name="ConnectionString" value="server=AVC;database=NNN;uid=User;pwd=user" />

</connectionStrings>
</configuration>






LOGIN.VB

Protected Sub btnLogin_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnLogin.Click

       

        Dim adPath As String = "LDAP://DC=cool,DC=net"
        Dim adAuth As New SITE.LDAPAuthentication(adPath)
        Try
            If True = adAuth.IsAuthenticated(txtDomain.Text, txtusername.Text, txtPassword.Text) Then

                'get user roles
                Dim groups As String = adAuth.GetGroups()

                'Create the ticket, and add the groups.
                Dim isCookiePersistent As Boolean = chkPersist.Checked
                Dim authTicket As New FormsAuthenticationTicket(1, txtUsername.Text, DateTime.Now, DateTime.Now.AddHours(12), isCookiePersistent, groups)

                'Encrypt the ticket.
                Dim encryptedTicket As String = FormsAuthentication.Encrypt(authTicket)

                'Create a cookie, and then add the encrypted ticket to the cookie as data.
                Dim authCookie As New HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket)

                'If ChkPersist is Checked 'in order for browser to write the cookie expiration time has to be set
                'do not confuse FormsAuthenticationTicket.Expire with cookie's expire time
                If True = isCookiePersistent Then
                    authCookie.Expires = authTicket.Expiration
                End If

                'Add the cookie to the outgoing cookies collection.
                HttpContext.Current.Response.Cookies.Add(authCookie)


                'You can redirect now.
                'Response.Redirect(FormsAuthentication.GetRedirectUrl(txtUsername.Text, False))
                Response.Redirect(FormsAuthentication.GetRedirectUrl(txtUsername.Text, chkPersist.Checked))
                'Response.Redirect("default.aspx")
            Else
                errorLabel.Text = "Authentication did not succeed. Check user name and password. Make sure your Caps Lock on your keyboard is off."
            End If
        Catch ex As Exception
            errorLabel.Text = "Error authenticating. " + ex.Message
        End Try


       
    End Sub



GLOBAL.ASAX

<%@ Application Language="VB" %>



<script runat="server">

   
    Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs)
        ' Code that runs on application startup
    End Sub
   
    Sub Application_End(ByVal sender As Object, ByVal e As EventArgs)
        ' Code that runs on application shutdown
    End Sub
       
    Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)
        ' Code that runs when an unhandled error occurs
    End Sub

    Sub Session_Start(ByVal sender As Object, ByVal e As EventArgs)
        ' Code that runs when a new session is started
       ‘ Session.Timeout = 1
    End Sub

    Sub Session_End(ByVal sender As Object, ByVal e As EventArgs)
       
    End Sub
   
    Sub Application_BeginRequest(ByVal sender As Object, ByVal e As EventArgs)
        ' Fires at the beginning of each request
    End Sub

    Sub Application_AuthenticateRequest(ByVal sender As Object, ByVal e As EventArgs)
        ' Fires upon attempting to authenticate the use

        Dim cookieName As String = FormsAuthentication.FormsCookieName
        Dim authCookie As HttpCookie = Context.Request.Cookies(cookieName)

       
       
        If authCookie Is Nothing Then
            'There is no authentication/authorization cookie.
            Return
        End If
       
        Dim authTicket As FormsAuthenticationTicket = Nothing
        Try
            authTicket = FormsAuthentication.Decrypt(authCookie.Value)
        Catch ex As Exception
            Throw New Exception(ex.Message)
            'Write the exception to the Event Log.
            '            Return
        End Try
       
       
        If Not (authTicket.IsPersistent) Then
            If (authTicket.Expired) Then
                'Cookie failed to decrypt.
                Return
            End If
        End If
       
               
       
       
        'When the ticket was created, the UserData property was assigned a
        'pipe-delimited string of group names.
        Dim groups As String() = authTicket.UserData.Split(New Char() {"|"c})
        'Create an Identity.
        Dim id As New System.Security.Principal.GenericIdentity(authTicket.Name, "LDAPAuthentication")
       
        'This principal flows throughout the request.
        Dim principal As New System.Security.Principal.GenericPrincipal(id, groups)
       
        'attach the new principal object to the current HttpContext object
        Context.User = principal

       
               
    End Sub
   
</script>


LDAPAuthentication.VB

Imports System
Imports Microsoft.VisualBasic
Imports System.DirectoryServices
Imports System.Exception


Namespace SITE

    Public Class LDAPAuthentication
        Private _path As String
        Private _filterAttribute As String

        Public Sub New(ByVal path As String)
            _path = path
        End Sub

        Public Function IsAuthenticated(ByVal domain As String, ByVal username As String, ByVal pwd As String) As Boolean

            Dim domainAndUsername As String = domain + "\" + username
            Dim entry As New DirectoryEntry(_path, domainAndUsername, pwd)

            Try
                'Bind to the native AdsObject to force authentication.
                Dim obj As Object = entry.NativeObject

                Dim search As New DirectorySearcher(entry)

                search.SearchScope = SearchScope.Subtree
                search.Filter = "(CN=" + username + ")"

                'sAMAccountName = name.  Old NT 4.0 logon name, must be unique in the domain.  Can be confused with CN.
                search.Filter = "(SAMAccountName=" + username + ")"
                search.PropertiesToLoad.Add("cn")
                Dim result As SearchResult = search.FindOne()

                If result Is Nothing Then
                    Return False
                End If

                'Update the new path to the user in the directory.
                _path = result.Path
                _filterAttribute = DirectCast(result.Properties("cn")(0), String)
            Catch ex As System.Exception
                Throw New System.Exception("Error authenticating user. " + ex.Message)
            End Try

            Return True
        End Function

        Public Function GetGroups() As String

            Dim search As New DirectorySearcher(_path)
            search.Filter = "(cn=" & _filterAttribute & ")"
            search.PropertiesToLoad.Add("memberOf")

            'search.PropertiesToLoad.Add("sAMAccountname")


            Dim groupNames As New System.Text.StringBuilder()

            Try
                Dim result As SearchResult = search.FindOne()
                Dim propertyCount As Integer = result.Properties("memberOf").Count
                Dim dn As String
                Dim equalsIndex As Integer, commaIndex As Integer

                Dim propertyCounter As Integer = 0
                While propertyCounter < propertyCount
                    dn = DirectCast(result.Properties("memberOf")(propertyCounter), String)
                    equalsIndex = dn.IndexOf("=", 1)
                    commaIndex = dn.IndexOf(",", 1)
                    If -1 = equalsIndex Then
                        Return Nothing
                    End If
                    groupNames.Append(dn.Substring((equalsIndex + 1), (commaIndex - equalsIndex) - 1))
                    groupNames.Append("|")
                    System.Math.Max(System.Threading.Interlocked.Increment(propertyCounter), propertyCounter - 1)
                End While
            Catch ex As Exception
                Throw New System.Exception("Error obtaining group names. " + ex.Message)
            End Try
            Return groupNames.ToString()
        End Function
    End Class
End Namespace

Answer : Detect Session State TimeOut

Why don't you just change your SessionState mode to "StateServer".  You might be having an issue with application pool recycling and in InProc if that happens, both session state and asp.net worker process are recycled.  In SessionState, session thread and asp.net worker thread are separated and if it recycles, it only affects the worker thread.  Anyway, check the link below.

<sessionState mode="StateServer" stateConnectionString="tcpip=127.0.0.1:42424" sqlConnectionString="data source=127.0.0.1;user id=sa;password=" cookieless="false" timeout="750" cookieName ="ASP.NET_SessionId" regenerateExpiredSessionId ="true"/>  

http://msdn.microsoft.com/en-us/library/ms178586.aspx

Don't forget to activate ASP.NET State Service.

You can execute it in a VS2008 command prompt with this command

net start aspnet_state

Random Solutions  
 
programming4us programming4us