/// <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 void QueryTransactionIdReturn200Results()
        {
            AnalyticsService service = new AnalyticsService(this.ApplicationName);

            service.Credentials = new GDataCredentials(this.userName, this.passWord);

            DataQuery query = new DataQuery(DataFeedUrl);

            query.Ids              = this.accountId;
            query.Dimensions       = "ga:transactionId,ga:date";
            query.Metrics          = "ga:transactionRevenue";
            query.Sort             = "ga:date";
            query.GAStartDate      = new DateTime(2009, 04, 01).ToString("yyyy-MM-dd");
            query.GAEndDate        = new DateTime(2009, 04, 30).ToString("yyyy-MM-dd");
            query.NumberToRetrieve = 200;
            DataFeed actual = service.Query(query);

            Assert.AreEqual(200, actual.ItemsPerPage);

            Assert.IsNotNull(actual.Aggregates);
            Assert.AreEqual(1, actual.Aggregates.Metrics.Count);

            foreach (DataEntry entry in actual.Entries)
            {
                Assert.IsNotNull(entry.Id);
            }
        }
Beispiel #3
0
        /**
         * Creates a new service object, attempts to authorize using the Client Login
         * authorization mechanism and requests data from the Google Analytics API.
         */
        public DataFeedExample()
        {
            // Configure GA API.
            AnalyticsService asv = new AnalyticsService("gaExportAPI_acctSample_v2.0");

            // Client Login Authorization.
            asv.setUserCredentials(CLIENT_USERNAME, CLIENT_PASS);

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

            DataQuery query = new DataQuery(baseUrl);

            query.Ids              = TABLE_ID;
            query.Dimensions       = "ga:source,ga:medium";
            query.Metrics          = "ga:visits,ga:bounces";
            query.Segment          = "gaid::-11";
            query.Filters          = "ga:medium==referral";
            query.Sort             = "-ga:visits";
            query.NumberToRetrieve = 5;
            query.GAStartDate      = "2010-03-01";
            query.GAEndDate        = "2010-03-15";
            Uri url = query.Uri;

            Console.WriteLine("URL: " + url.ToString());


            // Send our request to the Analytics API and wait for the results to
            // come back.

            feed = asv.Query(query);
        }
Beispiel #4
0
        public static Int64 GetVisitors(string tableId, DateTime gaStartDate, DateTime gaEndDate)
        {
            if (_asv == null)
            {
                _asv = new AnalyticsService("gaExportAPI_acctSample_v2.0");
                _asv.setUserCredentials(CLIENT_USERNAME, CLIENT_PASS);
            }
            String    baseUrl = "https://www.google.com/analytics/feeds/data";
            DataQuery query   = new DataQuery(baseUrl);

            query.Ids         = tableId;
            query.Metrics     = "ga:visits";
            query.GAStartDate = gaStartDate.ToString("yyyy'-'MM'-'dd");
            query.GAEndDate   = gaEndDate.ToString("yyyy'-'MM'-'dd");
            Uri      url = query.Uri;
            DataFeed feed;

            try
            {
                feed = _asv.Query(query);
            }
            catch { return(-1); }
            //var singleEntry = feed.Entries.Single() as DataEntry;
            //return Convert.ToInt64(singleEntry.Metrics.Single().Value);
            return(Convert.ToInt64(feed.Aggregates.Metrics[0].Value));
        }
        public void QueryBrowserMetrics()
        {
            AnalyticsService service = new AnalyticsService(this.ApplicationName);

            service.Credentials = new GDataCredentials(this.userName, this.passWord);

            DataQuery query = new DataQuery(DataFeedUrl);

            query.Ids              = this.accountId;
            query.Metrics          = "ga:pageviews";
            query.Dimensions       = "ga:browser";
            query.Sort             = "ga:browser,ga:pageviews";
            query.GAStartDate      = DateTime.Now.AddDays(-14).ToString("yyyy-MM-dd");
            query.GAEndDate        = DateTime.Now.AddDays(-2).ToString("yyyy-MM-dd");
            query.NumberToRetrieve = 200;

            DataFeed actual = service.Query(query);

            XmlTextWriter writer = new XmlTextWriter("QueryBrowserMetricsOutput.xml", Encoding.UTF8);

            writer.Formatting  = Formatting.Indented;
            writer.Indentation = 2;

            actual.SaveToXml(writer);

            foreach (DataEntry entry in actual.Entries)
            {
                Assert.IsNotNull(entry.Id);
            }
        }
        public void QueryPageViews()
        {
            AnalyticsService service = new AnalyticsService(this.ApplicationName);

            service.Credentials = new GDataCredentials(this.userName, this.passWord);

            DataQuery query = new DataQuery(DataFeedUrl);

            query.Ids              = this.accountId;
            query.Metrics          = "ga:pageviews";
            query.Dimensions       = "ga:pageTitle";
            query.Sort             = "-ga:pageviews";
            query.GAStartDate      = DateTime.Now.AddDays(-14).ToString("yyyy-MM-dd");
            query.GAEndDate        = DateTime.Now.AddDays(-2).ToString("yyyy-MM-dd");
            query.NumberToRetrieve = 200;
            DataFeed actual = service.Query(query);

            Assert.IsNotNull(actual.Aggregates);
            Assert.AreEqual(1, actual.Aggregates.Metrics.Count);

            foreach (DataEntry entry in actual.Entries)
            {
                Assert.IsNotNull(entry.Id);
            }
        }
Beispiel #7
0
        private void InitGACon()
        {
            string username = "******";
            string pass     = "******";
            string gkey     = "?key=AIzaSyCYI0zTx4iGzL4gMqaplbd1TfkF9vMukZs";

            string dataFeedUrl    = "https://www.google.com/analytics/feeds/data" + gkey;
            string accountFeedUrl = "https://www.googleapis.com/analytics/v2.4/management/accounts" + gkey;

            AnalyticsService service = new AnalyticsService("HealthyAustraliaClub");

            service.setUserCredentials(username, pass);

            DataQuery query1 = new DataQuery(dataFeedUrl);


            query1.Ids     = "ga:12345678";
            query1.Metrics = "ga:visits";
            query1.Sort    = "ga:visits";

            query1.GAStartDate = new DateTime(2012, 1, 2).ToString("yyyy-MM-dd");
            query1.GAEndDate   = DateTime.Now.ToString("yyyy-MM-dd");
            query1.StartIndex  = 1;

            DataFeed dataFeedVisits = service.Query(query1);

            foreach (DataEntry entry in dataFeedVisits.Entries)
            {
                string st = entry.Title.Text;
                string ss = entry.Metrics[0].Value;
            }
        }
        /// <summary>
        /// Runs a Query against the Google Analytics provider - AnalyticsService
        /// </summary>
        /// <param name="dimensions">multiple dimensions separated by a comma: ga:dimensionName, ga:dimensionName</param>
        /// <param name="metrics">multiple metrics separated by a comma: ga:metricName, ga:metricName</param>
        /// <param name="numberToRetrieve">the max number of entries to return</param>
        public void RunQuery(string dimensions, string metrics, int numberToRetrieve = default(int))
        {
            try
            {
                // GA Data Feed query uri.
                DataQuery query = new DataQuery(_baseUrl);
                query.Ids        = GaProfileId;
                query.Dimensions = dimensions; //"ga:date";
                query.Metrics    = metrics;    //"ga:visitors, ga:newVisits, ga:bounces";
                //query.Segment = "gaid::-11";
                //query.Filters = "ga:medium==referral";
                //query.Sort = "-ga:visits";
                //query.NumberToRetrieve = 5;
                if (numberToRetrieve != default(int))
                {
                    query.NumberToRetrieve = numberToRetrieve;
                }
                query.GAStartDate = DateAsGAString(StartDate);
                query.GAEndDate   = DateAsGAString(EndDate);
                Uri url = query.Uri;

                // Send our request to the Analytics API and wait for the results to
                // come back.
                queryResults = AnalyticsService.Query(query);
            }
            catch (AuthenticationException ex)
            {
                throw new Exception("Authentication failed : " + ex.Message);
            }
            catch (Google.GData.Client.GDataRequestException ex)
            {
                throw new Exception("Authentication failed : " + ex.Message);
            }
        }
        public List <object[]> ObterDados(string dimensao, string metrica, string ordernarPor, int?limiteResultados = null)
        {
            var query = new DataQuery(_feedURL);

            query.Ids         = _ids;
            query.GAStartDate = DataInicio.ToString("yyyy-MM-dd");
            query.GAEndDate   = DataTermino.ToString("yyyy-MM-dd");

            query.Dimensions = dimensao;
            query.Metrics    = metrica;
            query.Sort       = ordernarPor;

            if (limiteResultados != null)
            {
                query.ExtraParameters = "max-results=" + limiteResultados;
            }

            var dataFeed   = _service.Query(query);
            var resultados = new List <object[]>();

            foreach (DataEntry item in dataFeed.Entries)
            {
                var resultado = new object[2];

                resultado[0] = item.Dimensions[0].Value;
                resultado[1] = item.Metrics[0].Value;

                resultados.Add(resultado);
            }

            return(resultados);
        }
        public void QueryTransactionIdReturnAllResults()
        {
            AnalyticsService service = new AnalyticsService(this.ApplicationName);

            service.Credentials = new GDataCredentials(this.userName, this.passWord);

            int             currentIndex   = 1;
            const int       resultsPerPage = 1000;
            List <DataFeed> querys         = new List <DataFeed>();

            DataQuery query = new DataQuery(DataFeedUrl);

            query.Ids              = this.accountId;
            query.Dimensions       = "ga:transactionId,ga:date";
            query.Metrics          = "ga:transactionRevenue";
            query.Sort             = "ga:date";
            query.GAStartDate      = new DateTime(2009, 04, 01).ToString("yyyy-MM-dd");
            query.GAEndDate        = new DateTime(2009, 04, 30).ToString("yyyy-MM-dd");
            query.NumberToRetrieve = resultsPerPage;

            query.StartIndex = currentIndex;
            DataFeed actual = service.Query(query);

            querys.Add(actual);

            double totalPages = Math.Round(((double)actual.TotalResults / (double)resultsPerPage) + 0.5);

            for (int i = 1; i < totalPages; i++)
            {
                currentIndex    += resultsPerPage;
                query.StartIndex = currentIndex;
                actual           = service.Query(query);
                querys.Add(actual);
            }

            for (int i = 0; i < querys.Count; i++)
            {
                foreach (DataEntry entry in querys[i].Entries)
                {
                    Assert.IsNotNull(entry.Id);
                }
            }
        }
Beispiel #11
0
        /**
         * Creates a new service object, attempts to authorize using the Client Login
         * authorization mechanism and requests data from the Google Analytics API.
         * @throws AuthenticationException if an error occurs with authorizing with
         *     Google Accounts.
         * @throws IOException if a network error occurs.
         * @throws ServiceException if an error occurs with the Google Analytics API.
         */
        public AccountFeedExample()
        {
            // Configure GA API.
            AnalyticsService asv = new AnalyticsService("gaExportAPI_acctSample_v2.0");

            // Client Login Authorization.
            asv.setUserCredentials(CLIENT_USERNAME, CLIENT_PASS);

            // GA Account Feed query uri.

            AccountQuery query = new AccountQuery();

            // Send our request to the Analytics API and wait for the results to
            // come back.
            accountFeed = asv.Query(query);
        }
Beispiel #12
0
        private static Dictionary <DateTime, GoogleAnalyticsData> GetVisitsData(AnalyticsService service)
        {
            var data = new Dictionary <DateTime, GoogleAnalyticsData>();

            var query = new DataQuery(DataFeedUrl + SettingsSEO.GoogleAnalyticsAPIKey)
            {
                Ids         = "ga:" + SettingsSEO.GoogleAnalyticsAccountID,
                Metrics     = "ga:visitors,ga:visits,ga:pageviews",
                Dimensions  = "ga:date",
                GAStartDate = DateTime.Now.AddDays(-7).ToString("yyyy-MM-dd"),
                GAEndDate   = DateTime.Now.ToString("yyyy-MM-dd"),
                StartIndex  = 1
            };

            // try to get actual data from google

            try
            {
                var dataFeedVisits = service.Query(query);
                if (dataFeedVisits != null)
                {
                    foreach (DataEntry entry in dataFeedVisits.Entries)
                    {
                        data.Add(DateTime.ParseExact(entry.Title.Text.Split('=').LastOrDefault(), "yyyyMMdd", CultureInfo.InvariantCulture),
                                 new GoogleAnalyticsData
                        {
                            Visitors  = entry.Metrics[0].Value.TryParseInt(),
                            Visits    = entry.Metrics[1].Value.TryParseInt(),
                            PageViews = entry.Metrics[2].Value.TryParseInt(),
                        });
                    }
                }

                // saving and return data if all is ok
                SettingsSEO.GoogleAnalyticsCachedData = Newtonsoft.Json.JsonConvert.SerializeObject(data);
                SettingsSEO.GoogleAnalyticsCachedDate = DateTime.Now;
                return(data);
            }
            catch (Exception ex)
            {
                Debug.LogError(ex, false);
            }
            return(null);
        }
        public void QuerySiteStatsResultForPeriod()
        {
            AnalyticsService service = new AnalyticsService(this.ApplicationName);

            service.Credentials = new GDataCredentials(this.userName, this.passWord);

            DataQuery query = new DataQuery(DataFeedUrl);

            query.Ids         = this.accountId;
            query.Metrics     = "ga:pageviews,ga:visits,ga:newVisits,ga:transactions,ga:uniquePageviews";
            query.GAStartDate = new DateTime(2009, 04, 19).ToString("yyyy-MM-dd");
            query.GAEndDate   = new DateTime(2009, 04, 25).ToString("yyyy-MM-dd");
            query.StartIndex  = 1;

            DataFeed actual = service.Query(query);

            Assert.IsNotNull(actual.Aggregates);
            Assert.AreEqual(5, actual.Aggregates.Metrics.Count);
        }
        public DataFeed_KeywordsCost(DateTime Start, DateTime Finish, string GALogin, string GAPassword, string ids)
        {
            string           start = Start.ToString("yyyy-MM-dd");
            AnalyticsService asv   = new AnalyticsService("gaExportAPI_acctSample_v2.0");

            asv.setUserCredentials(GALogin, GAPassword);

            String baseUrl = "https://www.google.com/analytics/feeds/data";

            DataQuery query = new DataQuery(baseUrl);

            query.Ids              = "ga:" + ids;
            query.Dimensions       = "ga:adGroup,ga:keyword";
            query.Metrics          = "ga:CPC";
            query.GAStartDate      = Start.ToString("yyyy-MM-dd");
            query.NumberToRetrieve = 10000;
            query.GAEndDate        = Start.ToString("yyyy-MM-dd");
            feed = asv.Query(query);
        }
        public void QueryAccountIds()
        {
            AnalyticsService service = new AnalyticsService(this.ApplicationName);

            service.Credentials = new GDataCredentials(this.userName, this.passWord);

            AccountQuery feedQuery = new AccountQuery(AccountFeedUrl);
            AccountFeed  actual    = service.Query(feedQuery);

            foreach (AccountEntry entry in actual.Entries)
            {
                Assert.IsNotNull(entry.Id);
                Assert.IsNotNull(entry.ProfileId.Value);
                if (this.accountId == null)
                {
                    this.accountId = entry.ProfileId.Value;
                }
            }
        }
        public DataFeed_DirectTraffic(DateTime Start, DateTime Finish, string GALogin, string GAPassword, string ids)
        {
            string           start = Start.ToString("yyyy-MM-dd");
            AnalyticsService asv   = new AnalyticsService("gaExportAPI_acctSample_v2.0");

            asv.setUserCredentials(GALogin, GAPassword);

            String baseUrl = "https://www.google.com/analytics/feeds/data";

            DataQuery query = new DataQuery(baseUrl);

            query.Ids        = "ga:" + ids;
            query.Dimensions = "ga:eventLabel";
            //  query.Metrics = "ga:timeOnSite, ga:newVisits";
            query.Metrics          = "ga:visits";
            query.Segment          = "gaid::-7";
            query.GAStartDate      = Start.ToString("yyyy-MM-dd");
            query.NumberToRetrieve = 10000;
            query.GAEndDate        = Finish.ToString("yyyy-MM-dd");
            feed = asv.Query(query);
        }
        public void QueryProductCategoryResultForPeriod()
        {
            AnalyticsService service = new AnalyticsService(this.ApplicationName);

            service.Credentials = new GDataCredentials(this.userName, this.passWord);

            DataQuery query = new DataQuery(DataFeedUrl);

            query.Ids         = this.accountId;
            query.Dimensions  = "ga:productCategory,ga:productName";
            query.Metrics     = "ga:itemRevenue,ga:itemQuantity";
            query.Sort        = "ga:productCategory";
            query.GAStartDate = new DateTime(2009, 04, 19).ToString("yyyy-MM-dd");
            query.GAEndDate   = new DateTime(2009, 04, 25).ToString("yyyy-MM-dd");

            DataFeed actual = service.Query(query);

            Assert.IsNotNull(actual);
            Assert.IsNotNull(actual.Entries);

            foreach (DataEntry entry in actual.Entries)
            {
                Assert.AreEqual(2, entry.Dimensions.Count);
                Assert.IsNotNull(entry.Dimensions[0]);
                Assert.IsNotNull(entry.Dimensions[0].Name);
                Assert.IsNotNull(entry.Dimensions[0].Value);
                Assert.IsNotNull(entry.Dimensions[1]);
                Assert.IsNotNull(entry.Dimensions[1].Name);
                Assert.IsNotNull(entry.Dimensions[1].Value);
                Assert.AreEqual(2, entry.Metrics.Count);
                Assert.IsNotNull(entry.Metrics[0]);
                Assert.IsNotNull(entry.Metrics[0].Name);
                Assert.IsNotNull(entry.Metrics[0].Value);
                Assert.IsNotNull(entry.Metrics[1]);
                Assert.IsNotNull(entry.Metrics[1].Name);
                Assert.IsNotNull(entry.Metrics[1].Value);
            }
        }
Beispiel #18
0
        private static int GetTotalVisitors(AnalyticsService service)
        {
            var totalVisitorsQuerry = new DataQuery(DataFeedUrl + SettingsSEO.GoogleAnalyticsAPIKey)
            {
                Ids         = "ga:" + SettingsSEO.GoogleAnalyticsAccountID,
                Metrics     = "ga:visitors",
                Dimensions  = "ga:year",
                GAStartDate = DateTime.Now.AddYears(-1).ToString("yyyy-MM-dd"),
                GAEndDate   = DateTime.Now.ToString("yyyy-MM-dd"),
                StartIndex  = 1
            };

            try
            {
                var totalVisitors = service.Query(totalVisitorsQuerry);
                return(totalVisitors.Aggregates.Metrics[0].Value.TryParseInt());
            }
            catch (Exception ex)
            {
                Debug.LogError(ex, false);
            }
            return(0);
        }
Beispiel #19
0
        /// <summary>
        /// Gets the data feed.
        /// </summary>
        /// <param name="start">The start.</param>
        /// <param name="end">The end.</param>
        /// <param name="dimensionVariables">The dimension variables.</param>
        /// <param name="metricVariables">The metric variables.</param>
        /// <param name="sortByVariables">The sort by variables.</param>
        /// <returns></returns>
        public DataFeed GetDataFeed(DateTime start, DateTime end,
                                    string dimensionVariables, string metricVariables, string sortByVariables)
        {
            // Configure GA API.
            AnalyticsService asv =
                new AnalyticsService(Constants.Service.ApplicationName);

            // Client Login Authorization.
            asv.setUserCredentials(userName, password);

            // GA Data Feed query uri.
            String baseUrl = Constants.Service.QueryUrl;

            DataQuery query = new DataQuery(baseUrl);

            query.Ids = tableId;

            //query.Segment = "gaid::-1";
            //query.Filters = "ga:medium==referral";
            //query.NumberToRetrieve = 5;

            query.Dimensions  = dimensionVariables;
            query.Metrics     = metricVariables;
            query.Sort        = sortByVariables;
            query.GAStartDate = start.ToString("yyyy-MM-dd");
            query.GAEndDate   = end.ToString("yyyy-MM-dd");

            //Uri url = query.Uri;
            //Console.WriteLine("URL: " + url.ToString());

            // Send our request to the Analytics API and wait for the results to
            // come back.

            DataFeed feed = asv.Query(query);

            return(feed);
        }
        private ActionResult ConfigView(Settings settings, Config model)
        {
            // Grab all of the available sites that the authorized account has access to
            var authFactory = new GAuthSubRequestFactory("analytics", ApplicationName)
            {
                Token = settings.SessionToken
            };
            var analytics = new AnalyticsService(authFactory.ApplicationName)
            {
                RequestFactory = authFactory
            };

            foreach (AccountEntry entry in analytics.Query(new AccountQuery()).Entries)
            {
                var account = entry.Properties.First(x => x.Name == "ga:accountName").Value;
                if (!model.Sites.ContainsKey(account))
                {
                    model.Sites.Add(account, new Dictionary <string, string>());
                }
                model.Sites[account].Add(entry.ProfileId.Value, entry.Title.Text);
            }

            return(View("Config", model));
        }
        public string VisitsNumber()
        {
            string visits   = string.Empty;
            string username = "******";
            string pass     = "******";
            string gkey     = "?key= **** --> Your APY key <--  ****";

            string dataFeedUrl    = "https://www.google.com/analytics/feeds/data" + gkey;
            string accountFeedUrl = "https://www.googleapis.com/analytics/v2.4/management/accounts" + gkey;

            AnalyticsService service = new AnalyticsService("WebApp");

            service.setUserCredentials(username, pass);

            DataQuery query1 = new DataQuery(dataFeedUrl);

            query1.Ids     = "ga:********";
            query1.Metrics = "ga:visits";
            query1.Sort    = "ga:visits";


            query1.GAStartDate = new DateTime(2013, 1, 2).ToString("yyyy-MM-dd");
            query1.GAEndDate   = DateTime.Now.ToString("yyyy-MM-dd");
            query1.StartIndex  = 1;

            DataFeed dataFeedVisits = service.Query(query1);

            foreach (DataEntry entry in dataFeedVisits.Entries)
            {
                string st = entry.Title.Text;
                string ss = entry.Metrics[0].Value;
                visits = ss;
            }

            return(visits);
        }
Beispiel #22
0
        public void GetVisitorStatistics(string hostname, DateTime startDate, DateTime endDate)
        {
            var query = new DataQuery(BaseUrl)
            {
                Ids         = TableId,
                Dimensions  = "ga:date,ga:referralPath,ga:source,ga:keyword,ga:country",
                Metrics     = "ga:visits,ga:pageviews,ga:timeOnSite",
                Segment     = string.Format("dynamic::ga:hostname=={0}", hostname),
                Sort        = "ga:date",
                GAStartDate = startDate.ToString("yyyy-MM-dd"),
                GAEndDate   = endDate.ToString("yyyy-MM-dd")
            };

            Uri url = query.Uri;

            try
            {
                // try to get from the cache first
                var cachekey = string.Concat(hostname, startDate.ToShortDateString(), endDate.ToShortDateString());
                var data     = SimpleCache.Get(cachekey, SimpleCacheType.GOOGLE_ANALYTICS);
                if (data == null)
                {
                    data = service.Query(query);
                    SimpleCache.Add(cachekey, data, SimpleCacheType.GOOGLE_ANALYTICS, DateTime.UtcNow.AddDays(1));
                }

                feed = (DataFeed)data;

                FeedTitle    = feed.Title.Text;
                FeedID       = feed.Id.Uri.Content;
                TotalResults = feed.TotalResults;
                StartIndex   = feed.StartIndex;
                ItemsPerPage = feed.ItemsPerPage;

                foreach (DataEntry entry in feed.Entries)
                {
                    var stat = new VisitorStat();
                    foreach (var dimension in entry.Dimensions)
                    {
                        switch (dimension.Name)
                        {
                        case "ga:country":
                            stat.country = dimension.Value;
                            break;

                        case "ga:date":
                            stat.visitDate = DateTime.ParseExact(dimension.Value, "yyyyMMdd", CultureInfo.InvariantCulture);
                            break;

                        case "ga:referralPath":
                            stat.referrerPath = dimension.Value;
                            break;

                        case "ga:source":
                            stat.referrerHostname = dimension.Value;
                            break;

                        case "ga:keyword":
                            stat.keyword = dimension.Value;
                            break;
                        }
                    }
                    foreach (var metric in entry.Metrics)
                    {
                        switch (metric.Name)
                        {
                        case "ga:visits":
                            stat.visitCount = metric.IntegerValue;
                            break;

                        case "ga:pageviews":
                            stat.pageViews = metric.IntegerValue;
                            break;

                        case "ga:timeOnSite":
                            stat.timeOnSite = metric.FloatValue;
                            break;
                        }
                    }
                    stats.Add(stat);
                }
            }
            catch (Exception ex)
            {
                Syslog.Write(ex);
                Syslog.Write(string.Concat(ex.Message, ":", url.ToString()));
            }
        }
        public ActionResult Analytics(int?duration)
        {
            CacheContext.InvalidateOn(TriggerFrom.Any <SiteSettings>());

            var settings = _siteSettingsService.GetSettings();

            if (string.IsNullOrEmpty(settings.AnalyticsToken))
            {
                const string scope = "https://www.google.com/analytics/feeds/";
                var          next  = Url.Absolute(Url.AnalyticsWidget().AuthResponse());
                var          auth  = new Authorize
                {
                    Url = AuthSubUtil.getRequestUrl(next, scope, false, true)
                };
                return(View("AnalyticsAuthorize", auth));
            }

            if (string.IsNullOrEmpty(settings.AnalyticsProfileId))
            {
                var config = new Config
                {
                    Accounts = GetAccounts(settings),
                    Profiles = GetProfiles(settings)
                };

                return(View("AnalyticsConfig", config));
            }

            duration = duration ?? 30;
            var model = new ViewModels.Widgets.Analytics
            {
                Duration     = duration.Value,
                Start        = DateTime.Today.AddDays(-1 * duration.Value),
                End          = DateTime.Now,
                Visits       = new Dictionary <DateTime, int>(),
                PageViews    = new Dictionary <string, int>(),
                PageTitles   = new Dictionary <string, string>(),
                TopReferrers = new Dictionary <string, int>(),
                TopSearches  = new Dictionary <string, int>()
            };

            if (model.Start > model.End)
            {
                var tempDate = model.Start;
                model.Start = model.End;
                model.End   = tempDate;
            }

            var profiles = GetProfiles(settings);
            var profile  = profiles.SingleOrDefault(x => x.Id == settings.AnalyticsProfileId);

            if (profile == null)
            {
                throw new Exception("Unable to find the specified analytics profile: " + settings.AnalyticsProfileId);
            }
            model.Profile = profile;

            var authFactory = new GAuthSubRequestFactory("analytics", "MvcKickstart")
            {
                Token = settings.AnalyticsToken
            };

            var analytics = new AnalyticsService(authFactory.ApplicationName)
            {
                RequestFactory = authFactory
            };

            var profileId = "ga:" + settings.AnalyticsProfileId;

            // Get from All Visits
            var visits = new DataQuery(profileId, model.Start, model.End)
            {
                Metrics    = "ga:visits",
                Dimensions = "ga:date",
                Sort       = "ga:date"
            };
            var count = 0;

            foreach (DataEntry entry in analytics.Query(visits).Entries)
            {
                var value = entry.Metrics.First().IntegerValue;

                model.Visits.Add(model.Start.AddDays(count++), value);
            }

            // Get Site Usage
            var siteUsage = new DataQuery(profileId, model.Start, model.End)
            {
                Metrics = "ga:visits,ga:pageviews,ga:percentNewVisits,ga:avgTimeOnSite,ga:entranceBounceRate,ga:exitRate,ga:pageviewsPerVisit,ga:avgPageLoadTime"
            };
            var siteUsageResult = (DataEntry)analytics.Query(siteUsage).Entries.FirstOrDefault();

            if (siteUsageResult != null)
            {
                foreach (var metric in siteUsageResult.Metrics)
                {
                    switch (metric.Name)
                    {
                    case "ga:visits":
                        model.TotalVisits = metric.IntegerValue;
                        break;

                    case "ga:pageviews":
                        model.TotalPageViews = metric.IntegerValue;
                        break;

                    case "ga:percentNewVisits":
                        model.PercentNewVisits = metric.FloatValue;
                        break;

                    case "ga:avgTimeOnSite":
                        model.AverageTimeOnSite = TimeSpan.FromSeconds(metric.FloatValue);
                        break;

                    case "ga:entranceBounceRate":
                        model.EntranceBounceRate = metric.FloatValue;
                        break;

                    case "ga:exitRate":
                        model.PercentExitRate = metric.FloatValue;
                        break;

                    case "ga:pageviewsPerVisit":
                        model.PageviewsPerVisit = metric.FloatValue;
                        break;

                    case "ga:avgPageLoadTime":
                        model.AveragePageLoadTime = TimeSpan.FromSeconds(metric.FloatValue);
                        break;
                    }
                }
            }

            // Get Top Pages
            var topPages = new DataQuery(profileId, model.Start, model.End)
            {
                Metrics          = "ga:pageviews",
                Dimensions       = "ga:pagePath,ga:pageTitle",
                Sort             = "-ga:pageviews",
                NumberToRetrieve = 20
            };

            foreach (DataEntry entry in analytics.Query(topPages).Entries)
            {
                var value = entry.Metrics.First().IntegerValue;
                var url   = entry.Dimensions.Single(x => x.Name == "ga:pagePath").Value.ToLowerInvariant();
                var title = entry.Dimensions.Single(x => x.Name == "ga:pageTitle").Value;

                if (!model.PageViews.ContainsKey(url))
                {
                    model.PageViews.Add(url, 0);
                }
                model.PageViews[url] += value;

                if (!model.PageTitles.ContainsKey(url))
                {
                    model.PageTitles.Add(url, title);
                }
            }

            // Get Top Referrers
            var topReferrers = new DataQuery(profileId, model.Start, model.End)
            {
                Metrics          = "ga:visits",
                Dimensions       = "ga:source,ga:medium",
                Sort             = "-ga:visits",
                Filters          = "ga:medium==referral",
                NumberToRetrieve = 5
            };

            foreach (DataEntry entry in analytics.Query(topReferrers).Entries)
            {
                var visitCount = entry.Metrics.First().IntegerValue;
                var source     = entry.Dimensions.Single(x => x.Name == "ga:source").Value.ToLowerInvariant();

                model.TopReferrers.Add(source, visitCount);
            }

            // Get Top Searches
            var topSearches = new DataQuery(profileId, model.Start, model.End)
            {
                Metrics          = "ga:visits",
                Dimensions       = "ga:keyword",
                Sort             = "-ga:visits",
                Filters          = "ga:keyword!=(not set);ga:keyword!=(not provided)",
                NumberToRetrieve = 5
            };

            foreach (DataEntry entry in analytics.Query(topSearches).Entries)
            {
                var visitCount = entry.Metrics.First().IntegerValue;
                var source     = entry.Dimensions.Single(x => x.Name == "ga:keyword").Value.ToLowerInvariant();

                model.TopSearches.Add(source, visitCount);
            }

            return(View(model));
        }
        public ActionResult AnalyticsSummary()
        {
            var to   = DateTime.Today.AddDays(-1);
            var from = to.AddDays(-30);

            var model = new AnalyticsSummary
            {
                Visits       = new List <int>(),
                PageViews    = new Dictionary <string, int>(),
                PageTitles   = new Dictionary <string, string>(),
                TopReferrers = new Dictionary <string, int>(),
                TopSearches  = new Dictionary <string, int>()
            };

            var settings = RavenSession.Load <Settings>(Settings.DefaultId);

            var authFactory = new GAuthSubRequestFactory("analytics", ApplicationName)
            {
                Token = settings.SessionToken
            };


            var analytics = new AnalyticsService(authFactory.ApplicationName)
            {
                RequestFactory = authFactory
            };

            // Get from All Visits
            var visits = new DataQuery(settings.SiteId, from, to)
            {
                Metrics    = "ga:visits",
                Dimensions = "ga:date",
                Sort       = "ga:date"
            };

            foreach (DataEntry entry in analytics.Query(visits).Entries)
            {
                var value = entry.Metrics.First().IntegerValue;

                model.Visits.Add(value);
            }

            // Get Site Usage
            var siteUsage = new DataQuery(settings.SiteId, from, to)
            {
                Metrics = "ga:visits,ga:pageviews,ga:percentNewVisits,ga:avgTimeOnSite,ga:entranceBounceRate,ga:exitRate,ga:pageviewsPerVisit,ga:avgPageLoadTime"
            };
            var siteUsageResult = (DataEntry)analytics.Query(siteUsage).Entries.FirstOrDefault();

            if (siteUsageResult != null)
            {
                foreach (var metric in siteUsageResult.Metrics)
                {
                    switch (metric.Name)
                    {
                    case "ga:visits":
                        model.TotalVisits = metric.IntegerValue;
                        break;

                    case "ga:pageviews":
                        model.TotalPageViews = metric.IntegerValue;
                        break;

                    case "ga:percentNewVisits":
                        model.PercentNewVisits = metric.FloatValue;
                        break;

                    case "ga:avgTimeOnSite":
                        model.AverageTimeOnSite = TimeSpan.FromSeconds(metric.FloatValue);
                        break;

                    case "ga:entranceBounceRate":
                        model.EntranceBounceRate = metric.FloatValue;
                        break;

                    case "ga:exitRate":
                        model.PercentExitRate = metric.FloatValue;
                        break;

                    case "ga:pageviewsPerVisit":
                        model.PageviewsPerVisit = metric.FloatValue;
                        break;

                    case "ga:avgPageLoadTime":
                        model.AveragePageLoadTime = TimeSpan.FromSeconds(metric.FloatValue);
                        break;
                    }
                }
            }

            // Get Top Pages
            var topPages = new DataQuery(settings.SiteId, from, to)
            {
                Metrics          = "ga:pageviews",
                Dimensions       = "ga:pagePath,ga:pageTitle",
                Sort             = "-ga:pageviews",
                NumberToRetrieve = 20
            };

            foreach (DataEntry entry in analytics.Query(topPages).Entries)
            {
                var value = entry.Metrics.First().IntegerValue;
                var url   = entry.Dimensions.Single(x => x.Name == "ga:pagePath").Value.ToLowerInvariant();
                var title = entry.Dimensions.Single(x => x.Name == "ga:pageTitle").Value;

                if (!model.PageViews.ContainsKey(url))
                {
                    model.PageViews.Add(url, 0);
                }
                model.PageViews[url] += value;

                if (!model.PageTitles.ContainsKey(url))
                {
                    model.PageTitles.Add(url, title);
                }
            }

            // Get Top Referrers
            var topReferrers = new DataQuery(settings.SiteId, from, to)
            {
                Metrics          = "ga:visits",
                Dimensions       = "ga:source,ga:medium",
                Sort             = "-ga:visits",
                Filters          = "ga:medium==referral",
                NumberToRetrieve = 5
            };

            foreach (DataEntry entry in analytics.Query(topReferrers).Entries)
            {
                var visitCount = entry.Metrics.First().IntegerValue;
                var source     = entry.Dimensions.Single(x => x.Name == "ga:source").Value.ToLowerInvariant();

                model.TopReferrers.Add(source, visitCount);
            }

            // Get Top Searches
            var topSearches = new DataQuery(settings.SiteId, from, to)
            {
                Metrics          = "ga:visits",
                Dimensions       = "ga:keyword",
                Sort             = "-ga:visits",
                Filters          = "ga:keyword!=(not set);ga:keyword!=(not provided)",
                NumberToRetrieve = 5
            };

            foreach (DataEntry entry in analytics.Query(topSearches).Entries)
            {
                var visitCount = entry.Metrics.First().IntegerValue;
                var source     = entry.Dimensions.Single(x => x.Name == "ga:keyword").Value.ToLowerInvariant();

                model.TopSearches.Add(source, visitCount);
            }

            return(View(model));
        }