有没有办法在查询数据之前验证AnalyticsService

时间:2015-08-10 15:49:13

标签: c# google-analytics-api google-api-dotnet-client service-accounts

我有以下方法在验证Google Developer服务帐户后返回AnalyticsService

public static AnalyticsService AuthenticateUsingServiceAccount(string keyfilePath, string serviceAccountEmail)
{
    if (serviceAccountEmail == null)
        throw new ArgumentNullException("serviceAccountEmail", "serviceAccountEmail cannot be a null reference");
    if (keyfilePath == null)
        throw new ArgumentNullException("keyfilePath", "keyfilePath cannot be a null reference");


    if (!File.Exists(keyfilePath))
    {
        throw new FileNotFoundException("Keyfile does not exist");
    }

    string[] scopes = new string[]
    {
        AnalyticsService.Scope.Analytics, // view and manage your analytics data
        AnalyticsService.Scope.AnalyticsEdit, // edit management actives
        AnalyticsService.Scope.AnalyticsManageUsers, // manage users
        AnalyticsService.Scope.AnalyticsReadonly
    }; // View analytics data       

    var certificate = new X509Certificate2(keyfilePath, "notasecret", X509KeyStorageFlags.Exportable);
    var credential = new ServiceAccountCredential(new ServiceAccountCredential.Initializer(serviceAccountEmail)
    {
        Scopes = scopes
    }.FromCertificate(certificate));

    AnalyticsService service = new AnalyticsService(new BaseClientService.Initializer()
    {
        HttpClientInitializer = credential,
        ApplicationName = "My analytics service",
    });

    return service;
}

在返回之前,有没有办法验证service(确保使用正确的密钥文件和正确的服务帐户电子邮件初始化它)?知道new AnalyticsService将始终返回service对象,无论输入参数是否正确。

目前的行为是,如果参数(凭证)不正确,service只会在调用API后抛出异常,对我来说,这有点晚了。

0 个答案:

没有答案