1. Create a data table IPStat to store user information
The user information stored in the IPStat table only includes the IP address (IP_Address), IP source (IP_Src), and logon time (IP_DateTime) of the logon user ), some table information is saved for only one day. If you want to count the information of each month, you need to save it for one month. Because I do not know much about data log operations, I am stupid to create this table.
2. obtain user information in Global. asax
The Session_Start function of Global. asax obtains relevant information when a new session is enabled. the incremental statistics of the number of online users and total number of visits are also provided here. The Code is as follows:
Copy codeThe Code is as follows:
Void Session_Start (object sender, EventArgs e)
{
// Obtain the visitor's IP address
String ipAddress = Request. ServerVariables ["REMOTE_ADDR"];
// Obtain the visitor's source
String ipSrc;
// Determine whether to navigate from the search engine
If (Request. UrlReferrer = null)
{
IpSrc = "";
}
Else
{
// Obtain the source address
IpSrc = Request. UrlReferrer. ToString ();
}
// Obtain the access time
DateTime ipDatetime = DateTime. Now;
// Save IP information to the database
IPControl cont = new IPControl ();
Cont. AddIP (ipAddress, ipSrc, ipDatetime );
// Obtain the page accessed by the user
String pageurl = Request. Url. ToString ();
// Determine whether the access is a response page
If (pageurl. EndsWith ("IPStat. aspx "))
{
// Lock the variable
Application. Lock ();
// For page access + 1
Application ["StatCount"] = int. Parse (Application ["StatCount"]. ToString () + 1;
// Unlock
Application. UnLock ();
}
// Lock the variable
Session. Timeout = 10; // set the Timeout value to 10 minutes.
Application. Lock ();
Application ["countSession"] = Convert. ToInt32 (Application ["countSession"]) + 1; // total number of visits + 1
Application ["onlineWhx"] = (int) Application ["onlineWhx"] + 1; // number of online users plus + 1
Session ["login_name"] = null;
// Unlock
Application. UnLock ();
}
Remind me not to forget the following code to reduce the number of online users by 1 when the user is offline.
Copy codeThe Code is as follows:
Void Session_End (object sender, EventArgs e)
{
// The code that runs when the session ends.
// Note: The Session_End event is triggered only when the sessionstate mode in the Web. config file is set to InProc. If the session mode is set to StateServer
// Or SQLServer, the event is not triggered.
// Lock the variable
Application. Lock ();
Application ["onlineWhx"] = (int) Application ["onlineWhx"]-1; // decrease the number of online users by-1
Session ["login_name"] = null;
// Unlock
Application. UnLock ();
}
3. Save the above information to the database IPStat
An IPControl () class for obtaining IP data is created to perform operations on IPStat data in the database. The IPControl () class is used to perform operations on the database in C, to solve the SQL server database, you can understand it. I will not introduce it here. Please click this link to view it.
In order to store user IP information into the database, IPControl () is called in the above Code.
Copy codeThe Code is as follows:
// Save IP information to the database
IPControl cont = new IPControl ();
Cont. AddIP (ipAddress, ipSrc, ipDatetime );
The ipAddress parameter is the user IP address, ipSrc is the user source, and ipDatetime is the user entry time.
4. Create a timer and regularly operate related data
For the above IPSta database data, you need to create one or several timers, and count the traffic for one day within 10 seconds before 24 hours every night, and then delete it, save the statistical result to another data table, so that the page displays yesterday's traffic. To create and use a timer, click Create one or more timers for your reference.
Please criticize and correct the above mistakes. Thank you!
Method for collecting website traffic statistics in ASP.net-class for obtaining IP Address Data
Copy codeThe Code is as follows:
Using System;
Using System. Data;
Using System. Data. SqlClient;
Using System. Text;
///
/// Class for retrieving IP data
///
Public class IPControl
{
// Constant is used to represent the variable name used in the T-SQL statement
Private const string PARM_IP_ADDRESS = "@ IPAddress ";
Private const string PARM_IP_SRC = "@ IPSrc ";
Private const string PARM_IP_DATETIME = "@ IPDateTime ";
// T-SQL statement
Private const string SQL _INSERT_IPSTAT = "INSERT INTO IPStat VALUES (@ IPAddress, @ IPSrc, @ IPDateTime )";
Private const string SQL _DELETE_IPSTAT = "delete from IPStat WHERE DATEDIFF (d, ip_datetime, getdate ()> 30"; // only keep data for one month
Private const string SQL _SELECT_TOTAL = "SELECT COUNT (*) FROM IPStat ";
Private const string SQL _SELECT_TODAY = "SELECT COUNT (*) FROM IPStat WHERE DATEDIFF (d, ip_datetime, getdate () = 0 ";
Private const string SQL _SELECT_YESTERDAY = "SELECT COUNT (*) FROM IPStat WHERE DATEDIFF (d, ip_datetime, getdate () = 1 ";
Private const string SQL _SELECT_MONTH = "SELECT COUNT (*) FROM IPStat WHERE DATEDIFF (d, ip_datetime, getdate () <30 and DATEDIFF (mm, ip_datetime, getdate ()) = 0 ";
Public IPControl ()
{
}
///
/// Save IP address data to the database
///
///
///
Public void AddIP (string ipAddress, string ipSrc, DateTime ipDatetime)
{
// Construct the connection statement string
StringBuilder strSQL = new StringBuilder ();
// Create a parameter indicating the QQ number
SqlParameter [] parms = new SqlParameter [] {new SqlParameter (PARM_IP_ADDRESS, SqlDbType. NVarChar, 20 ),
New SqlParameter (PARM_IP_SRC, SqlDbType. NVarChar, 80 ),
New SqlParameter (PARM_IP_DATETIME, SqlDbType. DateTime )};
SqlCommand cmd = new SqlCommand ();
// Assign values to parameters in sequence and add them to execution statements.
Parms [0]. Value = ipAddress;
Parms [1]. Value = ipSrc;
Parms [2]. Value = ipDatetime;
Foreach (SqlParameter parm in parms)
Cmd. Parameters. Add (parm );
// Defines the storage range of object Resources. Once the using range ends, the resources occupied by the other party are released.
Using (SqlConnection conn = new SqlConnection (SqlHelper. ConnectionStringLocalTransaction ))
{
// Load the insert statement in the execution string
StrSQL. Append (SQL _INSERT_IPSTAT );
Conn. Open ();
// Set SqlCommand attributes
Cmd. Connection = conn;
Cmd. CommandType = CommandType. Text;
Cmd. CommandText = strSQL. ToString ();
// Execute the SqlCommand command
Cmd. ExecuteNonQuery ();
Cmd. Parameters. Clear ();
// If the execution is successful, true is returned; otherwise, false is returned.
}
}
Public string GetTotal ()
{
// Call SqlHelper to access the component and return the value in the first column of the First row
Object count = SqlHelper. ExecuteScalar (SqlHelper. ConnectionStringLocalTransaction, CommandType. Text, SQL _SELECT_TOTAL, null );
// Return the statistical result
Return count. ToString ();
}
Public string GetToday ()
{
// Call SqlHelper to access the component and return the value in the first column of the First row
Object count = SqlHelper. ExecuteScalar (SqlHelper. ConnectionStringLocalTransaction, CommandType. Text, SQL _SELECT_TODAY, null );
// Return the statistical result
Return count. ToString ();
}
Public string GetYesterday ()
{
// Call SqlHelper to access the component and return the value in the first column of the First row
Object count = SqlHelper. ExecuteScalar (SqlHelper. ConnectionStringLocalTransaction, CommandType. Text, SQL _SELECT_YESTERDAY, null );
// Return the statistical result
Return count. ToString ();
}
Public string GetMonth ()
{
// Call SqlHelper to access the component and return the value in the first column of the First row
Object count = SqlHelper. ExecuteScalar (SqlHelper. ConnectionStringLocalTransaction, CommandType. Text, SQL _SELECT_MONTH, null );
// Return the statistical result
Return count. ToString ();
}
}
Use a timer in Global. asax to count online users and daily visits
1. Create a timer in Application_Start
Copy codeThe Code is as follows:
// The following describes how to use multiple Timer System. Timers. Timer.
// Use thread to package again and define two timers
System. Threading. Thread myTimer_1 = new System. Threading. Thread (new System. Threading. ThreadStart (write_1 ));
MyTimer_1.Start ();
System. Threading. Thread myTimer_2 = new System. Threading. Thread (new System. Threading. ThreadStart (write_2 ));
MyTimer_2.Start ();
2. Use the timer to update the number of online users every 10 minutes to check whether the information of the daily traffic needs to be stored
Copy codeThe Code is as follows:
// Use the first timer to update the number of online users every 10 minutes
Private void write_1 ()
{
// Use the System. Timers. Timer class to store data every 10 minutes.
System. Timers. Timer myTimer1 = new System. Timers. Timer (600000); // instantiate the Timer class and set the interval to 600000 milliseconds (the total number of persons saved once in 10 minutes );
MyTimer1.Enabled = true; // whether to execute the System. Timers. Timer. Elapsed event;
MyTimer1.Elapsed + = new System. Timers. ElapsedEventHandler (myTimer_Elapsed); // execute the event myTimer_Elapsed at the arrival time;
MyTimer1.AutoReset = true; // set whether to execute once (false) or always execute (true );
}
// Use the second timer,
Private void write_2 ()
{
// The following uses the System. Timers. Timer class to check whether traffic is saved for one day every 10 minutes.
System. Timers. Timer myTimer2 = new System. Timers. Timer (600000); // instantiate the Timer class and set the interval to 600000 milliseconds (the total number of persons saved once in 10 minutes );
MyTimer2.Enabled = true; // whether to execute the System. Timers. Timer. Elapsed event;
MyTimer2.Elapsed + = new System. Timers. ElapsedEventHandler (myTimer_peopleDay); // execute the event myTimer_peopleDay when the arrival time;
MyTimer2.AutoReset = true; // set whether to execute once (false) or always execute (true );
}
3. Create a myTimer process to process online users and collect daily, monthly, and yearly traffic.
Copy codeThe Code is as follows:
// Create the myTimer_Elapsed process and define the first timer event. The code used to process the number of online users
Private void myTimer_Elapsed (object sender, System. Timers. ElapsedEventArgs e)
{
// If the number of current users is greater than the number of current users, replace the number of current users in the data table.
Int MaxOnline = Convert. ToInt32 (Application ["OnlineMax"]);
Int MinOnline = Convert. ToInt32 (Application ["OnlineWhx"]);
If (MaxOnline <MinOnline)
{
SqlConnection con = Db. DB. createconnection ();
Con. Open ();
SqlCommand cmd = new SqlCommand ("update countpeople set totol = '" + Application ["countSession"]. toString () + "', OnLine = +'" + Application ["onlineWhx"] + "', DataTimes ='" + DateTime. now. toString ("yyyy-MM-dd HH: mm: ss") + "'", con );
Cmd. ExecuteNonQuery ();
Con. Close ();
Application ["OnlineMax"] = Application ["OnlineWhx"]; // assign the current number of online users to OnlineMax
Application ["dataTimes"] = DateTime. Now. ToString ("yyyy-MM-dd HH: mm: ss ");
}
Else
{
// Write the total number of visitors to the database
SqlConnection con = Db. DB. createconnection ();
Con. Open ();
SqlCommand cmd = new SqlCommand ("update countpeople set totol =" + Application ["countSession"]. ToString (), con );
Cmd. ExecuteNonQuery ();
Con. Close ();
}
}
// Create the myTimer_peopleDay process and define the second timer event to count the daily, monthly, and yearly traffic
Private void myTimer_peopleDay (object sender, System. Timers. ElapsedEventArgs e)
{
Try
{
// 24 o'clock that night
If (DateTime. Now. Hour = 23)
{
If (DateTime. Now. Minute> = 50)
{
// Write traffic for one day at 24 o'clock that day
// Initialize an iP Address Data Access Object
IPControl cont = new IPControl ();
// Obtain today's traffic
Int32 countToday = Convert. ToInt32 (cont. GetToday ());
// Obtain the traffic volume for this month
Int32 countMonth = Convert. ToInt32 (cont. GetMonth ());
// Name of the stored procedure sp_InsertCountPeopleDay
SqlConnection con1 = Db. DB. createconnection ();
Con1.Open ();
SqlCommand cmd1 = new SqlCommand ("sp_insertcountleleday", con1 );
Statement 1.commandtype = CommandType. StoredProcedure; // name of the stored procedure
// Call and set stored procedure parameters
Parameters 1.parameters. Add (new SqlParameter ("@ peopleDay", SqlDbType. Int ));
Parameters 1.parameters. Add (new SqlParameter ("@ dateTimes", SqlDbType. DateTime ));
// Assign a value to the parameter
Parameters 1.parameters ["@ peopleDay"]. Value = countToday;
Parameters 1.parameters ["@ dateTimes"]. Value = DateTime. Now. ToString ("yyyy-MM-dd HH: mm: ss ");
Statement 1.executenonquery ();
Con1.Close ();
// Write the traffic volume for this month on the last day of the month
// Obtain the last day of the month (30 or 31)
DateTime lastDay = Convert. ToDateTime (DateTime. Now. AddMonths (1). ToString ("yyyy-MM-01"). AddDays (-1 );
Int lastDay1 = DateTime. Now. Day; // the date of the current time.
If (lastDay1.ToString () = lastDay. ToString () // if the date is the date of the last day of the month, the traffic of the previous month is written to the database.
{
SqlConnection conM = Db. DB. createconnection ();
ConM. Open ();
SqlCommand cmdM = new SqlCommand ("sp_insertcountlelemonth", conM );
CmdM. CommandType = CommandType. StoredProcedure; // name of the stored procedure
// Call and set stored procedure parameters
CmdM. Parameters. Add (new SqlParameter ("@ peopleMonth", SqlDbType. Int ));
CmdM. Parameters. Add (new SqlParameter ("@ dateTimeMonth", SqlDbType. DateTime ));
// Assign a value to the parameter
CmdM. Parameters ["@ peopleMonth"]. Value = countMonth;
CmdM. Parameters ["@ dateTimeMonth"]. Value = DateTime. Now. ToString ("yyyy-MM-dd HH: mm: ss ");
CmdM. ExecuteNonQuery ();
ConM. Close ();
}
}
}
}
Catch
{
}
}