Web site Traffic Statistics method code in ASP

Source: Internet
Author: User
First, establish a data table Ipstat for storing user information

The user information I store in the Ipstat table only includes the logged-on user's IP (ip_address), IP source (IP_SRC) and logon time (Ip_datetime), the information of the tables I only save one day of information, if you want to count the information for each month to be kept for one months. Because I don't quite understand the operation of the data log, so I created this table, so I am stupid, haha.

Ii. Obtaining user information in Global.asax

Get information about Global.asax's Session_Start, when new session is enabled, and the number of people who are online and the total number of visitors, the code is as follows:

void Session_Start (object sender, EventArgs e) {//Get the visitor's ipstring ipAddress = request.servervariables["REMOTE_ADDR"];// Gets the source of the visitor string ipsrc;//determines whether to navigate from the search engine if (request.urlreferrer = = null) {ipsrc = "";} else{//Get Source Address ipsrc = Request.UrlReferrer.ToString ();} Gets the access time for DateTime Ipdatetime = datetime.now;//to save the IP information to the database Ipcontrol cont = new Ipcontrol (); Cont. Addip (ipAddress, IPSRC, ipdatetime);//Gets the page accessed by the user string pageurl = Request.Url.ToString ();//Determines whether the access is the default page if (Pageurl. EndsWith ("ipstat.aspx")) {//Lock variable Application.Lock ();//For page traffic +1application["statcount"] = Int. Parse (application["Statcount"). ToString ()) + 1;//unlock application.unlock ();} Lock variable session.timeout = 10; Set timeout to 10 minutes application.lock ();  application["countsession"] = Convert.ToInt32 (application["countsession"]) + 1; Total number of visits +1application["ONLINEWHX"] = (int) application["ONLINEWHX"] + 1; Online number plus +1session["login_name"] = null;//unlock application.unlock ();}

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

void Session_End (object sender, EventArgs e) {//code that runs at the end of the session. Note: The Session_End event is 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 -1session["login_name"] = null;//unlock application.unlock ();}

Third, save the above information to the database Ipstat

A class Ipcontrol () that obtains IP data information is created to implement operations on the database Ipstat data, about the contents 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 on the link to view it.

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

Save the 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 to enter time.

IV. Create timers and operate the relevant data on a timed basis

To the above Ipsta database data, you need to create one or several timers, and 10 seconds before 24 o'clock every night to count the day's traffic, and then delete it, save the results to another data table, for the page to display yesterday's visit is called. Timer creation and use Click Create one or several timers for your reference.

Please criticize me for the above irregularities. Thank you!

Web site Access Statistics in ASP-class for obtaining IP data information

Using system;using system.data;using system.data.sqlclient;using system.text;//////public class for IP data information The ipcontrol{//constant is used to represent the variable name in the T-SQL statement Private Const string parm_ip_address = "@IPAddress";p rivate const string PARM_IP_SRC = "@IPSrc";p rivate const string parm_ip_datetime = "@IPDateTime";//t-sql statement Private Const string sql_insert_ipstat = "INSERT Into Ipstat VALUES (@IPAddress, @IPSrc, @IPDateTime) ";p rivate const string sql_delete_ipstat =" DELETE from Ipstat WHERE DAT Ediff (D,ip_datetime,getdate ()) >30 "; Only one months of data are reserved Private Const string sql_select_total = "Select COUNT (*) from Ipstat";p rivate const string sql_select_today = "Select COUNT (*) from Ipstat WHERE DATEDIFF (D,ip_datetime,getdate ()) =0";p rivate const string sql_select_yesterday = " Select COUNT (*) from Ipstat WHERE DATEDIFF (D,ip_datetime,getdate ()) =1 ";p rivate const string sql_select_month =" Select CO UNT (*) from Ipstat WHERE DATEDIFF (D,ip_datetime,getdate ()) <30 and DATEDIFF (Mm,ip_datetime,getdate ()) =0 ";p ublic Ipcontrol () {}Save IP data information to database///////public void Addip (string ipaddress,string ipsrc,datetime ipdatetime) {// Build the connection statement string StringBuilder strSQL = new StringBuilder ();//Create a parameter that represents the QQ number sqlparameter[] parms = new sqlparameter[] {new Sqlparame ter (parm_ip_address, SqlDbType.NVarChar, a), 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 in which the object resource is saved and, once the using scope ends, frees the resource using (SqlConnection conn = new SqlConnection ( Sqlhelper.connectionstringlocaltransaction)) {//Load INSERT statement strsql.append (Sql_insert_ipstat) in execution string; conn. Open ();//Set SqlCommand property 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 () {//Calls SqlHelper access the component's method to returnBack to the first row the value of the first Column object count = Sqlhelper.executescalar (sqlhelper.connectionstringlocaltransaction, CommandType.Text, SQL_ Select_total, NULL);//Returns the statistic result return count. ToString ();} public string Gettoday () {///call SqlHelper to access the component returns the value of the first column of the first row, object count = Sqlhelper.executescalar ( Sqlhelper.connectionstringlocaltransaction, CommandType.Text, sql_select_today, NULL);//Returns the statistic result return count. ToString ();} public string Getyesterday () {///call SqlHelper to access the component returns the value of the first column of the first row, object count = Sqlhelper.executescalar ( Sqlhelper.connectionstringlocaltransaction, CommandType.Text, sql_select_yesterday, NULL);//Returns the statistic result return count. ToString ();} public string GetMonth () {///call SqlHelper to access the component returns the value of the first column of the first row, object count = Sqlhelper.executescalar ( Sqlhelper.connectionstringlocaltransaction, CommandType.Text, sql_select_month, NULL);//Returns the statistic result 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

The following is a processing method 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 online population check if you want to deposit the information of the day traffic

Use the first timer to update the number of online users every 10 minutes private void Write_1 () {//below use System.Timers.Timer class to save data System.Timers.Timer every 10 minutes per interval myTimer1 = new System.Timers.Timer (600000); Instantiate the Timer class, set the interval to 600000 milliseconds (10 minutes to save the total); mytimer1.enabled = true; Whether the System.Timers.Timer.Elapsed event is performed; mytimer1.elapsed + = new System.Timers.ElapsedEventHandler (mytimer_elapsed); Execution event mytimer_elapsed at time of arrival; Mytimer1.autoreset = true; Whether the setting is executed once (false) or always (true);}//uses the second timer, private void write_2 () {//below using the System.Timers.Timer class Check to see if you want to deposit one day's traffic every 10 minutes System.Timers.Timer MyTimer2 = new System.Timers.Timer (600000); Instantiate the Timer class, set the interval to 600000 milliseconds (10 minutes to save the total); mytimer2.enabled = true; Whether the System.Timers.Timer.Elapsed event is performed; mytimer2.elapsed + = new System.Timers.ElapsedEventHandler (mytimer_peopleday); Execution event Mytimer_peopleday at time of arrival; Mytimer2.autoreset = true; Whether the setting is executed once (false) or always (true);}

III. Create a MyTimer process to handle online numbers and statistics daily, monthly, and yearly traffic

Create a mytimer_elapsed procedure and define the first timer event to be used to process the online number of code private void Mytimer_elapsed (object sender, System.Timers.ElapsedEventArgs e) {//If the present number of people is greater than the original in the present number, the replacement data table in the present number of people 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 onlinemaxapplication["datatimes" = DateTime.Now.ToString ("Yyyy-mm-dd HH:mm:ss");} else{//writes 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 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 that evening if (DateTime.Now.Hour = =) {if (DateTime.Now.Minute >= 50) {//the same night 24 o'clock, write a day's traffic// Initializes an IP data Access object Ipcontrol cont = new Ipcontrol ();//Get today's traffic Int32 counttoday = Convert.ToInt32 (cont. Gettoday ());//Get this month's traffic Int32 countmonth = Convert.ToInt32 (cont. GetMonth ());//stored procedure name Sp_insertcountpeopledaysqlconnection Con1 = Db.DB.createconnection (); Con1. Open (); SqlCommand cmd1 = new SqlCommand ("Sp_insertcountpeopleday", con1); cmd1.commandtype = CommandType.StoredProcedure; Stored Procedure name//call and set stored procedure parameter cmd1. Parameters.Add (New SqlParameter ("@peopleDay", SqlDbType.Int)); cmd1. Parameters.Add (New SqlParameter ("@dateTimes", Sqldbtype.datetime));//assigns a value cmd1 to a parameter. parameters["@peopleDay"]. Value = counttoday;cmd1. parameters["@dateTimes"]. Value = DateTime.Now.ToString ("Yyyy-mm-dd HH:mm:ss"); cmd1. ExecuteNonQuery (); Con1. Close ();//On the last day of one months write this month's visit volume//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 date of the last day of the month, the previous month's traffic 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//call and set stored procedure parameter 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{}}
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.