3

I'm extracting data from Google Analytics API and i want to extract total visitors per day and organize them in a list ordered by dates.

For example:

Property "Rows" contains all the dates within the timeframe I specified.

Each row contains:

Date - 2014-02-24
Visitors - 3000
newVisits - 2400
PageViews - 10000
PercentNewVisits - 38,001302

I need to organize and structure this data so i can display it properly in my C# / .NET application but how??

For example:

If I choose start and endate "2014-01-24 - 2014-02-28" I want to see all visits between those days.

  • 2014-01-24 = 100 visits
  • 2014-01-25 = 200 visits
  • ..... and so on

Dates are organised in the property "Rows" in GaData class. However it's a list of strings and the property looks like this:

public virtual IList<IList<string>> Rows { get; set; }

Here's the GaData class with Rows property:

enter image description here

This is what i get when debugging, the dates are displayed". Check this out:

enter image description here

Each row contains visitor data for each day within the query StartDate and EndDate!

Here's the nested class with metric, dimensions etc:

enter image description here

This is my current query:

var r = gas.Data.Ga.Get("ProfileID", "2014-01-24", "2014-02-28", "ga:pageviews,ga:newVisits,ga:visitors,ga:percentNewVisits");

r.Dimensions = "ga:date";
r.Sort = "-ga:date";
r.MaxResults = 10000;

Google.Apis.Analytics.v3.Data.GaData d = r.Execute();

Console.WriteLine("VisitorStats" + "  " + 
                  d.Query.StartDate + " " + "-" + " " + d.Query.EndDate + "\r\n" +
                    "------------------------------------------" + "\r\n" +
                 "Visitors:" + " " + d.TotalsForAllResults["ga:visitors"] + "\r\n" +
                 "NewVisits:" + " " + d.TotalsForAllResults["ga:newVisits"] + "\r\n" +
                 "PageViews:" + " " + d.TotalsForAllResults["ga:pageviews"] + "\r\n" +
                 "PercentNewVisits:" + " " + d.TotalsForAllResults["ga:percentNewVisits"] +"%");

And this is the output I get:

 VisitorStats 2010-02-24 - 2014-02-24
        ------------------------------------------
        NewVisits: 343272
        NewVisits: 147693
        PageViews: 255000
        PersentNewVisits: 42.54700702044485%

I'm getting pretty close now. What I'm trying to archive here is this:

enter image description here

My code looks like this:

ControllerClass:

public class GAStatisticsController : Controller
{
        // GET: /ShopStatistics/
        public string GAnalyticsService()
        {
            //Users Google Service Account
            string serviceAccountEmail = "xxx@developer.gserviceaccount.com";

            //Public key for authorisation
            X509Certificate2 certificate = new X509Certificate2(@"C:\Users\xxx\NopCommerce\Presentation\Nop.Web\key.p12", "notasecret", X509KeyStorageFlags.Exportable);

            //Account credentials of authorisation
            ServiceAccountCredential credential = new ServiceAccountCredential(
            new ServiceAccountCredential.Initializer(serviceAccountEmail)
            {
                Scopes = new[] { AnalyticsService.Scope.Analytics }
            }.FromCertificate(certificate));

            // Create the service.
            //Twistandtango
            AnalyticsService GoogleAnalyticsService = new AnalyticsService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName = "Twist",
            });

            var r = gas.Data.Ga.Get("ProfileID", "2014-01-24", "2014-02-28", "ga:visitors");

            r.Dimensions = "ga:date";
            r.Sort = "-ga:date";
            r.MaxResults = 10000;

            //Execute and fetch the results of our query
            Google.Apis.Analytics.v3.Data.GaData d = request.Execute();

            return "Visitor statistics" + "  " +
                    d.Query.StartDate + " " + "-" + " " + d.Query.EndDate + "<br/>" +
                    "------------------------------------------" + "<br/>" +
                 "Total visitors:" + " " + d.TotalsForAllResults["ga:visitors"].ToString();
        }

        public ActionResult GAStatistics()
        {
            GAnalyticsService();

            return View(new GAStatisticsListModel());
        }
    }
}

ListModel so customer can select what to query. StartDate, EndDate, Visitors, Sales, ConversionRate etc (this model is not doing anything atm):

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;
using Nop.Web.Framework;
using Nop.Web.Framework.Mvc;

namespace Nop.Admin.Models.GAStatistics
{
    public class GAStatisticsListModel : BaseNopModel
    {
        public GAStatisticsListModel()
        {
            AvailableGAStatistics = new List<SelectListItem>();

            Visitors = new List<SelectListItem>();
            ConversionRate = new List<SelectListItem>();
            Sales = new List<SelectListItem>();
        }

        [NopResourceDisplayName("Admin.ShopStatistics.List.StartDate")]
        [UIHint("DateNullable")]
        public DateTime? StartDate { get; set; }

        [NopResourceDisplayName("Admin.ShopStatistics.List.EndDate")]
        [UIHint("DateNullable")]
        public DateTime? EndDate { get; set; }
         [NopResourceDisplayName("Admin.GAStatistics.GAStatistics.AvailableGAStatistics")]
        public int GAStatisticsId { get; set; }

        public List<SelectListItem> AvailableGAStatistics { get; set; }
        public IList<SelectListItem> Sales { get; set; }
        public IList<SelectListItem> ConversionRate { get; set; }
        public IList<SelectListItem> Visitors { get; set; }
    }
}

Any ideas??

This post is related and I've managed to create a temporary fix: Display Google Analytics Data in View

Thx

Community
  • 1
  • 1
WhoAmI
  • 1,188
  • 6
  • 17
  • 47
  • the API isn't going to sum it up for you. Your going to have to extract the visits and then add them up yourself. – Linda Lawton - DaImTo Mar 07 '14 at 12:25
  • Ok. Is that possible? So i have to make a querry for each day i wan't to extract visitors? I mean if i use demention "r.Sort = "-ga:date";" shouldn't i get visitors for for all the days between the dates i specified? Shouldn't all dates show in the debugger? It must be possible to get a number of visitors for each day from the api, how else can it use Line Charts in Analytics Dashboard? – WhoAmI Mar 07 '14 at 12:38
  • have you been testing your requests here first? http://ga-dev-tools.appspot.com/explorer/ – Linda Lawton - DaImTo Mar 07 '14 at 12:47
  • if you don't need ga:visitCount just remove the dimension and it will give you the total of visits for that time frame. With the dimension in there you are going to be getting the visitors for each of the different visitcounts. – Linda Lawton - DaImTo Mar 07 '14 at 12:48
  • Update: i wrote the wrong dates. I wrote from 2010-2014, ofcourse the numbers where wrong, lol. I now get all the dates within my specified timespan in "rows". Next problem is how i can make objects out of the data or atleast organise them in to lists and so on.. – WhoAmI Mar 07 '14 at 14:27
  • the data is returned as an object, from the API. – Linda Lawton - DaImTo Mar 07 '14 at 14:45
  • DalmTo - I watched your GA API V3 tutorial and i found something interesting. In this part i looks to me you create a list out of metrics: http://daimto.com/wp-content/uploads/2013/11/GoogleAnaltysv3MetaDataItems.png. Can i use this code to create a list out of the demensions im using in my querry aswell? I tried applyi g this code in my app but i get an error saying - "The name 'service' does not exist in the current context". service seem to be nested in this method - public ColumnsResource(IClientService service); in ColumnsResource class. Meaby i'm missing a referance? Thx – WhoAmI Mar 10 '14 at 07:55
  • That's because you have your service named gas. – Linda Lawton - DaImTo Mar 11 '14 at 08:12

1 Answers1

0

The data is returned to you already in lists:

Looping though the column headers:

foreach (GaData.ColumnHeadersData header in d.ColumnHeaders)
        {
            Console.Write(header.Name);            
        }

If you want to be able to sum them up I suggest at this time you note nr column it is by creating a counter of some kind, if its a ColumnType = "METRIC". You cant sum up Dimensions.

var r = gas.Data.Ga.Get("ga:7811042x", "2014-01-24", "2014-02-28", "ga:visitors");        
        r.Dimensions = "ga:date";
        r.Sort = "-ga:date";
        r.MaxResults = 10000;

Looping through each row:

        foreach (var row in d.Rows)
        {

            foreach (var Column in row)
            {
                // here is where I would check the counter if its Colum nr x 
                // add it to some counter.
                Console.Write(Column);
            }
        }

I would also like to add that I think this question is going beyond the scope of the original question. Also the bounty question doesn't sound like the original question and to me sounds more like you want someone to do your work for you.

Linda Lawton - DaImTo
  • 106,405
  • 32
  • 180
  • 449
  • Hello. Ofcourse i don't want annyone do the work for me and that is not the point. The point is to be able to separate the data, either in a list or an array. For ex extract all dates from GaData.Rows and make a list of dates. I'm rather hoping for somekind of suggestion that helps. I'm sorry if the bounty question is giving that impression. – WhoAmI Mar 11 '14 at 10:47
  • If you don't know how to make a list in C# I suggest you post a question about that. Its not related to the GA api. – Linda Lawton - DaImTo Mar 11 '14 at 10:49
  • Well i'm fairly new at programing but i do know how to make a list. I just have problem taking the values i wan't from google and put them in a list of my own. Annywas, figured out how to extract what i want, this works great: foreach (var row in d.Rows) { Console.WriteLine("Date:" + " " + row[0] + " " + "Visitors:" + " " + row[1]); Console.ReadLine(); } This separates the two values like intended. Thx – WhoAmI Mar 11 '14 at 13:15