/// <summary> /// Returns real-time Google Analytics data for a view (profile). /// https://developers.google.com/analytics/devguides/reporting/realtime/v3/reference/data/realtime/get /// /// /// Beta: /// The Real Time Reporting API is currently available as a developer preview in limited beta. If you're interested in signing up, request access to the beta. /// https://docs.google.com/forms/d/1qfRFysCikpgCMGqgF3yXdUyQW4xAlLyjKuOoOEFN2Uw/viewform /// Apply for access wait 24 hours and then try you will not hear from Google when you have been approved. /// /// Documentation: Dimension and metric reference https://developers.google.com/analytics/devguides/reporting/realtime/dimsmets/ /// </summary> /// <param name="service">Valid authenticated Google analytics service</param> /// <param name="profileId">Profile id to request data from </param> /// <param name="metrics">Valid Real time Metrics (Required)</param> /// <param name="optionalValues">Optional values can be null</param> /// <returns>https://developers.google.com/analytics/devguides/reporting/realtime/v3/reference/data/realtime#resource</returns> public static RealtimeData Get(AnalyticsService service, string profileId, string metrics, OptionalValues optionalValues) { try { DataResource.RealtimeResource.GetRequest request = service.Data.Realtime.Get(String.Format("ga:{0}", profileId), metrics); request.MaxResults = 10000; if (optionalValues != null) { request.Dimensions = optionalValues.Dimensions; request.Sort = optionalValues.Sort; request.Filters = optionalValues.Filter; } RealtimeData feed = request.Execute(); return(feed); } catch (Exception ex) { Console.WriteLine(ex.Message); return(null); } }
static void Main(string[] args) { System.IO.Directory.SetCurrentDirectory(System.AppDomain.CurrentDomain.BaseDirectory); // Adding JSON file into IConfiguration. IConfiguration config = new ConfigurationBuilder().AddJsonFile("config/appsettings.json", true, true).Build(); string[] scopes = new string[] { AnalyticsService.Scope.Analytics }; // view and manage your Google Analytics data var keyFilePath = "config/analytics.p12"; // Downloaded from https://console.developers.google.com var serviceAccountEmail = config["ServiceAccountEmail"]; // found https://console.developers.google.com //loading the Key file var certificate = new X509Certificate2(keyFilePath, "notasecret", X509KeyStorageFlags.Exportable); var credential = new ServiceAccountCredential(new ServiceAccountCredential.Initializer(serviceAccountEmail) { Scopes = scopes }.FromCertificate(certificate)); var service = new AnalyticsService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = "Analytics API Sample", }); while (true) { try { DataResource.RealtimeResource.GetRequest realtimeReq = service.Data.Realtime.Get(String.Format("ga:{0}", config["GAID"]), "rt:activeUsers"); realtimeReq.Dimensions = "rt:country,rt:region,rt:city,rt:deviceCategory,rt:latitude,rt:longitude"; realtimeReq.Sort = "rt:activeUsers"; DataResource.RealtimeResource.GetRequest realtimePageViewsReq = service.Data.Realtime.Get(String.Format("ga:{0}", config["GAID"]), "rt:pageviews"); realtimePageViewsReq.Dimensions = "rt:country,rt:region,rt:city,rt:deviceCategory,rt:latitude,rt:longitude"; realtimePageViewsReq.Sort = "rt:pageviews"; RealtimeData realtime = realtimeReq.Execute(); RealtimeData realtimePageViews = realtimePageViewsReq.Execute(); Console.WriteLine(DateTime.Now.ToString("dd-MMM-yyyy hh:mm:ss")); Console.WriteLine("Total Active Users: " + realtime.TotalsForAllResults.FirstOrDefault().Value); Console.WriteLine("Total Page Views: " + realtimePageViews.TotalsForAllResults.FirstOrDefault().Value); Console.WriteLine("-----------------------------------------"); var userData = CreateData("RealtimeActiveUsers", realtime); var pageData = CreateData("RealtimePageViews", realtimePageViews); using (var webClient = new WebClient()) { webClient.Headers.Add("content-type", "application/json"); webClient.UploadString(config["ElasticSearchUrl"], String.Join("\r\n", userData) + "\r\n"); webClient.Headers.Add("content-type", "application/json"); webClient.UploadString(config["ElasticSearchUrl"], String.Join("\r\n", pageData) + "\r\n"); } } catch (Exception e) { Console.WriteLine("Error:" + e.Message); } Thread.Sleep(Convert.ToInt32(config["IntervalMs"])); } }