/
GoogleAnalyticsApi.cs
86 lines (76 loc) · 2.9 KB
/
GoogleAnalyticsApi.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;
namespace GAEvents
{
public class GoogleAnalyticsApi
{
private const string trackingId = "UA-35473401-2";
public static void TrackEvent(string category, string action, string label, int? value = null)
{
Track(HitType.@event, category, action, label, value);
}
public static void TrackPageview(string category, string action, string label, int? value = null)
{
Track(HitType.@pageview, category, action, label, value);
}
private static void Track(HitType type, string category, string action, string label,
int? value = null)
{
if (string.IsNullOrEmpty(category)) throw new ArgumentNullException("category");
if (string.IsNullOrEmpty(action)) throw new ArgumentNullException("action");
var request = (HttpWebRequest)WebRequest.Create("http://www.google-analytics.com/collect");
request.Method = "POST";
request.KeepAlive = false;
var postData = new Dictionary<string, string>
{
{ "v", "1" },
{ "tid", trackingId },
{ "cid", "555" },
{ "t", type.ToString() },
{ "ec", category },
{ "ea", action },
};
if (!string.IsNullOrEmpty(label))
{
postData.Add("el", label);
}
if (value.HasValue)
{
postData.Add("ev", value.ToString());
}
var postDataString = postData
.Aggregate("", (data, next) => string.Format("{0}&{1}={2}", data, next.Key,
HttpUtility.UrlEncode(next.Value)))
.TrimEnd('&');
request.ContentLength = Encoding.UTF8.GetByteCount(postDataString);
using (var writer = new StreamWriter(request.GetRequestStream()))
{
writer.Write(postDataString);
}
try
{
var webResponse = (HttpWebResponse)request.GetResponse();
if (webResponse.StatusCode != HttpStatusCode.OK)
{
throw new HttpException((int)webResponse.StatusCode,
"Google Analytics tracking did not return OK 200");
}
webResponse.Close();
}
catch (Exception ex)
{
Console.Out.WriteLine(ex.Message);
}
}
private enum HitType
{
@event,
@pageview,
}
}
}