prolong session time variable

Hi,

How can we prolong the session time for session variables? I've been using session variable to pass values from one page to another, we have created a web.config, sadly to no avail. (I've place the web.config in the same folder as the pages)

Thanks.

asp.net
                       if Session("USER_LOGGED_IN") = nothing then
                       Response.Redirect("../zzauthmas.aspx")
                       end if

web config


    <system.web>

        <!--

            The <sessionState" section is used to configure session state for the application.
            It supports four modes: "Off", "InProc", "StateServer", and "SqlServer".  The
            later two modes enable session state to be stored off the web server machine -
            allowing failure redundancy and web farm session state scenarios.

            <sessionState mode="InProc"
                          stateConnectionString="tcpip=127.0.0.1:42424"
                          sqlConnectionString="data source=127.0.0.1;trusted_connection=true"
                          cookieless="false"
                          timeout="120" />

EdwardPeterAsked:
Who is Participating?
 
softplusConnect With a Mentor Commented:
Hi Edward
Let me show you how I did it in a site of mine, maybe there are better ways (certainly) :), but it works for me.
- I use forms-authentication (you use Windows, though it shouldn't make much of a difference)
- I let the users specify that they can save their login infos and save it to a cookie (see my code above)
- If the cookie is available, asp.net will login the user automatically, but then I still need to restore the user settings, etc.
- In each form in the Page_Load Event I have:
        If Not Page.IsPostBack Then
            ' restore user settings
            Login_Confirm(Session, Response, Request)
        End If

- Login_Confirm is a public sub which I have similar to this:
   Public Sub Login_Confirm(ByRef p_session As SessionState.HttpSessionState, _
            ByRef p_response As HttpResponse, ByRef p_request As HttpRequest)
        ' check loged in user name, confirm with session variable
        Dim strName As String = HttpContext.Current.User.Identity.Name.ToString
        ' check to see if my session variable is filled, else I need to restore the session variables from the database
        If StrComp(p_session("username"), strName, CompareMethod.Text) <> 0 Then
            ' read login data ...
            Dim cn As New Odbc.OdbcConnection(OdbcConnectString)
            cn.Open()
            Dim cmd As New Odbc.OdbcCommand("SELECT * FROM user WHERE UserName=?", cn)
            cmd.Parameters.Add("UserName", strName)
            Dim dr As Odbc.OdbcDataReader = cmd.ExecuteReader(CommandBehavior.SingleRow)
            If dr.Read Then
                ' check if active?
                If dr("allowaccess") <> 1 Then ' the user has been blocked, log him out and let him clear it up with us
                    FormsAuthentication.SignOut()
                Else
                    ' fill interesting fields
                    p_session("online") = 1
                    p_session("username") = strName
                    p_session("userid") = dr("UserId")
.... load other variables here
                End If
            End If
            'close rest
            dr.Close()
            cn.Close()
        End If
    End Sub

- In the global.asax.vb, in Session_Start I have:
 Sub Session_Start(ByVal sender As Object, ByVal e As EventArgs)
        ' Fires when the session is started
        Session("username") = ""
.... reset session variables, etc.
End Sub

- In the global.asax.vb, in Session_End I have:
    Sub Session_End(ByVal sender As Object, ByVal e As EventArgs)
        ' Fires when the session ends
       ' save user settings, just the general stuff..
     If Session("username") <> "" Then
        Dim strSQL As String
        Dim cn As New Odbc.OdbcConnection(OdbcConnectString)
        cn.Open()
        strSQL = "UPDATE user SET Setting1=?, Setting2=? " ' <--your settings here
        strSQL &= " WHERE UserId=" & Session("userid")
        If cn.State = ConnectionState.Closed Then cn.Open()
        Dim cmd As New Odbc.OdbcCommand(strSQL, cn)
        cmd.Parameters.Add("Setting1", Session("Setting1"))
'... your settings here again
        Try
            cmd.ExecuteNonQuery()
        Catch ex As Exception
            ' ignore error ... too late anyhow :)
        End Try
        cn.Close()
    End Sub

So in the endeffect, if the user has his credentials in the cookie, he can access any page in the site directly. It will automatically log him in, restore his session-settings, save them when the session ends and there is no need to worry about timeouts. One problem could be if the server dies (service restarts, etc.) - it won't process the Session_End, so it won't save the session settings. I hope that this doesn't happen too often anyway :) but you can get around this problem by saving the settings to the database each time the session-settings change (depending on how often this is, of course).

I hope this helped :)

John
0
 
softplusCommented:
Hi EdwardPeter,
Just change the timeout-value to something higher, that should work. (or did you already try that? your web.config is closed, correct (missing the </system.web> tag)?)
John
0
 
EdwardPeterAuthor Commented:
the timeout value seeems to be 10-15 minutes.

how can we make it last 3 hours or more? are we on the correct path?

Thanks.

<?xml version="1.0" encoding="UTF-8" ?>
<configuration>
    <!--
         The <appSettings> section is used to configure application-specific configuration
         settings.  These can be fetched from within apps by calling the
         "ConfigurationSettings.AppSettings(key)" method:
         <appSettings>
            <add key="connectionstring" value="server=localhost;trusted_connection=true;database=pubs"/>
         </appSettings>
    -->
    <system.web>
        <!--
           The <sessionState" section is used to configure session state for the application.
            It supports four modes: "Off", "InProc", "StateServer", and "SqlServer".  The
            later two modes enable session state to be stored off the web server machine -
            allowing failure redundancy and web farm session state scenarios.
            <sessionState mode="InProc"
                          stateConnectionString="tcpip=127.0.0.1:42424"
                          sqlConnectionString="data source=127.0.0.1;trusted_connection=true"
                          cookieless="false"
                          timeout="120" />
       -->
        <!--
            The <customErrors> section enables configuration of what to do if/when an
            unhandled error occurs during the execution of a request.  Specifically, it
            enables developers to configure html error pages to be displayed in place of
            a error stack trace:
            <customErrors mode="RemoteOnly" defaultRedirect="GenericErrorPage.htm">
               <error statusCode="403" redirect="NoAccess.htm"/>
               <error statusCode="404" redirect="FileNotFound.htm"/>
            <customErrors>
        -->
        <!--
            The <authentication> section enables configuration of the security authentication
            mode used by ASP.NET to identify an incoming user.  It supports a "mode"
            attribute with four valid values: "Windows", "Forms", "Passport" and "None":
            The <forms> section is a sub-section of the <authentication> section,
            and supports configuring the authentication values used when Forms
            authentication is enabled above:
            <authentication mode="Windows">
                    <forms name=".ASPXAUTH"
                           loginUrl="login.aspx"
                           protection="Validation"
                           timeout="999999" />
             </authentication>
        -->
        <!--
            The <authorization> section enables developers/administrators to configure
            whether a user or role has access to a particular page or resource.  This is
            accomplished by adding "<allow>" and "<deny>" sub-tags beneath the <authorization>
            section - specifically detailing the users/roles allowed or denied access.
            Note: The "?" character indicates "anonymous" users (ie: non authenticated users).
            The "*" character indicates "all" users.
            <authorization>
               <allow users="joeuser" />
               <allow roles="Admins" />
               <deny users="*" />
            </authorization>
        -->
    </system.web>
</configuration>
0
Never miss a deadline with monday.com

The revolutionary project management tool is here!   Plan visually with a single glance and make sure your projects get done.

 
kamalgupta29Commented:
session timeout value in web.conifg is in seconds.If you have set this value as 120 secs then it will prolong for 2 mins only. So decide the value for the time you require.
Also you need not to change the path of web.config file.IOt is automaticallty created when you create an ASP.NET project.

0
 
softplusCommented:
Hmm, 3 hours is a long time for a timeout (default is 20 minutes, if I remember correctly).

I would go a different route in that case - have the pages refresh themselves, i.e. add a meta-tag on top to refresh after ca. 15 minutes. You can do this by just replaceing your <body> tag with this:

<body onLoad="doRefresh();">

and placing the following javascript in your <HEAD> section:

<script>
function doRefresh()
{
     timeOut = setInterval("window.location.reload()", 15 * 60000);
}
</script>

This will refresh your page every 15 minutes, thereby keeping the IIS session limits. You could of course increase this time matching your timeout in the config file.

John
0
 
raterusCommented:
I'd be wary of setting up any and every asp.net page to refresh.  How asp.net pages postback, there is a good chance the page they are looking at has already been postbacked.  Say they just added some data to your DB, and they minimize the browser on the "Data Added Successfully Page", if you don't specifically code for the possibility of a refresh, the page may be adding data every 15 minutes if the user keeps his browser open.  Not a good thing...

0
 
EdwardPeterAuthor Commented:
raterus,

This is weird, we've set the timeout to 7200.

every 15 mintues it the session expires, is there anything we can do ?

Thanks.
0
 
raterusConnect With a Mentor Commented:
One thing I see from your first example that may be messing you up,

If Session("USER_LOGGED_IN") = nothing Then

You don't test object existance like this, it should be like this

If Session("USER_LOGGED_IN") Is Nothing Then
0
 
softplusCommented:
If you save the login in a cookie, this shouldn't be a problem - it would authenticate automatically the next time the user clicks somewhere on the website, after an hour or after a day. You could easily add this logic to your login.aspx page (as is in most samples). I use something like this in my RedirectFromLoginPageEx:

        ' set cookie
        If persistentCookie And ExpirationDays > 0 Then
            ' get ref to cookie, edit
            Dim cookie As HttpCookie = _
                Response.Cookies(FormsAuthentication.FormsCookieName)
            ' set expiration
            cookie.Expires = Now.AddDays(ExpirationDays)
        End If

If you need session variables, you could save these to a database when the session ends and restore them when you log in.
John
0
 
EdwardPeterAuthor Commented:
John,

I'm kinda lost, I've been using session variable to pass data from one page to another. (around 10 variables)

I thought the web.config took care of this issue? sadly i'm using www.asp.net webmatrix software tool to create pages.

I manually created the we.config, seems it's not working...my apology for the confusion.

Thanks.

0
All Courses

From novice to tech pro — start learning today.