Session Counter counting fast

Last post 11-12-2009 10:43 AM by budugu. 22 replies.

Sort Posts:

  • Session Counter counting fast

    10-28-2009, 7:01 PM
    • Member
      23 point Member
    • eengin
    • Member since 04-08-2008, 12:55 PM
    • Posts 32

    Hi,

    I have a counter to count distinct users browsing my site.  So it counts the sessions.  The Global.asax has the following functions


    void Application_Start(Object sender, EventArgs e) {
    // Code that runs on application startup
    Application["Hits"] = 0;
    }


    void Session_Start(Object sender, EventArgs e)
    {
    // Code that runs when a new session is started
    Application.Lock();
    Application["Hits"] = (int)Application["Hits"] + 1;
    Application.UnLock();
    }

    When I monitor Application["Hits"] variable I see that it keeps on incrementing as I browse the different pages of the same project.
    Since I am the only user I have only one session it should not increment it within my session.
    And the other problem is that it increment not one by one but it increments with steps of 4.

    Anyone had similar problem or have suggestions?

    thanks



     Application["Hits"]
  • Re: Session Counter counting fast

    10-29-2009, 1:01 AM
    Answer
    • Contributor
      6,487 point Contributor
    • anzer
    • Member since 10-19-2004, 4:00 AM
    • UAE
    • Posts 1,302

    Seems strange

    Try setting some explicit session value in the Session_Start event before incrementing the app variable


    if(Session["Date"] == null)
                Session["Date"] = DateTime.Now.ToLongTimeString();

    and if the problem persists, place breakpoints and check what is happening..



    If this post was useful to you, please mark it as answer.

    ClientSideAsp.Net | Blog
  • Re: Session Counter counting fast

    11-04-2009, 2:16 AM
    • Contributor
      6,487 point Contributor
    • anzer
    • Member since 10-19-2004, 4:00 AM
    • UAE
    • Posts 1,302

    Hi you got it solved??

    What was the actual problem?

    If this post was useful to you, please mark it as answer.

    ClientSideAsp.Net | Blog
  • Re: Session Counter counting fast

    11-09-2009, 10:22 AM
    • Member
      23 point Member
    • eengin
    • Member since 04-08-2008, 12:55 PM
    • Posts 32

    Thanks for the suggestion but it did not solve my problem.  Still the session_start is launched several time.  Maybe it is because I use a Template Page whic contains several user controls inside it.  If we think these User controls as different pages embedded in the page,  is Session_Start being fired when each of these user controls are being rendered (or loaded).

    I have placed a breakpoing to Session_Start(Object sender, EventArgs e) function and when you browse the properties "sender":

    ((System.Web.SessionState.SessionStateModule)(sender))._rqContext.Handler

    property takes the names of these user controls each time the cursor enters the Session_Start function.


    I think this makes the situation more clear.   So the question is how can I prevent this child controls firing the session start function?


    Thanks


       void Application(Object sender, EventArgs e)_Error
  • Re: Session Counter counting fast

    11-10-2009, 5:01 AM
    • Contributor
      5,226 point Contributor
    • RickNZ
    • Member since 01-01-2009, 8:43 AM
    • Nelson, New Zealand
    • Posts 872

    I'm not sure I have the whole answer, but I can offer a few tidbits that might help:

    1. If you don't store anything into the Session dictionary, a new session will be created for each request
    2. Session_End() is not guaranteed to be called for every session, only for the ones that are explicitly ended/expired/abandoned. If a session just times out and no subsequent request is made, then Session_End() won't be called.
    3. If you're running under Cassini, HttpModules in the pipeline such as the one that manages session state get invoked for images and other static files, as well as for your .aspx pages. I don't recall for sure if the SessionModule checks for *.aspx only, but I don't think it does.


  • Re: Session Counter counting fast

    11-10-2009, 8:50 AM
    • All-Star
      91,750 point All-Star
    • SGWellens
    • Member since 01-02-2007, 4:27 PM
    • Twin Cities, MN
    • Posts 7,486
    • Moderator
      TrustedFriends-MVPs

    RickNZ:
    1. If you don't store anything into the Session dictionary, a new session will be created for each request
     

    That is not true (or I am misunderstanding what it says).

    You can verify it by this code:

        protected void Page_Load(object sender, EventArgs e)
        {
            Response.Write(Session.SessionID + "<br />");


     

    Steve Wellens

    My blog
  • Re: Session Counter counting fast

    11-10-2009, 1:05 PM
    • Star
      12,874 point Star
    • Kumar Reddi
    • Member since 11-11-2004, 9:54 PM
    • Virginia
    • Posts 2,357

    RickNZ:

    2. Session_End() is not guaranteed to be called for every session, only for the ones that are explicitly ended/expired/abandoned. If a session just times out and no subsequent request is made, then Session_End() won't be called.

    Not trying to be nitpicky, but what is the difference between session timing out and expiring?

    Kumar Reddi
  • Re: Session Counter counting fast

    11-10-2009, 2:54 PM
    • Member
      23 point Member
    • eengin
    • Member since 04-08-2008, 12:55 PM
    • Posts 32

    Thank you all for replies.  I would never imagine putting a counter to an ASP.NET web site to be so difficult.  I could not find a solution for the problem although it is a very basic common element of a page.


    I think I have to make it more clear.


    In my page template I have a UserControl called "RSSreader.ascx".  Inside the Rssreader  Page_PreRender event it does this


    XmlDataDocument feed = new XmlDataDocument();
    feed.Load(GetFullUrl(this.RssUrl));
    XmlNodeList posts = feed.GetElementsByTagName("item");

    ...........

    and it puts the data to the gridview appropriately


    where RssUrl is another page in my project called RssFeed.aspx.  RssFeed.aspx has a repeater inside and it turns the database data into XML format.  For example if you call this RssFeed page you will see

          <rss version="2.0">
    <channel>
    <title><![CDATA[SomeTEXT]]></title>
    <link>
                    SomeTEXT
    </link>
    <description>
    SomeTEXT
    </description>
         

    </channel>
    </rss>



    I put the break point to the very top of the Session_Start function and I click a link in my default page:

    The cursor comes to my break point and I observe

    ((System.Web.SessionState.SessionStateModule)(sender))._rqContext.Handler  being      ASP.RssFeed.aspx

    and the

    Session ID  some value like  say "asd432qrfaaq4fdsfadaf"


    I push run and the cursor again comes to the same point

    ((System.Web.SessionState.SessionStateModule)(sender))._rqContext.Handler  is again ASP.RssFeed.aspx

    and Session ID is some different value.


    When I push run again the page I wanted to go becomes available. 


    So one problem is why the Session_Start is called twice by this RssFeed.aspx page?  and another is why do I get different SessionID s each time?


    I tried storing something to the Cookie and read it when Session_Start is called again but I cannot find the cookie I placed.  It is vanished.


    My web.config has this

    <sessionState cookieless="false" timeout="60"/>


    Thanks


  • Re: Session Counter counting fast

    11-10-2009, 3:29 PM
    Answer
    • Member
      23 point Member
    • eengin
    • Member since 04-08-2008, 12:55 PM
    • Posts 32

    Mystery finally resolved.  I added EnableSessionState="False" to the tag of the RssFeed.aspx page therefore it nolonger called the Session_Start function.


    Thanks All,  I hope this thread help others.

  • Re: Session Counter counting fast

    11-10-2009, 8:10 PM
    • Contributor
      5,226 point Contributor
    • RickNZ
    • Member since 01-01-2009, 8:43 AM
    • Nelson, New Zealand
    • Posts 872

    Let me rephrase:

    Until you store something into the Session dictionary for a given user, the session HttpModule will not set a session cookie.  Until the session cookie is set, the session HttpModule will create a new session for each request; that includes a new session ID.

    If you execute the code in your example for a user that has never had anything previously set in the session dictionary, then the reported session ID will be different every time (I just double-checked that myself).

    However, if the user accessess another page that sets something in the Session dictionary, then the session ID will be the same for each subsequent request, until the session expires - even if that page doesn't set anything itself in the Session dictionary.


  • Re: Session Counter counting fast

    11-10-2009, 8:16 PM
    • Contributor
      5,226 point Contributor
    • RickNZ
    • Member since 01-01-2009, 8:43 AM
    • Nelson, New Zealand
    • Posts 872

    Kumar Reddi:

    Not trying to be nitpicky, but what is the difference between session timing out and expiring?

    Nothing, really.

    The differences are in how a session expires.

    It can happen in one of two ways:

    1. An explicit call by the server to Session.Abandon(). That will delete the session cookie and call Session_End().
    2. No action by the server; the session just ages past its intended life time.  Session_End() won't be called in that case.  If you're storing session data in SQL Server, some time later, SQL Agent will run and remove the now-expired session data from the database.

    There is also an in-between case, where the session can expire, and the client then calls the server before the DB cleanup has happened.  I'm not sure if Session_End() is called in that case, but I think it might be.

  • Re: Session Counter counting fast

    11-10-2009, 8:29 PM
    • All-Star
      91,750 point All-Star
    • SGWellens
    • Member since 01-02-2007, 4:27 PM
    • Twin Cities, MN
    • Posts 7,486
    • Moderator
      TrustedFriends-MVPs

    RickNZ:

    Until you store something into the Session dictionary for a given user, the session HttpModule will not set a session cookie.  Until the session cookie is set, the session HttpModule will create a new session for each request; that includes a new session ID.

    If you execute the code in your example for a user that has never had anything previously set in the session dictionary, then the reported session ID will be different every time (I just double-checked that myself).

     

    I just tested it and I get the same SessionID everytime even with nothing in the Session dictionary.

    Then I made the sessions 'cookieless', retested and the same deal.

    On further consideration, if what you say is true, then the session start event would trigger everytime the user refreshed the page (with nothing stored in the session dictionary).  That doesn't happen.

     

    Steve Wellens

    My blog
  • Re: Session Counter counting fast

    11-10-2009, 9:20 PM
    • Contributor
      5,226 point Contributor
    • RickNZ
    • Member since 01-01-2009, 8:43 AM
    • Nelson, New Zealand
    • Posts 872

    SGWellens:

    I just tested it and I get the same SessionID everytime even with nothing in the Session dictionary.

    Then I made the sessions 'cookieless', retested and the same deal.

    On further consideration, if what you say is true, then the session start event would trigger everytime the user refreshed the page (with nothing stored in the session dictionary).  That doesn't happen.

    Very curious.  I tested it, too, and the session ID changes every time.

    Is your page getting cached somewhere, perhaps (does it behave the same if you hit control-refresh)?  Or is the session ID written into ViewState? Or do you have an HttpModule that's writing something in the Session object?  Can you use Fiddler to see if the session cookie is set?  What happens if you view the same page from a different browser?

    Here's my code:

    <%@ Page Language="C#"  %>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <script runat="server">
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            this.lbl.Text = this.Session.SessionID;
        }
    </script>
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title></title>
    </head>
    <body>
        <asp:Label runat="server" ID="lbl" />
    </body>
    </html>
    

    Every time I hit refresh, the session ID changes.  For the test, I had session state configured in InProc mode (though that shouldn't matter). I'm using .NET 3.5 and VS 2008.

  • Re: Session Counter counting fast

    11-10-2009, 9:59 PM
    • All-Star
      91,750 point All-Star
    • SGWellens
    • Member since 01-02-2007, 4:27 PM
    • Twin Cities, MN
    • Posts 7,486
    • Moderator
      TrustedFriends-MVPs

    I tried your embedded code and the session ID is fixed.

    I also added a timestamp (both to mine and yours) to see if caching was a problem...nope:

        protected void Page_Load(object sender, EventArgs e)
        {
            Response.Write(Session.SessionID + "<br />");
            Response.Write(DateTime.Now.ToLongTimeString() + "<br />");
            if (IsPostBack == true)
            {
            }
        }


    RickNZ:
    For the test, I had session state configured in InProc mode (though that shouldn't matter). I'm using .NET 3.5 and VS 2008.
     

    Ditto, My config is simple:

      <system.web>
        <sessionState timeout="20" >    
        </sessionState>
      </system.web>

    I'm using the built in web server....are you using a web farm or something?

    Steve Wellens

    My blog
  • Re: Session Counter counting fast

    11-10-2009, 10:47 PM
    • Contributor
      5,226 point Contributor
    • RickNZ
    • Member since 01-01-2009, 8:43 AM
    • Nelson, New Zealand
    • Posts 872

    I was using IIS.  I switched to Cassini, and it behaves the same (different every time).

    The session ID cookie *must* be getting set on your system somehow.  That's the only way the server could create the same session ID from one page view to another.

    If you look at the HTTP request with Fiddler, I'm sure you will see it.  Since you're using Cassini, you can replace "localhost" with "ipv4.fiddler" to see the request.

    What I can't tell in your case is how the cookie is getting set.  It may have been from an earlier test of some kind, or perhaps from an HttpModule or some code in your Global.asax.

    On my machine, the request looks like this:

    GET /TestWeb/p/Default2.aspx HTTP/1.1
    Accept: image/gif, image/jpeg, image/pjpeg, application/x-ms-application, application/vnd.ms-xpsdocument, application/xaml+xml, application/x-ms-xbap, application/x-shockwave-flash, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*
    Accept-Language: en-us
    User-Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0; SLCC1; .NET CLR 2.0.50727; Media Center PC 5.0; InfoPath.2; .NET CLR 3.5.21022; .NET CLR 1.1.4322; .NET CLR 3.5.30428; MS-RTC LM 8; .NET CLR 3.5.30729; .NET CLR 3.0.30618; OfficeLiveConnector.1.4; OfficeLivePatch.1.3)
    Accept-Encoding: gzip, deflate
    Connection: Keep-Alive
    Host: 127.0.0.1:17337
    


    and the response looks like this (with the session ID in the <span>):

    HTTP/1.1 200 OK
    Server: ASP.NET Development Server/9.0.0.0
    Date: Wed, 11 Nov 2009 03:36:53 GMT
    Cache-Control: private
    Content-Type: text/html; charset=utf-8
    Content-Length: 284
    Connection: Close
    
    
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head><title>
    
    </title></head>
    <body>
        <span id="lbl">hl2o5yehdirthw45pb5qhnii</span>
    </body>
    </html>
    

    Notice: no cookies.



Page 1 of 2 (23 items) 1 2 Next >