Google Analytics API 및 .NET
-
16-09-2019 - |
문제
Google이 발표했습니다 분석 데이터 수출 API 며칠 전, 사이트에 대한 분석 데이터를 훨씬 쉽게 얻을 수 있습니다. API는 Java 및 JavaScript 클라이언트와 데뷔했지만 직접 .NET 지원은 없습니다 (XML을 위해 직접 진행하는 것 외에는). API는 다른 Google 데이터 API와 비슷한 것 같습니다. .NET 클라이언트. 해당 라이브러리의 구성 요소를 사용하여 분석 데이터를 얻으려고 시도한 사람이 있습니까?
저는 ASP.NET MVC 사이트를 구축하는 과정에 있으며 Google 웹 로그 분석을 사용하여 "가장 많이 본"목록과 그와 같은 것들을 생성 할 것이라고 생각했습니다 (Google은 스퓨리어스 요청, 로봇 등을 제출하는 데 더 나을 것입니다). . 그 아이디어에 대한 생각이 있다면, 그들도 듣는 것에 감사드립니다.
해결책
을 체크하다 트렁크 Google의 .NET 라이브러리 중 분석 지원을 추가했습니다.
또한 그룹 게시물을 확인하십시오.
http://groups.google.com/group/gdata-dotnet-client-library/browse_thread/2d2eec9103b731c6
그리고
http://groups.google.com/group/gdata-dotnet-client-library/browse_thread/thread/70c638734823b8d
다른 팁
내 게시물 위치를 확인하십시오.http://www.akamarketing.com/blog/103-introducting-google-analytics-api-with-aspnet-c.html
언급 한 내장 도서관을 사용하지는 않지만 잘 작동합니다. 전체 API는 XML/HTTP이므로 사용하기에 매우 편리합니다. 기본적으로 Google에게 웹 페이지를 요청하고 필요한 것에 대한 응답을 검사합니다.
//For this you will have to add some dll in your .net project i.e.
using DotNetOpenAuth.OAuth2;
using Google.Apis.Authentication.OAuth2;
using Google.Apis.Authentication.OAuth2.DotNetOpenAuth;
using Google.Apis.Analytics.v3;
using Google.Apis.Analytics.v3.Data;
using Google.Apis.Services;
public ActionResult GetAnalyticsData(string GroupType, string date_from, string date_to)
{
try
{
AnalyticsService gas = AuthenticateUser();
// Creating our query
DataResource.GaResource.GetRequest r = gas.Data.Ga.Get("ga:88028792", date_from, date_to, "ga:visits, ga:pageviews, ga:users, ga:newUsers, ga:sessions");
//Hour,Day,Week,Month
if (GroupType == "Hour") { r.Dimensions = "ga:nthHour"; }
else if (GroupType == "Day") { r.Dimensions = "ga:nthDay"; }
else if (GroupType == "Week") { r.Dimensions = "ga:nthWeek"; }
else if (GroupType == "Month") { r.Dimensions = "ga:nthMonth"; }
//d: Execute and fetch the results of our query
GaData d = r.Execute();
List<TotalsForAllResults> tr = new List<TotalsForAllResults>();
List<CustomeData> cd = new List<CustomeData>();
foreach (var item in d.Rows)
{
CustomeData mydata = new CustomeData();
// mydata.CreatedDate = item[0].ToString();
mydata.visits = Convert.ToInt32(item[1]);
mydata.pageviews = Convert.ToInt32(item[2]);
mydata.users = Convert.ToInt32(item[3]);
mydata.newUsers = Convert.ToInt32(item[4]);
mydata.sessions = Convert.ToInt32(item[5]);
#region Date Conversion
DateTime Now = DateTime.Parse(date_from, CultureInfo.InvariantCulture, DateTimeStyles.None);
DateTime TempDate = new DateTime(Now.Year, Now.Month, Convert.ToInt32(Now.ToString("dd")));
if (GroupType == "Day")
{
TempDate = TempDate.AddDays((Convert.ToInt32(item[0])));
mydata.CreatedDate = TempDate.ToLongDateString();
}
else if (GroupType == "Hour")
{
TempDate = TempDate.AddHours((Convert.ToInt32(item[0])));
mydata.CreatedDate = TempDate.ToString("dddd, MMM dd, yyyy hh:mm tt");
}
else if (GroupType == "Month")
{
TempDate = TempDate.AddMonths((Convert.ToInt32(item[0])));
mydata.CreatedDate = TempDate.ToString("MMMM, yyyy");
}
else
{
//DateTime NewDate = DateTime.Parse(date_from, CultureInfo.InvariantCulture, DateTimeStyles.None);
//NewDate = NewDate.AddDays(((Convert.ToInt32(item[0]) + 1) - 1) * 7);
//string NewDate1 = NewDate.ToLongDateString();
mydata.CreatedDate = item[0].ToString();
}
#endregion
cd.Add(mydata);
}
foreach (var item in d.TotalsForAllResults)
{
TotalsForAllResults tfa = new TotalsForAllResults();
tfa.metrics = item.Key;
tfa.count = Convert.ToInt32(item.Value);
tr.Add(tfa);
}
// At this point, d should contain the number of visitors you got between dates
return Json(new { TotalsForAllResults = tr, LineChartData = cd });
}
catch (Exception ex)
{
return Json(null);
}
}
public AnalyticsService AuthenticateUser()
{
// This is the physical path to the key file you downloaded when you created your Service Account
String key_file = @"E:\be8eab1c9893eac9f9fdac95cd64bcc58c86a158-privatekey.p12";//@"C:\Users\path\XXXXX-privatekey.p12";
// Is the "Email Address", not the "Client ID" one!!!
String client_id = "450122396803-jt0vt4do8ui6ah74iv1idh1pt9jsvqa6@developer.gserviceaccount.com"; //"0000000-xxxxx@developer.gserviceaccount.com";
// Probably the password for all is "notasecret"
String key_pass = "notasecret";
String scope_url = "https://www.googleapis.com/auth/" + Google.Apis.Analytics.v3.AnalyticsService.Scopes.Analytics.ToString().ToLower();
//scope_url = "https://www.googleapis.com/auth/analytics";
//scope_url = "https://www.googleapis.com/auth/analytics.readonly";
AuthorizationServerDescription desc = GoogleAuthenticationServer.Description;
X509Certificate2 key = new X509Certificate2(key_file, key_pass, X509KeyStorageFlags.Exportable);
AssertionFlowClient client = new AssertionFlowClient(desc, key) { ServiceAccountId = client_id, Scope = scope_url };
OAuth2Authenticator<AssertionFlowClient> auth = new OAuth2Authenticator<AssertionFlowClient>(client, AssertionFlowClient.GetState);
//AnalyticsService gas = new AnalyticsService(auth);
AnalyticsService gas = new AnalyticsService(new BaseClientService.Initializer() { Authenticator = auth });
return gas;
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace GAExampleMVC.Models
{
public class TotalsForAllResults
{
public string metrics { get; set; }
public int count { get; set; }
public double Percent { get; set; }
public DateTime Time { get; set; }
}
public class CustomeData
{
public string CreatedDate { get; set; }
public int visits { get; set; }
public int pageviews { get; set; }
public int users { get; set; }
public int newUsers { get; set; }
public int sessions { get; set; }
public string avgSessionDuration { get; set; }
public double bounceRate { get; set; }
public double percentNewSessions { get; set; }
public double percentNewVisits { get; set; }
public string Location { get; set; }
public int uniquePageviews { get; set; }
public string pagePath { get; set; }
}
}
Google은 다음에 나열된 새로운 품종의 API를 출시했습니다. Google API 탐색기, 당신은 항목을 볼 수 있습니다 Google 웹 로그 분석. 그리고 A가 있습니다 .NET 클라이언트