Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/316.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 谷歌分析实时API.Net客户端_C#_Google Api_Google Analytics Api_Google Api Dotnet Client_Service Accounts - Fatal编程技术网

C# 谷歌分析实时API.Net客户端

C# 谷歌分析实时API.Net客户端,c#,google-api,google-analytics-api,google-api-dotnet-client,service-accounts,C#,Google Api,Google Analytics Api,Google Api Dotnet Client,Service Accounts,是否有人可以使用Google.API.Analytics.v3 API和服务器身份验证共享任何示例c#代码,以获取我网站上的当前用户数 背景: 我有一个MVC内部网站,它有一个支持仪表板。它与不同的API挂钩,以整理一些有用的数据。 我收到一个请求,要求添加我们网站上当前的用户数量,如谷歌分析门户网站所示 我不想让用户单独使用google帐户登录,我希望我可以使用“ServiceCredentials”方法,但我迷路了 谢谢你的帮助 谢谢请确保您在Google analytics的帐户级别授予您

是否有人可以使用Google.API.Analytics.v3 API和服务器身份验证共享任何示例c#代码,以获取我网站上的当前用户数

背景: 我有一个MVC内部网站,它有一个支持仪表板。它与不同的API挂钩,以整理一些有用的数据。 我收到一个请求,要求添加我们网站上当前的用户数量,如谷歌分析门户网站所示

我不想让用户单独使用google帐户登录,我希望我可以使用“ServiceCredentials”方法,但我迷路了

谢谢你的帮助


谢谢

请确保您在Google analytics的帐户级别授予您的服务帐户访问权限

警告:Google Analytics api上的配额是每天每次查看10000个请求。如果你一天内提出超过10000个请求,你将被拒之门外。不要试图经常刷新实时数据,最好是在后台脚本中每分钟刷新一次

认证:

//
///使用服务帐户向Google进行身份验证
///文件:https://developers.google.com/accounts/docs/OAuth2#serviceaccount
/// 
///从谷歌开发者控制台https://console.developers.google.com
///从Google开发者控制台下载的.p12或Json服务帐户密钥文件的位置https://console.developers.google.com
///AnalyticsService用于针对Analytics API发出请求
公共静态分析服务AuthenticateServiceAccount(字符串serviceAccountEmail、字符串serviceAccountCredentialFilePath)
{
尝试
{
if(string.IsNullOrEmpty(serviceAccountCredentialFilePath))
抛出新异常(“需要服务帐户凭据文件的路径”);
如果(!File.Exists(serviceAccountCredentialFilePath))
抛出新异常(“服务帐户凭据文件不存在于:“+serviceAccountCredentialFilePath”);
if(string.IsNullOrEmpty(serviceAccountEmail))
抛出新异常(“需要ServiceAccountEmail”);
//这些是您需要的权限范围。最好只请求您需要的权限,而不是所有权限
string[]scopes=新字符串[]{AnalyticsReportingService.Scope.Analytics};//查看您的Google分析数据
//对于Json文件
if(Path.GetExtension(serviceAccountCredentialFilePath.ToLower()==“.json”)
{
谷歌认证证书;
使用(var stream=newfilestream(serviceAccountCredentialFilePath,FileMode.Open,FileAccess.Read))
{
credential=GoogleCredential.FromStream(流)
.CreateScoped(范围);
}
//创建分析服务。
返回新的AnalyticsService(新的BaseClientService.Initializer()
{
HttpClientInitializer=凭证,
ApplicationName=“分析服务帐户验证示例”,
});
}
else if(Path.GetExtension(serviceAccountCredentialFilePath.ToLower()==“.p12”)
{//如果是P12文件
var证书=新的X509Certificate2(serviceAccountCredentialFilePath,“notasecret”,X509KeyStrageFlags.MachineKeySet | X509KeyStrageFlags.Exportable);
var凭证=新ServiceAccountCredential(新ServiceAccountCredential.Initializer(serviceAccountEmail)
{
范围=范围
}.FromCertificate(证书));
//创建分析服务。
返回新的AnalyticsService(新的BaseClientService.Initializer()
{
HttpClientInitializer=凭证,
ApplicationName=“分析验证示例”,
});
}
其他的
{
抛出新异常(“不支持的服务帐户凭据”);
}
}
捕获(例外情况除外)
{
Console.WriteLine(“创建服务帐户分析服务失败”+ex.Message);
抛出新异常(“CreateServiceAccountAnalyticsFailed”,ex);
}
}
}
请求:

public static class RealtimeSample
{

    public class RealtimeGetOptionalParms
    {
        /// A comma-separated list of real time dimensions. E.g., 'rt:medium,rt:city'.
        public string Dimensions { get; set; }  
        /// A comma-separated list of dimension or metric filters to be applied to real time data.
        public string Filters { get; set; }  
        /// The maximum number of entries to include in this feed.
        public int Max-results { get; set; }  
        /// A comma-separated list of dimensions or metrics that determine the sort order for real time data.
        public string Sort { get; set; }  

    }

    /// <summary>
    /// Returns real time data for a view (profile). 
    /// Documentation https://developers.google.com/analytics/v3/reference/realtime/get
    /// Generation Note: This does not always build corectly.  Google needs to standardise things I need to figuer out which ones are wrong.
    /// </summary>
    /// <param name="service">Authenticated analytics service.</param>  
    /// <param name="ids">Unique table ID for retrieving real time data. Table ID is of the form ga:XXXX, where XXXX is the Analytics view (profile) ID.</param>
    /// <param name="metrics">A comma-separated list of real time metrics. E.g., 'rt:activeUsers'. At least one metric must be specified.</param>
    /// <param name="optional">Optional paramaters.</param>        /// <returns>RealtimeDataResponse</returns>
    public static RealtimeData Get(analyticsService service, string ids, string metrics, RealtimeGetOptionalParms optional = null)
    {
        try
        {
            // Initial validation.
            if (service == null)
                throw new ArgumentNullException("service");
            if (ids == null)
                throw new ArgumentNullException(ids);
            if (metrics == null)
                throw new ArgumentNullException(metrics);

            // Building the initial request.
            var request = service.Realtime.Get(ids, metrics);

            // Applying optional parameters to the request.                
            request = (RealtimeResource.GetRequest)SampleHelpers.ApplyOptionalParms(request, optional);

            // Requesting data.
            return request.Execute();
        }
        catch (Exception ex)
        {
            throw new Exception("Request Realtime.Get failed.", ex);
        }
    }


}
    public static class SampleHelpers
{

    /// <summary>
    /// Using reflection to apply optional parameters to the request.  
    /// 
    /// If the optonal parameters are null then we will just return the request as is.
    /// </summary>
    /// <param name="request">The request. </param>
    /// <param name="optional">The optional parameters. </param>
    /// <returns></returns>
    public static object ApplyOptionalParms(object request, object optional)
    {
        if (optional == null)
            return request;

        System.Reflection.PropertyInfo[] optionalProperties = (optional.GetType()).GetProperties();

        foreach (System.Reflection.PropertyInfo property in optionalProperties)
        {
            // Copy value from optional parms to the request.  They should have the same names and datatypes.
            System.Reflection.PropertyInfo piShared = (request.GetType()).GetProperty(property.Name);
            if (property.GetValue(optional, null) != null) // TODO Test that we do not add values for items that are null
                piShared.SetValue(request, property.GetValue(optional, null), null);
        }

        return request;
    }
}
公共静态类RealtimeSample
{
公共类RealtimeGetOptionalParms
{
///以逗号分隔的实时维度列表。例如,“rt:medium,rt:city”。
公共字符串维度{get;set;}
///要应用于实时数据的维度或度量筛选器的逗号分隔列表。
公共字符串筛选器{get;set;}
///此提要中要包含的最大条目数。
公共int Max结果{get;set;}
///以逗号分隔的维度或度量列表,用于确定实时数据的排序顺序。
公共字符串排序{get;set;}
}
/// 
///返回视图(纵断面)的实时数据。
///文件https://developers.google.com/analytics/v3/reference/realtime/get
///代注:这并不总是建立正确的。谷歌需要标准化的东西,我需要找出哪些是错误的。
/// 
///验证分析服务。
///用于检索实时数据的唯一表ID。表ID的格式为ga:XXXX,其中XXXX是分析视图(概要文件)ID。
///以逗号分隔的实时指标列表。例如,“rt:activeUsers”。必须至少指定一个指标。
///可选参数。///RealtimeDataResponse
公共静态RealtimeData获取(analyticsService服务、字符串ID、字符串度量、RealtimeGetOptionalParms可选=null)
{
尝试
{
//初步验证。
if(服务==null)
public static class RealtimeSample
{

    public class RealtimeGetOptionalParms
    {
        /// A comma-separated list of real time dimensions. E.g., 'rt:medium,rt:city'.
        public string Dimensions { get; set; }  
        /// A comma-separated list of dimension or metric filters to be applied to real time data.
        public string Filters { get; set; }  
        /// The maximum number of entries to include in this feed.
        public int Max-results { get; set; }  
        /// A comma-separated list of dimensions or metrics that determine the sort order for real time data.
        public string Sort { get; set; }  

    }

    /// <summary>
    /// Returns real time data for a view (profile). 
    /// Documentation https://developers.google.com/analytics/v3/reference/realtime/get
    /// Generation Note: This does not always build corectly.  Google needs to standardise things I need to figuer out which ones are wrong.
    /// </summary>
    /// <param name="service">Authenticated analytics service.</param>  
    /// <param name="ids">Unique table ID for retrieving real time data. Table ID is of the form ga:XXXX, where XXXX is the Analytics view (profile) ID.</param>
    /// <param name="metrics">A comma-separated list of real time metrics. E.g., 'rt:activeUsers'. At least one metric must be specified.</param>
    /// <param name="optional">Optional paramaters.</param>        /// <returns>RealtimeDataResponse</returns>
    public static RealtimeData Get(analyticsService service, string ids, string metrics, RealtimeGetOptionalParms optional = null)
    {
        try
        {
            // Initial validation.
            if (service == null)
                throw new ArgumentNullException("service");
            if (ids == null)
                throw new ArgumentNullException(ids);
            if (metrics == null)
                throw new ArgumentNullException(metrics);

            // Building the initial request.
            var request = service.Realtime.Get(ids, metrics);

            // Applying optional parameters to the request.                
            request = (RealtimeResource.GetRequest)SampleHelpers.ApplyOptionalParms(request, optional);

            // Requesting data.
            return request.Execute();
        }
        catch (Exception ex)
        {
            throw new Exception("Request Realtime.Get failed.", ex);
        }
    }


}
    public static class SampleHelpers
{

    /// <summary>
    /// Using reflection to apply optional parameters to the request.  
    /// 
    /// If the optonal parameters are null then we will just return the request as is.
    /// </summary>
    /// <param name="request">The request. </param>
    /// <param name="optional">The optional parameters. </param>
    /// <returns></returns>
    public static object ApplyOptionalParms(object request, object optional)
    {
        if (optional == null)
            return request;

        System.Reflection.PropertyInfo[] optionalProperties = (optional.GetType()).GetProperties();

        foreach (System.Reflection.PropertyInfo property in optionalProperties)
        {
            // Copy value from optional parms to the request.  They should have the same names and datatypes.
            System.Reflection.PropertyInfo piShared = (request.GetType()).GetProperty(property.Name);
            if (property.GetValue(optional, null) != null) // TODO Test that we do not add values for items that are null
                piShared.SetValue(request, property.GetValue(optional, null), null);
        }

        return request;
    }
}