I need to set a Custom Dimension from the server side, I am trying this request:
In the "t" value I also try "event" and "pageview" but it doesn't work.
I created this class for do the request.
public static class GoogleAnalyticsServerSide
{
private static string googleURL = "http://www.google-analytics.com/collect";
private static string googleVersion = "1";
private static string googleTrackingID = "UA-XXXXXX-X";
private static string googleClientID = "111111111.11111111";
private static Dictionary<string, string> baseValues()
{
Dictionary<string, string> data = new Dictionary<string, string>();
data.Add("v", googleVersion); // Version.
data.Add("tid", googleTrackingID); // Tracking ID / Web property / Property ID.
data.Add("cid", googleClientID); // Anonymous Client ID.
return data;
}
public static void TrackEvent(string category, string action, string label)
{
Dictionary<string, string> postData = new Dictionary<string, string>();
postData = baseValues();
postData.Add("t", "event");
postData.Add("ec", category);
postData.Add("ea", action);
postData.Add("el", label);
Track(postData);
}
public static void TrackCustomDimension(string index, string value)
{
Dictionary<string, string> postData = new Dictionary<string, string>();
postData = baseValues();
postData.Add("t", "all");
postData.Add("cd" + index, value);
Track(postData);
}
private static void Track(Dictionary<string, string> postData)
{
try
{
var request = (HttpWebRequest)WebRequest.Create(googleURL);
request.Method = "POST";
var postDataString = postData
.Aggregate("", (data, next) => string.Format("{0}&{1}={2}", data, next.Key,
HttpUtility.UrlEncode(next.Value)))
.TrimEnd('&');
// set the Content-Length header to the correct value
request.ContentLength = Encoding.UTF8.GetByteCount(postDataString);
// write the request body to the request
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");
}
}
catch (Exception ex)
{
}
}
catch (Exception e)
{
}
}
}
The class works well because if I use the TrackEvent
method it works. I am not sure if I missing something in the post request of Custom Dimension.
Thanks in advance.
I'm not sure what you mean by "it doesn't work" because what you have looks fine to me.
Regardless, you should try using the Measurement Protocol Hit Builder to create and validate your hits prior to sending them, just to make sure all required fields are there.
If you want to validate your hits in code, you send your hits to the Measurement Protocol Validation Server to check their validity before sending them to Google Analytics. The hit builder actually uses this tool under the hood to validate the hits.