locked
Hit counter - using global.asax RRS feed

  • Question

  • User1028962535 posted

    Hi,  I have been following a tutorial on how to create a hit counter for my web page using the global.asax page, but the counter resets to 0 after a while, how can I prevent that from happening?..(see code below).  

    https://www.webcodeexpert.com/2013/10/how-to-count-number-of-times-website.html

    thanks

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

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

    Sunday, October 18, 2020 11:13 AM

Answers

  • User475983607 posted

    Thanks for the answer, so I need to save the counter to a database every 20 minutes?..is there an easier way to make counter more persistent?

    Well, at stated above, store the value in persistent storage like a database table.  Your current approach stores the value in volatile memory.  Change the code to save the value in a table. 

    I

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Sunday, October 18, 2020 5:27 PM

All replies

  • User475983607 posted

    Hi,  I have been following a tutorial on how to create a hit counter for my web page using the global.asax page, but the counter resets to 0 after a while, how can I prevent that from happening?..(see code below).  

    This is the expected behavior.  The variables reset when the application restarts.  Web application spin down after nonuse.  The default timeout is 20 minutes.

    The solution is storing the count in persistent storage like a database table. 

    Sunday, October 18, 2020 1:18 PM
  • User1028962535 posted

    Thanks for the answer, so I need to save the counter to a database every 20 minutes?..is there an easier way to make counter more persistent?

    Sunday, October 18, 2020 1:46 PM
  • User475983607 posted

    Thanks for the answer, so I need to save the counter to a database every 20 minutes?..is there an easier way to make counter more persistent?

    Well, at stated above, store the value in persistent storage like a database table.  Your current approach stores the value in volatile memory.  Change the code to save the value in a table. 

    I

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Sunday, October 18, 2020 5:27 PM