-
-
Save jmhdez/2105391 to your computer and use it in GitHub Desktop.
Usage Tracking with Google Analytics
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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