Asp. NET use application and session statistics online people, historical visits

Source: Internet
Author: User
Tags session id

Reprinted from: HTTP://WWW.TUICOOL.COM/ARTICLES/QYE3E2A

Let's talk briefly about the application and session in ASP.

Is the structure of a Web application that we are very familiar with:

In this diagram, the Web application running in the Web server is what we call the application, and the connection made between each client and the Web server can be seen as a session. For example, now the server is running a forum system, then this is running on the server-side of the forum system software can be regarded as application, and each online user to establish a connection is equivalent to a session.

It is easy to understand that application is shared, equivalent to a "global variable", that the session is not shared and is owned by each client (browser).

So using application and session can be expressed as:

Application

Common Properties:

Property Description
All Returns all Application object variables to an array of objects
AllKeys Returns all Application object variables to an array of strings
Count Returns the number of object variables in the application

Common methods:

Method Description
Add Add a Application variable value
Clear Empty all Application variable values
Get Variable value returned by variable name
Set Update Application Variable Value
Lock Lock variable values for all application
UnLock The value of the variable that unlocks the application

Session

Common Properties:

Property Description
Count Gets the number of session objects in the conversation-state collection
Contents Gets a reference to the current session-state object
Keys Gets a collection of all values stored in the session
SessionID Gets the unique session ID used to identify the session
TimeOut Gets or sets the time-out period allowed before the session-state provider terminates the session
Mode Gets the current session state mode

Common methods:

Method Description
Add Add a Session Object
Clear Clears all values in the session state
CopyTo Sets the set of session-state values in a one-dimensional array of rich islands
Remove To delete an item in a session-state collection
RemoveAll Clears values for all session states

Asp. NET to count the number of online and historical visitors, four more events are required: the Application_Start () event, the Application_End (), the Session_Start () event, and the Session_End () event.

When the program starts, the application Application_Start () event is first triggered in the Global.asax.cs file. We need to add two application variable values in this event (because these two values are the variable values in the application, so it is equivalent to the "public variable" of the entire program): TotalCount (used to denote total traffic), Onlinecount (used to indicate the current number of people online):

Protectedvoid Application_Start ()  {    String strconn ="server=192.168.24.123;database= database name; uid=sa;pwd=123456;";Database connection string  SqlConnection conn =New SqlConnection (strconn);Instantiating a database Connection object  Conn. Open ();Open a database connection   String Cmdtext ="SELECT count from Count";//define query string   SqlCommand cmd = new SqlCommand (CMDTEXT, conn); //Instantiate Command object    int count = (int) cmd. ExecuteScalar (); //Remove the number of historical visitors in the database   application["Total" = count; //Define Application variable value Total and assign a value of historical traffic   application["onLine"] = 0;  Define the application variable value online and assign a value of 0 }            

The Session_Start () event code is written below, and when each client (browser) accesses the server, the Session_Start () event is triggered, which causes the "public variables" totalcount and Onlinecount to increment by 1, When there are multiple clients accessing at the same time, it is possible to make an error, so the lock () method to be application locks the variables in the application (application executes the lock () method, All operations on application in the entire station are locked for deferred execution, including application assignment and application read, so that only one client can increment the two variables and then unlock them for other clients to operate:

Protectedvoid Session_Start ()  {   Applica tion. Lock (); //lock application   Application[ "total"] = (int) application[ "total"] + 1; //total traffic plus 1   Application[ "online"] = (int) application[ "online" + 1; //online number plus 1   Application.UnLock (); //unlocked  }        

Now that the number of online and historical visits are counted, it is possible to call application["variable value" directly when it is displayed, such as to display the number of people online on a control named label, just label.text=application["online". ToString () is OK! It is important to note that the variables stored in the application and session are of type object and can be assigned directly when assigned to them, but they need to be considered when taking out the values.

When a client (browser) disconnects from the server (that is, the client-to-server session is closed), the Session_End () event is triggered, and the number of historical visits does not change, and the number of people online needs to be reduced by 1:

void Session_End ()        {            application.lock ();                                          //Lock Application            application["OnLine"] = (int) application[//unlocked}   

For the convenience of testing, the above example can be opened by a computer on a number of browsers, it is equivalent to the server set up a number of sessions, perhaps you will find a problem when testing, if the number of people online is 10, you close a browser, Test whether the current number of online people is application["online" value or 10, and does not perform a "minus 1" operation. This is because the timeout value of the session defaults to 20 minutes, that is, by default, closing the browser does not mean that the connection between the browser and the server has been disconnected, and that the connection will not be disconnected until 20 minutes. (To test the effect, you can set the value of timeout to a smaller point)

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

Protectedvoid Application_End ()  {    String strconn ="server=192.168.24.123;database= database name; uid=sa;pwd=123456;";Defining a database connection string  SqlConnection conn =New SqlConnection (strconn);Instantiating a database Connection object  Conn. Open ();Open a database connection   string cmdtext = //definition execution Command    SqlCommand cmd = new SqlCommand (Cmdtext, conn); //instantiate Command object    cmd. Parameters.Add (new sqlparameter ( "total"])); //assigns the current total traffic to the parameter @count    cmd. ExecuteNonQuery (); //execute command    Conn. Close (); //close database  }        

Most people's doubts about the Application_End () event are most common throughout the process, because if you're just testing on VisualStudio, the Application_End () event is not triggered when you shut down the system. The new data is not written to the database. So when will the Application_End () be triggered?

To figure this out, you need to publish the program, which, in the case of IIS, runs after you publish the program with IIS, and when you want to trigger the Application_End () event to write the latest historical traffic to the database, you need to shut down the program in IIS, such as:

Note : Just stopping the program on the server will trigger the Application_End () event, which does not trigger a reboot or power outage.

Although statistics on-line and historical visits is a small and insignificant function, but by smoothing over, carefully summed up a bit, and learned a lot of things, the knowledge network in the brain increased a little bit ....

Asp. NET use application and session statistics online people, historical visits

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.