Session variables timing out too soon in ASP 2.0

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • emajka21
    New Member
    • May 2007
    • 38

    Session variables timing out too soon in ASP 2.0

    I created a website in ASP 2.0/c# that connects to an Access 2000 database. Currently I have 4 pages that people can view without logging in, which are reports that post marathon race results. Only one maybe two people will actually ever have to log in to enter the race data.

    For the login I created a form that asks for user name and password. Then I do a sql query to see if that matches the information in the database. If it does it grabs their role which would be admin.

    Here is my code for this:
    [code=cpp]
    protected void Button1_Click(o bject sender, EventArgs e)
    {
    if (txtUser.Text != "" && txtPassword.Tex t != "")
    {
    OleDbConnection conn = new OleDbConnection ("Provider=Micr osoft.Jet.OLEDB .4.0;data source=" + Server.MapPath( "~/App_Data/pfrpc.mdb"));
    OleDbCommand cmd = new OleDbCommand("s elect RunnerID, Role from Runner WHERE UserName = @UserName and Pass = @Password", conn);

    cmd.Parameters. Add("@UserName" , OleDbType.VarCh ar, 50);
    cmd.Parameters["@UserName"].Value = txtUser.Text;
    cmd.Parameters. Add("@Password" , OleDbType.VarCh ar, 50);
    cmd.Parameters["@Password"].Value = txtPassword.Tex t;

    conn.Open();

    OleDbDataReader reader = cmd.ExecuteRead er();
    string test = "";
    if (reader.Read())
    {
    Session["userRole"] = reader["Role"];
    Session["RunnerID"] = reader["RunnerID"];

    test = Session["userRole"] + "";


    if (test == "admin")
    {
    Response.Redire ct("RaceTimes.a spx");
    }

    }
    else
    {
    lblError.Text = "Invalid Login";
    }
    reader.Close();
    conn.Close();

    }
    else
    {
    lblError.Text = "You must fill in both the username and password fields";
    }

    }
    [/code]
    Once the session variable is equal to admin the other pages become available. By default in all of the admin pages the controls are not visible and if the session variable is equal to admin it will make the items visable. Here is a sample of one of the pages:
    [code=cpp]
    string test = Session["UserRole"] + "";

    //verifies if user logged in

    if (test == "admin")
    {
    txtMinutes.Visi ble = true;
    txtSeconds.Visi ble = true;
    txtYear.Visible = true;
    ddlBibNum.Visib le = true;
    ddlRace.Visible = true;
    lblBibNum.Visib le = true;
    lblMinutes.Visi ble = true;
    lblSeconds.Visi ble = true;
    lblYear.Visible = true;
    lblRaceNum.Visi ble = true;
    btnSave.Visible = true;

    }
    else
    {
    lblError.Text = "You must login to have access to this page!";
    }
    [/code]
    Anyways this works on my pc through development but after I put these files on a server (which is on a free hosting server that I am using for testing) it times out really fast. After about 30 seconds to a minute my session loses that it is an admin and the pages tell me that I am not an admin anymore. Any thoughts on this? Are session variables the best way to go in this case? Hopefully I provided enough code for you to have an understanding of what I am trying to do. Any help would be much appreciated!

    Thanks!
    Last edited by Frinavale; Aug 7 '07, 01:50 PM. Reason: Added [code] tags to make more legible
  • TRScheel
    Recognized Expert Contributor
    • Apr 2007
    • 638

    #2
    Curiously, do you ever set the timeout on the Session?

    Comment

    • emajka21
      New Member
      • May 2007
      • 38

      #3
      No, I'm not sure how to do that. Where do I set that? In the web.config?

      Comment

      • TRScheel
        Recognized Expert Contributor
        • Apr 2007
        • 638

        #4
        Originally posted by emajka21
        No, I'm not sure how to do that. Where do I set that? In the web.config?
        The session object itself should have a timeout property

        Comment

        • Plater
          Recognized Expert Expert
          • Apr 2007
          • 7872

          #5
          Originally posted by emajka21
          No, I'm not sure how to do that. Where do I set that? In the web.config?
          Some session timeout settings are in the IIS settings for the web-application itself.

          Comment

          • emajka21
            New Member
            • May 2007
            • 38

            #6
            Well I had time to play with it a bit more. It seems that if I stay in the same page and add data (while refreshing and clearing the form after the data is saved)the session doesn't time out. It seems to loose the session variable when I go from page to page. It has to be the way I coded the pages. Any thoughts on this?

            Comment

            • emajka21
              New Member
              • May 2007
              • 38

              #7
              Well I have to change that theory again. After more testing I have found that the pages are timing out. It is just the form because visible and I didn't have them to turn back to invisible if the user wasn't an admin.

              At least I found one flaw....

              I also emailed my host provider to ask about their servers... Lets see what they say. Does anyone have any other suggestion other then session variables?

              Comment

              • Plater
                Recognized Expert Expert
                • Apr 2007
                • 7872

                #8
                Are you set to use "InProc" as your seesion mode?

                Comment

                • emajka21
                  New Member
                  • May 2007
                  • 38

                  #9
                  Umm I'm not sure. I am using what ever is default for session variables. Here is my web.config:
                  [code=xml]
                  <?xml version="1.0"?>

                  <configuratio n>
                  <appSettings/>
                  <connectionStri ngs/>
                  <system.web>

                  <pages theme ="purple" />

                  <compilation debug="true"/>

                  <authenticati on mode="Windows"/>



                  <siteMap defaultProvider ="AspNetXmlSite MapProvider" enabled="true">

                  <providers>

                  <add siteMapFile="~\ web.sitemap" name="MyXmlSite MapProvider" type="System.We b.XmlSiteMapPro vider"/>
                  <add siteMapFile="~\ web2.sitemap" name="MyXmlSite MapProvider2" type="System.We b.XmlSiteMapPro vider"/>
                  </providers>

                  </siteMap>


                  </system.web>
                  </configuration>[/code]
                  Last edited by Frinavale; Aug 14 '07, 01:05 PM. Reason: Added [code] tags to make more legible

                  Comment

                  • Frinavale
                    Recognized Expert Expert
                    • Oct 2006
                    • 9749

                    #10
                    Originally posted by emajka21
                    Anyways this works on my pc through development but after I put these files on a server (which is on a free hosting server that I am using for testing) it times out really fast. After about 30 seconds to a minute my session loses that it is an admin and the pages tell me that I am not an admin anymore. Any thoughts on this? Are session variables the best way to go in this case? Hopefully I provided enough code for you to have an understanding of what I am trying to do. Any help would be much appreciated!

                    Thanks!
                    I know this wont help you to understand your Session Time out issues....

                    But Since you've ask if Session variables are the best way to go in this case I'm going to suggest you use something completely different.

                    Since you're using .NET 2.0 framework there are tools available to you that simplify the user authentication and authorization process.

                    Check out this video first.

                    Then I'd suggest looking into the information provided by MSDN on the following:

                    The video was taken from a website that contains a lot of useful information on the topic:this website is found here.


                    I hope this helps you out!

                    -Frinny

                    Comment

                    • Plater
                      Recognized Expert Expert
                      • Apr 2007
                      • 7872

                      #11
                      The Session Timeout and InProc settings are in the IIS management controls, which, you probably don't have access to since you're hosted.
                      Check with your host, and if they're not already there, have them set the Session Timeout to like 15-20mins (or whatever) and make sure it's set to "InProc".
                      That might not help, but it's good to check.

                      My settings:
                      Session State Mode: "InProc"
                      Cookieless mode: "UseCookies "
                      Session Timeout(inutes) : "20"


                      Hmm, is your session cookie being set and passed correctly between pages? That could cause the problem you are seeing as well.

                      Comment

                      • emajka21
                        New Member
                        • May 2007
                        • 38

                        #12
                        Hello again,
                        Thanks for everyone's help on this. I contacted the host provider and got a generic message stating to check the tech support page which sucks. So I replied with a more specific question. Lets see if they get back to me with a real answer or not.

                        Either way I plan on looking into the form authentication this weekend. I have other things going on that I can't spend alot of time on it until then. If I run into anymore problems I will post again.

                        Thanks!

                        Comment

                        • emajka21
                          New Member
                          • May 2007
                          • 38

                          #13
                          Well I sort of got the form authentication working except for 1 thing. My sitemaps. I have 2 sitemaps, 1 for anyone and 1 for admins. I don't want the admin sitemap to be visible until the admin logs in. I read to do this I could use securityTrimmin gEnabled="true" . This does hide the second sitemap but it doesn't bring it back when I log in. I don't know what I am doing wrong here. I know my security is working because if I take out that line the site map appears and if those links are clicked it redirects to the login page. Once logged in those pages are accessible. Any thoughts?

                          Here is my webconfig:
                          [code=xml]
                          <?xml version="1.0"?>

                          <configuratio n>
                          <appSettings/>
                          <connectionStri ngs/>
                          <system.web>
                          <roleManager enabled="true" />
                          <pages theme="purple"/>

                          <compilation debug="true">
                          <assemblies>
                          <add assembly="Syste m.Windows.Forms , Version=2.0.0.0 , Culture=neutral , PublicKeyToken= B77A5C561934E08 9"/>
                          <add assembly="Syste m.Security, Version=2.0.0.0 , Culture=neutral , PublicKeyToken= B03F5F7F11D50A3 A"/>
                          <add assembly="Acces sibility, Version=2.0.0.0 , Culture=neutral , PublicKeyToken= B03F5F7F11D50A3 A"/>
                          <add assembly="Syste m.Runtime.Seria lization.Format ters.Soap, Version=2.0.0.0 , Culture=neutral , PublicKeyToken= B03F5F7F11D50A3 A"/>
                          <add assembly="Syste m.Deployment, Version=2.0.0.0 , Culture=neutral , PublicKeyToken= B03F5F7F11D50A3 A"/></assemblies></compilation>

                          <authenticati on mode="Forms" />


                          <siteMap defaultProvider ="AspNetXmlSite MapProvider"
                          enabled="true">
                          <providers>
                          <add siteMapFile="~\ web.sitemap" name="MyXmlSite MapProvider" type="System.We b.XmlSiteMapPro vider" />
                          <add siteMapFile="~\ web2.sitemap" name="MyXmlSite MapProvider2" type="System.We b.XmlSiteMapPro vider" />

                          </providers>
                          </siteMap>


                          </system.web>
                          </configuration>
                          [/code]
                          Here are my sitemaps (admin):
                          [code=xml]
                          <?xml version="1.0" encoding="utf-8" ?>
                          <siteMap xmlns="http://schemas.microso ft.com/AspNet/SiteMap-File-1.0" >
                          <siteMapNode url="" title="" description="">

                          <siteMapNode url="admin\Chan gePassword.aspx " title="Change Password" description="Ch ange User Name or Password" />
                          <siteMapNode url="admin\NewR unner.aspx" title="New Runner" description="Ad d New Runners" roles="Administ rator"/>
                          <siteMapNode url="admin\Upda teRunner.aspx" title="Update Runner" description="Up date Runner information" roles="Administ rator"/>
                          <siteMapNode url="admin\Race Times.aspx" title="Enter Race Times" description="En ter Race Times" roles="Administ rator"/>
                          <siteMapNode url="admin\Edit Times.aspx" title="Edit Race Times" description="Ed it Current Year Race Times" roles="Administ rator"/>
                          <siteMapNode url="admin\Regi sterRunner.aspx " title="Register Runners" description="Re gister Runners for the year" roles="Administ rator"/>
                          <siteMapNode url="admin\Regi steredRunners.a spx" title="List of Registered Runners" description="Li st of Registered Runners" roles="Administ rator"/>


                          </siteMapNode>
                          </siteMap>
                          [/code]

                          NON ADMIN:
                          [code=xml]
                          <?xml version="1.0" encoding="utf-8" ?>
                          <siteMap xmlns="http://schemas.microso ft.com/AspNet/SiteMap-File-1.0" >
                          <siteMapNode url="" title="" description="">

                          <siteMapNode url="age.aspx" title=" Race Times by Sex/Age" description="Re port of Race times sorted first by Sex, then Age groups" />
                          <siteMapNode url="individual .aspx" title="Individu al Race Times" description=" Race Times for each individual runner" />
                          <siteMapNode url="Overall.as px" title="All Marathon Totals" description="Re port of overall Marathon Progress" />
                          <siteMapNode url="OverallbyA ge.aspx" title="Marathon Totals by Sex/Age" description="Re port of overall Marathon Progress by Sex/Age" />
                          <siteMapNode url="http://www.pfrpc.com" title="PFPRC Home" description="Pa rk Forest Running and Pancake Club Home Page" target="_blank"/>
                          <siteMapNode url="http://www.pfrpc.com/about-us.html" title="About PFPRC" description="Ab out the Park Forest Running and Pancake Club" target="_blank"/>
                          <siteMapNode url="http://www.pfrpc.com/contact-us.html" title="Contact Us" description="Co ntact the PFRPC" target="_blank"/>


                          </siteMapNode>
                          </siteMap>
                          [/code]

                          HERE IS MY MASTERPAGE:
                          [code=html]
                          <%@ Master Language="C#" AutoEventWireup ="true" CodeFile="Maste rPage.master.cs " Inherits="test" %>

                          <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dt d">

                          <html xmlns="http://www.w3.org/1999/xhtml" >
                          <head runat="server">
                          <title>Untitl ed Page</title>
                          </head>
                          <body>
                          <form id="form1" runat="server">
                          <!-- Header -->
                          <div class="Header">
                          <asp:Image ID="Image1" runat="server" ImageUrl="~/images/title.png" AlternateText=" PFRPC Progressive Marathon" Width="750px" />&nbsp;<br />

                          </div>

                          <!--Menu-->
                          <div class="Menu">
                          <asp:SiteMapDat aSource id="NotLoggedIn SiteMap" runat="server" ShowStartingNod e="false" SiteMapProvider ="MyXmlSiteMapP rovider2" />
                          <asp:HyperLin k ID="hlHome" runat="server" NavigateUrl="~/Default.aspx">H ome</asp:HyperLink>< br />
                          <asp:HyperLin k ID="hlLogin" runat="server" NavigateUrl="~/login.aspx">Adm in Login</asp:HyperLink>
                          <asp:HyperLin k ID="hlLogout" runat="server" NavigateUrl="~a dmin/LogoutSuccess.a spx" Visible="False" >Logout</asp:HyperLink>
                          <asp:Menu ID="NotLoggedIn Menu" runat="server" DataSourceID="N otLoggedInSiteM ap" OnMenuItemDataB ound="NotLogged InMenu_MenuItem DataBound">

                          </asp:Menu>
                          </div>

                          <!-- Menu -->
                          <div class="Menu2">
                          <asp:SiteMapDat aSource id="LoggedInSit eMap" runat="server" ShowStartingNod e="false" SiteMapProvider ="MyXmlSiteMapP rovider" />
                          <asp:Menu id="LoggedInMen u" runat="server" DataSourceID="L oggedInSiteMap" Visible="true" ></asp:Menu>
                          &nbsp;&nbsp;

                          </div>
                          [/code]

                          MASTERPAGE CODE BEHIND:
                          [code=cpp]
                          public partial class test : System.Web.UI.M asterPage
                          {
                          protected void Page_Load(objec t sender, EventArgs e)
                          {

                          }

                          protected void NotLoggedInMenu _MenuItemDataBo und(object sender, MenuEventArgs e)
                          {

                          e.Item.Target = ((SiteMapNode)( e.Item.DataItem ))["target"];
                          }[/code]
                          Last edited by Frinavale; Aug 14 '07, 01:04 PM. Reason: Added [code] tags to make more legible

                          Comment

                          • emajka21
                            New Member
                            • May 2007
                            • 38

                            #14
                            Never mind. I think I got it working. The next step is to upload it to the server and see if it works!

                            Comment

                            • emajka21
                              New Member
                              • May 2007
                              • 38

                              #15
                              Well I uploaded it to the server and it isn't working. This is quite frustrating!

                              When I go to log in I just get an application runtime error. Any thoughts on why??

                              I am going to email them back about this.

                              This was the web hosts answer:
                              Dear Customer,

                              Thank you for your inquiry regarding your account(s).

                              Free sites are hosted in busy environment. They are
                              hosted in Application pools where many others sites
                              are hosted too. The application pools have a limit on
                              amount of memory they can use. After reaching the
                              memory limit application pool will recycle causing a
                              reset of session variables among other things.
                              If sites that have a memory leaks are hosted with your
                              site in the same application pool you'll experience a
                              problem you've described.
                              Without complicated investigation we cannot detect a
                              sites with severe memory leaks. An we do not
                              investigate this sort of problems on our servers with
                              free hosting plans.
                              There are however many web servers with hundreds of
                              application pools where you can host you site.

                              To workaround the issue: Delete your site wait 5
                              minutes, and then register it again.
                              -----------------------------------------------

                              I guess I can try that but after getting form validation to work I see how much nicer and secure it is. I don't want to go back...

                              Any thoughts or suggestions would be much appreciated!

                              Comment

                              Working...