How to configure/setup/use multiple Google Analytics Tracking Codes in a Web Application (ASP.NET MVC 5), how to track/collect web applications’s Custom Data in Google Analytics’s Custom Dimensions and how to track events in Google Analytics.

a) How to configure/setup/use multiple Google Analytics Tracking Codes in a Web Application (ASP.NET MVC 5).

Add a googleAnalyticsFunctions.js file to your web application & include it on the pages that you want to track.  Do, update the ‘gaAnalyticsIds’ tracking ids array with your tracking ids.

googleAnalyticsFunctions.js

var GoogleAnalyticsFunctions = {

    // Google Analytics - IDs.
    gaAnalyticsIds: ['UA-xxxxxxxxx-1', 'UA-xxxxxxxxx-2'],

    // Google Analytics - name prefixes.
    gaNamePrefixes: [],

    // Google Analytics - initialization.
    init: function () {
        var gaAnalyticsIds = GoogleAnalyticsFunctions.gaAnalyticsIds;

        if (typeof (gaAnalyticsIds) !== 'undefined' && gaAnalyticsIds.length > 0 && gaAnalyticsIds[0].length > 0) {
            (function (i, s, o, g, r, a, m) {
                i['GoogleAnalyticsObject'] = r; i[r] = i[r] || function () {
                    (i[r].q = i[r].q || []).push(arguments)
                }, i[r].l = 1 * new Date(); a = s.createElement(o),
                m = s.getElementsByTagName(o)[0]; a.async = 1; a.src = g; m.parentNode.insertBefore(a, m)
            })(window, document, 'script', 'https://www.google-analytics.com/analytics.js', 'ga');

            for (var i = 0; i < gaAnalyticsIds.length; i++) {
                var prefix = 'GATracker' + i;
                ga('create', gaAnalyticsIds[i], { 'name': prefix });
                GoogleAnalyticsFunctions.gaNamePrefixes.push(prefix);
                ga(prefix + '.send', 'pageview');
            }
        }
    },
};

$(function () {
    GoogleAnalyticsFunctions.init();
});

Results:

As shown below, data collection started successfully for the same web application under multiple tracking ids.

For first Tracking ID

Google Analytics Multiple Analytics Codes

For second Tracking ID

 

Google Analytics Multiple Analytics Codes

b) Book Store Web Application (ASP.NET MVC 5)

We want to collect some Custom Data  (User Id, Book Publisher,  Book Category, Book ID) in Google Analytic when Buy Now event occur.

Application architecture

Application With Google Analytics Tracking Enabled

User Interface

Books Application

Models:

Book Model:

Book.cs

namespace SampleApplication.Models
{
    public class Book
    {
        public string Publisher { get; set; }
        public string BookCategory { get; set; }
        public int Id { get; set; }
        public string Title { get; set; }
        public decimal Price { get; set; }
    }
}

Home Page View Model:

HomePageModel.cs

using System;
using System.Collections.Generic;

namespace SampleApplication.Models
{
    public class HomePageModel
    {
        public List<Book> Books { get; set; }
        public Guid UserId { get; set; }
    }
}

Home Controller with Index Action Method:

HomeController.cs

using SampleApplication.Models;
using System;
using System.Collections.Generic;
using System.Web.Mvc;

namespace SampleApplication.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            var books = new List<Book>
            {
               new  Book { Publisher = "wrox", BookCategory = "Web Development", Id = 1, Price = 450, Title = "Book1"  },
               new  Book { Publisher = "Apress", BookCategory = "Programming", Id = 2, Price = 250, Title = "Book2"  },
               new  Book { Publisher = "wrox", BookCategory = "Databases", Id = 3, Price = 499, Title = "Book3"  },
               new  Book { Publisher = "Apress", BookCategory = "Mobile", Id = 5, Price = 350, Title = "Book5"  },
               new  Book { Publisher = "wrox", BookCategory = "ASP.NET", Id = 6, Price = 485, Title = "Book6"  },
               new  Book { Publisher = "Apress", BookCategory = "C#", Id = 7, Price = 380, Title = "Book7"  },
               new  Book { Publisher = "Apress", BookCategory = "C#", Id = 9, Price = 500, Title = "Book9"  },
               new  Book { Publisher = "wrox", BookCategory = "ASP.NET", Id = 10, Price = 650, Title = "Book10"  },
               new  Book { Publisher = "Apress", BookCategory = "C#", Id = 11, Price = 200, Title = "Book11"  },
               new  Book { Publisher = "Apress", BookCategory = "Sql Server", Id = 12, Price = 250, Title = "Book12"  },
               new  Book { Publisher = "wrox", BookCategory = "C#", Id = 13, Price = 300, Title = "Book13"  },
               new  Book { Publisher = "wrox", BookCategory = "C#", Id = 14, Price = 150, Title = "Book14"  },
               new  Book { Publisher = "Apress", BookCategory = "Sql Server", Id = 15, Price = 200, Title = "Book15"  },
               new  Book { Publisher = "Apress", BookCategory = "Sql Server", Id = 16, Price = 475, Title = "Book16"  },
               new  Book { Publisher = "wrox", BookCategory = "ASP.NET", Id = 17, Price = 375, Title = "Book17"  },
               new  Book { Publisher = "wrox", BookCategory = "ASP.NET", Id = 18, Price = 425, Title = "Book18"  },
               new  Book { Publisher = "Apress", BookCategory = "Sql Server", Id = 19, Price = 430, Title = "Book19"  },
               new  Book { Publisher = "wrox", BookCategory = "C#", Id = 20, Price = 625, Title = "Book20"  },
               new  Book { Publisher = "Apress", BookCategory = "C#", Id = 21, Price = 500, Title = "Book21"  },
               new  Book { Publisher = "wrox", BookCategory = "ASP.NET", Id = 4, Price = 750, Title = "Book4"  },
               new  Book { Publisher = "Apress", BookCategory = "Java", Id = 8, Price = 175, Title = "Book8"  },
            };

            var model = new HomePageModel
            {
                 Books = books,
                 UserId = Guid.NewGuid()
            };

            return View(model);
        }
    }
}

Client-side code for handling BuyNow click:

home.js

var Home = {
    init: function () {
        $(document).on("click", ".buynow", Home.buyNow);
    },
    buyNow: function () {
        // Some code
    },
};

$(function () {
    Home.init();
});

Index view:

Index.cshtml

Scripts section contains references to googleAnalyticsFunctions.js & home.js.

@model SampleApplication.Models.HomePageModel
@{
    ViewBag.Title = "Home Page";
}

@section Scripts{
    @Scripts.Render("~/Scripts/google-analytics/GoogleAnalyticsFunctions.js")
    @Scripts.Render("~/Scripts/home/home.js")
}


<div class="row">
    <div class="col-md-4">
        <table id="BookListing" data-userid="@Model.UserId" style="width:100%">
            <tr>
                <th>Publisher</th>
                <th>BookCategory</th>
                <th>Id</th>
                <th>Title</th>
                <th>Price</th>
                <th></th>
            </tr>
            @foreach (var item in Model.Books)
            {
                <tr>
                    <td>@item.Publisher</td>
                    <td>@item.BookCategory</td>
                    <td>@item.Id</td>
                    <td>@item.Title</td>
                    <td>@item.Price</td>
                    <td><a href="#"
                           class="btn btn-default buynow"
                           data-bookpublisher="@item.Publisher"
                           data-bookcategory="@item.BookCategory"
                           data-bookid="@item.Id">Buy Now</a></td>
                </tr>
            }
        </table>
    </div>
</div>

c) How to create and track data in Custom Dimensions in Google Analytics under multiple tracking ids for same web application.

Setup Custom Dimensions in Google Analytics Account

First of all setup custom dimensions in Google Analytics using the Admin Tab as shown below for all the tracking ids under which you want to track data. Here, four custom dimensions are configured:

‘dimension1’ – User Id,
‘dimension2’ – Book Publisher,
‘dimension3’ –  Book Category,
‘dimension4’ – Book ID

In all 20 custom dimensions can be configured in Google Analytics.

Google Analytics Custom Dimensions

Update the googleAnalyticsFunctions.js with method to send custom data to Google Analytics as shown below

var GoogleAnalyticsFunctions = {

    // Google Analytics - name prefixes.
    gaAnalyticsIds: ['UA-xxxxxxxxx-1', 'UA-xxxxxxxxx-2'],

    // Google Analytics - name prefixes.
    gaNamePrefixes: [],

    // Google Analytics - initialization.
    init: function () {
        var gaAnalyticsIds = GoogleAnalyticsFunctions.gaAnalyticsIds;

        if (typeof (gaAnalyticsIds) !== 'undefined' && gaAnalyticsIds.length > 0 && gaAnalyticsIds[0].length > 0) {
            (function (i, s, o, g, r, a, m) {
                i['GoogleAnalyticsObject'] = r; i[r] = i[r] || function () {
                    (i[r].q = i[r].q || []).push(arguments)
                }, i[r].l = 1 * new Date(); a = s.createElement(o),
                m = s.getElementsByTagName(o)[0]; a.async = 1; a.src = g; m.parentNode.insertBefore(a, m)
            })(window, document, 'script', 'https://www.google-analytics.com/analytics.js', 'ga');

            for (var i = 0; i < gaAnalyticsIds.length; i++) {
                var prefix = 'GATracker' + i;
                ga('create', gaAnalyticsIds[i], { 'name': prefix });
                GoogleAnalyticsFunctions.gaNamePrefixes.push(prefix);
                ga(prefix + '.send', 'pageview');
            }
        }
    },

    // Google Analytics - send event data.
    sendEventData: function (userId, bookPublisher, bookCategory, bookId, eventCategory, eventAction) {
        var gaAnalyticsIds = GoogleAnalyticsFunctions.gaAnalyticsIds;

        if (typeof (gaAnalyticsIds) === 'undefined' || gaAnalyticsIds.length <= 0 || gaAnalyticsIds[0].length <= 0) {
            return;
        }

        $.each(GoogleAnalyticsFunctions.gaNamePrefixes, function (index, value) {
            GoogleAnalyticsFunctions.setCustomDimensions(value, userId, bookPublisher, bookCategory, bookId);
            ga(value + '.send', 'event', eventCategory, eventAction);
        });
    },

    // Google Analytics - set custom dimentions.
    setCustomDimensions: function (gaNamePrefix, userId, bookPublisher, bookCategory, bookId) {
        ga(gaNamePrefix + '.set', {
            'dimension1': userId,
            'dimension2': bookPublisher,
            'dimension3': bookCategory,
            'dimension4': bookId
        });
    },
};

$(function () {
    GoogleAnalyticsFunctions.init();
});

Lastly, update Home.buyNow method in home.js to call the GoogleAnalyticsFunctions.sendEventData method as shown below

var Home = {
    init: function () {
        $(document).on("click", ".buynow", Home.buyNow);
    },
    buyNow: function () {
        // Some code...

        var bookListingData = $('#BookListing').data();
        var bookData = $(this).data();
        GoogleAnalyticsFunctions.sendEventData(bookListingData.userid, bookData.bookpublisher, bookData.bookcategory, bookData.bookid, "BuyNow", "click");

        // Some code...
    },
};

$(function () {
    Home.init();
});

So, now when user click BuyNow, Custom Data (User Id, Book Publisher,  Book Category, Book ID)  is send to Google Analytics in respective Custom Dimensions (dimension1, dimension2, dimension3, dimension4) that were set in Google Analytics.

d) How to setup and track events in Google Analytics.

As, shown in the above code in GoogleAnalyticsFunctions.js, event tracking is done using:

ga(value + '.send', 'event', eventCategory, eventAction);

Result: Event gets tracked in respective Tracking IDs

For first Tracking ID

Google Analytics Event Tracking

For second Tracking ID

Google Analytics Event Tracking

e) Result can be seen in Google Analytics Query Analyser Tool for the respective tracking ids as shown below

Query parameters

Google Analytics Query Analyser Tool

Query Result

Results In Google Analytics Query Analyser Tool

Happy tracking !!!

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *