Skip to content

Instantly share code, notes, and snippets.

@jmhdez
Forked from gregoryyoung/analytics.cs
Created March 19, 2012 09:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jmhdez/2105391 to your computer and use it in GitHub Desktop.
Save jmhdez/2105391 to your computer and use it in GitHub Desktop.
Usage Tracking with Google Analytics
public class TrackingService
{
// Sample usage:
// service.TrackEvent("customers/add");
// service.TrackEvent("order/discount-applied");
public void TrackEvent(string path)
{
ThreadPool.QueueUserWorkItem(x => TrackPageView("/events/" + path));
}
private const string VERSION = "4.4sa";
private static readonly int VISITOR = Guid.NewGuid().GetHashCode();
private void TrackPageView(string path)
{
try
{
var connection = WebRequest.Create(GetGAUrl(path));
((HttpWebRequest)connection).UserAgent = "";
connection.Headers.Add("Accept-Language", "EN-US");
using (connection.GetResponse())
{
// Ignore response
}
}
catch
{
// Swallow exception. It could be logged
}
}
private static string GetGAUrl(string path)
{
const string DOMAIN = "mydomain.com";
const string RESOURCE = "myapp";
const string GA_ACCOUNT = "MO-111111-1";
return "http://www.google-analytics.com/__utm.gif" + "?" +
"utmwv=" + VERSION +
"&utmn=" + GetRandomNumber() +
"&utmhn=" + DOMAIN +
"&utmr=" + RESOURCE +
"&utmp=" + path.Replace("/", "%2F") +
"&utmac=" + GA_ACCOUNT +
"&utmcc=__utma%3D999.999.999.999.999.1%3B" +
"&utmvid=" + (VISITOR - DateTime.Today.GetHashCode());
}
private static string GetRandomNumber()
{
return new Random().Next(0x7fffffff).ToString();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment