cool hit counter ASP. NET in the use of Application and Session statistics online, the number of historical visits_Intefrankly

ASP. NET in the use of Application and Session statistics online, the number of historical visits

Copyright: This is an original post by the blogger and may not be reproduced without the blogger's permission.

Let's start with a brief explanation of Application and Session in ASP.NET

The following diagram shows the structure of a very familiar web application.

In this diagram, the Web application running in the Web server is what we call an Application, and the connection established between each client and the Web server can be thought of as a Session. For example, if a forum system is running on the server side, then the software that is running on the server side of the forum system can be seen as an Application, and each connection established by an online user to it is equivalent to a Session.

Then it is easy to understand that Application is shared and is equivalent to a "global variable", while Session is not shared and is private to each client (browser).

So the above diagram with Application and Session can be represented as


Common Attributes.




Returns all Application object variables to an array of objects


Returns all Application object variables to a string array


Returns the number of object variables in the Application

Commonly used methods.




Add an Application variable value


Clear all Application variable values


The value of the variable passed back by the variable name


Update the Application variable value


Lock the values of all Application's variables


Unlock the variable value of the Application


Common Attributes.




Get the number of Session objects in the session state collection


Get a reference to the current session state object


Get the set of all values stored in the session


Get the unique session ID used to identify the session


Gets or sets the timeout period allowed before the session status provider terminates the session


Get the current session status mode

Commonly used methods.




Add a Session object


Clear all values in the session state


Put the set of session state values in a one-dimensional array of Tominoshima


Deleting items from the session status collection


Clear the value of all session states

ASP. NET to count the number of people online and the number of historical visits, four more events are needed: the Application_Start() event, Application_End(), Session_Start() event and Session_End() event.

When the program starts, it will first trigger the Application_Start() event of the Application in the Global.asax.cs file. We need to add two Application variable values to this event (because they are variable values in the Application, they are equivalent to the "public variables" of the whole program): totalCount (to indicate the total number of visits), onlineCount (to indicate the number of people currently online).

protected void Application_Start()
            string strConn = "server=;database=Database name;uid=sa;pwd=123456;";    // Database connection string
             SqlConnection conn = new SqlConnection(strConn);                                   // Instantiate the database connection object
             conn. Open();                                                                       // Open database connection
            string cmdText = "select count from Count";                                       // Define the query string
             SqlCommand cmd = new SqlCommand(cmdText, conn);                                    // Instantiate the command object
             int count = (int)cmd.ExecuteScalar();                                              // Retrieve the number of historical visitors in the database

            Application["total"] = count;                                                     // meaningApplication variable valuetotal and assign a value to the historical visits
            Application["onLine"] = 0;                                                        // meaningApplication variable valueonLine and assign a value of0

The following is to write the Session_Start() event code, when each client (browser) accesses the server, it will trigger the Session_Start() event, this thing is to let the "public variables" totalCount and onlineCount are self-incremented by 1, at this time, when there are more than one client access at the same time, there is a possibility of error, so to Application's Lock() method to lock the variables in the Application first (after Application executes the Lock() method, all the operations in the whole site about Application will be locked to delay the execution, including Application assignment and Application reading), only let one client to carry out the self-increment of these two variables, and then unlocked for other clients to operate.

protected void Session_Start()
             Application.Lock();                                         //Lock the Application
            Application["total"] = (int)Application["total"] + 1;      // Total visits plus1
            Application["onLine"] = (int)Application["onLine"] + 1;    // Number of people online plus1
             Application.UnLock();                                       //Unlock

The number of people online and the number of historical visits are now counted, Call directly when you need to displayApplication[" variable value"] then you can, For example, to create a new file namedLabel The number of people online is displayed on the control of the, simplyLabel.Text=Application["onLine"].ToString() just (emphasis)OK finish! need note The thing is that the values of the variables stored in Application and Session are of type object, and you can assign values to them directly, but you need to consider the type when you take them out.

The Session_End() event is triggered when a client (browser) disconnects from the server (i.e. the session between this client and the server is closed), at which point the number of historical visits does not change and the number of people online needs to be subtracted by 1.

protected void Session_End()
             Application.Lock();                                           //Lock the Application
            Application["onLine"] = (int)Application["onLine"] - 1;      // No change in the total number of visits, Decrease in the number of people online1
             Application.UnLock();                                         //Unlock

To facilitate testing, The above example can be done by opening multiple browsers on one computer, It is also equivalent to establishing multipleSession, Perhaps you will find a problem when you test, If the number of people online now is10, When you close a browser, Test the current number of people online i.e.Application["onLine"] The value of or10 , It was not implemented“ diminish1” operations。 This is becauseSession ofTimeOut The value defaults to20 minutes, that is say, By default, Closing a browser does not mean that the connection between that browser and the server has been disconnected, And to wait for20 It takes minutes to disconnect。( To test the effect, You can add theTimeOut set a smaller value for)

Finally, if the server is to be shut down, the total number of historical accesses currently stored in the Application will have to be re-updated to the database, which needs to be done in the Application_End() event.

protected void Application_End()
            string strConn = "server=;database=Database name;uid=sa;pwd=123456;";    // Define the database connection string
             SqlConnection conn = new SqlConnection(strConn);                                   // Instantiate the database connection object
             conn. Open();                                                                       // Open database connection
            string cmdText = "update Count set count=@count";                                 // Define the execution command
             SqlCommand cmd = new SqlCommand(cmdText, conn);                                    // Instantiate the command object
            cmd.Parameters.Add(new SqlParameter("@count", Application["total"]));             // as a parameter@count Assign a value to the total number of visits now
             cmd.ExecuteNonQuery();                                                             //Execute the command
             conn. Close();                                                                      // Close the database

Usually during the whole process, The majority of people are interested inApplication_End() This event is the most questionable, Because if you are just inVisualStudio If the test was done on, When shutting down the system, No triggerApplication_End() events, The new data is also not written to the database。 or soApplication_End() At what point does it actually get triggered??

Trying to figure this out, you need to publish the program, here to IIS as an example, with IIS published after running the program, when you want to trigger the Application_End () event to write the latest history of visits to the database, you need to close the operation of this program in IIS, as follows.

note : The Application_End() event is only triggered by stopping the program on the server; restarts, power failures, etc. do not trigger it.

Although the statistics of the number of people online and historical visits is a small and insignificant function, but by running through it, a detailed summary, and learned a lot of things, the brain of the knowledge network has increased a little 。。。。

1、Save your money Look out if you have a mobile phone network speed and traffic reduction 2018 special action is coming
2、The most comprehensive frontend learning resource ever
3、7Python Learning Sharing ArticleTuple Introduction and Basic Operations
4、Letter on Invitation to the First Digital Economy and Artificial Intelligence Conference of the European and American Institute
5、Blockchain technology is ready to restructure the healthcare industry

    已推荐到看一看 和朋友分享想法
    最多200字,当前共 发送









    Contact US

    Welcome to Intefrankly.

    Intefrankly is a platform that you can show your opnions related to IT technology, and communicates to the people who interested in IT and Artificial Intelligence area.