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; }
private void PageviewFeed() { string userName = this.Username.Text; string passWord = this.Password.Text; string profileId = this.ProfileIds.SelectedItems[0].SubItems[1].Text; const string dataFeedUrl = "https://www.google.com/analytics/feeds/data"; AnalyticsService service = new AnalyticsService("AnalyticsSampleApp"); if (!string.IsNullOrEmpty(userName)) { service.setUserCredentials(userName, passWord); } DataQuery query = new DataQuery(dataFeedUrl); query.Ids = profileId; 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"); DataFeed dataFeed = service.Query(query); foreach (DataEntry entry in dataFeed.Entries) { ListViewItem item = new ListViewItem(entry.Title.Text); item.SubItems.Add(entry.Metrics[0].Value); this.ListPageviews.Items.Add(item); } }
public ReadOnlyCollection<Region> GetRegionInfo() { var dataQuery = new DataQuery(_profileId, DateTime.Today - TimeSpan.FromDays(30), DateTime.Today, "ga:visitors", "ga:region,ga:operatingSystem", "-ga:visitors"); return _service.Query(dataQuery).Entries .Cast<DataEntry>() .Select( entry => new Region(entry.Dimensions[0].Value) { MacUsers = entry.Dimensions[1].Value == "Macintosh" ? entry.Metrics[0].IntegerValue : 0, WindowsUsers = entry.Dimensions[1].Value == "Windows" ? entry.Metrics[0].IntegerValue : 0, }) .Aggregate(new Dictionary<string, Region>(), (dict, region) => { Region existing; if (!dict.TryGetValue(region.Name, out existing)) { existing = new Region(region.Name); dict[region.Name] = existing; } existing.MacUsers += region.MacUsers; existing.WindowsUsers += region.WindowsUsers; return dict; }, dict => dict.Values.ToList().AsReadOnly()); }
/// <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); } }
private static void GetPageViews(AtomEntry Account) { string ProfileID = Account.Id.AbsoluteUri.Substring(47); DataFeedUrl = "https://www.google.com/analytics/feeds/data"; DataQuery PageViewQuery = new DataQuery(DataFeedUrl) { Ids = ProfileID, Dimensions = "ga:date", Metrics = "ga:pageviews", Sort = "ga:date", GAStartDate = (DateTime.Now).AddDays(-7).ToString("yyyy-MM-dd"), GAEndDate = (DateTime.Now).ToString("yyyy-MM-dd") }; DataFeed Results = Service.Query(PageViewQuery); foreach (AtomEntry Result in Results.Entries) { DataEntry Entry = (DataEntry)Result; Console.WriteLine(String.Format("{0}\t{1}", Entry.Title.Text.Split('=')[1], Entry.Metrics[0].Value)); } }
/** * 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); }
public void DimensionPropertyTest() { DataQuery target = new DataQuery(); const string expected = "ga:productCategory,ga:productName"; target.Dimensions = expected; string actual = target.Dimensions; Assert.AreEqual(expected, actual); }
public void MetricParseTest() { const string expected = "ga:itemRevenue,ga:itemQuantity"; DataQuery target = new DataQuery(); //Force expected to be parsed target.Uri = new Uri("http://test.com?metrics=" + expected); string actual = target.Metrics; Assert.AreEqual(expected, actual); }
public void DimensionParseTest() { const string expected = "ga:productCategory,ga:productName"; DataQuery target = new DataQuery(); //Force expected to be parsed target.Uri = new Uri("http://test.com?dimensions=" + expected); string actual = target.Dimensions; Assert.AreEqual(expected, actual); }
private DataFeed UseGoogleAnalyticsApiToReturnInSearchKeywordDataFeed(string profileId) { var dataQuery = new DataQuery("https://www.google.com/analytics/feeds/data") { Ids = profileId, Dimensions = "ga:searchKeyword", Metrics = "ga:pageviews", Sort = "-ga:pageviews", GAStartDate = DateTime.Now.AddDays(-30).ToString("yyyy-MM-dd"), GAEndDate = DateTime.Now.ToString("yyyy-MM-dd"), NumberToRetrieve = 10000 }; return ReturnGoogleAnalyticsDataFeed(dataQuery); }
private const String TABLE_ID = "ga:37386554"; //"INSERT_TABLE_ID_HERE"; #endregion Fields #region Constructors 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); }
private DataFeed ReturnGoogleAnalyticsDataFeed(DataQuery dataQuery) { string userName = ConfigurationManager.AppSettings["GoogleUsername"]; string passWord = ConfigurationManager.AppSettings["GooglePassword"]; var service = new AnalyticsService(ConfigurationManager.AppSettings["ApplicationName"]); GDataRequestFactory f = new GDataRequestFactory(ConfigurationManager.AppSettings["UserAgent"]); if (_proxyProvider != null) { var proxy = _proxyProvider.CreateProxy(); f.Proxy = proxy; } service.RequestFactory = f; service.setUserCredentials(userName, passWord); return service.Query(dataQuery); }
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 GAEndDateParseTest() { const string expected = "2009-04-25"; DataQuery target = new DataQuery(); //Force expected to be parsed target.Uri = new Uri("http://test.com?end-date=" + expected); string actual = target.GAEndDate; Assert.AreEqual(expected, actual); }
public void FeedQueryConstructorTest() { const string baseUri = "http://www.test.com/"; DataQuery target = new DataQuery(baseUri); Assert.AreEqual(target.Uri, new Uri(baseUri)); }
/// <summary> /// overloaded to create typed version of Query /// </summary> /// <param name="feedQuery"></param> /// <returns>DataFeed</returns> public DataFeed Query(DataQuery feedQuery) { return(base.Query(feedQuery) as DataFeed); }
public void EndDateTest() { DataQuery target = new DataQuery(); DateTime expected = DateTime.Now; DateTime actual; target.EndDate = expected; actual = target.EndDate; Assert.AreEqual(expected, actual); }
public void DataQueryConstructorTest1() { DataQuery target = new DataQuery(); Assert.IsNotNull(target); }
public void ExtraParametersTest() { DataQuery target = new DataQuery(); string expected = "TestValue"; string actual; target.ExtraParameters = expected; actual = target.ExtraParameters; Assert.AreEqual(expected, actual); }
public void NumberToRetrieveTest() { DataQuery target = new DataQuery(); int expected = 12; int actual; target.NumberToRetrieve = expected; actual = target.NumberToRetrieve; Assert.AreEqual(expected, actual); }
public void FiltersParseTest() { const string expected = "ga:country%3D%3DCanada"; DataQuery target = new DataQuery(); //Force expected to be parsed target.Uri = new Uri("http://test.com?filters=" + expected); string actual = target.Filters; Assert.AreEqual(expected, actual); }
private DataFeed getGADataFeed(Site site, DateTime fromDay, DateTime toDay, string dimensions, string metrics, string filters, string sort, int startIndex) { AnalyticsService asv = new AnalyticsService(applicationName); asv.setUserCredentials(userId, password); DataQuery query = new DataQuery(analyticsApiURL); query.Ids = site.account; query.Dimensions = dimensions; query.Metrics = metrics; query.Filters = filters; query.Sort = sort; query.NumberToRetrieve = numberOfGARecordsToRetrievePerRequest; query.StartIndex = startIndex; query.GAStartDate = String.Format("{0:yyyy-MM-dd}", fromDay); query.GAEndDate = String.Format("{0:yyyy-MM-dd}", toDay); log.Debug("Querying Google API : " + query.Uri.ToString()); DataFeed feed = asv.Query(query); System.Threading.Thread.Sleep(requestPause); // wait between requests return feed; }
public void SortParseTest() { const string expected = "ga:productCategory"; DataQuery target = new DataQuery(); //Force expected to be parsed target.Uri = new Uri("http://test.com?sort=" + expected); string actual = target.Sort; Assert.AreEqual(expected, actual); }
public void IdsParseTest() { const string expected = "ga:1234"; DataQuery target = new DataQuery(); //Force expected to be parsed target.Uri = new Uri("http://test.com?ids=" + expected); string actual = target.Ids; Assert.AreEqual(expected, actual); }
public void ParseTest() { const string dimensionExpected = "ga:productCategory,ga:productName"; const string metricExpected = "ga:itemRevenue,ga:itemQuantity"; const string idsExpected = "ga:1234"; const string filtersExpected = "ga:country%3D%3DCanada"; const string sortExpected = "ga:productCategory"; const string startDateExpected = "2009-04-1"; const string endDateExpected = "2009-04-25"; DataQuery target = new DataQuery(); target.Uri = new Uri(string.Format("http://test.com?ids={0}&dimensions={1}&metrics={2}&filters={3}&sort={4}&start-date={5}&end-date={6}", idsExpected, dimensionExpected, metricExpected, filtersExpected, sortExpected, startDateExpected, endDateExpected)); Assert.AreEqual("http://test.com/", target.BaseAddress); Assert.AreEqual(dimensionExpected, target.Dimensions); Assert.AreEqual(metricExpected, target.Metrics); Assert.AreEqual(idsExpected, target.Ids); Assert.AreEqual(filtersExpected, target.Filters); Assert.AreEqual(sortExpected, target.Sort); Assert.AreEqual(startDateExpected, target.GAStartDate); Assert.AreEqual(endDateExpected, target.GAEndDate); }
/// <summary> /// overloaded to create typed version of Query /// </summary> /// <param name="feedQuery"></param> /// <returns>DataFeed</returns> public DataFeed Query(DataQuery feedQuery) { return base.Query(feedQuery) as DataFeed; }
public void CalculateQueryTest() { const string baseUrlExpected = "http://test.com/"; const string dimensionExpected = "ga:productCategory,ga:productName"; const string metricExpected = "ga:itemRevenue,ga:itemQuantity"; const string idsExpected = "ga:1234"; const string filtersExpected = "ga:country%3D%3DCanada"; const string sortExpected = "ga:productCategory"; const string startDateExpected = "2009-04-1"; const string endDateExpected = "2009-04-25"; DataQuery target = new DataQuery(); target.BaseAddress = baseUrlExpected; target.Dimensions = dimensionExpected; target.Metrics = metricExpected; target.Ids = idsExpected; target.Filters = filtersExpected; target.Sort = sortExpected; target.GAStartDate = startDateExpected; target.GAEndDate = endDateExpected; Uri expectedResult = new Uri(string.Format("http://test.com?dimensions={0}&end-date={1}&filters={2}&ids={3}&metrics={4}&sort={5}&start-date={6}", Utilities.UriEncodeReserved(dimensionExpected), Utilities.UriEncodeReserved(endDateExpected), Utilities.UriEncodeReserved(filtersExpected), Utilities.UriEncodeReserved(idsExpected), Utilities.UriEncodeReserved(metricExpected), Utilities.UriEncodeReserved(sortExpected), Utilities.UriEncodeReserved(startDateExpected))); Assert.AreEqual(expectedResult.AbsoluteUri, target.Uri.AbsoluteUri); }
/// <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; }
public void UriTest() { DataQuery target = new DataQuery(); Uri expected = new Uri("http://www.test.com/"); Uri actual; target.Uri = expected; actual = target.Uri; Assert.AreEqual(expected, actual); }
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.Admin().Home().AuthResponse()); var auth = new AnalyticsAuthorize { Url = AuthSubUtil.getRequestUrl(next, scope, false, true) }; return View("AnalyticsAuthorize", auth); } if (string.IsNullOrEmpty(settings.AnalyticsProfileId)) { var config = new AnalyticsConfig { Accounts = GetAccounts(settings), Profiles = GetProfiles(settings) }; return View("AnalyticsConfig", config); } duration = duration ?? 30; var model = new 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 void QueryTest() { DataQuery target = new DataQuery(); string expected = "TestValue"; string actual; target.Query = expected; actual = target.Query; Assert.AreEqual(expected, actual); }