使用 Google Analytics API 在 C# 中显示信息 [英] Use Google Analytics API to show information in C#

查看:21
本文介绍了使用 Google Analytics API 在 C# 中显示信息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一整天都在寻找一个好的解决方案,但 google 发展得太快了,以至于我找不到任何可行的方法.我想要做的是,我有一个 Web 应用程序,它有一个管理部分,用户需要登录才能查看信息.在本节中,我想显示一些来自 GA 的数据,例如某些特定 url 的综合浏览量.由于我显示的不是用户信息,而是谷歌分析的用户,我想连接传递信息(用户名/密码或 APIKey),但我不知道如何连接.我找到的所有样本都使用 OAuth2(女巫,如果我理解,会要求访问者使用谷歌登录).

I been looking for a good solution all day but google evolve so fast that I can't find something working. What I want to do is that, I have a Web app that has an admin section where user need to be logged in to see the information. In this section I want to show some data from GA, like pageviews for some specific urls. Since it's not the user information that I'm showing but the google analytics'user I want to connect passing information (username/password or APIKey) but I can't find out how. All the sample I found use OAuth2 (witch, if I understand, will ask the visitor to log in using google).

到目前为止我发现了什么:

What I found so far :

  • Google official Client Library for .Net : http://code.google.com/p/google-api-dotnet-client/, no sample for GA
  • official developers help : https://developers.google.com/analytics/
  • an other question with code on SO : Google Analytics API - Programmatically fetch page views in server side but I get a 403 when I try to authenticate
  • some source that access the API : http://www.reimers.dk/jacob-reimers-blog/added-google-analytics-reader-for-net downloaded the source but I can't figure out how it works
  • this other question on SO : Google Analytics Access with C# but it does not help
  • while writing this they suggest me this 09 old post Google Analytics API and .Net...

也许我只是累了,明天很容易找到解决方案,但现在我需要帮助!

Maybe I'm just tired and that tomorrow it will be easy to find a solution but right now I need help!

谢谢

推荐答案

我进行了大量搜索,最后要么从多个地方查找代码,然后围绕它包装我自己的界面,我想出了以下解决方案.不确定人们是否将他们的整个代码粘贴在这里,但我想为什么不节省其他人的时间:)

I did a lot of search and finally either looking up code from multiple places and then wrapping my own interface around it i came up with the following solution. Not sure if people paste their whole code here, but i guess why not save everyone else time :)

先决条件,您需要安装 Google.GData.Client 和 google.gdata.analytics 包/dll.

Pre-requisites, you will need to install Google.GData.Client and google.gdata.analytics package/dll.

这是完成工作的主类.

namespace Utilities.Google
{
    public class Analytics
    {
        private readonly String ClientUserName;
        private readonly String ClientPassword;
        private readonly String TableID;
        private AnalyticsService analyticsService;

        public Analytics(string user, string password, string table)
        {
            this.ClientUserName = user;
            this.ClientPassword = password;
            this.TableID = table;

            // Configure GA API.
            analyticsService = new AnalyticsService("gaExportAPI_acctSample_v2.0");
            // Client Login Authorization.
            analyticsService.setUserCredentials(ClientUserName, ClientPassword);
        }

        /// <summary>
        /// Get the page views for a particular page path
        /// </summary>
        /// <param name="pagePath"></param>
        /// <param name="startDate"></param>
        /// <param name="endDate"></param>
        /// <param name="isPathAbsolute">make this false if the pagePath is a regular expression</param>
        /// <returns></returns>
        public int GetPageViewsForPagePath(string pagePath, DateTime startDate, DateTime endDate, bool isPathAbsolute = true)
        {
            int output = 0;

            // GA Data Feed query uri.
            String baseUrl = "https://www.google.com/analytics/feeds/data";

            DataQuery query = new DataQuery(baseUrl);
            query.Ids = TableID;
            //query.Dimensions = "ga:source,ga:medium";
            query.Metrics = "ga:pageviews";
            //query.Segment = "gaid::-11";
            var filterPrefix = isPathAbsolute ? "ga:pagepath==" : "ga:pagepath=~";
            query.Filters = filterPrefix + pagePath;
            //query.Sort = "-ga:visits";
            //query.NumberToRetrieve = 5;
            query.GAStartDate = startDate.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture);
            query.GAEndDate = endDate.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture);
            Uri url = query.Uri;
            DataFeed feed = analyticsService.Query(query);
            output = Int32.Parse(feed.Aggregates.Metrics[0].Value);

            return output;
        }

        public Dictionary<string, int> PageViewCounts(string pagePathRegEx, DateTime startDate, DateTime endDate)
        {
            // GA Data Feed query uri.
            String baseUrl = "https://www.google.com/analytics/feeds/data";

            DataQuery query = new DataQuery(baseUrl);
            query.Ids = TableID;
            query.Dimensions = "ga:pagePath";
            query.Metrics = "ga:pageviews";
            //query.Segment = "gaid::-11";
            var filterPrefix = "ga:pagepath=~";
            query.Filters = filterPrefix + pagePathRegEx;
            //query.Sort = "-ga:visits";
            //query.NumberToRetrieve = 5;
            query.GAStartDate = startDate.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture);
            query.GAEndDate = endDate.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture);
            Uri url = query.Uri;
            DataFeed feed = analyticsService.Query(query);

            var returnDictionary = new Dictionary<string, int>();
            foreach (var entry in feed.Entries)
                returnDictionary.Add(((DataEntry)entry).Dimensions[0].Value, Int32.Parse(((DataEntry)entry).Metrics[0].Value));

            return returnDictionary;
        }
    }
}

这是我用来包装它的接口和实现.

And this is the interface and implementation that i use to wrap it up with.

namespace Utilities
{
    public interface IPageViewCounter
    {
        int GetPageViewCount(string relativeUrl, DateTime startDate, DateTime endDate, bool isPathAbsolute = true);
        Dictionary<string, int> PageViewCounts(string pagePathRegEx, DateTime startDate, DateTime endDate);
    }

    public class GooglePageViewCounter : IPageViewCounter
    {
        private string GoogleUserName
        {
            get
            {
                return ConfigurationManager.AppSettings["googleUserName"];
            }
        }

        private string GooglePassword
        {
            get
            {
                return ConfigurationManager.AppSettings["googlePassword"];
            }
        }

        private string GoogleAnalyticsTableName
        {
            get
            {
                return ConfigurationManager.AppSettings["googleAnalyticsTableName"];
            }
        }

        private Analytics analytics;

        public GooglePageViewCounter()
        {
            analytics = new Analytics(GoogleUserName, GooglePassword, GoogleAnalyticsTableName);
        }

        #region IPageViewCounter Members

        public int GetPageViewCount(string relativeUrl, DateTime startDate, DateTime endDate, bool isPathAbsolute = true)
        {
            int output = 0;
            try
            {
                output = analytics.GetPageViewsForPagePath(relativeUrl, startDate, endDate, isPathAbsolute);
            }
            catch (Exception ex)
            {
                Logger.Error(ex);
            }

            return output;
        }

        public Dictionary<string, int> PageViewCounts(string pagePathRegEx, DateTime startDate, DateTime endDate)
        {
            var input = analytics.PageViewCounts(pagePathRegEx, startDate, endDate);
            var output = new Dictionary<string, int>();

            foreach (var item in input)
            {
                if (item.Key.Contains('&'))
                {
                    string[] key = item.Key.Split(new char[] { '?', '&' });
                    string newKey = key[0] + "?" + key.FirstOrDefault(k => k.StartsWith("p="));

                    if (output.ContainsKey(newKey))
                        output[newKey] += item.Value;
                    else
                        output[newKey] = item.Value;
                }
                else
                    output.Add(item.Key, item.Value);
            }
            return output;
        }

        #endregion
    }
}

现在剩下的就是显而易见的东西了 - 您必须将 web.config 值添加到您的应用程序配置或 webconfig 并调用 IPageViewCounter.GetPageViewCount

And now the rest is the obvious stuff - you will have to add the web.config values to your application config or webconfig and call IPageViewCounter.GetPageViewCount

这篇关于使用 Google Analytics API 在 C# 中显示信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆