0
Digg me

Prevent Session Timeout in Asp.net [VB]

ASP.Net 2.0 [VB]

Inspired by this article from Code Project. [Thanks Ach1lles ]


I slightly modified few things to work for VB and VS2005 environment. The code works perfect and I’m very happy with it.First I created a Module file and created this function.
[sourcecode language="vb"]

Public Function KeepAlive() As String

        Dim int_MilliSecondsTimeOut As Integer = (HttpContext.Current.Session.Timeout * 60000) – 30000
        Dim sScript As New StringBuilder
        sScript.Append(“")

        KeepAlive = sScript.ToString
End Function

[/sourcecode]
All this code does is, build a simple javascript function and its called from server side.The works like this,- Gets the current session timeout duration.
- Subtract 30 seconds from it and assign it to MilliSecondsTimeOut variable
- Create a Reconnect() javascript function
- Create a global variable with max value 6
- Get current hour and Min [just for displaying the last refresh time]
- Verify whether count is less than max value (ie 6)
- If so, change the window status with Text
- Create a dummy image and set reconnect.aspx url as its source [this way a call is made to server and it wont session timeout]Create a timer using window.setInterval and assign the MilliSecondsTimeOut value.
[this way this function is called 30 seconds before session timeout]Tha max value (6) can be set to any number. If its 6 then this session timeout is avoided 5 times.

Default session timeout is 20min. 20 * 5 = 100 mins. Which is good for non-secure page.

Then

On the pages where I want to prevent Session Timeout I entered this line.

[sourcecode language="vb"]

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Try
'dont forget to add this line 
Page.ClientScript.RegisterClientScriptBlock(Me.GetType, "reconn key", KeepAlive())
 
 If Not Page.IsPostBack Then
 ---
 ---
 ---
 End If

Catch eX as Exception
 '----
End Try
End Sub

[/sourcecode]
Created reconnect.aspx in Visual Studio and deleted the .vb and .designer.vb files.This is the final version of reconnect.aspx
[sourcecode language="html"]

< %@ Page Language="vb" AutoEventWireup="false"%>
< %@ OutputCache Location="None" VaryByParam="None" %>
< !DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
http://www.w3.org/1999/xhtml" >

[/sourcecode]
Note : When you compile the project sometimes, VS2005 complains reconnect.aspx is not in right format.
So I EXCLUDED this file from my project. Now VS 2005 will compile without complaining and the logic will also work.- Happy Programming