0 Comments
  •   Posted in: 
  • C#

google-analytics-logo

Everybody who has a website should have Google Analytics. It is awesome and moreover:

It is free!

There are still people who do not like the idea that Google knows everything about their visitors. And I do know that there might be a new law in a year which prohibits the use of cookies which is also used in Google Analytics. So let’s hope that EDPS cancels it’s upcoming law.

My situation:

There is this email newsletter application which has a list of all the mailings so far, and I would like to add the conversion ratio from the send mailing next to it. To achieve it, I prepared the following (which I will not cover in this blog post)

  1. I have added the Google Analytics tracking code to the site and verified that it works.
  2. I have added query parameters to each link in our HTML email newsletter with the URL Builder tool provided by Google.      [more]

    My query parameter additions:

    &utm_source=nl&utm_medium=email&utm_campaign=nl1004


    as campaign I chose this format so that I can distinguish the following: NewsLetter2010-April.

  3. I have already send the newsletter and have statistics in my Analytics account under the Traffic sources –> Campaign

 

The C# solution:

You have to start off by building the correct query to retrieve de desired results. Therefore I used the Data Feed Query Explorer (again a tool provided by Google)

My URL to retrieve the results from looks like this:

https://www.google.com/analytics/feeds/data?ids=accountIdFromGoogleAnalytics&dimensions=ga%3Acampaign&metrics=ga%3Atransactions%2Cga%3AtransactionRevenue%2Cga%3Avisits%2Cga%3AuniquePageviews&start-date=2010-04-22&end-date=2010-04-25&max-results=250

I have taken the GAnalyticsAPI class from

http://blogs.freshlogicstudios.com/Posts/View.aspx?Id=fc73a272-c361-4ed9-b9f0-1716e96701d7

and added this method (because I did not get it to work with the SyndicationFeed object.

public static XmlDocument GetDataFeedV2(string authorizationToken, string profileId, DateTime startDate, DateTime endDate, string metrics, string dimensions, string sort, int? maxResults, string filters)
    {
        using (var webClient = new WebClient())
        {
            var query = HttpUtility.ParseQueryString(String.Empty);
            query.Add("ids", profileId);
            query.Add("start-date", startDate.ToString("yyyy-MM-dd"));
            query.Add("end-date", endDate.ToString("yyyy-MM-dd"));
            query.Add("metrics", metrics);

            if (!String.IsNullOrEmpty(dimensions))
            {
                query.Add("dimensions", dimensions);
            }

            if (!String.IsNullOrEmpty(sort))
            {
                query.Add("sort", sort);
            }
            if (!String.IsNullOrEmpty(filters))
            {
                query.Add("filters", filters);
            }

            if (maxResults.HasValue)
            {
                query.Add("max-results", maxResults.Value.ToString());
            }

            var uri = new UriBuilder("https://www.google.com/analytics/feeds/data");
            uri.Query = query.ToString();

            webClient.Headers.Add("GData-Version", "2");
            webClient.Headers.Add("Authorization", String.Format("GoogleLogin Auth={0}", authorizationToken));

            var response = webClient.DownloadString(uri.Uri.AbsoluteUri);
            XmlDocument xmld = new XmlDocument();
            xmld.Load(XmlReader.Create(new StringReader(response)));
            return xmld;
        }
    }

 

After that addition to the class, you can use it like this:

	string strGoogleAnalyticsAccountID = "fill in your GA id, for instance ga:123456";
        
        if (strGoogleAnalyticsAccountID.Length > 0)
        {
            string authToken    = GAnalyticsAPI.GetAuthorizationToken("yourGoogleAccountLoginName", "yourGoogleAccountPassword");
            string metrics      = Server.UrlDecode("ga%3Atransactions%2Cga%3AtransactionRevenue%2Cga%3Avisits%2Cga%3AuniquePageviews");
            string dimensions   = Server.UrlDecode("ga%3Acampaign");
            string filters      = Server.UrlDecode("ga%3Acampaign%3D~%5E" + campaignName);

            XmlDocument xmld = GAnalyticsAPI.GetDataFeedV2(authToken, strGoogleAnalyticsAccountID, DateTime.Now.AddDays(-10), DateTime.Now, metrics, dimensions, "", null, filters);
            string result ="";
            XmlNamespaceManager xmlnsm = new XmlNamespaceManager(xmld.NameTable);
            xmlnsm.AddNamespace("dxp", "http://schemas.google.com/analytics/2009");
            xmlnsm.AddNamespace("openSearch", "http://a9.com/-/spec/opensearch/1.1/");
            xmlnsm.AddNamespace("gd", "http://schemas.google.com/g/2005");

            foreach (XmlNode xmln in xmld.SelectNodes("//dxp:aggregates/dxp:metric", xmlnsm))
            {
                string val = xmln.Attributes["value"].Value;
                string name = xmln.Attributes["name"].Value.Replace("ga:", "");

                if (Convert.ToDouble(val) > 0)
                {
                    char[] nameAr = name.ToCharArray();
                    nameAr[0] = char.ToUpper(nameAr[0]);
                    if (val.Contains('.'))
                    {
                        val = val.Replace('.', ',');
                        val = Convert.ToDouble(val).ToString("C");
                    }
                    result += "";
                }
            }
            result += "
" + new string(nameAr) + "" + val + "
"; return result; } else { return ""; }

 

Ow for the best performance, you should replace the string concatenation with a System.Text.StringBuilder.

Good luck with the Google Analytics API!

kick it on DotNetKicks.com

Pin on pinterest Plus on Googleplus Post on LinkedIn