ASP.net website Traffic Statistics Method Code _ Practical Skills

Source: Internet
Author: User
Tags datetime get ip getdate first row time interval

First, the establishment of a data table Ipstat for the storage of user information

The user information I hold in the Ipstat table includes only the IP (ip_address) of the logged-on user, the IP source (ip_src) and the login time (ip_datetime), the information of some tables I only keep one day's information, if the information to be counted each month will be kept for one months. Because I do not understand the operation of the data log, so create this table, so say I stupid, haha.

Second, in the Global.asax to obtain the user information

Get the information when the Global.asax Session_Start is enabled for a new session, with the number of online people and the incremental statistics for the total number of visitors, as follows:

Copy Code code as follows:

void Session_Start (object sender, EventArgs e)
{
Get the IP of the visitor
string ipaddress = request.servervariables["REMOTE_ADDR"];
Get the source of the visitor
String ipsrc;
To determine if the search engine has navigated
if (Request.urlreferrer = null)
{
IPSRC = "";
}
Else
{
Get Source Address
IPSRC = Request.UrlReferrer.ToString ();
}
Get access Time
DateTime ipdatetime = DateTime.Now;
Save IP information to the database
Ipcontrol cont = new Ipcontrol ();
Cont. Addip (IPAddress, IPSRC, Ipdatetime);

Get the page that the user visited
String pageurl = Request.Url.ToString ();
Determines whether the access is a default page
if (Pageurl. EndsWith ("ipstat.aspx"))
{
Lock variable
Application.Lock ();
+1 for page traffic
application["Statcount"] = Int. Parse (application["Statcount"). ToString ()) + 1;
Unlock
Application.UnLock ();
}

Lock variable
Session.Timeout = 10; Set timeout of 10 minutes
Application.Lock ();
application["countsession"] = Convert.ToInt32 (application["countsession"]) + 1; Total number of visits +1
application["ONLINEWHX"] = (int) application["ONLINEWHX"] + 1; Online number plus +1
session["login_name"] = null;
Unlock
Application.UnLock ();
}

As a reminder, don't forget the following code to make the number of people online minus 1 when the user is offline.

Copy Code code as follows:

void Session_End (object sender, EventArgs e)
{
Code that runs at the end of the session.
Note: Session_End events are raised only if the sessionstate mode in the Web.config file is set to InProc. If the session mode is set to StateServer
or SQL Server, the event is not raised.

Lock variable
Application.Lock ();
application["ONLINEWHX"] = (int) application["ONLINEWHX"]-1; Online number minus 1
session["login_name"] = null;
Unlock
Application.UnLock ();
}

Third, save the above information to the database Ipstat

Created a class Ipcontrol () to obtain IP data information, which is used to implement the operation of IPSTAT data on the database, the content of the Ipcontrol () class, because it is the operation of the database in C # to solve the SQL Server database, you can understand it, here is not introduced, Please click the link to view.

In order to implement the user IP information into the database, in the above code to Ipcontrol () to call

Copy Code code as follows:

Save IP information to the database
Ipcontrol cont = new Ipcontrol ();
Cont. Addip (IPAddress, IPSRC, Ipdatetime);

Parameter ipaddress for user ip,ipsrc as user source, Ipdatetime for user access time.

Four, create timer, timed operation of the data

For the above Ipsta database data, need to create one or several timers, and every night before 24 o'clock in 10 seconds to count the flow of the day, and then delete it, the results are saved to another data table for the page to display yesterday traffic is called. The creation and use of timers please click to create one or several timers for your reference.

Please criticize the above irregularities. Thank you!

Web site traffic statistics in asp.net-class for obtaining IP data information

Copy Code code as follows:

Using System;
Using System.Data;
Using System.Data.SqlClient;
Using System.Text;

///
///class
///
public class Ipcontrol
{
//constants to get IP data information to represent the variable name used in a 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"; Keep only one months of data
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 D DATEDIFF (Mm,ip_datetime,getdate ()) =0 ";

Public Ipcontrol ()
{
}
///
Save IP data information to the database
///
///
///
public void Addip (string ipaddress,string ipsrc,datetime ipdatetime)
{
Building a Connection statement string
StringBuilder strSQL = new StringBuilder ();
Create a parameter that represents 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 a value to the parameter in turn and add it to the execution statement
Parms[0]. Value = IPAddress;
PARMS[1]. Value = IPSRC;
PARMS[2]. Value = Ipdatetime;
foreach (SqlParameter parm in parms)
Cmd. Parameters.Add (Parm);

Defines the scope of the object resource save, and releases the resource of the other when the using scope ends
using (SqlConnection conn = new SqlConnection (Sqlhelper.connectionstringlocaltransaction))
{
Loading the INSERT statement in the execution string
Strsql.append (Sql_insert_ipstat);
Conn. Open ();

Set the SqlCommand properties
Cmd. Connection = conn;
Cmd.commandtype = CommandType.Text;
Cmd.commandtext = Strsql.tostring ();
Execute SqlCommand command
Cmd. ExecuteNonQuery ();
Cmd. Parameters.clear ();
If execution succeeds, returns True, otherwise false.
}
}
public string Gettotal ()
{
The method that invokes the SqlHelper access component returns the value of the first column in the first row
Object count = Sqlhelper.executescalar (sqlhelper.connectionstringlocaltransaction, CommandType.Text, SQL_SELECT_ Total, null);
Return statistic Results
return count. ToString ();
}
public string Gettoday ()
{
The method that invokes the SqlHelper access component returns the value of the first column in the first row
Object count = Sqlhelper.executescalar (sqlhelper.connectionstringlocaltransaction, CommandType.Text, SQL_SELECT_ Today, NULL);
Return statistic Results
return count. ToString ();
}
public string Getyesterday ()
{
The method that invokes the SqlHelper access component returns the value of the first column in the first row
Object count = Sqlhelper.executescalar (sqlhelper.connectionstringlocaltransaction, CommandType.Text, SQL_SELECT_ Yesterday, NULL);
Return statistic Results
return count. ToString ();
}
public string getmonth ()
{
The method that invokes the SqlHelper access component returns the value of the first column in the first row
Object count = Sqlhelper.executescalar (sqlhelper.connectionstringlocaltransaction, CommandType.Text, SQL_SELECT_ MONTH, NULL);
Return statistic Results
return count. ToString ();
}
}

Use timers in Global.asax to count online numbers and monthly visits per day

First, create the timer in the Application_Start

Copy Code code as follows:

The following are the processing methods for using multiple timer System.Timers.Timer
Re-wrap with thread, 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 ();

second, use the timer every 10 minutes to update the number of online check whether to deposit a day of traffic information

Copy Code code as follows:

//Use the first timer, update online number every 10 minutes
private void Write_1 ()
{
//below uses system . Timers.timer class saves data every 10 minutes
System.Timers.Timer myTimer1 = new System.Timers.Timer (600000);//Instantiate Timer class, Set interval of 600000 milliseconds (total number of 10 minutes);
mytimer1.enabled = true;/whether to execute System.Timers.Timer.Elapsed event;
mytimer1.elapsed + + new System.Timers.ElapsedEventHandler (mytimer_elapsed); Executes the event mytimer_elapsed at the time of arrival
Mytimer1.autoreset = true;//Set to execute once (false) or always (true);

//Use the second timer,
private void write_2 ()
{
//The following uses the System.Timers.Timer class to check whether you want to deposit one day's traffic at a 10-minute interval
System.Timers.Timer myTimer2 = New System.Timers.Timer (600000); Instantiate the Timer class, setting a time interval of 600000 milliseconds (10 minutes for the total number of people);
mytimer2.enabled = true;//whether to perform System.Timers.Timer.Elapsed events;
mytimer2.elapsed + = new System.Timers.ElapsedEventHandler (mytimer_peopleday); Execution of event Mytimer_peopleday at time of arrival
Mytimer2.autoreset = true;//Set to execute once (false) or always (true);

Third, create MyTimer process to deal with online numbers and statistics daily, month, year of traffic

Copy Code code as follows:

Create the mytimer_elapsed process and define the first timer event, the code to be used to process the number of people online
private void Mytimer_elapsed (object sender, System.Timers.ElapsedEventArgs e)
{
If the current number is larger than the current number, replace the current number in the datasheet
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 line number to Onlinemax
application["datatimes"] = DateTime.Now.ToString ("Yyyy-mm-dd HH:mm:ss");
}
Else
{
Write 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 a second timer event to be used to count the daily, monthly, and yearly traffic
private void Mytimer_peopleday (object sender, System.Timers.ElapsedEventArgs e)
{
Try
{
24 O'Clock the same night.
if (DateTime.Now.Hour = 23)
{
if (DateTime.Now.Minute >= 50)
{
The same night 24 o'clock, writing a day's traffic
Initialization of an IP data Access object
Ipcontrol cont = new Ipcontrol ();
Get the number of visits today
Int32 counttoday = Convert.ToInt32 (cont. Gettoday ());
Get the number of visits this month
Int32 countmonth = Convert.ToInt32 (cont. GetMonth ());

Stored Procedure name Sp_insertcountpeopleday
SqlConnection con1 = Db.DB.createconnection ();
Con1. Open ();
SqlCommand cmd1 = new SqlCommand ("Sp_insertcountpeopleday", Con1);
Cmd1.commandtype = CommandType.StoredProcedure; Stored Procedure Name

Calling and setting stored procedure parameters
Cmd1. Parameters.Add (New SqlParameter ("@peopleDay", SqlDbType.Int));
Cmd1. Parameters.Add (New SqlParameter ("@dateTimes", Sqldbtype.datetime));

Assigning values to a parameter
Cmd1. parameters["@peopleDay"]. Value = Counttoday;
Cmd1. parameters["@dateTimes"]. Value = DateTime.Now.ToString ("Yyyy-mm-dd HH:mm:ss");

Cmd1. ExecuteNonQuery ();
Con1. Close ();

Write this month's visit on the last day of one months
Take the last day of the month (30 or 31st)
DateTime Lastday = Convert.todatetime (DateTime.Now.AddMonths (1). ToString ("yyyy-mm-01")). AddDays (-1);
int lastDay1 = DateTime.Now.Day; Take the date of the current time
if (lastday1.tostring () = Lastday.tostring ())////If the previous date equals the last day of this month, the traffic for the previous month is written to the database
{
SqlConnection conm = Db.DB.createconnection ();
Conm.open ();
SqlCommand CmdM = new SqlCommand ("Sp_insertcountpeoplemonth", conm);
Cmdm.commandtype = CommandType.StoredProcedure; Stored Procedure Name

Calling and setting stored procedure parameters
CMDM.PARAMETERS.ADD (New SqlParameter ("@peopleMonth", SqlDbType.Int));
CMDM.PARAMETERS.ADD (New SqlParameter ("@dateTimeMonth", Sqldbtype.datetime));

Assigning values to a parameter
cmdm.parameters["@peopleMonth"]. Value = Countmonth;
cmdm.parameters["@dateTimeMonth"]. Value = DateTime.Now.ToString ("Yyyy-mm-dd HH:mm:ss");

Cmdm.executenonquery ();
Conm.close ();
}
}
}
}
Catch
{

}
}

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.