Wednesday, May 30, 2012

Google Analytics in SharePoint

In this post, I'm going to discuss how to use Google Analytics with SharePoint. It is quite easy to implement and I have done it with a user control which I developed and with a little bit of additional JavaScript on top of what Google Provides.
Armed with this, you can use Google Analytics for free (I mean its free anyway!) to generate some great tracking data for your websites. Simple, reliable and easy to implement; here is the solution:

  1. In my project solution, I had created an ascx file called GoogleAnalytics.ascx and a code behind file called GoogleAnalytics.ascx.cs. 
  2. In the GoogleAnalytics.ascx file, I have added the script which you get by registering your website in Google Analytics website.
  3. From the code behind file I assigned the tracking code and the meta content for the Google webmaster tool which is provided by Google.
  4. Additionally, I have added a piece of JavaScript which lets you track events such as downloads that happen in your website
The code for the ascx file is as follows:

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="GoogleAnalytics.ascx.cs"
    Inherits="MySolution.UserControls.GoogleAnalytics, MySolution, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31578ca297cd4d8e" %>

<script type="text/javascript" src="http://www.google-analytics.com/ga.js"></script>
<script type="text/javascript">
  
    var _gaq = _gaq || []; 
    _gaq.push(['_setAccount', '<%=GoogleAnalyticTrackingCode %>']); 
    _gaq.push(['_trackPageview']); 

    (function () {

        var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;

        ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';

        var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);

    })();

    document.onclick = function (event) {
        event = event || window.event;
        var target = event.target || event.srcElement;
        var targetElement = target.tagName.toLowerCase();
        if (targetElement == "a") {
            var href = target.getAttribute("href"); eventCheck(href);
        }

        function eventCheck(href) {
            if ((href.match(/^https?\:/i)) && (!href.match(document.domain))) {
                _gaq.push(['_trackEvent', 'External', 'click', href]);
            }
            else if (href.match(/^mailto\:/i)) {
                _gaq.push(['_trackEvent', 'Email', 'click', href.substr(7)]);
            }
            else if (href.match(/^.*\.(doc|docx|eps|jpg|jpeg|png|svg|xls|xlsx|ppt|pptx|ppt|pdf|zip|txt|swf|vsd|vxd|js|css|rar|exe|dmg|wma|mov|avi|wmv|mp3)$/i)) {
                _gaq.push(['_trackEvent', 'Download', 'click', href]);
            }
        }
    }; 

</script>

<meta name="google-site-verification" content="<%=GoogleAnalyticSiteVerificationMetaName %>" /> 

The code for the ascx.cs file is as follows:



    /// <summary>
    /// The code behind class for the user control
    /// </summary>
    public partial class GoogleAnalytics : System.Web.UI.UserControl
    {
        /// <summary>
        /// This is the tracking code which is provided by Google when you register your website in Google Analytics
        /// Here I'm fetching it from web.config. You can get it from other sources such as your custom SharePoint list etc.
        /// </summary>
        public string GoogleAnalyticTrackingCode
        {
            get
            {
                return ConfigurationManager.AppSettings["GoogleAnalyticTrackingCode"];
            }
        }
        /// <summary>
        /// This is the verification meta name which is provided by Google when you install Google Webmaster in your website
        /// Here I'm fetching it from web.config. You can get it from other sources such as your custom SharePoint list etc.
        /// </summary>
        public string GoogleAnalyticSiteVerificationMetaName
        {
            get
            {
                return ConfigurationManager.AppSettings["GoogleAnalyticSiteVerificationMetaName"];
            }
        }
     
        #region "PageLoadEvent"
        protected void Page_Load(object sender, EventArgs e)
        {
            
        }
        #endregion
    }

Once I have built my solution, I deployed the DLL to GAC and the ascx file in the SharePoint's CONTROLTEMPLATES directory in the 14 hive.


Next I have edited the master page of my site and added the control in the <head> section of the website.
Waited for a couple of hours and the data started coming through.


To learn more about Google Analytics, you can visit the official Google's website here  http://www.google.com/analytics/
Please note: You can use the same control in an ASP .Net website as well.