Esempio n. 1
0
        /// <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);
            }
        }
Esempio n. 2
0
 /// <summary>
 /// Creates a new GoogleRealtimeDataCollector object using the Influx Database with the given name at the given endpoint to store the data using the given measurement name.
 /// </summary>
 /// <param name="databaseEndpoint">The address of an Influx Database endpoint. Usually defaults to http://localhost:8086.</param>
 /// <param name="databaseName">The name of the database the collector will save the data in.</param>
 /// <param name="measurementName">The measurement name that will be used when saving data in the database.</param>
 /// <param name="oAuthJSONPath">The location of the JSON file obtained from the Google Developer Console. It contains the data in order to authenticate against the Google OAuth 2.0 API.</param>
 /// <param name="userName">The user name of the Google account that is supposed to run the app.</param>
 public GoogleRealtimeDataCollector(string databaseEndpoint, string databaseName, string measurementName, string oAuthJSONPath, string userName) : base(databaseEndpoint, databaseName, measurementName, oAuthJSONPath, userName)
 {
     Scopes.Add("https://www.googleapis.com/auth/analytics.readonly");
     AnalyticsService      = Auth.GoogleAuthenticator_v3.AuthenticateByOAuth2(OAuthJSONPath, UserName, Scopes.ToArray());
     GetRequest            = AnalyticsService.Data.Realtime.Get("ga:148601695", "rt:pageviews");
     GetRequest.Dimensions = "rt:minutesAgo";
 }
Esempio n. 3
0
        private DataResource.RealtimeResource.GetRequest BuildRealtimeRequest(string profileId, string[] dimensions, string[] metrics)
        {
            DataResource.RealtimeResource.GetRequest request = Service.Data.Realtime.Get(profileId, string.Join(",", metrics));

            if (dimensions != null)
            {
                request.Dimensions = string.Join(",", dimensions);
            }

            return(request);
        }
Esempio n. 4
0
        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"]));
            }
        }