3
votes

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 = "[email protected]";

            //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

1
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. - DaImTo
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
have you been testing your requests here first? ga-dev-tools.appspot.com/explorer - DaImTo
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. - DaImTo
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

1 Answers

0
votes

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.