我正在尝试调试此代码,以找出错误所在,但无法执行。
我不确定viewId
应该只是int还是ga:<viewId>
,我尝试了两种方法,但仍获取空数据。
List<Report>.Data
始终返回null。
代码:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using Google.Apis.Analytics.v3;
using Google.Apis.Analytics.v3.Data;
using Google.Apis.Services;
using Google.Apis.AnalyticsReporting.v4;
using Google.Apis.AnalyticsReporting.v4.Data;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Util;
using Google.Apis.Logging;
public class GoogleAnalyticsApi
{
private const string keyPath = @"<JsonFileAbsolutePath>";
private string accountEmailAddress = "googleaccount@mail";
private string keyPassword = "<secret>";
private string viewId;
public AnalyticsService Service { get; set; }
private AnalyticsReportingService gaService;
public GoogleAnalyticsApi(string viewId)
{
try
{
var logger = new ConsoleLogger(LogLevel.Error);
GoogleCredential credentials;
using (var stream = new FileStream(keyPath, FileMode.Open, FileAccess.Read))
{
string[] scopes = {AnalyticsReportingService.Scope.AnalyticsReadonly};
var googleCredential = GoogleCredential.FromStream(stream);
credentials = googleCredential.CreateScoped(scopes).ThrowIfNull("");
}
this.gaService = new AnalyticsReportingService(
new BaseClientService.Initializer
{
ApplicationName = "Testing",
HttpClientInitializer = credentials
});
}
catch (Exception e)
{
throw new Exception("Can't start Google service.");
}
this.viewId = viewId;
}
public IList<Report> GetReports(DateRange dateRange, List<Metric> metrics, List<Dimension> dimensions, string filters = null, List<OrderBy> orderBys = null)
{
var reportRequest = new ReportRequest
{
DateRanges = new List<DateRange> { dateRange },
Dimensions = dimensions,
Metrics = metrics,
FiltersExpression = filters,
ViewId = this.viewId,
OrderBys = orderBys
};
var getReportsRequest = new GetReportsRequest
{
ReportRequests = new List<ReportRequest> { reportRequest }
};
ReportsResource.BatchGetRequest batchRequest = this.gaService.Reports.BatchGet(getReportsRequest);
GetReportsResponse resp = batchRequest.Execute();
return resp.Reports;
}
public IList<Profile> GetAvailableProfiles()
{
var response = Service.Management.Profiles.List("~all", "~all").Execute();
return response.Items;
}
}
我要过滤的类别存在,如果我尝试在https://ga-dev-tools.appspot.com/query-explorer/#report-end使用这些确切的指标,维度和过滤器,那么一切都很好。
我正在从该控制器中调用它:
private void Test(HttpContext ctx)
{
var dateRange = new DateRange
{
StartDate = "2018-01-01",
EndDate = "2018-02-01"
};
List<Metric> metrics = GenerateMetricsListFromStrings(new ArrayList()
{
"ga:pageviews",
"ga:totalEvents",
"ga:pageviewsPerSession",
"ga:users",
"ga:sessions"
});
List<Dimension> dimensions = GenerateDimensionsListFromStrings(new ArrayList()
{
"ga:browser",
"ga:operatingSystem",
"ga:country",
"ga:hour",
"ga:date"
});
string filters = "ga:eventCategory==Test";
IList<Report> data = this.ga.GetReports(dateRange, metrics, dimensions, filters);
foreach (var item in data.First().Data.Rows)
{
ctx.Response.Write(
String.Join(", ", item.Dimensions) + " " + String.Join(", ", item.Metrics.First().Values)
);
}
}
/**
* ...
*/
private List<Metric> GenerateMetricsListFromStrings(ArrayList metrics)
{
List<Metric> metrictsList = new List<Metric>();
foreach (string metric in metrics)
{
metrictsList.Add(new Metric()
{
Expression = metric
});
}
return metrictsList;
}
/**
* ...
*/
private List<Dimension> GenerateDimensionsListFromStrings(ArrayList dimensions)
{
List<Dimension> dimensionsList = new List<Dimension>();
foreach (string dim in dimensions)
{
dimensionsList.Add(new Dimension()
{
Name = dim
});
}
return dimensionsList;
}
谢谢。
答案 0 :(得分:0)
悲伤,我错了日期...
我试图从2018年而不是今年获得数据...
var dateRange = new DateRange
{
StartDate = "2018-01-01",
EndDate = "2019-02-01"
};