Example #1
0
        internal AnalyticsDataResponse GetCachedData(string key, AnalyticsDataOptions options)
        {
            // Declare the path to the cache directory
            string cacheDir = HttpContext.Current.Server.MapPath(DashboardConstants.AnalyticsCachePath + (PageId > 0 ? "Pages/" : ""));

            // Make sure the cache directory exists
            if (!Directory.Exists(cacheDir))
            {
                Directory.CreateDirectory(cacheDir);
            }

            // Generate a combined key
            string combinedKey = (PageId > 0 ? PageId + "" : Site.Analytics.ProfileId) + "_" + key + "_" + Days + ".json";

            // Declare the path to the cache file (based on the cache key)
            string path = Path.Combine(cacheDir, combinedKey + ".json");

            // Return the cache response if present and not expired
            if (EnableCaching && File.Exists(path) && File.GetLastWriteTimeUtc(path) > DateTime.Today)
            {
                return(AnalyticsDataResponse.LoadJson(path));
            }

            // Get the data from the Analytics API
            AnalyticsDataResponse response = Service.Analytics.GetData(Site.Analytics.ProfileId, options);

            // Save the response to the cache
            response.SaveJson(path);

            // Return the response
            return(response);
        }
        /// <summary>
        /// Get Transactions
        /// </summary>
        /// <param name="profile"></param>
        /// <returns></returns>
        public StatsApiResult GetTransactions(string profile, DateTime? startDate, DateTime? endDate)
        {
            if (!startDate.HasValue)
                startDate = DateTime.Now.Subtract(TimeSpan.FromDays(31));
            if (!endDate.HasValue)
                endDate = DateTime.Now;
            //Profile, Start Date, End Date, Metrics (Array), Dimensions (Array)

            AnalyticsDataResponse data = GetGoogleService().Analytics.GetData(profile, new AnalyticsDataOptions
            {
                StartDate = startDate.Value,
                EndDate = endDate.Value,
                Metrics = AnalyticsMetric.Transactions + AnalyticsMetric.TransactionRevenue,
                Dimensions = AnalyticsDimension.TransactionId,
                Sorting = new AnalyticsSortOptions().AddDescending(AnalyticsMetric.Transactions)
            });

            //Store API result in our new object along with chart data
            var transactionsResult = new StatsApiResult();
            transactionsResult.ApiResult = data;                             //The data back from Google's API
            transactionsResult.ChartData = ChartHelper.GetChartData(data);   //Add chart data to device result via Helper

            // Return the data as JSON
            return transactionsResult;
        }
        /// <summary>
        /// Get Product Performance
        /// </summary>
        /// <param name="profile"></param>
        /// <returns></returns>
        public StatsApiResult GetProductPerformance(string profile, DateTime? startDate, DateTime? endDate)
        {
            if (!startDate.HasValue)
                startDate = DateTime.Now.Subtract(TimeSpan.FromDays(31));
            if (!endDate.HasValue)
                endDate = DateTime.Now;
            //Profile, Start Date, End Date, Metrics (Array), Dimensions (Array)

            AnalyticsDataResponse data = GetGoogleService().Analytics.GetData(profile, new AnalyticsDataOptions
            {
                StartDate = startDate.Value,
                EndDate = endDate.Value,
                Metrics = AnalyticsMetric.UniquePurchases + AnalyticsMetric.ItemRevenue + AnalyticsMetric.RevenuePerItem + AnalyticsMetric.ItemsPerPurchase,
                Dimensions = AnalyticsDimension.ProductSku + AnalyticsDimension.ProductName,
                Sorting = new AnalyticsSortOptions().AddDescending(AnalyticsMetric.ItemRevenue)
            });

            //Store API result in our new object along with chart data
            var productsResult = new StatsApiResult();
            productsResult.ApiResult = data;                             //The data back from Google's API
            productsResult.ChartData = ChartHelper.GetChartData(data);   //Add chart data to device result via Helper

            // Return the data as JSON
            return productsResult;
        }
Example #4
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="profile"></param>
        /// <returns></returns>
        public StatsApiResult GetCountry(string profile, DateTime?startDate, DateTime?endDate)
        {
            if (!startDate.HasValue)
            {
                startDate = DateTime.Now.Subtract(TimeSpan.FromDays(31));
            }
            if (!endDate.HasValue)
            {
                endDate = DateTime.Now;
            }
            //Profile, Start Date, End Date, Metrics (Array), Dimensions (Array)

            AnalyticsDataResponse data = GetGoogleService().Analytics.GetData(profile, new AnalyticsDataOptions {
                StartDate  = startDate.Value,
                EndDate    = endDate.Value,
                Metrics    = AnalyticsMetric.Visits + AnalyticsMetric.Pageviews,
                Dimensions = AnalyticsDimension.Country,
                Sorting    = new AnalyticsSortOptions().AddDescending(AnalyticsMetric.Visits)
            });

            //Store API result in our new object along with chart data
            var countryResult = new StatsApiResult();

            countryResult.ApiResult = data;                                 //The data back from Google's API
            countryResult.ChartData = ChartHelper.GetGeoChartData(data);    //Add chart data to device result via Helper

            // Return the data as JSON
            return(countryResult);
        }
        public static DataRow[] Convert(AnalyticsDataResponse data)
        {
            List <DataRow> rows = new List <DataRow>();

            foreach (AnalyticsDataRow row in data.Rows)
            {
                DataRow temp = new DataRow();
                for (int i = 0; i < data.ColumnHeaders.Length; i++)
                {
                    AnalyticsDataColumnHeader column = data.ColumnHeaders[i];
                    string name  = column.Name.Substring(3);
                    string value = row.Cells[i].Value;
                    switch (column.DataType)
                    {
                    case "INTEGER":
                        temp.Cells[name] = Int32.Parse(value);
                        break;

                    case "STRING":
                        temp.Cells[name] = value;
                        break;

                    case "TIME":
                        temp.Cells[name] = Double.Parse(value);
                        break;

                    default:
                        temp.Cells[name] = value + " (" + column.DataType + ")";
                        break;
                    }
                }
                rows.Add(temp);
            }
            return(rows.ToArray());
        }
Example #6
0
        public static ChartData GetLineChartData(AnalyticsDataResponse apiResults)
        {
            // Get the amount of dimensions and metrics
            int dimensions = apiResults.ColumnHeaders.Count(x => x.ColumnType == "DIMENSION");
            int metrics    = apiResults.ColumnHeaders.Count(x => x.ColumnType == "METRIC");

            var chartLabels = new string[] {};

            if (apiResults.ColumnHeaders.Count() == 5)
            {
                chartLabels = apiResults.Rows.Select(row => row.Cells[2] + "/" + row.Cells[1] + "/" + row.Cells[0]).ToArray();
            }
            else
            {
                chartLabels = apiResults.Rows.Select(row => row.Cells[1] + "/" + row.Cells[0]).ToArray();
            }

            // Initialize the data object
            ChartData cd = new ChartData
            {
                labels   = chartLabels,
                datasets = new LineChartDataSet[metrics]
            };

            // Add a dataset for each metric
            for (int metric = 0; metric < metrics; metric++)
            {
                // Initialize the data object
                LineChartDataSet ds = cd.datasets[metric] = new LineChartDataSet();
                ds.fillColor            = GetFillColor(metric);
                ds.strokeColor          = GetStrokeColor(metric);
                ds.pointColor           = GetFillColor(metric);
                ds.pointStrokeColor     = GetStrokeColor(metric);
                ds.pointHighlightFill   = GetPointHighlightFillColor();
                ds.pointHighlightStroke = GetPointHighlightStrokeColor(metric);
                ds.data = new object[apiResults.Rows.Length];

                for (int row = 0; row < apiResults.Rows.Length; row++)
                {
                    // Get the value
                    string value = apiResults.Rows[row].Cells[dimensions + metric].Value;

                    // Set the value with the proper type
                    if (Regex.IsMatch(value, "^[0-9]+$"))
                    {
                        ds.data[row] = Int32.Parse(value);
                    }
                    else
                    {
                        ds.data[row] = value;
                    }
                }
            }

            return(cd);
        }
Example #7
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="profile"></param>
        /// <param name="startDate"></param>
        /// <param name="endDate"></param>
        /// <returns></returns>
        public ChartData GetVisitsOverTime(string profile, DateTime?startDate, DateTime?endDate)
        {
            if (!startDate.HasValue)
            {
                startDate = DateTime.Now.Subtract(TimeSpan.FromDays(31));
            }
            if (!endDate.HasValue)
            {
                endDate = DateTime.Now;
            }

            //Span of time
            TimeSpan span = endDate.Value - startDate.Value;

            //Dimensions that changes based on time period
            AnalyticsDimensionCollection dimensions;


            //If less than 60 days show days
            if (span.TotalDays < 60)
            {
                dimensions = AnalyticsDimension.Year + AnalyticsDimension.Month + AnalyticsDimension.Day;
            }
            else
            {
                dimensions = AnalyticsDimension.Year + AnalyticsDimension.Month;
            }



            // Get the visits from the Google Analytics API
            AnalyticsDataResponse data = GetGoogleService().Analytics.GetData(profile, new AnalyticsDataOptions {
                StartDate  = startDate.Value,
                EndDate    = endDate.Value,
                Metrics    = AnalyticsMetric.Visits + AnalyticsMetric.Pageviews,
                Dimensions = dimensions,
                Sorting    = new AnalyticsSortOptions().AddAscending(AnalyticsDimension.Year)
            });

            //Store API result in our new object along with chart data
            var visitsMonthResult = ChartHelper.GetLineChartData(data);   //Add chart data to device result via Helper

            // Return the data as JSON
            return(visitsMonthResult);
        }
        /// <summary>
        /// Get Visits
        /// </summary>
        /// <param name="profile"></param>
        /// <param name="startDate"></param>
        /// <param name="endDate"></param>
        /// <returns></returns>
        public AnalyticsDataResponse GetVisits(string profile, DateTime? startDate, DateTime? endDate)
        {
            if (!startDate.HasValue)
                startDate = DateTime.Now.Subtract(TimeSpan.FromDays(31));
             if (!endDate.HasValue)
                 endDate = DateTime.Now;

            // Get the visits from the Google Analytics API
            AnalyticsDataResponse data = GetGoogleService().Analytics.GetData(profile, new AnalyticsDataOptions {
                StartDate = startDate.Value,
                EndDate = endDate.Value,
                Metrics = AnalyticsMetric.Visits + AnalyticsMetric.Pageviews,
                Dimensions = AnalyticsDimension.PagePath,
                Sorting = new AnalyticsSortOptions().AddDescending(AnalyticsMetric.Visits)
            });

            // Return the data as JSON
            return data;
        }
Example #9
0
        ///// <summary>
        ///// Returns an array with exactly two elements. The first element will be data for the
        ///// previous preiod (as defined by properties <code>PreviousStartDate</code> and
        ///// <code>PreviousEndDate</code>). The second element will be data for the current period
        ///// (as defined by <code>CurrentStartDate</code> and <code>CurrentEndDate</code>).
        ///// </summary>
        ///// <param name="key"></param>
        ///// <param name="options"></param>
        internal void GetCachedDataPreviousAndCurrent(string key, out AnalyticsDataResponse previous, out AnalyticsDataResponse current, AnalyticsDataOptions options)
        {
            previous = GetCachedData(key + "_Previous", new AnalyticsDataOptions {
                StartDate  = PreviousStartDate,
                EndDate    = PreviousEndDate,
                Metrics    = options.Metrics,
                Dimensions = options.Dimensions,
                Filters    = options.Filters,
                Sorting    = options.Sorting,
                MaxResults = options.MaxResults
            });

            current = GetCachedData(key + "_Current", new AnalyticsDataOptions {
                StartDate  = CurrentStartDate,
                EndDate    = CurrentEndDate,
                Metrics    = options.Metrics,
                Dimensions = options.Dimensions,
                Filters    = options.Filters,
                Sorting    = options.Sorting,
                MaxResults = options.MaxResults
            });
        }
Example #10
0
        public static dynamic GetGeoChartData(AnalyticsDataResponse apiResults)
        {
            List <object> geoChartData = new List <object>();

            var headerRow = new[] { "Country", "Visits" };

            geoChartData.Add(headerRow);

            foreach (var row in apiResults.Rows)
            {
                //Get Data out of the api results
                var country = row.Cells[0].Value;
                var visits  = Convert.ToInt32(row.Cells[1].Value);

                //Create an array
                var dataRow = new object[] { country, visits };

                geoChartData.Add(dataRow);
            }

            //Return the object
            return(geoChartData);
        }
Example #11
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="profile"></param>
        /// <returns></returns>
        public AnalyticsDataResponse GetLanguage(string profile, DateTime?startDate, DateTime?endDate)
        {
            if (!startDate.HasValue)
            {
                startDate = DateTime.Now.Subtract(TimeSpan.FromDays(31));
            }
            if (!endDate.HasValue)
            {
                endDate = DateTime.Now;
            }
            //Profile, Start Date, End Date, Metrics (Array), Dimensions (Array)

            AnalyticsDataResponse data = GetGoogleService().Analytics.GetData(profile, new AnalyticsDataOptions {
                StartDate  = startDate.Value,
                EndDate    = endDate.Value,
                Metrics    = AnalyticsMetric.Visits + AnalyticsMetric.Pageviews,
                Dimensions = AnalyticsDimension.Language,
                Sorting    = new AnalyticsSortOptions().AddDescending(AnalyticsMetric.Visits)
            });

            // Return the data as JSON
            return(data);
        }
 public static AnalyticsDataResponse GetData(this AnalyticsEndpoint endpoint, string profileId, DateTime startDate, DateTime endDate, string[] metrics, string[] dimensions, string[] filters, string[] sort)
 {
     return(AnalyticsDataResponse.ParseJson(endpoint.Service.Client.Analytics.GetData(profileId, startDate, endDate, metrics, dimensions, filters, sort)));
 }
 public AnalyticsDataResponse GetData(string profileId, AnalyticsDataOptions options)
 {
     return(AnalyticsDataResponse.ParseJson(Raw.GetData(profileId, options)));
 }
 public AnalyticsDataResponse GetData(AnalyticsProfile profile, AnalyticsDataOptions options)
 {
     return(AnalyticsDataResponse.ParseJson(Raw.GetData(profile.Id, options)));
 }
 public AnalyticsDataResponse GetData(string profileId, DateTime startDate, DateTime endDate, AnalyticsMetricCollection metrics, AnalyticsDimensionCollection dimensions)
 {
     return(AnalyticsDataResponse.ParseJson(Raw.GetData(profileId, startDate, endDate, metrics, dimensions)));
 }
 public AnalyticsDataResponse GetData(string profileId, DateTime startDate, DateTime endDate, string[] metrics, string[] dimensions)
 {
     return(AnalyticsDataResponse.ParseJson(Raw.GetData(profileId, startDate, endDate, metrics, dimensions)));
 }