谷歌分析API和.Net
谷歌几天前宣布了这一计划,从而使网站更容易获得分析数据。该API首次使用Java和Javascript客户端,但没有直接的.Net支持(除了直接使用XML)。不过,该API似乎与其他Google数据API类似,而且存在一个新的API。是否有人尝试使用该库中的组件获取分析数据谷歌分析API和.Net,.net,asp.net-mvc,api,google-analytics,analytics,.net,Asp.net Mvc,Api,Google Analytics,Analytics,谷歌几天前宣布了这一计划,从而使网站更容易获得分析数据。该API首次使用Java和Javascript客户端,但没有直接的.Net支持(除了直接使用XML)。不过,该API似乎与其他Google数据API类似,而且存在一个新的API。是否有人尝试使用该库中的组件获取分析数据 我正在构建一个ASP.NETMVC网站,我想我应该使用谷歌分析来生成“浏览量最大”的列表之类的东西(因为谷歌可能更擅长剔除虚假请求、机器人等)。如果您对这个想法有任何想法,我也非常感谢您的建议。请查看我的帖子: 它没有使用
我正在构建一个ASP.NETMVC网站,我想我应该使用谷歌分析来生成“浏览量最大”的列表之类的东西(因为谷歌可能更擅长剔除虚假请求、机器人等)。如果您对这个想法有任何想法,我也非常感谢您的建议。请查看我的帖子: 它没有使用你提到的内置库,但它工作得很好。整个API都是XML/HTTP,因此使用起来非常方便。你基本上是向谷歌索要一个网页,然后检查你所需要的回复 查看Google的.NET库,他们增加了分析支持 此外,请查看他们的小组在此发布的帖子: 及
谷歌发布了一种新的API,在中列出,您可以看到的条目。还有一个为所有这些API提供.dll的。这是谷歌,所以它仍处于测试阶段,但我正在开发它,没有任何问题
//为此,您必须在.net项目中添加一些dll,即。
//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; }
}
使用DotNetOpenAuth.OAuth2;
使用Google.api.Authentication.OAuth2;
使用Google.api.Authentication.OAuth2.DotNetOpenAuth;
使用Google.api.Analytics.v3;
使用Google.api.Analytics.v3.Data;
使用Google.api.Services;
public ActionResult GetAnalyticsData(字符串组类型、字符串日期从、字符串日期到)
{
尝试
{
分析服务气体=认证者();
//创建我们的查询
DataResource.GaResource.GetRequest r=gas.Data.Ga.Get(“Ga:88028792,date_from,date_to,“Ga:visions,Ga:pageviews,Ga:users,Ga:newUsers,Ga:sessions”);
//小时、日、周、月
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:nthmond”;}
//d:执行并获取查询结果
GaData d=r.Execute();
List tr=新列表();
列表cd=新列表();
foreach(d.行中的变量项)
{
CustomeData mydata=新CustomeData();
//mydata.CreatedDate=项[0]。ToString();
mydata.Visites=转换为32(项目[1]);
mydata.pageviews=Convert.ToInt32(项目[2]);
mydata.users=Convert.ToInt32(第[3]项);
mydata.newUsers=Convert.ToInt32(第[4]项);
mydata.sessions=Convert.ToInt32(第[5]项);
#地区日期转换
DateTime Now=DateTime.Parse(date\u from,CultureInfo.InvariantCulture,datetimestyle.None);
DateTime TempDate=新的日期时间(Now.Year,Now.Month,Convert.ToInt32(Now.ToString(“dd”));
如果(组类型=“天”)
{
TempDate=TempDate.AddDays((转换为32(项目[0]));
mydata.CreatedDate=TempDate.ToLongDateString();
}
else if(组类型=“小时”)
{
TempDate=TempDate.AddHours((转换为32(项目[0]));
mydata.CreatedDate=TempDate.ToString(“dddd,mmmdd,yyyy hh:mm tt”);
}
else if(GroupType==“月”)
{
TempDate=TempDate.AddMonths((转换为32(项目[0]));
mydata.CreatedDate=TempDate.ToString(“MMMM,yyyy”);
}
其他的
{
//DateTime NewDate=DateTime.Parse(date\u from,CultureInfo.InvariantCulture,datetimestyle.None);
//NewDate=NewDate.AddDays((转换为第32项(项目[0])+1)-1)*7);
//字符串NewDate1=NewDate.ToLongDateString();
mydata.CreatedDate=项[0]。ToString();
}
#端区
cd.Add(mydata);
}
foreach(d.TotalsForAllResults中的var项)
{
TotalsForAllResults tfa=新的TotalsForAllResults();
tfa.metrics=item.Key;
tfa.count=Convert.ToInt32(item.Value);
tr.Add(tfa);
}
//在这一点上,d应该包含日期之间的访客数量
返回Json(新的{TotalsForAllResults=tr,LineChartData=cd});
}
捕获(例外情况除外)
{
返回Json(null);
}
}
公共分析服务认证者()
{
//这是创建服务帐户时下载的密钥文件的物理路径
字符串key_file=@“E:\be8eab1c9893eac9f9fdac95cd64bcc58c86a158 privatekey.p12”;/@“C:\Users\path\XXXXX-privatekey.p12”;
//是“电子邮件地址”,而不是“客户ID”!!!
String client_id=“450122396803-jt0vt4do8ui6ah74iv1idh1pt9jsvqa6@developer.gserviceaccount.com"; //"0000000-xxxxx@developer.gserviceaccount.com";
//可能所有人的密码都是“notacret”
字符串密钥\u pass=“notasecret”;
字符串范围\u url=”https://www.googleapis.com/auth/“+Google.api.Analytics.v3.AnalyticsService.Scopes.Analytics.ToString().ToLower();
//作用域url=”https://www.googleapis.com/auth/analytics";
//作用域url=”https://www.googleapis.com/auth/analytics.readonly";
AuthorizationServerDescription desc=GoogleAuthenticationServer.Description;