Ejemplo n.º 1
0
        /// <summary>
        /// Gets data points for browser type, version and device categories
        /// </summary>
        /// <param name="profile">Google Analytics profile identifier</param>
        /// <param name="dateSpan">Number of days preceding the current day</param>
        /// <param name="filter">The page path</param>
        /// <returns></returns>
        public HttpResponseMessage GetBrowserDatapoints(string profile, string dateSpan, string filter)
        {
            EnsureGoogleService();

            AnalyticsGetDataResponse data = _googleService.Analytics.Data.GetData(new AnalyticsGetDataOptions
            {
                ProfileId  = profile,
                StartDate  = StartDate(dateSpan),
                EndDate    = DateTime.Now,
                Filters    = filter,
                Dimensions = AnalyticsDimensions.Browser + AnalyticsDimensions.DeviceCategory + AnalyticsDimensions.BrowserVersion,
                Metrics    = AnalyticsMetrics.Users,
                Sorting    = new AnalyticsDataSortOptions().AddDescending(AnalyticsMetrics.Users),
                MaxResults = 10
            });

            Dictionary <string, int>       browserCatData = new Dictionary <string, int>();
            List <ApiResponse.BrowserData> browserData    = new List <ApiResponse.BrowserData>();
            Dictionary <string, Dictionary <string, int> > browserDict = new Dictionary <string, Dictionary <string, int> >();

            foreach (AnalyticsDataRow analyticsDataRow in data.Body.Rows)
            {
                string browserName    = analyticsDataRow.Cells[0].ToString();
                string deviceCategory = analyticsDataRow.Cells[1].ToString();
                string browserVersion = analyticsDataRow.Cells[2].ToString();
                int    views          = Convert.ToInt32(analyticsDataRow.Cells[3].Value);

                if (!browserCatData.ContainsKey(deviceCategory))
                {
                    browserCatData.Add(deviceCategory, 0);
                }

                // why? isn't this just assigning a value back into browsercatdata for the device category?
                Dictionary <string, int> dictionary3;
                string index2;
                (dictionary3 = browserCatData)[index2 = deviceCategory] = dictionary3[index2] + views;

                if (!browserDict.ContainsKey(browserName))
                {
                    browserDict.Add(browserName, new Dictionary <string, int>());
                }
                browserDict[browserName][browserVersion] = views;
            }

            foreach (KeyValuePair <string, Dictionary <string, int> > keyValuePair in browserDict.Take(5)
                     .ToDictionary(t => t.Key, t => t.Value))
            {
                browserData.Add(new ApiResponse.BrowserData()
                {
                    browser = keyValuePair.Key,
                    version = keyValuePair.Value
                });
            }

            return(Response(new ApiResponse.BrowserDataObject
            {
                browserData = browserData.OrderBy(x => x.browser),
                browserCatData = browserCatData
            }));
        }
Ejemplo n.º 2
0
 /// <summary>
 /// Gets historical data based on the specified <paramref name="options"/>.
 /// </summary>
 /// <param name="options">The options for the request to the API.</param>
 /// <returns>An instance of <see cref="AnalyticsGetDataResponse"/> representing the response.</returns>
 public AnalyticsGetDataResponse GetData(AnalyticsGetDataOptions options)
 {
     if (options == null)
     {
         throw new ArgumentNullException(nameof(options));
     }
     return(AnalyticsGetDataResponse.ParseResponse(Raw.GetData(options)));
 }
Ejemplo n.º 3
0
        private object GetHistory(AnalyticsEndpoint analytics, string profileId, IPublishedContent content, AnalyticsDataMode mode, Period period)
        {
            // Declare the options for the request
            AnalyticsGetDataOptions options = new AnalyticsGetDataOptions {
                ProfileId  = profileId,
                StartDate  = period.StartDate,
                EndDate    = period.EndDate,
                Metrics    = AnalyticsMetrics.Sessions + AnalyticsMetrics.Pageviews,
                Dimensions = AnalyticsDimensions.Hour
            };

            if (mode == AnalyticsDataMode.Page)
            {
                // Google Analytics sees the same URL with and without a trailing slash as two different pages, so we should tell the query to check both
                string pageUrlTrimmed = content.Url.TrimEnd('/');
                string pageUrlSlashed = pageUrlTrimmed + '/';

                options.Filters.Add(new AnalyticsDimensionFilter(AnalyticsDimensions.PagePath, AnalyticsDimensionOperator.ExactMatch, pageUrlTrimmed));
                options.Filters.Add(new AnalyticsDimensionFilter(AnalyticsDimensions.PagePath, AnalyticsDimensionOperator.ExactMatch, pageUrlSlashed));
            }

            // Determine the dimension based on the length of the period
            if (period.Days <= 1)
            {
                options.Dimensions = AnalyticsDimensions.Hour;
            }
            else if (period.Days <= 31)
            {
                options.Dimensions = AnalyticsDimensions.Date;
            }
            else
            {
                options.Dimensions = AnalyticsDimensions.YearWeek;
            }

            // Get the data from the Analytics API
            AnalyticsGetDataResponse response = analytics.Data.GetData(options);

            // Return an empty model if there are no valid rows
            if (response.Body.Rows.All(x => x.GetInt32(AnalyticsMetrics.Sessions) == 0))
            {
                return(new AnalyticsHistory());
            }

            // Initialize the data sets
            ChartJsDataSet pageviews = new ChartJsDataSet("Pageviews", "#F1BFBD");
            ChartJsDataSet sessions  = new ChartJsDataSet("Sessions", "#1D274E");

            // Initialize the chart data
            ChartJsData chart = new ChartJsData {
                DataSets = new List <ChartJsDataSet> {
                    pageviews, sessions
                }
            };

            // Populate the labels and data of each data set
            foreach (AnalyticsDataRow row in response.Body.Rows)
            {
                if (row.TryGetValue(AnalyticsDimensions.Date, out string date))
                {
                    DateTime dt = DateTime.ParseExact(date, "yyyyMMdd", CultureInfo.InvariantCulture);
                    chart.Labels.Add(dt.ToString("MMM d"));
                }
                else if (row.TryGetValue(AnalyticsDimensions.Hour, out string hour))
                {
                    chart.Labels.Add(hour);
                }
                else if (row.TryGetValue(AnalyticsDimensions.YearWeek, out string yearWeek))
                {
                    chart.Labels.Add("W" + Int32.Parse(yearWeek.Substring(4)));
                }
                else
                {
                    chart.Labels.Add(row.Cells[0].Value);
                }

                chart.Rows.Add(row);

                pageviews.Data.Add(row.GetString(AnalyticsMetrics.Pageviews));
                sessions.Data.Add(row.GetString(AnalyticsMetrics.Sessions));
            }

            return(new AnalyticsHistory {
                Chart = chart
            });
        }