HOME   ARTICLES   DIRECTORY   CONTACT   ABOUT 

Article Menu
superdotnet originals
Intro Lessons
Tips and Tricks
Data Access
Code-Behind/Controls
Quick Code
General ASP.NET
Windows Forms

All Articles
Reader Comments

Resource Options
Alphabetically
Directory

Hosts
.NET Hosts

More Resources
Namespace List
More MSDN Links
QuickStart Lists


Google



Gathering your own site statistics
Article Categories: Data Access | Quick Code
Rated: | Number Of Ratings 4 | Add Rating/View Ratings


For any site, knowing user statistics are vital for usability, marketing, and maintenance. While there are many programs that analyze log files, sometimes you may want to keep your own records of page views and user access allowing you to better filter through data, as well as reconcile the differences among the many stats programs (the more information you have to work with, the better your reporting and results will be).

An easy way to accomplish this is by using the Global.asax and Application_BeginRequest which is fired each time a user accesses an aspx page in your application. In the code below we're just grabbing the user information we want to log each time a user views a page in the application, and then storing that in our SQL Server database.

<%@ Language="C#" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>

<script runat="server">

void Application_Start(Object Sender, EventArgs e)
{

}

void Application_BeginRequest(Object Sender, EventArgs e){
String PV_sql;

SqlConnection PV_conn = new SqlConnection(ConfigurationSettings.AppSettings["SqlDataSource"]);
PV_conn.Open();
PV_sql="INSERT INTO PageViews(PageAccessed,QueryString,IpAddress,Referer,UserAgent) " +
	"VALUES(" +
	"'" + Request.ServerVariables["URL"]+"'," +
	"'" + Request.ServerVariables["QUERY_STRING"] +"'," +
	"'" + Request.ServerVariables["REMOTE_ADDR"] +"'," +
	"'" + Request.ServerVariables["HTTP_REFERER"] +"'," +
	"'" + Request.ServerVariables["HTTP_USER_AGENT"] +"')";
	
SqlCommand PV_conncommand = new SqlCommand(PV_sql,PV_conn);
PV_conncommand.ExecuteNonQuery();
PV_conncommand.Dispose();
PV_conn.Close();
PV_conn.Dispose();
}

void Session_Start(Object Sender, EventArgs e)
{

}

void Session_End(Object Sender, EventArgs e)
{

}

void Application_EndRequest(Object sender, EventArgs E) {

}

void Application_End(Object Sender, EventArgs e)
{

}
</script>

As you can see, the code is pretty easy and self-explanatory. We're just opening up a connection and then inserting the Request variables like the current page, any querystring information, the IP address of the client, referrer, and user agent, and then inserting that into our table called PageViews.



Advertisement

Copyright superdotnet.com, all rights reserved. Original articles and site content may not be reproduced from our site without consent from superdotnet.com.
Privacy Policy and User Site Agreement