Google c# Api, changing from v2.3 to v3

2019-02-25 15:04发布

I have the following code to query google analytics using the C# v2.3 api:

string username = "SAMPLE@SAMPLE.COM";
string pass = "PASS";
string gkey = "?key=XXXXXXXXXXXXXXXXXXXXXXXXXXX";

string dataFeedUrl = "https://www.google.com/analytics/feeds/data" + gkey;            

AnalyticsService service = new AnalyticsService("API Sample");
service.setUserCredentials(username, pass);

DataQuery query1 = new DataQuery(dataFeedUrl);

query1.Ids = "ga:34197921";
query1.Dimensions = "ga:medium,ga:campaign,ga:date,ga:isMobile,ga:isTablet,ga:searchKeyword,ga:hostname";
query1.Metrics = "ga:visits,ga:visitors,ga:visitBounceRate,ga:goalStartsAll,ga:goalCompletionsAll,ga:goal1Starts,ga:goal1Completions,ga:goal2Starts,ga:goal2Completions,ga:goal3Starts,ga:goal3Completions,ga:goal4Starts,ga:goal4Completions,ga:adCost,ga:totalValue";
query1.Sort = "ga:date,ga:hour";
query1.NumberToRetrieve = 50;    

query1.GAStartDate = new DateTime(2012, 1, 2).ToString("yyyy-MM-dd");
query1.GAEndDate = DateTime.Now.ToString("yyyy-MM-dd");
query1.StartIndex = 1;
DataFeed dataFeedVisits = service.Query(query1);

foreach (DataEntry entry in dataFeedVisits.Entries)
{
.... 
}

I would like to upgrade the newer v3 api but find it difficult to see any simple examples online where someone authenticates using the google oAuth and then queries the google analytics data.

I install the following NuGet package: Install-Package Google.Apis.Analytics.v3 -Pre In a new c# solution, it gives me the following additional references:

  • Google.Apis
  • Google.Apis.Analytics.v3
  • Google.Apis.Auth
  • Google.Apis.Auth.PlatformServices
  • Google.Apis.PlatformServices
  • log4net
  • Newtownsoft.Json
  • Zlib.Portable

I have seen this article, which seems to run a similar piece of code to what I need to run: How to send Google analytic report query using ASP.net Google analytic api Version 3(Google.Apis.Analytics.v3.dll)?

However, none of the code in this article resolves using the google libraries that where referenced in the NuGet.

What am I missing and how can I complete the picture. How do I authenticate and the run my query to google analytics.

Thumbs down to google for not having an easy to follow tutorial online to support their .net library!

Thanks in advance for any advice!

2条回答
虎瘦雄心在
2楼-- · 2019-02-25 15:30

Accessing Google Analtyics with v3 client library is really nice tbh. The only thing i havent worked out is how to send it a refreshtoken i have stored in the database. Im stuck with the one it stores for me on the Pc.

Request autentication: All the client scret stuff is stored in client_secret.json you can download the file from google apis consol. It will pop up a browser window if it doesnt have approval if it does it will just continue on.

private void Form1_Load(object sender, EventArgs e)
{
 UserCredential credential;
 using (var stream = new System.IO.FileStream("client_secret.json", System.IO.FileMode.Open, System.IO.FileAccess.Read))
 {
  credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
  GoogleClientSecrets.Load(stream).Secrets,
  new[] { AnalyticsService.Scope.AnalyticsReadonly },
  "user", CancellationToken.None, new FileDataStore("Analytics.Auth.Store")).Result;
  }

}

Now to access Google Analytics you need to make an analytics Service.

AnalyticsService service = new AnalyticsService(new BaseClientService.Initializer() {
 HttpClientInitializer = credential,
 ApplicationName = "Analytics API sample",
 });

All your calls will now be run against that.

Yours should end up being something like:

DataResource.GaResource.GetRequest request = service.Data.Ga.Get(ga:34197921, new DateTime(2012, 1, 2).ToString("yyyy-MM-dd"), DateTime.Now.ToString("yyyy-MM-dd"), ""ga:visits,ga:visitors,ga:visitBounceRate,ga:goalStartsAll,ga:goalCompletionsAll,ga:goal1Starts,ga:goal1Completions,ga:goal2Starts,ga:goal2Completions,ga:goal3Starts,ga:goal3Completions,ga:goal4Starts,ga:goal4Completions,ga:adCost,ga:totalValue");
request.Dimensions = "ga:medium,ga:campaign,ga:date,ga:isMobile,ga:isTablet,ga:searchKeyword,ga:hostname";

I have a blog post that runs though most of the diffrent calls you can make. http://daimto.com/google-analytics-api-v3-with-c/

查看更多
霸刀☆藐视天下
3楼-- · 2019-02-25 15:31

I was having the same problem. I'd installed the nuget packages, but get the same error "Could not load file or assembly 'Microsoft.Threading.Tasks.Extensions.Desktop, Version=1.0.16.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The system cannot find the file specified." I tried removing and re-installing the nuget packages to no avail. So, I eventually just searched for the Microsoft.Threading.Tasks.Extensions.Desktop.dll file and it was found in the net40 folder. I copied it to my bin folder and then it worked.

查看更多
登录 后发表回答