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 IList <AdPerformance> GetCampaignPerformance(DataQuery partialQuery) { Google.GData.Analytics.AnalyticsService asv = new Google.GData.Analytics.AnalyticsService("gaExportAPI_acctSample_v2.0"); asv.setUserCredentials(CLIENT_USERNAME, CLIENT_PASS); AddApiKeyToQuery(partialQuery); var dataFeed = asv.Query(partialQuery); var resultList = new List <AdPerformance>(); foreach (DataEntry entry in dataFeed.Entries) { Dimension campaignDimension = entry.Dimensions[0]; string adName = "Adwords - " + campaignDimension.Value; //"ga:adCost,ga:CPC,ga:adClicks" Metric costMetric = entry.Metrics[0]; Metric cpcMetric = entry.Metrics[1]; Metric clickMetric = entry.Metrics[2]; double cost = Convert.ToDouble(costMetric.FloatValue); double click = Convert.ToDouble(clickMetric.FloatValue); double cpc = Convert.ToDouble(cpcMetric.FloatValue); resultList.Add(new AdPerformance(adName, (decimal)cost, (int)click, (decimal)cpc)); } return(resultList); }
/** * 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. Google.GData.Analytics.AnalyticsService asv = new Google.GData.Analytics.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"; query.Metrics = "ga:visits"; query.Segment = ""; query.Filters = ""; query.Sort = "-ga:visits"; query.NumberToRetrieve = 5; query.GAStartDate = "2012-01-01"; query.GAEndDate = "2012-01-16"; 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); }
private static IList <KeyValuePair <string, double> > GetData2Dim(DataQuery partialQuery, Func <string, string, string> translator) { Google.GData.Analytics.AnalyticsService asv = new Google.GData.Analytics.AnalyticsService("gaExportAPI_acctSample_v2.0"); asv.setUserCredentials(CLIENT_USERNAME, CLIENT_PASS); AddApiKeyToQuery(partialQuery); var dataFeed = asv.Query(partialQuery); var resultList = new List <KeyValuePair <String, Double> >(); foreach (DataEntry entry in dataFeed.Entries) { Dimension dim1 = entry.Dimensions[0]; Dimension dim2 = entry.Dimensions[1]; string value = translator(dim1.Value, dim2.Value); Metric met = entry.Metrics[0]; int numVisitors = Convert.ToInt32(met.Value); resultList.Add(new KeyValuePair <String, Double>(value, numVisitors)); } return(resultList); }
public string VisitsNumber() { string visits = string.Empty; 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; Google.GData.Analytics.AnalyticsService service = new Google.GData.Analytics.AnalyticsService("HealthyAustraliaClub"); service.setUserCredentials(username, pass); DataQuery query1 = new DataQuery(dataFeedUrl); query1.Ids = "ga:76315108"; query1.Metrics = "ga:visits"; query1.Sort = "ga:visits"; query1.GAStartDate = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1).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); }
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; } }
/** * 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); }
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); }
protected void Page_Load(object sender, EventArgs e) { username = "******"; password = "******"; AccountsFeedUrl = "https://www.google.com/analytics/feeds/accounts/default"; Service = new AnalyticsService("AnalyticsSampleApp"); Service.setUserCredentials(username, password); AccountQuery AccountsQuery = new AccountQuery(AccountsFeedUrl); AccountFeed AccountsFeed = Service.Query(AccountsQuery); List<AtomEntry> Accounts = AccountsFeed.Entries.ToList(); foreach (AtomEntry Account in Accounts) if (Account.Title.Text.Equals("www.sonetreach.com")) { GetPageViews(Account); } }
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 void RefreshFeed() { string userName = this.Username.Text; string passWord = this.Password.Text; AccountQuery query = new AccountQuery(); AnalyticsService service = new AnalyticsService("AnalyticsSampleApp"); if (!string.IsNullOrEmpty(userName)) { service.setUserCredentials(userName, passWord); } AccountFeed accountFeed = service.Query(query); foreach (AccountEntry entry in accountFeed.Entries) { ListViewItem item = new ListViewItem(entry.Title.Text); //item.SubItems.Add(entry.Title.Text); item.SubItems.Add(entry.ProfileId.Value); this.ProfileIds.Items.Add(item); } }
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); }
static void Main(string[] args) { //test limiter //TestLimiter(); //initialize a new limiter with 10 concurrent and 10 requests per second. Limiter limiter = new Limiter(TimeSpan.FromSeconds(1), 10, 10); string username = "******"; string password = "******"; //first, initialize a service, its the query provider. var service = new Google.GData.Analytics.AnalyticsService("AnalyticsReader"); //you can also use service.setUserCredentials(username,password) service.Credentials = new Google.GData.Client.GDataCredentials(username, password); //first, query for all accounts var accountquery = new Google.GData.Analytics.AccountQuery(); accountquery.NumberToRetrieve = 10000; //Maximum limiter.Enter(); var accountresult = service.Query(accountquery); limiter.Exit(); //for each account, retrieve records foreach (AccountEntry account in accountresult.Entries) { //get the timezone for the account, as all data is saved based on that timezone. Property timezone = account.Properties.Where(i => i.Name == "ga:timezone").FirstOrDefault(); Console.WriteLine( "\nProfile Title = " + account.Title.Text + "\nProfile ID = " + account.ProfileId.Value + "\nTimeZone = " + timezone.Value); TzTimeZone tzinfo = null; if (timezone != null) { tzinfo = TzTimeZone.GetTimeZone(timezone.Value); } //retrieve analytics data DataQuery query = new DataQuery(); query.Ids = account.ProfileId.Value; //Data //dimensions are the "group by" query.Dimensions = "ga:date,ga:hour,ga:hostname,ga:country,ga:keyword,ga:source,ga:referralPath"; //metrics are the values query.Metrics = "ga:bounces,ga:newVisits,ga:pageviews,ga:timeOnSite,ga:visits"; //start from yesterday query.GAStartDate = DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd"); //until today query.GAEndDate = DateTime.Now.ToString("yyyy-MM-dd"); query.StartIndex = 1; //Maximum allowed by Quota. query.NumberToRetrieve = 10000; limiter.Enter(); DataFeed dataFeedVisits = service.Query(query); limiter.Exit(); //process each record returned foreach (DataEntry dentry in dataFeedVisits.Entries) { var line = new Dictionary <string, string>(); //insert into directory for each processing for (int i = 0; i < dentry.Metrics.Count; i++) { line[dentry.Metrics[i].Name] = dentry.Metrics[i].Value; } for (int i = 0; i < dentry.Dimensions.Count; i++) { line[dentry.Dimensions[i].Name] = dentry.Dimensions[i].Value; } //get the UTC datetime from the ga:date + ga:hour + profile timezone combination DateTime date = DateTime.ParseExact(line["ga:date"], "yyyyMMdd", System.Globalization.CultureInfo.CurrentCulture); int hour = Convert.ToInt32(line["ga:hour"]); date = date.AddHours(hour); line["dateutc"] = ConvertToUtc(date, tzinfo).ToString(); //dump to console all data found Console.Write("UTC: {0}, ", line["dateutc"]); for (int i = 0; i < dentry.Dimensions.Count; i++) { Console.Write("{0}: {1}, ", dentry.Dimensions[i].Name, dentry.Dimensions[i].Value); } for (int i = 0; i < dentry.Metrics.Count; i++) { Console.Write("{0}: {1}, ", dentry.Metrics[i].Name, dentry.Metrics[i].Value); } Console.WriteLine(); } } }
static void Main(string[] args) { //test limiter //TestLimiter(); //initialize a new limiter with 10 concurrent and 10 requests per second. Limiter limiter = new Limiter(TimeSpan.FromSeconds(1), 10, 10); string username = "******"; string password = "******"; //first, initialize a service, its the query provider. var service = new Google.GData.Analytics.AnalyticsService("AnalyticsReader"); //you can also use service.setUserCredentials(username,password) service.Credentials = new Google.GData.Client.GDataCredentials(username, password); //first, query for all accounts var accountquery = new Google.GData.Analytics.AccountQuery(); accountquery.NumberToRetrieve = 10000; //Maximum limiter.Enter(); var accountresult = service.Query(accountquery); limiter.Exit(); //for each account, retrieve records foreach (AccountEntry account in accountresult.Entries) { //get the timezone for the account, as all data is saved based on that timezone. Property timezone = account.Properties.Where(i => i.Name == "ga:timezone").FirstOrDefault(); Console.WriteLine( "\nProfile Title = " + account.Title.Text + "\nProfile ID = " + account.ProfileId.Value + "\nTimeZone = " + timezone.Value); TzTimeZone tzinfo = null; if (timezone != null) tzinfo = TzTimeZone.GetTimeZone(timezone.Value); //retrieve analytics data DataQuery query = new DataQuery(); query.Ids = account.ProfileId.Value; //Data //dimensions are the "group by" query.Dimensions = "ga:date,ga:hour,ga:hostname,ga:country,ga:keyword,ga:source,ga:referralPath"; //metrics are the values query.Metrics = "ga:bounces,ga:newVisits,ga:pageviews,ga:timeOnSite,ga:visits"; //start from yesterday query.GAStartDate = DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd"); //until today query.GAEndDate = DateTime.Now.ToString("yyyy-MM-dd"); query.StartIndex = 1; //Maximum allowed by Quota. query.NumberToRetrieve = 10000; limiter.Enter(); DataFeed dataFeedVisits = service.Query(query); limiter.Exit(); //process each record returned foreach (DataEntry dentry in dataFeedVisits.Entries) { var line = new Dictionary<string, string>(); //insert into directory for each processing for (int i = 0; i < dentry.Metrics.Count; i++) line[dentry.Metrics[i].Name] = dentry.Metrics[i].Value; for (int i = 0; i < dentry.Dimensions.Count; i++) line[dentry.Dimensions[i].Name] = dentry.Dimensions[i].Value; //get the UTC datetime from the ga:date + ga:hour + profile timezone combination DateTime date = DateTime.ParseExact(line["ga:date"], "yyyyMMdd", System.Globalization.CultureInfo.CurrentCulture); int hour = Convert.ToInt32(line["ga:hour"]); date = date.AddHours(hour); line["dateutc"] = ConvertToUtc(date, tzinfo).ToString(); //dump to console all data found Console.Write("UTC: {0}, ", line["dateutc"]); for (int i = 0; i < dentry.Dimensions.Count; i++) Console.Write("{0}: {1}, ", dentry.Dimensions[i].Name, dentry.Dimensions[i].Value); for (int i = 0; i < dentry.Metrics.Count; i++) Console.Write("{0}: {1}, ", dentry.Metrics[i].Name, dentry.Metrics[i].Value); Console.WriteLine(); } } }
public string ResgisterScript(string clientID) { AnalyticsService service = new AnalyticsService("AnalyticsSampleApp"); if (!string.IsNullOrEmpty( GAEmailAddress)) { service.setUserCredentials(GAEmailAddress, GAPassword); } DataQuery query = new DataQuery(dataFeedUrl); query.Ids = "ga:" + GAProfileId; query.Metrics = "ga:visits,ga:pageviews"; query.Dimensions = "ga:date"; query.Sort = ""; query.GAStartDate = FromDate.ToString("yyyy-MM-dd"); query.GAEndDate = ToDate.ToString("yyyy-MM-dd"); DataFeed dataFeed = service.Query(query); List<VisitorsOverviewQueryEntity> ResultData = HttpContext.Current.Cache["VisitorsOverview_" + GAProfileId] as List<VisitorsOverviewQueryEntity>; if (ResultData == null) { //ResultData = VisitorsOverviewQuery.getVisitorsOverviewQueryResults(GAToken, GAProfileId, FromDate == DateTime.MinValue ? DateTime.Now.AddDays(-31) : FromDate, ToDate > DateTime.Now ? DateTime.Now : ToDate); //HttpContext.Current.Cache.Add("VisitorsOverview_" + GAProfileId, ResultData, null, DateTime.Now.AddHours(2), System.Web.Caching.Cache.NoSlidingExpiration, System.Web.Caching.CacheItemPriority.Default, null); } StringBuilder JavascriptBuilder = new StringBuilder(); JavascriptBuilder.Append("<script type=\"text/javascript\">"); JavascriptBuilder.Append("google.load('visualization', '1', {'packages':['annotatedtimeline']});") .Append("google.setOnLoadCallback(drawChart);"); JavascriptBuilder.Append(@" function drawChart() { var data = new google.visualization.DataTable(); data.addColumn('date', 'Date'); data.addColumn('number', 'Visite'); data.addColumn('string', 'title1'); data.addColumn('string', 'text1'); data.addColumn('number', 'Page Viewed'); data.addColumn('string', 'title1'); data.addColumn('string', 'text1'); data.addRows(["); foreach (DataEntry entry in dataFeed.Entries) { //entry.Metrics[0].Value; JavascriptBuilder.Append(@"[new Date(" + entry.Dimensions[0].Value.Substring(0, 4) + "," + (Convert.ToInt16(entry.Dimensions[0].Value.Substring(4, 2)) - 1).ToString() + "," + (Convert.ToInt16(entry.Dimensions[0].Value.Substring(6))).ToString() + "), " + entry.Metrics[0].Value.ToString().ToString() + ", undefined, undefined," + entry.Metrics[1].Value.ToString() + ", undefined, undefined],"); } //foreach (VisitorsOverviewQueryEntity obj in ResultData) //{ // JavascriptBuilder.Append(@"[new Date(" + obj.Date.Substring(0, 4) + "," + (Convert.ToInt16(obj.Date.Substring(4, 2)) - 1).ToString() + "," + (Convert.ToInt16(obj.Date.Substring(6))).ToString() + "), " + obj.Visit + ", undefined, undefined," + obj.Pages + ", undefined, undefined],"); //} JavascriptBuilder.Remove(JavascriptBuilder.Length - 1, 1); JavascriptBuilder.Append(@"]);"); JavascriptBuilder.Append(@"var chart2 = new google.visualization.AnnotatedTimeLine(document.getElementById('" + clientID + "'));"); JavascriptBuilder.Append(@"chart2.draw(data, {displayAnnotations: true,thickness:2,fill:10}); } "); JavascriptBuilder.Append("</script>"); return JavascriptBuilder.ToString(); }
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 JsonResult QuickStatistics() { // user login //const string dataFeedUrl = "https://www.google.com/analytics/feeds/data"; string userName = Context.CurrentSite.GoogleDataUserName; string passWord = Context.CurrentSite.GoogleDataPassword; string profileId = Context.CurrentSite.GoogleDataProfileID; AnalyticsService service = new AnalyticsService("AnalyticsSampleApp"); if (!string.IsNullOrEmpty(userName)) { service.setUserCredentials(userName, passWord); } //string gaStartDate = DateTime.Now.AddDays(-30).ToString("yyyy-MM-dd"); //string gaEndDate = DateTime.Now.AddDays(-2).ToString("yyyy-MM-dd"); #region Visits & Page Views DataQuery visitorsQuery = GetGoogleDataQuery(DateTime.Now.AddDays(-30), DateTime.Now.AddDays(-2), "ga:date", "ga:visits,ga:pageviews", "ga:date"); DataFeed data = service.Query(visitorsQuery); int count = data.Entries.Count; IList<string[]> arrayVisits = new List<string[]>(); IList<string[]> arrayPageViews = new List<string[]>(); foreach (DataEntry entry in data.Entries) { string date = DateTime.ParseExact(entry.Dimensions[0].Value, "yyyyMMdd", null).ToJavascriptTimestamp().ToString(); //log.DebugFormat("DateTime: {0}, GoogleData: {1}, Js: {2}", DateTime.ParseExact(entry.Dimensions[0].Value, "yyyyMMdd", null), entry.Dimensions[0].Value, date); arrayVisits.Add(new string[] {date, entry.Metrics[0].Value}); arrayPageViews.Add(new string[] {date, entry.Metrics[1].Value}); } var visitsList = from x in arrayVisits select new { date = x[0], visits = x[1] }; var pageviewsList = from x in arrayPageViews select new { date = x[0], pageviews = x[1] }; #endregion #region Browsers DataQuery browsersQuery = GetGoogleDataQuery(DateTime.Now.AddDays(-30), DateTime.Now.AddDays(-2), "ga:browser", "ga:visits", string.Empty); DataFeed data2 = service.Query(browsersQuery); IList<string[]> arrayBrowsers = new List<string[]>(); foreach (DataEntry entry in data2.Entries) { // browser, visits arrayBrowsers.Add(new string[] { entry.Dimensions[0].Value, entry.Metrics[0].Value }); //log.DebugFormat("Browser: {0}, Visits: {1}", entry.Dimensions[0].Value, entry.Metrics[0].Value); } var browsersList = from x in arrayBrowsers select new { browser = x[0], visits = x[1] }; #endregion return Json(new { visits = visitsList, pageviews = pageviewsList, browsers = browsersList }, JsonRequestBehavior.AllowGet); //// #2 visits by type //// x = date, y = visits, type //// New| 1 2 1 0 4 //// Returning| 2 3 4 1 9 //// |----------------------------- //// | t t1 t2 t3 t4 //DataQuery visitsByTypeQuery = new DataQuery(dataFeedUrl) //{ // Ids = profileId, // GAStartDate = gaStartDate, // GAEndDate = gaEndDate, // Dimensions = "ga:date,ga:visitorType", // Metrics = "ga:visits", // Sort = "ga:date" //}; //DataFeed visitsByTypeData = service.Query(visitsByTypeQuery); //GoogleDataQuickModel model = new GoogleDataQuickModel(); ////model.VisitorsData = visitorsData; ////model.VisitsByTypeData = GetVisitorChartData(visitsByTypeData); //model.VisitorsArray = visitors.ToString(); //return model; }
public string ResgisterScript( string clientID) { AnalyticsService service = new AnalyticsService("AnalyticsSampleApp"); if (!string.IsNullOrEmpty(GAEmailAddress)) { service.setUserCredentials(GAEmailAddress, GAPassword); } //"https://www.google.com/analytics/feeds/data?ids=ga:{0}&dimensions=ga:source,ga:medium&metrics=ga:visits&sort=-ga:visits&start-date={1}&end-date={2}&start-index=1&max-results=10000"; DataQuery query = new DataQuery(dataFeedUrl); query.Ids = "ga:" + GAProfileId; query.Metrics = "ga:visits"; query.Dimensions = "ga:source,ga:medium"; query.Sort = "-ga:visits"; query.GAStartDate = FromDate.ToString("yyyy-MM-dd"); query.GAEndDate = ToDate.ToString("yyyy-MM-dd"); DataFeed dataFeed = service.Query(query); //Hashtable ResultData = HttpContext.Current.Cache["TrafficSourcesOverview_" + GAProfileId] as Hashtable; //if (ResultData == null) //{ // ResultData = TrafficSourcesOverviewQuery.getTrafficSourcesOverviewQueryResults(GAToken, GAProfileId, FromDate == DateTime.MinValue ? DateTime.Now.AddDays(-31) : FromDate, ToDate > DateTime.Now ? DateTime.Now : ToDate); // HttpContext.Current.Cache.Add("TrafficSourcesOverview_" + GAProfileId, ResultData, null, DateTime.Now.AddHours(2), System.Web.Caching.Cache.NoSlidingExpiration, System.Web.Caching.CacheItemPriority.Default, null); //} StringBuilder JavascriptBuilder = new StringBuilder(); JavascriptBuilder.Append("<script type=\"text/javascript\">"); JavascriptBuilder.Append(@" google.load('visualization', '1', {packages:['piechart']}); google.setOnLoadCallback(drawPieChart); var chart; function drawPieChart() { var data = new google.visualization.DataTable(); data.addColumn('string', 'Task'); data.addColumn('number', 'Hours per Day');"); JavascriptBuilder.Append(@"data.addRows(" + dataFeed.Entries.Count.ToString() + ");"); //IDictionaryEnumerator en = dataFeed.GetEnumerator(); //while (en.MoveNext()) //{ // string key = en.Key.ToString(); // string val = en.Value.ToString(); // key = key == "(none)" ? "Direct" : key; // JavascriptBuilder.Append(@"data.setValue(" + count.ToString() + ",0,'" + key + "');data.setValue(" + count.ToString() + ",1," + val + ");"); // count++; //} int count = 0; foreach (DataEntry entry in dataFeed.Entries) { string key = entry.Dimensions[0].Value; string val = entry.Metrics[0].Value; key = key == "(none)" ? "Direct" : key; //entry.Metrics[0].Value; //JavascriptBuilder.Append(@"[new Date(" + entry.Dimensions[0].Value.Substring(0, 4) + "," + (Convert.ToInt16(entry.Dimensions[0].Value.Substring(4, 2)) - 1).ToString() + "," + (Convert.ToInt16(entry.Dimensions[0].Value.Substring(6))).ToString() + "), " + entry.Metrics[0].Value.ToString().ToString() + ", undefined, undefined," + entry.Metrics[1].Value.ToString() + ", undefined, undefined],"); JavascriptBuilder.Append(@"data.setValue(" + count.ToString() + ",0,'" + key + "');data.setValue(" + count.ToString() + ",1," + val + ");"); count++; } JavascriptBuilder.Append(@"chart = new google.visualization.PieChart(document.getElementById('" + clientID + "'));"); JavascriptBuilder.Append(@"chart.draw(data, {width: " + Width + ", height: " + Height + ", is3D: true, title: 'Traffic Source Overview'});"); JavascriptBuilder.Append(@"google.visualization.events.addListener(chart, 'onmouseover',DisplayData); } function DisplayData(e) { chart.setSelection([e]); } "); JavascriptBuilder.Append("</script>"); return JavascriptBuilder.ToString(); }
/** * 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); }
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 string ContentOverview() { AnalyticsService service = new AnalyticsService("AnalyticsSampleApp"); if (!string.IsNullOrEmpty(GAEmailAddress)) { service.setUserCredentials(GAEmailAddress, GAPassword); } DataQuery query = new DataQuery(dataFeedUrl); query.Ids = "ga:" + GAProfileId; query.Metrics = "ga:pageviews"; query.Dimensions = "ga:pagePath,ga:pageTitle"; query.Sort = "-ga:pageviews"; query.GAStartDate = FromDate.ToString("yyyy-MM-dd"); query.GAEndDate = ToDate.ToString("yyyy-MM-dd"); DataFeed dataFeed = service.Query(query); if ( dataFeed == null) { StringBuilder JavascriptBuilder = new StringBuilder(); JavascriptBuilder.Append(@"<table><tr><th width='300'>Pages</th><th>Page Views</th></tr>"); foreach (DataEntry entry in dataFeed.Entries) { JavascriptBuilder.Append(@"<tr><td>" + entry.Dimensions[0].Value + "</td><td align='right'>" + entry.Metrics[0].Value.ToString() + "</td></tr>"); } JavascriptBuilder.Append(@"</table>"); return JavascriptBuilder.ToString(); } else { return ""; } }
public static void Query(SqlString profileids, SqlString username, SqlString password, SqlDateTime dateFrom, SqlDateTime dateTo, SqlString dimensions, SqlString metrics, SqlString sort, SqlString segments, SqlString filters) { // Google Analytics service endpoint const string dataFeedUrl = "https://www.google.com/analytics/feeds/data"; // Create a GData.net service object to contact the endpoint with our authentication details AnalyticsService service = new AnalyticsService("Skyscanner Analytics"); service.setUserCredentials(username.ToString(), password.ToString()); // Construct and populate an analytics query object DataQuery query = new DataQuery(dataFeedUrl); query.Ids = profileids.ToString(); query.Metrics = metrics.ToString(); query.Dimensions = dimensions.ToString(); query.GAStartDate = dateFrom.Value.ToString("yyyy-MM-dd"); query.GAEndDate = dateTo.Value.ToString("yyyy-MM-dd"); query.Sort = sort.ToString(); query.Segment = segments.ToString(); query.Filters = filters.ToString(); query.NumberToRetrieve = 10000; // Count the number of metrics and dimensions to be returned int metricCount = query.Metrics.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Length; int dimensionCount = query.Dimensions.Split(new char[] {','}, StringSplitOptions.RemoveEmptyEntries).Length; // Not possible to query the API without at least one metric, so return immediately if none were specified if (metricCount == 0) return; // Gather the results from the Google Analytics API DataFeed dataFeed = service.Query(query); // Prepare a set of columns for our SQL result set SqlMetaData[] columns = new SqlMetaData[metricCount + dimensionCount]; // Iterate through each of the dimensions, and begin populating the column array DataEntry header = (DataEntry)dataFeed.Entries[0]; for (int i = 0; i < dimensionCount; i++) { SqlParameter col = new SqlParameter(header.Dimensions[i].Name, header.Dimensions[i].Value); columns[i] = new SqlMetaData ( col.ParameterName, col.SqlDbType, SqlMetaData.Max ); } // Continue populating the column array with each of the metrics for (int i = 0; i < metricCount; i++) { SqlParameter col = new SqlParameter(header.Metrics[i].Name, header.Metrics[i].Value); columns[dimensionCount + i] = new SqlMetaData ( col.ParameterName, col.SqlDbType, SqlMetaData.Max ); } // Create a placeholder record based on the column metadata SqlDataRecord record = new SqlDataRecord(columns); // Set up a pipe to return results to the stored procedure callee SqlPipe pipe = SqlContext.Pipe; pipe.SendResultsStart(record); // Iterate through the data feed results foreach (DataEntry entry in dataFeed.Entries) { // Populate each dimension entry in the row for (int i = 0; i < dimensionCount; i++) { record.SetValue(i, entry.Dimensions[i].Value); } // Populate each metric entry in the row for (int i = 0; i < metricCount; i++) { record.SetValue(dimensionCount + i, entry.Metrics[i].Value); } // Send the result back to the callee pipe.SendResultsRow(record); } // Indicate that the result set is finished pipe.SendResultsEnd(); }
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); } }
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); } } }
public string ResgisterScript(string clientID) { AnalyticsService service = new AnalyticsService("AnalyticsSampleApp"); if (!string.IsNullOrEmpty(GAEmailAddress)) { service.setUserCredentials(GAEmailAddress, GAPassword); } DataQuery query = new DataQuery(dataFeedUrl); query.Ids = "ga:" + GAProfileId; query.Metrics = "ga:visits"; query.Dimensions = "ga:country"; query.Sort = ""; query.GAStartDate = FromDate.ToString("yyyy-MM-dd"); query.GAEndDate = ToDate.ToString("yyyy-MM-dd"); DataFeed dataFeed = service.Query(query); //if (String.IsNullOrEmpty(GAToken) == false) { StringBuilder JavascriptBuilder = new StringBuilder(); JavascriptBuilder.Append("<script type=\"text/javascript\">"); JavascriptBuilder.Append(@" google.load('visualization', '1', {'packages': ['geomap']}); google.setOnLoadCallback(drawMap); function drawMap() { var data = new google.visualization.DataTable(); data.addRows(" + dataFeed.Entries.Count.ToString() + @"); data.addColumn('string', 'Country'); data.addColumn('number', 'Popularity'); "); Int32 CountryIndex = 0; // foreach (CountryPageViewResultEntity dataEntity in ResultData) // { // JavascriptBuilder.Append(@" // data.setValue(" + CountryIndex.ToString() + @", 0, '" + dataEntity.Country + @"'); // data.setValue(" + CountryIndex.ToString() + @", 1, " + dataEntity.VisitCount.ToString() + @"); //"); // CountryIndex++; // } foreach (DataEntry entry in dataFeed.Entries) { //entry.Metrics[0].Value; JavascriptBuilder.Append(@" data.setValue(" + CountryIndex.ToString() + @", 0, '" + entry.Dimensions[0].Value.ToString()+ @"'); data.setValue(" + CountryIndex.ToString() + @", 1, " + entry.Metrics[0].Value.ToString() + @"); "); CountryIndex++; } JavascriptBuilder.Append(@" var options = {}; options['dataMode'] = 'regions';"); JavascriptBuilder.Append(@"options['width'] = '" + Width + "';"); JavascriptBuilder.Append(@"options['height'] = '" + Height + "';"); JavascriptBuilder.Append(@"var container = document.getElementById('" + clientID + @"'); var geomap = new google.visualization.GeoMap(container); geomap.draw(data, options); }; "); JavascriptBuilder.Append("</script>"); return JavascriptBuilder.ToString(); } }
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); }
private const String TABLE_ID = "ga:37386554"; //"INSERT_TABLE_ID_HERE"; #endregion Fields #region Constructors 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 JsonResult FullStatistics(string dateFrom, string dateTo) { DateTime startDate = DateTime.ParseExact(dateFrom, "d", Thread.CurrentThread.CurrentCulture.DateTimeFormat); DateTime endDate = DateTime.ParseExact(dateTo, "d", Thread.CurrentThread.CurrentCulture.DateTimeFormat); string userName = Context.CurrentSite.GoogleDataUserName; string passWord = Context.CurrentSite.GoogleDataPassword; AnalyticsService service = new AnalyticsService("AnalyticsSampleApp"); if (!string.IsNullOrEmpty(userName)) service.setUserCredentials(userName, passWord); // Visits & Page Views DataQuery visitsAndPageViewsQuery = GetGoogleDataQuery(startDate, endDate, "ga:date", "ga:visits,ga:pageviews", "ga:date"); DataFeed data1 = service.Query(visitsAndPageViewsQuery); IList<string[]> arrayVisits = new List<string[]>(); IList<string[]> arrayPageViews = new List<string[]>(); foreach (DataEntry entry in data1.Entries) { string date = DateTime.ParseExact(entry.Dimensions[0].Value, "yyyyMMdd", null).ToJavascriptTimestamp().ToString(); arrayVisits.Add(new string[] { date, entry.Metrics[0].Value }); arrayPageViews.Add(new string[] { date, entry.Metrics[1].Value }); } // Browsers DataQuery browsersQuery = GetGoogleDataQuery(startDate, endDate, "ga:browser", "ga:visits", string.Empty); DataFeed data5 = service.Query(browsersQuery); IList<string[]> arrayBrowsersSource = new List<string[]>(); foreach (DataEntry entry in data5.Entries) { arrayBrowsersSource.Add(new string[] { entry.Dimensions[0].Value, entry.Metrics[0].Value }); } // New visitors / Returning DataQuery pieVisitorTypesQuery = GetGoogleDataQuery(startDate, endDate, "ga:visitorType", "ga:visits", string.Empty); DataFeed data6 = service.Query(pieVisitorTypesQuery); IList<string[]> arrayVisitorTypes = new List<string[]>(); foreach (DataEntry entry in data6.Entries) { arrayVisitorTypes.Add(new string[] { entry.Dimensions[0].Value, entry.Metrics[0].Value }); } // All Traffic Source (PIE) DataQuery pieTrafficSourceQuery = GetGoogleDataQuery(startDate, endDate, "ga:medium", "ga:visits", string.Empty); DataFeed data4 = service.Query(pieTrafficSourceQuery); IList<string[]> arrayPieTrafficSource = new List<string[]>(); foreach (DataEntry entry in data4.Entries) { string source = entry.Dimensions[0].Value; if (source == "(none)") source = "Direct"; else if (source == "organic") source = "Search"; arrayPieTrafficSource.Add(new string[] { source, entry.Metrics[0].Value }); } // Traffic Soruce DataQuery trafficSourceQuery = GetGoogleDataQuery(startDate, endDate, "ga:source,ga:referralPath", "ga:visits,ga:visitBounceRate,ga:avgTimeOnSite,ga:percentNewVisits", "-ga:visits"); DataFeed data2 = service.Query(trafficSourceQuery); IList<string[]> arrayTrafficSource = new List<string[]>(); NumberFormatInfo numberFormat = new System.Globalization.CultureInfo("en-US").NumberFormat; foreach (DataEntry entry in data2.Entries) { // ga:avgTimeOnSite is in secs // ga:percentNewVisits is in % arrayTrafficSource.Add(new string[] { entry.Dimensions[0].Value, entry.Dimensions[1].Value, entry.Metrics[0].Value, entry.Metrics[1].Value, TimeSpan.FromSeconds(Convert.ToDouble(entry.Metrics[2].Value, numberFormat)).ToString("g"), string.Format("{0}%", Math.Round(Convert.ToDouble(entry.Metrics[3].Value, numberFormat), 2) ) }); } // Keywords DataQuery keywordsQuery = GetGoogleDataQuery(startDate, endDate, "ga:keyword", "ga:visits", string.Empty); DataFeed data3 = service.Query(keywordsQuery); IList<string[]> arrayKeywords = new List<string[]>(); foreach (DataEntry entry in data3.Entries) { arrayKeywords.Add(new string[] { entry.Dimensions[0].Value, entry.Metrics[0].Value }); } return Json(new { visits = arrayVisits, pageviews = arrayPageViews, piesource = arrayPieTrafficSource, source = arrayTrafficSource, keywords = arrayKeywords, browsers = arrayBrowsersSource, visitortypes = arrayVisitorTypes }, JsonRequestBehavior.AllowGet); }
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); } }
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); } }
/// <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 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 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 string VisitorsOverview(string clientID) { AnalyticsService service = new AnalyticsService("AnalyticsSampleApp"); if (!string.IsNullOrEmpty(GAEmailAddress)) { service.setUserCredentials(GAEmailAddress, GAPassword); } DataQuery query = new DataQuery(dataFeedUrl); query.Ids = "ga:" + GAProfileId; query.Metrics = "ga:visits,ga:pageviews"; query.Dimensions = "ga:date"; query.Sort = ""; query.GAStartDate = FromDate.ToString("yyyy-MM-dd"); query.GAEndDate = ToDate.ToString("yyyy-MM-dd"); DataFeed dataFeed = service.Query(query); HttpContext.Current.Cache["VisitorsOverview_" + GAProfileId] = dataFeed; StringBuilder JavascriptBuilder = new StringBuilder(); JavascriptBuilder.Append("<script type=\"text/javascript\">"); JavascriptBuilder.Append("google.load('visualization', '1', {'packages':['annotatedtimeline']});") .Append("google.setOnLoadCallback(drawChart);"); JavascriptBuilder.Append(@" function drawChart() { var data = new google.visualization.DataTable(); data.addColumn('date', 'Date'); data.addColumn('number', 'Visite'); data.addColumn('string', 'title1'); data.addColumn('string', 'text1'); data.addColumn('number', 'Page Viewed'); data.addColumn('string', 'title1'); data.addColumn('string', 'text1'); data.addRows(["); foreach (DataEntry entry in dataFeed.Entries) { JavascriptBuilder.Append(@"[new Date(" + entry.Dimensions[0].Value.Substring(0, 4) + "," + (Convert.ToInt16(entry.Dimensions[0].Value.Substring(4, 2)) - 1).ToString() + "," + (Convert.ToInt16(entry.Dimensions[0].Value.Substring(6))).ToString() + "), " + entry.Metrics[0].Value.ToString().ToString() + ", undefined, undefined," + entry.Metrics[1].Value.ToString() + ", undefined, undefined],"); } JavascriptBuilder.Remove(JavascriptBuilder.Length - 1, 1); JavascriptBuilder.Append(@"]);"); JavascriptBuilder.Append(@"var chart2 = new google.visualization.AnnotatedTimeLine(document.getElementById('" + clientID + "'));"); JavascriptBuilder.Append(@"chart2.draw(data, {displayAnnotations: true,thickness:2,fill:10}); } "); JavascriptBuilder.Append("</script>"); return JavascriptBuilder.ToString(); }