Generate Google Analytics E-Commerce code from C#

UPDATE: Dec 17, 2013 Google Universal Analytics

Following the recent announcement from Google that their will be a new release of Google Analytics. I have taken time to redesign the whole project to support the new architecture and release the source code on CodePlex to make the project more maintainable in the long run.

https://universalanalytics.codeplex.com/

This project will come with test project for unit testing and continuous integration. Also combine with ASP.NET MVC rendering example project for users to make better understanding utilizing the framework.

Universal Analytics

Tracking visitors on your e-commerce website is crucial step on internet business today, one tool from Google, call “Google Analytics” has come to help, armed with ability to track visitors from difference source traffic, content navigation, visitor’s system statistic, and most of all e-commerce tracking. Analytics E-commerce are executed by a block of JavaScript into the html code rendered to the client browser, this can sometime be difficult if you have more than one product (Which also happen on my site). Therefore we need a more powerful way generate this tracking code for Analytics, using the power of C# in ASP.NET, I’m able to create a namespace to dynamically generate the inject code for you simply at runtime.

UPDATE: July 16, 2010: Google Analytics Asynchronous Syntax

From the beginning this code was updated back to years ago and now that i’m updating the code to meet up with Google Analytics recommendation on using asynchronous syntax for informing Google about the tracking information. Also i made the code more easy to implement the code into existing.

Continue on to make the library containing the most features it could have in google analytics. i also add the Event, Campaign, Visitor Segment, and Browser settings detection to the namespace.

Ok, lets us at the namespace Google to see what we got here. We have total of 4 classes with Analytics as the master class and Transaction & Item are slaves classes. while event is independence.

1. Analytics: This class contain all the properties that google requires and it’s for generating the google javascript code into the head tag of your webpage.

2. Event: Assign visitors/customers to a particular page to a segment. normally to track return buyers.

3. Transaction: This class is for creating the transaction request for google and holding the items collection.

4. Item: This class is for storing information about each product that is included with the current transaction.

UPDATE: 5 August 2010: Attach project files

Due to some visitor are having problems viewing my codes with their browser, which my codes unreadable. So i’m making the package that visitors can download the whole project to make a better understanding with the codes that i have introduce here.

Download Google Analytics Version 1.1

Now let us see the update code shall we;

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text;

///
/// Summary description for Google Analytics
/// Version: 2.0
/// Author: Sarin Na Wangkanai
/// Website: www.sarin.mobi
/// License: GPL
///

namespace Google
{
public class Analytics
{
public string UA { get; set; }

#region BrowserSettings
public bool ClientInfo { get; set; }
public string DomainName { get; set; }
public bool AllowLinker { get; set; }
public bool AllowHash { get; set; }
public bool DetectFlash { get; set; }
public bool DetectTitle { get; set; }
#endregion
#region Campaign
public int CampaignCookieTimeout { get; set; }
public bool CampaignTrack { get; set; }
public string CampaignName { get; set; }
public string CampaignMedium { get; set; }
public string CampaignSource { get; set; }
public string CampaignTerm { get; set; }
public string CampaignContent { get; set; }
public string CampaignNoOverride { get; set; }
#endregion

///
/// Google Analytics allows you to define custom segments and analyze the behavior of each segment.
///

/// http://www.google.com/support/googleanalytics/bin/answer.py?answer=57045
public string VisitorSegment { get; set; }

private string GoogleJavascriptLibrary
{
get
{
StringBuilder builder = new StringBuilder();
builder.AppendLine("(function() {");
builder.AppendLine("\tvar ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;");
builder.AppendLine("\tga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';");
builder.AppendLine("\tvar s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);");
builder.AppendLine("})();");
return builder.ToString();
}
}
private Transaction trans { get; set; }

///
/// Create the google analytics tracking code instance
///

///(UA-XXXXX-YY) Your web property ID, informally referred to as UA number, can be found by clicking the "check status" link or by searching for "UA-" in the source code of your web page. public Analytics(string ua)
{
this.UA = ua;
this.ClientInfo = true;
this.AllowHash = true;
this.DetectFlash = true;
this.DetectTitle = true;
this.CampaignTrack = true;
}

///
/// Add transaction tracking to the google analytics tracker code
///

///transaction object public void AddTrans(Transaction transaction)
{
this.trans = transaction;
}

public override string ToString()
{
StringBuilder builder = new StringBuilder();
builder.AppendLine("<script type="\&quot;text/javascript\&quot;">// <![CDATA[
");
            builder.AppendLine("\tvar _gaq = _gaq || [];");
            builder.AppendLine(string.Format("\t_gaq.push(['_setAccount', '{0}']);", UA));
            if (!ClientInfo) builder.AppendLine("\t_gaq.push(['_setClientInfo', false]);");
            if (DomainName != null) builder.AppendLine(string.Format("\t_gaq.push(['_setDomainName', '{0}']);", DomainName));
            if (AllowLinker) builder.AppendLine("\t_gaq.push(['_setAllowLinker', true]);");
            if (!AllowHash) builder.AppendLine("\t_gaq.push(['_setAllowHash', false]);");
            if (!DetectFlash) builder.AppendLine("\t_gaq.push(['_setDetectFlash', false]);");
            if (!DetectTitle) builder.AppendLine("\t_gaq.push(['_setDetectTitle', false]);");

            if (!CampaignTrack) builder.AppendLine("\t_gaq.push(['_setCampaignTrack', false]);");
            if (CampaignCookieTimeout > 0) builder.AppendLine(string.Format("\t_gaq.push(['_setCampaignCookieTimeout', {0}]);", CampaignCookieTimeout));
            if (CampaignName != null) builder.AppendLine(string.Format("\t_gaq.push(['_setCampNameKey', '{0}']);", CampaignName));
            if (CampaignMedium != null) builder.AppendLine(string.Format("\t_gaq.push(['_setCampMediumKey', '{0}']);",CampaignMedium));
            if (CampaignSource != null) builder.AppendLine(string.Format("\t_gaq.push(['_setCampSourceKey', '{0}']);", CampaignSource));
            if (CampaignTerm != null) builder.AppendLine(string.Format("\t_gaq.push(['_setCampTermKey', '{0}']);", CampaignTerm));
            if (CampaignContent != null) builder.AppendLine(string.Format("\t_gaq.push(['_setCampContentKey', '{0}']);", CampaignContent));
            if (CampaignNoOverride != null) builder.AppendLine(string.Format("\t_gaq.push(['_setCampNOKey', '{0}']);", CampaignNoOverride));

            if (VisitorSegment != null) builder.AppendLine(string.Format("\t_gaq.push(['_setVar','{0}']);", VisitorSegment));

            builder.AppendLine("\t_gaq.push(['_trackPageview']);");
            if (trans != null)
            {
                builder.AppendLine("\t" + trans.AddTrans());
                foreach (Item item in trans.Items)
                    builder.AppendLine("\t" + item.ToScript(trans.OrderID));
                builder.AppendLine("\t" + trans.Submit());
            }
            builder.AppendLine();
            builder.AppendLine(GoogleJavascriptLibrary);
            builder.AppendLine("
// ]]></script>");
return builder.ToString();
}
}
public class Event
{
public string Category { get; set; }
public string Action { get; set; }
public string Label { get; set; }
public string Value { get; set; }

public Event(string category, string action)
{
this.Category = category;
this.Action = action;
}

public Event(string category, string action, string label, string value):this(category, action)
{
this.Label = label;
this.Value = value;
}

public override string ToString()
{
return string.Format("_gaq.push(['_trackEvent', '{0}', '{1}', '{2}', '{3}]);",
Category, Action, Label, Value);
}
}
public class Transaction
{
public string OrderID { get; set; } // order ID - required
public string StoreName { get; set; } // affiliation or store name
public decimal Total { get; set; } // total - required
public decimal Tax { get; set; } // tax
public decimal Shipping { get; set; } // shipping cost
public string City { get; set; } // city
public string State { get; set; } // state or province
public string Country { get; set; } // country

public List Items { get; set; } // List of itmes in this invoice transaction

///
/// The transaction object stores all the related information about a single transaction, such as the order ID, shipping charges, and billing address.
///

///transaction order id (required) ///affiliation or store name ///tax ///shipping cost ///city ///state or province ///country public Transaction(string orderID, string storename, decimal tax, decimal shipping, string city, string state, string country)
{
this.OrderID = orderID;
this.StoreName = storename;
this.Tax = tax;
this.Shipping = shipping;
this.City = city;
this.State = state;
this.Country = country;
this.Items = new List();
}

///
/// add item might be called for every item in the shopping cart
/// where your ecommerce engine loops through each item in the cart and
/// prints out _addItem for each
///

///item object public void Add(Item item)
{
this.Total += (item.Price * item.Quantity);
this.Items.Add(item);
}

#region googlejavascript
///
/// create a transaction javascript method call
///

/// google javascript codes
internal string AddTrans()
{
return string.Format("_gaq.push(['_addTrans', '{0}', '{1}', '{2}', '{3}', '{4}', '{5}', '{6}', '{7}']);",
OrderID, StoreName, Total, Tax, Shipping, City, State, Country);
}
///
/// submits transaction to the Analytics servers
///

/// google javascript codes
internal string Submit()
{
return "_gaq.push(['_trackTrans']);";
}
#endregion
}
public class Item
{
public string SKU { get; set; } // SKU/code - required
public string Name { get; set; } // product name
public string Category { get; set; } // category or variation
public decimal Price { get; set; } // unit price - required
public int Quantity { get; set; } // quantity - required

///
/// tracks information about each individual item in the user's shopping cart
/// and associates the item with each transaction.
///

///SKU/Code (required) ///Product name (optional) ///Category (optional) ///unit price (required) ///quantity (required) public Item(string sku, string name, string category, decimal price, int quantity)
{
this.SKU = sku;
this.Name = name;
this.Category = category;
this.Price = price;
this.Quantity = quantity;
}

///
/// Create a item javascript method call
///

///order ID for the transcation /// google javascript codes
internal string ToScript(string orderid)
{
return string.Format("_gaq.push(['_addItem', '{0}', '{1}', '{2}', '{3}', '{4}', '{5}']);",
orderid, SKU, Name, Category, Price, Quantity);
}
}
}

As you could see the code seem to more complex then older version, but believe me it’s much more easier to use in your web application. As all with OOP combine the aid of IntelliSense, a summary of the how to use the method will popup on fly when you are imputing the data to the function.

What about starting the using the code then. well for my recommendation would be to create a Google.Analytics property in the masterpage and create the instance of the object with overriding the OnInit() (if the instance is created in Page_Load() then transaction will never be populated into the object). Example:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class MasterPage : System.Web.UI.MasterPage
{
public Google.Analytics analytics { get; set; }

protected override void OnInit(EventArgs e)
{
analytics = new Google.Analytics("UA-XXXXX-YY");
base.OnInit(e);
}
}

And then add the Google.Analytics.ToString() in the header of the html code of the master page.

<%= analytics.ToString() %>

Then finally we can add the transaction to the analytics class in the thankyou.aspx page when customer has completed the payment to your product/service.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Thankyou : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Google.Transaction transaction = new Google.Transaction("1234", "sathai", 0, 10, "ruangsit", "pathumtani", "thailand");
transaction.Add(new Google.Item("PLOVE", "Product of love", "love", 19.99m, 1));
(Master as MasterPage).analytics.AddTrans(transaction);
}
}

what is the difference if the transaction added to the analytics object in the masterpage property. here is a figure of how the javascript code would look like if the transaction was not added to the analytics object;

And this source view when the transaction has been added to the analytics object;

I hope that you enjoy this updated and useful post of my about google analytics c# backend javascript generator namespace.

  • Ray
  • http://www.sarin.mobi Sarin Na Wangkanai
  • http://www.ivesmozart.com Ives
  • prakash singh
  • Marco Morreale
  • Marco Morreale
  • http://www.sarin.mobi Sarin Na Wangkanai
  • Marco Morreale
  • http://www.sarin.mobi Sarin Na Wangkanai
  • http://www.sarin.mobi Sarin Na Wangkanai
  • http://www.sarin.mobi Sarin Na Wangkanai
  • Tomas
  • Pepin
  • http://www.sarin.mobi Sarin Na Wangkanai
  • http://www.sarin.mobi Sarin Na Wangkanai
  • Pepin
  • http://www.sarin.mobi Sarin Na Wangkanai
  • http://new.cartridgesdirect.com.au Shailendra Jain
  • http://www.sarin.mobi Sarin Na Wangkanai
  • Simon
  • cha
  • http://www.facebook.com/people/Ronald-Shawn/100001960464404 Ronald Shawn
  • http://www.sarin.mobi/ sathai
  • Dave
  • http://www.sarin.mobi/ sathai
  • Isfrench
  • Andrew__clements
  • Andrew__clements
  • bjarkeck
  • sandeep
  • ljamesv19
  • Dbasb Sfsf
  • KKI
  • http://www.sarin.mobi/ sathai
  • http://www.sarin.mobi/ sathai
  • brayden
  • http://www.sarin.mobi/ sathai