Search code examples
c#.netgoogle-analyticsgoogle-analytics-apigoogle-api-client

Retrieve data from Google Analytics API with .NET, multiple metrics?


I'm writing this Console Application to get some basic "Google Analytics Api-data" logic going. Everythings works fine but i wan't to add some more metrics to query to google analytics API. I wan't to add ga:newvisitors, ga:reaccuringvisitors etc. How do i implement this in the code below?

Here's a relevant piece of the code:

var gas = new AnalyticsService(new BaseClientService.Initializer()
      {
       HttpClientInitializer = credential,
       ApplicationName = "TestGoogleAnalytics",
       });

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

//Specify some addition query parameters
r.Dimensions = "ga:pagePath";
r.Sort = "-ga:visitors";
r.MaxResults = 10000;

//Execute and fetch the results of our query
Google.Apis.Analytics.v3.Data.GaData d = r.Execute();
foreach (KeyValuePair<string, string> kvp in d.TotalsForAllResults)
    {
    Console.WriteLine("Total Visitors:" +" " + kvp.Value);
    }

Console.WriteLine(d.TotalsForAllResults.Keys + " = " + d.TotalsForAllResults.Values);
Console.ReadLine();

Thanks


Solution

  • Metrics are the last item in the get request just separate them with a comma.

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

    Might be easer to read this way:

    string Metrics = "ga:visitors,ga:newvisitors,ga:reaccuringvisitors";
    var r = gas.Data.Ga.Get("ga:ProfileID", "2010-02-24", "2014-02-24", Metrics);
    

    make sure you have the names right those don't look right to me but I didn't check: Dimension and metric reference .

    Update: ga:newvisitors was removed back in 2009. I cant find any reference to ga:reaccuringvisitors. Make sure your requesting the correct metrics.