Click here to Skip to main content
15,879,474 members
Articles / Programming Languages / C#

Server-side Google Analytics Transactions

Rate me:
Please Sign up or sign in to vote.
4.86/5 (10 votes)
21 May 2013CPOL4 min read 42.5K   1.1K   25  
Handling Google Analytics Transactions on server-side using C# intead of JavaScript on client-side.
using System;
using System.Net;

namespace Middelpat.GoogleAnalytics
{
    public class GoogleRequest
    {
        private const string BASE_URL = "http://www.google-analytics.com/__utm.gif?";

        private const string ANALYTICS_VERSION = "5.3.7";
        private const string LANGUAGE_ENCODING = "UTF-8";
        private const string BROWSER_JAVA_ENABLED = "0";

        //Required parameters but not necessary for us, so just post a default
        private const string SCREEN_RESOLUTION = "1680x1050";
        private const string SCREEN_COLOR_DEPTH = "32-bit";
        private const string FLASH_VERSION = "11.5%20r31";
        private const string REFERAL = "0";

        //Internal request counter. Max requests = 500 per session
        private int _RequestCount = 0;

        private Random rand;

        /// <summary>
        /// Initialize a new GoogleRequest
        /// </summary>
        /// <param name="accountCode">Your Google tracking code (e.g. UA-12345678-1)</param>
        public GoogleRequest(string accountCode)
        {
            rand = new Random();

            _RequestCount = 0;
            AccountCode = accountCode;
        }

        /// <summary>
        /// Send the request to the google servers!
        /// </summary>
        /// <param name="eventObject">A corresponding Transaction, Page or Event</param>
        public void SendRequest(IGoogleEvent eventObject)
        {
            string requestUrl = BASE_URL + CreateParameterString() + "&" + eventObject.CreateParameterString();

            FireRequest(requestUrl);

            //A transaction also has subrequests for the TransactionItems
            if (eventObject is Transaction)
            {
                Transaction trans = eventObject as Transaction;

                foreach (TransactionItem transItem in trans.Items)
                {
                    FireRequest(BASE_URL + CreateParameterString() + "&" + transItem.CreateParameterString());
                }
            }
        }

        private void FireRequest(string url)
        {
            if (_RequestCount < 500)
            {
                _RequestCount++;

                WebRequest GaRequest = WebRequest.Create(url);

                GaRequest.BeginGetResponse(r =>
                {
                    try
                    {
                        // we don't need the response so this is the end of the request
                        var reponse = GaRequest.EndGetResponse(r);
                    }
                    catch
                    {
                        //eat the error 
                    }
                }, null);
            }
        }

        private string CreateParameterString()
        {
            return string.Format("utmwv={0}&utms={1}&utmn={2}&utmhn={3}&utmsr{4}&utmvp={5}&utmsc={6}&utmul={7}&utmje={8}&utmfl={9}&utmhid={10}&utmr={11}&utmp={12}&utmac={13}&utmcc={14}",
                                  ANALYTICS_VERSION,
                                  _RequestCount,
                                  GenerateRandomId(),
                                  HostName,
                                  SCREEN_RESOLUTION,
                                  SCREEN_RESOLUTION,
                                  SCREEN_COLOR_DEPTH,
                                  Culture,
                                  BROWSER_JAVA_ENABLED,
                                  FLASH_VERSION,
                                  GenerateRandomId(),
                                  "-",
                                  PageTitle,
                                  AccountCode,
                                  GetUtmcCookieString());
        }

        /// <summary>
        /// (utmn) A random id for each gif to prevent caching
        /// </summary>
        /// <returns></returns>
        private string GenerateRandomId()
        {
            string randomId = "";
      
            for (int i = 0; i < 10; i++)
            {
                randomId += rand.Next(9).ToString();
            }

            return randomId;
        }

        private int DomainHash
        {
            get
            {
                if (HostName != null)
                {
                    int a = 1;
                    int c = 0;
                    int h;
                    char chrCharacter;
                    int intCharacter;

                    a = 0;
                    for (h = HostName.Length - 1; h >= 0; h--)
                    {
                        chrCharacter = char.Parse(HostName.Substring(h, 1));
                        intCharacter = (int)chrCharacter;
                        a = (a << 6 & 268435455) + intCharacter + (intCharacter << 14);
                        c = a & 266338304;
                        a = c != 0 ? a ^ c >> 21 : a;
                    }

                    return a;
                }
                return 0;
            }
        }

        private string _UtmcCookieString = null;
        //The cookie collection string (we fake it)
        private string GetUtmcCookieString()
        {
            if (_UtmcCookieString == null)
            {
                //create the unix timestamp
                TimeSpan span = (DateTime.Now - new DateTime(1970, 1, 1, 0, 0, 0, 0).ToLocalTime());
                int timeStampCurrent = (int)span.TotalSeconds;

                string utma = String.Format("{0}.{1}.{2}.{3}.{4}.{5}",
                                            DomainHash,
                                            int.Parse(rand.Next(1000000000).ToString()),
                                            timeStampCurrent,
                                            timeStampCurrent,
                                            timeStampCurrent,
                                            "2");

                //referral information
                string utmz = String.Format("{0}.{1}.{2}.{3}.utmcsr={4}|utmccn={5}|utmcmd={6}",
                                            DomainHash,
                                            timeStampCurrent,
                                            "1",
                                            "1",
                                            "(direct)",
                                            "(direct)",
                                            "(none)");

                _UtmcCookieString = Uri.EscapeDataString(String.Format("__utma={0};+__utmz={1};", utma, utmz));
            }

            return (_UtmcCookieString);
        }

        #region get set

        private string _AccountCode;
        /// <summary>                           
        /// Your Google tracking code (e.g. UA-12345678-1)
        /// </summary>        
        public string AccountCode
        {
            get
            {
                return _AccountCode;
            }
            set
            {
                _AccountCode = value;
            }
        }

        private string _Culture;
        /// <summary>
        /// The language of the customer (e.g. nl-NL)
        /// </summary>
        public string Culture
        {
            get
            {
                if (string.IsNullOrWhiteSpace(_Culture))
                {
                    _Culture = "nl-NL";
                }

                return _Culture;
            }
            set
            {
                _Culture = value;
            }
        }

        private Uri _HostName;            
        /// <summary>
        /// The hostname of the website making the request (e.g. www.google.com)
        /// </summary>        
        public string HostName
        {
            get
            {
                return _HostName.Host;
            }
            set
            {
                _HostName = new Uri(value);
            }
        }

        private string _PageTitle;
        /// <summary>
        /// The title of the page making the request
        /// </summary>
        public string PageTitle
        {
            get
            {
                if (string.IsNullOrWhiteSpace(_PageTitle))
                {
                    _PageTitle = "ShoppingCart";
                }

                return _PageTitle;
            }
            set
            {
                _PageTitle = value;
            }
        }

        #endregion
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Junior)
Netherlands Netherlands
Student software engineer and partime .NET backend developer

Comments and Discussions