/// <summary>
        /// Constructor for the Google Analytics Helper
        /// </summary>
        /// <param name="serviceAccountEmail">Service account email for the Google API. Looks like [email protected]</param>
        /// <param name="applicationName">The name of the Google API Application</param>
        /// <param name="p12CertificatePath">Path to the downloaded p12 certificate</param>
        /// <param name="certificatePassword">Password to the p12 certificate - default "notasecret" </param>
        public Helper(string serviceAccountEmail, string applicationName, string p12CertificatePath, string certificatePassword)
        {
            var certificate = new X509Certificate2(p12CertificatePath, certificatePassword, X509KeyStorageFlags.Exportable);

            var credential = new ServiceAccountCredential(
            new ServiceAccountCredential.Initializer(serviceAccountEmail)
            {
                Scopes = new[] { AnalyticsService.Scope.Analytics }
            }.FromCertificate(certificate));

            service = new AnalyticsService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName = applicationName,
            });
        }
        /// <summary>
        /// Authenticate to Google Using Oauth2
        /// Documentation https://developers.google.com/accounts/docs/OAuth2
        /// </summary>
        /// <param name="clientId">From Google Developer console https://console.developers.google.com</param>
        /// <param name="clientSecret">From Google Developer console https://console.developers.google.com</param>
        /// <param name="userName">A string used to identify a user.</param>
        /// <returns></returns>
        public static AnalyticsService AuthenticateOauth(string clientId, string clientSecret, string userName)
        {

            string[] scopes = new string[] { AnalyticsService.Scope.Analytics,  // view and manage your analytics data
                                             AnalyticsService.Scope.AnalyticsEdit,  // edit management actives
                                             AnalyticsService.Scope.AnalyticsManageUsers,   // manage users
                                             AnalyticsService.Scope.AnalyticsReadonly};     // View analytics data

            try
            {
                // here is where we Request the user to give us access, or use the Refresh Token that was previously stored in %AppData%
                UserCredential credential = GoogleWebAuthorizationBroker.AuthorizeAsync(new ClientSecrets { ClientId = clientId, ClientSecret = clientSecret }
                                                                                             , scopes
                                                                                             , userName
                                                                                             , CancellationToken.None
                                                                                             , new FileDataStore("Daimto.GoogleAnalytics.Auth.Store")).Result;

                AnalyticsService service = new AnalyticsService(new BaseClientService.Initializer()
                {
                    HttpClientInitializer = credential,
                    ApplicationName = "BoardMe",
                });
                return service;
            }
            catch (Exception ex)
            {

                Console.WriteLine(ex.InnerException);
                return null;

            }

        }
        /// <summary>
        /// </summary>
        /// <param name="syncMetric"></param>
        /// <param name="accountName"></param>
        /// <returns>
        /// </returns>
        public async Task<bool> UploadSyncData(SyncMetric syncMetric, string accountName)
        {
            try
            {
                var analyticsService = new AnalyticsService(new BaseClientService.Initializer
                {
                    ApplicationName = ApplicationInfo.ProductName,
                    ApiKey = "AIzaSyBrpqcL6Nh1vVecfhIbxGVnyGHMZ8-aH6k"
                });
                var batchRequest = new BatchRequest(analyticsService);
                var metric = new CustomMetric
                {
                    Name = "SyncMetric",
                    Kind = "string"
                };

                var insertRequest = analyticsService.Management.CustomMetrics.Insert(metric, "", "");
                batchRequest.Queue<CustomMetric>(insertRequest, InsertMetricCallback);
                await batchRequest.ExecuteAsync();
            }
            catch (Exception ex)
            {
                Logger.Error(ex);
                return false;
            }
            return true;
        }
Beispiel #4
0
        public static string CreateCustomDimension(AnalyticsService ga, string accountId, string webPropertyId, string dimensionName, string scope, bool active)
        {
            List<CustomDimension> customDimensions = ga.Management.CustomDimensions.List(accountId, webPropertyId).Execute().Items as List<CustomDimension>;

            if (!customDimensions.Select(c => c.Name).Contains(dimensionName))
            {
                CustomDimension body = new CustomDimension
                {
                    AccountId = accountId,
                    WebPropertyId = webPropertyId,
                    Name = dimensionName,
                    Scope = scope,
                    Active = active
                };

                ManagementResource.CustomDimensionsResource.InsertRequest request = ga.Management.CustomDimensions.Insert(body, accountId, webPropertyId);
                CustomDimension newDimension = request.Execute();

                List<CustomDimension> newDimensions = ga.Management.CustomDimensions.List(accountId, webPropertyId).Execute().Items as List<CustomDimension>;
                if (newDimensions.Select(d => d.Id).Contains(newDimension.Id)) return "Success: Custom Dimension Added";
                else return "Failure: Unknown";
            } else
            {
                return "Custom Dimension Already Exists";
            }
        }
Beispiel #5
0
        public async static Task<int> GetPvAsync()
        {
            // Azure Web サイトで動かす場合には WEBSITE_LOAD_USER_PROFILE = 1 必須
            var file = ConfigurationManager.AppSettings["analyticsKeyFile"];
            var analyticsKeyFile = file[0] == '~' ? HttpContext.Current.Server.MapPath(file) : file;
            var certificate = new X509Certificate2(analyticsKeyFile, "notasecret", X509KeyStorageFlags.Exportable);

            // Scopes は指定しないとエラーになる
            var analyticsCredentialId = ConfigurationManager.AppSettings["analyticsCredentialId"];
            var credential = new ServiceAccountCredential(new ServiceAccountCredential.Initializer(analyticsCredentialId)
            {
                Scopes = new[] { AnalyticsService.Scope.Analytics, AnalyticsService.Scope.AnalyticsReadonly }
            }.FromCertificate(certificate));

            // HttpClientInitializer に credential 入れるのは違和感あるけど正しいらしい
            var service = new AnalyticsService(new BaseClientService.Initializer
            {
                HttpClientInitializer = credential,
                ApplicationName = "TweetPV",
            });

            // Azure は UTC なので +9 時間して -1 日
            var date = DateTime.UtcNow.AddHours(9).AddDays(-1).ToString("yyyy-MM-dd");

            // ****** はメモしたビューの ID
            var analyticsViewId = ConfigurationManager.AppSettings["analyticsViewId"];
            var data = await service.Data.Ga.Get("ga:" + analyticsViewId, date, date, "ga:pageviews").ExecuteAsync();

            return int.Parse(data.Rows[0][0]);
        }
        // GET: Connections/AuthenticateGoogleAnalytics
        public async Task<ActionResult> AuthenticateGoogleAnalytics(CancellationToken cancellationToken)
        {
            if (GoogleUserAuthenticated())
            {
                return RedirectToAction("Index");
            }
            else
            {
                var result = await new AuthorizationCodeMvcApp(this, new AppFlowMetadata()).AuthorizeAsync(cancellationToken);

                if (result.Credential == null)
                {
                    return new RedirectResult(result.RedirectUri);
                }

                Session.SetDataToSession("GoogleCredentials", result.Credential);

                var GoogleAnalytics = new AnalyticsService(new BaseClientService.Initializer
                {
                    HttpClientInitializer = result.Credential,
                    ApplicationName = "GAForce"
                });

                Session.SetDataToSession("GoogleAnalytics", GoogleAnalytics);

                return RedirectToAction("Index");
            }
        }
        /// <summary>
        /// Lists all accounts to which the user has access
        /// Documentation: https://developers.google.com/analytics/devguides/config/mgmt/v3/mgmtReference/management/accounts/list
        /// </summary>
        /// <param name="service">Valid authenticated Analytics Service</param>
        /// <returns>List of Account resource - https://developers.google.com/analytics/devguides/config/mgmt/v3/mgmtReference/management/accounts </returns>
        public static IList<Account> AccountList(AnalyticsService service)
        {
            //List all of the activities in the specified collection for the current user.
            // Documentation: https://developers.google.com/+/api/latest/activities/list

            ManagementResource.AccountsResource.ListRequest list = service.Management.Accounts.List();
            list.MaxResults = 1000; // Maximum number of Accounts to return, per request.

            Accounts feed = list.Execute();

            List<Account> resultList = new List<Account>();
            //// Loop through until we arrive at an empty page
            while (feed.Items != null)
            {
                //Adding return items.
                resultList.AddRange(feed.Items);

                // We will know we are on the last page when the next page token is
                // null.
                // If this is the case, break.
                if (feed.NextLink == null)
                {
                    break;
                }

                // Prepare the next page of results
                list.StartIndex = feed.StartIndex + list.MaxResults;
                // Execute and process the next page request
                feed = list.Execute();

            }
            return resultList;
        }
        /// <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;

            }


        }
        public static AnalyticsService authentify(string keyFilePath, string serviceAccountEmail)
        {
            string[] scopes =
             new string[] {
             AnalyticsService.Scope.Analytics,                 // view and manage your Google Analytics data
             AnalyticsService.Scope.AnalyticsManageUsers};     // View Google Analytics data

            if (!File.Exists(keyFilePath))
            {
                MessageBox.Show("An Error occurred - Key file does not exist \n" + keyFilePath, "KeyFile not found", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return null;
            }
            //loading the Key file
            var certificate = new X509Certificate2(keyFilePath, "notasecret", X509KeyStorageFlags.Exportable);
            ServiceAccountCredential credential = new ServiceAccountCredential(new ServiceAccountCredential.Initializer(serviceAccountEmail)
            {
                Scopes = scopes
            }.FromCertificate(certificate));
            AnalyticsService service = new AnalyticsService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName = "Analytics Add-In",
            });
            return service;
        }
        /// <summary>
        /// Lets you search on the different attributes returned with an item from the metadata api.
        /// Documentation: https://developers.google.com/analytics/devguides/reporting/metadata/v3/reference/metadata/columns/list
        /// </summary>
        /// <param name="service">Valid Analytics Service</param>
        /// <returns></returns>
        public static Columns GetSearchattributes(AnalyticsService service, string attributeName, string attributeValue)
        {
            Columns result = DaimtoAnaltyicsMetaDataHelper.MetaDataList(service);
            result.Items = result.Items.Where(a => a.Attributes[attributeName] == attributeValue).ToList();
            result.TotalResults = result.Items.Count();

            return result;

        }
        /// <summary>
        /// Returns only the Metrics from the MetaData api
        /// Documentation: https://developers.google.com/analytics/devguides/reporting/metadata/v3/reference/metadata/columns/list
        /// </summary>
        /// <param name="service">Valid Analytics Service</param>
        /// <returns></returns>
        public static Columns GetMetrics(AnalyticsService service)
        {
            Columns result = DaimtoAnaltyicsMetaDataHelper.MetaDataList(service);
            result.Items = result.Items.Where(a => a.Attributes["type"] == "METRIC").ToList();
            result.TotalResults = result.Items.Count();

            return result;

        }
 /// <summary>
 /// Constructor with required initializers.
 /// </summary>
 /// <param name="keyInformationFilePath">The file name storing the XML key used by the RSA object.</param>
 /// <param name="serviceAccount">The service account name used to authenticate the application.</param>
 /// <param name="applicationName">Optional. The application name to be used in the User-Agent header.</param>
 public GoogleAnalyticsService(string keyInformationFilePath, string serviceAccount, string applicationName)
 {
     KeyInformationFilePath = keyInformationFilePath;
     ServiceAccount = serviceAccount;
     ApplicationName = applicationName;
    
     GAService = new AnalyticsService(new BaseClientService.Initializer {
         HttpClientInitializer = GetServiceAccountCredentialFromCertificate(),
         ApplicationName = ApplicationName
     });
 }
Beispiel #13
0
        public async Task <IActionResult> OnGetAsync()
        {
            TotalUsers = await _context.Users.LongCountAsync();

            TotalRatings = await _context.ShowpieceRating.LongCountAsync();

            TotalShowpieces = await _context.Showpiece.LongCountAsync();

            //Google API testing

            string[] scopes = new string[] { AnalyticsService.Scope.Analytics };
            var      cred   = GoogleCredential.FromJson(_config["Google.API.ServiceAccount.Key"]).CreateScoped(scopes);

            var service = new Google.Apis.Analytics.v3.AnalyticsService(new BaseClientService.Initializer
            {
                ApplicationName       = "mtgdm",
                HttpClientInitializer = cred
            });

            //var request = service.Data.Ga.Get("ga:231311528",
            //                                  new DateTime(2020, 10, 01).ToString("yyy-MM-dd"),
            //                                  DateTime.Now.ToString("yyy-MM-dd"),
            //                                  "ga:visitors,ga:uniquePageviews");

            //request.Dimensions = "ga:pagePath";
            //var result = request.Execute();

            //Results = new GAResults()
            //{
            //    Columns = new List<string>(),
            //    Rows = new List<GAPageViewResults>()
            //};

            //foreach(var column in result.ColumnHeaders)
            //{
            //    Results.Columns.Add(column.Name);
            //}

            //foreach (var row in result.Rows)
            //{
            //    Results.Rows.Add(new GAPageViewResults()
            //    {
            //        PagePath = row[0],
            //        Vistitors = long.Parse(row[1]),
            //        PageViews = long.Parse(row[2])
            //    });
            //}

            //var hghg = "hello";

            return(Page());
        }
Beispiel #14
0
        public ActionResult Index()
        {
            var user = new UserProfile();
            try
            {
                Session["authenticator"] = Utils.getCredentials(Oauth2Service.Scopes.UserinfoProfile.GetStringValue());
              //  AnalyticsService.Scopes.AnalyticsReadonly.GetStringValue(),

            //ViewBag.Email = userInfo.Email;

            //try
            //{
            //    Session["authenticator"] = Utils.getCredsnew(AnalyticsService.Scopes.AnalyticsReadonly.GetStringValue());
            //}
            //catch (Exception ex)
            //{
            //    ViewBag.Error = ex.Message;
            //    return View();
            //}

            IAuthenticator auth = Session["authenticator"] as IAuthenticator;

            Userinfo userInfo = Utils.GetUserInfo(auth);
            user = new UserProfile();
            user.id = userInfo.Id;
            user.email = userInfo.Email;
            user.name = userInfo.Name;
            }

              catch (Exception ex)
            {
                ViewBag.Error = ex.Message;
                return View("Error");
            }

            try
            {
                Session["authenticator"] = Utils.getCredentials(AnalyticsService.Scopes.AnalyticsReadonly.GetStringValue());
                IAuthenticator authenticator = Session["authenticator"] as IAuthenticator;
                AnalyticsService service = new AnalyticsService(new BaseClientService.Initializer() { Authenticator = authenticator });
                var profiles = service.Management.Profiles.List("~all", "~all").Fetch();
                user.profiles = profiles;

            }
            catch (Exception ex)
            {
                ViewBag.Error = ex.Message;
                return View("Error");
            }

            return View(user);
        }
Beispiel #15
0
        private async Task <AnalyticsReport> GetAnalytics()
        {
            try
            {
                if (System.Configuration.ConfigurationManager.AppSettings["GoogleAnalytics"] != "Yes")
                {
                    return new AnalyticsReport {
                               PageViews = "Disabled", Sessions = "Disabled"
                    }
                }
                ;

                if (HttpRuntime.Cache[CacheEnum.GooglePageViews] != null)
                {
                    return((AnalyticsReport)HttpRuntime.Cache[CacheEnum.GooglePageViews]);
                }

                string fileName    = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "App_Data", "061868b5357ec57ce2cd01f7cba0d45c780d07f6-privatekey.p12");
                var    certificate = new X509Certificate2(fileName, "notasecret", X509KeyStorageFlags.Exportable | X509KeyStorageFlags.MachineKeySet);

                ServiceAccountCredential credential = new ServiceAccountCredential(
                    new ServiceAccountCredential.Initializer("*****@*****.**")
                {
                    Scopes = new[] { AnalyticsService.Scope.AnalyticsReadonly }
                }.FromCertificate(certificate));

                using (Google.Apis.Analytics.v3.AnalyticsService service = new Google.Apis.Analytics.v3.AnalyticsService(new BaseClientService.Initializer
                {
                    HttpClientInitializer = credential,
                    ApplicationName = "NSWC2014"
                }))
                {
                    var request = service.Data.Ga.Get("ga:87109047", DateTime.UtcNow.AddDays(-1).ToString("yyyy-MM-dd"), DateTime.UtcNow.ToString("yyyy-MM-dd"), "ga:pageviews,ga:sessions");
                    var result  = await request.ExecuteAsync();

                    var report = new AnalyticsReport {
                        PageViews = result.TotalsForAllResults["ga:pageviews"], Sessions = result.TotalsForAllResults["ga:sessions"]
                    };

                    HttpRuntime.Cache.Insert(CacheEnum.GooglePageViews, report, null, DateTime.UtcNow.AddMinutes(60), Cache.NoSlidingExpiration);
                    return(report);
                }
            }
            catch
            {
                return(new AnalyticsReport {
                    PageViews = "Pending..", Sessions = "Pending.."
                });
            }
        }
        private DataResource.RealtimeResource.GetRequest AnalyticsRequest(Google.Apis.Analytics.v3.AnalyticsService service, IGoogleAnalyticsRequestConfiguration requestConfig)
        {
            var metrics    = string.Join(",", requestConfig.Metrics.Select(GaMetadata.WithRealtimePrefix));
            var dimensions = string.Join(",", requestConfig.Dimensions.Select(GaMetadata.WithRealtimePrefix));

            var gRequest = service.Data.Realtime.Get(
                GaMetadata.WithPrefix(requestConfig.ProfileId),
                metrics);

            gRequest.Dimensions = dimensions == "" ? null : dimensions;
            gRequest.MaxResults = requestConfig.MaxResults;
            gRequest.Filters    = requestConfig.Filter;
            gRequest.Sort       = requestConfig.Sort;

            return(gRequest);
        }
Beispiel #17
0
        /// <summary>
        /// Creates a Queryer object to perform queries on Google Analytics, using a Service Account
        /// </summary>
        /// <param name="keyFilePath">Path to the Service Account's key file (what you download when you create a service account)</param>
        /// <param name="keyPassword">The password for the key file (defaults to "notapassword" when you create the service account)</param>
        /// <param name="serviceAccountEmail">The email associated with the service account (in format "(number)@developer.gserviceaccount.com")</param>
        /// <param name="applicationName">Name of application (I used the Name field in the Project Summary panel in https://code.google.com/apis/console/ )</param>
        public Queryer(string keyFilePath, string keyPassword, string serviceAccountEmail, string applicationName)
        {
            var key = new X509Certificate2(keyFilePath, keyPassword, X509KeyStorageFlags.Exportable);
            var credential = new ServiceAccountCredential(
                                new ServiceAccountCredential.Initializer(serviceAccountEmail)
                                {
                                    Scopes = new[] { AnalyticsService.Scope.Analytics }
                                }.FromCertificate(key));

            // Create the service.
            _service =
                new AnalyticsService(new BaseClientService.Initializer()
                {
                    ApplicationName = applicationName,
                    HttpClientInitializer = credential
                });
        }
Beispiel #18
0
        public static void Main(string[] args)
        {
            var tokenProvider = new NativeApplicationClient(GoogleAuthenticationServer.Description);
            tokenProvider.ClientIdentifier = "1083546295784-9ojhd793rbmo3bpas4gs811tvdsrbhlh.apps.googleusercontent.com";
            tokenProvider.ClientSecret = "UM5t_CWw9aogor0rKCkGkRcP";

            var auth = new OAuth2Authenticator<NativeApplicationClient>(tokenProvider, AuthProvider);

            var service = new AnalyticsService(auth);
            Accounts results = service.Management.Accounts.List().Fetch();
            Console.WriteLine("List:");
            foreach (Account a in results.Items)
            {
                Console.WriteLine(a.Name);
            }
            Console.ReadKey();
        }
        public IList<int> GetStats()
        {
            string scope = AnalyticsService.Scopes.AnalyticsReadonly.GetStringValue();

            //UPDATE this to match your developer account address. Note, you also need to add this address
            //as a user on your Google Analytics profile which you want to extract data from (this may take
            //up to 15 mins to recognise)
            string client_id = "*****@*****.**";

            //UPDATE this to match the path to your certificate
            string key_file = @"E:\path\to\cert.p12";
            string key_pass = "******";

            AuthorizationServerDescription desc = GoogleAuthenticationServer.Description;

            X509Certificate2 key = new X509Certificate2(key_file, key_pass, X509KeyStorageFlags.Exportable);

            AssertionFlowClient client =
                new AssertionFlowClient(desc, key) { ServiceAccountId = client_id, Scope = scope };

            OAuth2Authenticator<AssertionFlowClient> auth =
                new OAuth2Authenticator<AssertionFlowClient>(client, AssertionFlowClient.GetState);

            AnalyticsService gas = new AnalyticsService(new BaseClientService.Initializer() { Authenticator = auth });

            //UPDATE the ga:nnnnnnnn string to match your profile Id from Google Analytics
            DataResource.GaResource.GetRequest r =
                gas.Data.Ga.Get("ga:nnnnnnnn", "2013-01-01", "2013-01-31", "ga:visitors");

            r.Dimensions = "ga:pagePath";
            r.Sort = "-ga:visitors";
            r.MaxResults = 5;

            GaData d = r.Execute();

            IList<int> stats = new List<int>();

            for (int y = 0; y < d.Rows.Count; y++)
            {
                stats.Add(Convert.ToInt32(d.Rows[y][1]));
            }

            return stats;
        }
Beispiel #20
0
        public AnalyticsHelper(string analyticsKeyFile)
        {
            // Azure Web サイトで動かす場合には WEBSITE_LOAD_USER_PROFILE = 1 必須
            var certificate = new X509Certificate2(analyticsKeyFile, "notasecret", X509KeyStorageFlags.Exportable);

            // Scopes は指定しないとエラーになる
            var analyticsCredentialId = ConfigurationManager.AppSettings["analyticsCredentialId"];
            var credential = new ServiceAccountCredential(new ServiceAccountCredential.Initializer(analyticsCredentialId)
            {
                Scopes = new[] { AnalyticsService.Scope.Analytics, AnalyticsService.Scope.AnalyticsReadonly }
            }.FromCertificate(certificate));

            // HttpClientInitializer に credential 入れるのは違和感あるけど正しいらしい
            _service = new AnalyticsService(new BaseClientService.Initializer
            {
                HttpClientInitializer = credential,
                ApplicationName = "TweetPVSample",
            });
        }
        private GAResults CallAPIGetResults()
        {
            string[] scopes = new string[] { AnalyticsService.Scope.Analytics };
            var      cred   = GoogleCredential.FromJson(_config["Google.API.ServiceAccount.Key"]).CreateScoped(scopes);

            var service = new Google.Apis.Analytics.v3.AnalyticsService(new BaseClientService.Initializer
            {
                ApplicationName       = "mtgdm",
                HttpClientInitializer = cred
            });

            var request = service.Data.Ga.Get(_config["Google.Analytics.ProfileID"],
                                              new DateTime(2020, 10, 01).ToString("yyy-MM-dd"),
                                              DateTime.Now.ToString("yyy-MM-dd"),
                                              "ga:visitors,ga:uniquePageviews");

            request.Dimensions = "ga:pagePath";
            var result = request.Execute();

            var results = new GAResults()
            {
                Columns = new List <string>(),
                Rows    = new List <GAPageViewResults>()
            };

            foreach (var column in result.ColumnHeaders)
            {
                results.Columns.Add(column.Name);
            }

            foreach (var row in result.Rows)
            {
                results.Rows.Add(new GAPageViewResults()
                {
                    PagePath  = row[0],
                    Vistitors = long.Parse(row[1]),
                    PageViews = long.Parse(row[2])
                });
            }

            return(results);
        }
        private static void Main(string[] args)
        {
            //Analytics Service Setup
            var credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                new ClientSecrets
                {
                    ClientId = clientId,
                    ClientSecret = clientSecret
                },
                new[] {AnalyticsService.Scope.AnalyticsReadonly},
                gaUser,
                CancellationToken.None,
                new FileDataStore(oauthTokenFilestorage)
                ).Result;

            var service = new AnalyticsService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName = gaApplication
            });

            //The basic request to Google Analytics
            string start = new DateTime(2014, 1, 1).ToString("yyyy-MM-dd");
            string end = new DateTime(2014, 1, 10).ToString("yyyy-MM-dd");
            var query = service.Data.Ga.Get(profileId, start, end, "ga:visitors");

            query.Dimensions = "ga:visitCount, ga:date, ga:visitorType";
            query.Filters = "ga:visitorType==New Visitor";
            query.SamplingLevel = DataResource.GaResource.GetRequest.SamplingLevelEnum.HIGHERPRECISION;

            var response = query.Execute();

            Console.WriteLine("Entries in result: {0}", response.TotalResults);
            Console.WriteLine("You had : {0} new visitors from {1} to {2}"
                , response.TotalsForAllResults.First(), start, end);
            Console.WriteLine("Has more data: {0}", response.NextLink == null);
            Console.WriteLine("Sample data: {0}", response.ContainsSampledData);

            Console.ReadLine();
        }
Beispiel #23
0
        public static void getQueryAnalyticsResult(
            string accessToken,
            string metrics,
            string dimensions,
            string startDate = "2013-04-01",
            string endDate = "2013-04-30",
            string profileId = "ga:70717743"
            )
        {
            var logger = new Logger("GoogleService.Fetch");
            var service = new AnalyticsService();

            //var response = service.Data.Ga.Get(profileId, startDate, endDate, metrics);
            var resource = service.Data.Ga.Get(profileId, startDate, endDate, metrics);
            resource.Dimensions = dimensions;
            resource.MaxResults = 10000;
            resource.StartIndex = 1;
            resource.Oauth_token = accessToken;
            GaData report =  resource.FetchSync();

            logger.Write(0, "Successfully fetched data with " + report.Rows + " rows.");
        }
Beispiel #24
0
        public JsonResult Detail(string id)
        {
            IAuthenticator authenticator = Session["authenticator"] as IAuthenticator;
            AnalyticsService service = new AnalyticsService(new BaseClientService.Initializer() { Authenticator = authenticator });
            if (id == null)
            {
                var data = service.Management.Profiles.List("~all", "~all").Fetch();
                JsonResult datas = Json(data);
                datas.JsonRequestBehavior = JsonRequestBehavior.AllowGet;

                return datas;
            }
            else
            {

                var garesults = Utils.GetProfileReport(id, authenticator);
                JsonResult results = Json(garesults);
              //  JsonResult rows = Json(garesults.JSON);
                results.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
              //  rows.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
                return results;
            }
        }
Beispiel #25
0
        public static AnalyticsReport GetReport(AnalyticsProfile profile, IAuthenticator authenticator)
        {
            AnalyticsService service = new AnalyticsService(new BaseClientService.Initializer() { Authenticator = authenticator });

            var data =
                   service.Data.Ga.Get("ga:" + profile.id, profile.startDate.ToString("yyyy-MM-dd"), profile.endDate.ToString("yyyy-MM-dd"), "ga:visits,ga:bounces,ga:pageviews");
            data.Dimensions = "ga:source,ga:keyword,ga:pagePath,ga:city,ga:date,ga:landingPagePath,ga:visitorType";
            // data.MaxResults = 500;
            if (data.Fetch() == null)
            {
            try
            {
                //reauth if auth fail
                IAuthenticator auth = Utils.getCredsnew(AnalyticsService.Scopes.AnalyticsReadonly.GetStringValue());
                 data =service.Data.Ga.Get("ga:" + profile.id, profile.startDate.ToString("yyyy-MM-dd"), profile.endDate.ToString("yyyy-MM-dd"), "ga:visits,ga:bounces,ga:pageviews");
                data.Dimensions = "ga:source,ga:keyword,ga:pagePath,ga:city,ga:date,ga:landingPagePath,ga:visitorType";
            }
            catch (Exception ex)
            {
            }

            }

            GaData garesults = data.Fetch();
            AnalyticsReport report = new AnalyticsReport();
            report.id = profile.id;
            report.JSON = garesults.Rows;

            var test = garesults.TotalsForAllResults;
            report.TotalVisits = Convert.ToInt32(test["ga:visits"]);
            report.TotalPageViews = Convert.ToInt32(test["ga:pageviews"]);
            var bounces = Convert.ToInt32(test["ga:bounces"]);
            var visits = Convert.ToInt32(test["ga:visits"]);
            report.BounceRate = ( visits / 2);

            //Referral List
            List<string> reflinks = new List<string>();
            List<string> keyWordList = new List<string>();
            List<string> landingPages = new List<string>();
            List<string> cityList = new List<string>();
            List<string> pagePathList = new List<string>();
            List<string> visitorType = new List<string>();
            List<int> dayList = new List<int>();
            List<int> totalVisitors = new List<int>();
            List<int> newVisitors = new List<int>();
            List<int> returningVisitors = new List<int>();
            int maxReturningVisitors = 0;
            int maxNewVisitors = 0;
            if (garesults.Rows != null){
            foreach (var a in garesults.Rows)
            {
            string visType = a[6];
            var day = Convert.ToInt32(a[4]);
            if (dayList.Count() == 0)
            {
                dayList.Add(day);
            }
            else
            {
                var lastday = dayList.Last();
                if (day != lastday)
                {
                    dayList.Add(day);
                    filltoSameSize(newVisitors, returningVisitors);
                }
            }
            int numVisits = Convert.ToInt32(a[7]);
            if (visType == "New Visitor")
            {
                newVisitors.Add(numVisits);
                report.TotalNewVisitors = (report.TotalNewVisitors + numVisits);
                maxNewVisitors = Math.Max(maxNewVisitors, numVisits);
                totalVisitors.Add(numVisits);
            }

            else
            {
                totalVisitors.Add(numVisits);
                returningVisitors.Add(numVisits);
                report.TotalReturningVisitors = (report.TotalReturningVisitors + numVisits);
                maxReturningVisitors = Math.Max(maxReturningVisitors, numVisits);
            }
            reflinks.Add(a[0]);
            keyWordList.Add(a[1]);
            pagePathList.Add(a[2]);
            cityList.Add(a[3]);
            dayList.Add(day);
            landingPages.Add(a[5]);
            visitorType.Add(a[6]);
            }
            filltoSameSize(newVisitors, returningVisitors);
            report.totalVisitors = totalVisitors;
            report.maxNewVisitors = maxNewVisitors;
            report.maxReturningVisitors = maxReturningVisitors;
            report.newVisitors = newVisitors;
            report.retVisitors = returningVisitors;
            report.landingpagelist = landingPages;
            report.keylist = keyWordList;
            report.reflist = reflinks;
            report.keylist = keyWordList;
            report.citylist = cityList;
            report.pagelist = pagePathList;
            report.daylist = dayList;

            //KeyWord Entrances
            //  report.newVisitors = (from pages in arrPage group pages by pages into p where p.Key != null && !p.Key.Contains("Error") orderby p.Count() descending select new { Key = p.Key, Count = p.Count() }).Take(7);

            return report;
            }
            else
            {
            return null;
            }
        }
Beispiel #26
0
        public static AnalyticsReport GetProfileReport(string id, IAuthenticator authenticator)
        {
            AnalyticsService service = new AnalyticsService(new BaseClientService.Initializer() { Authenticator = authenticator });

            var data =
                   service.Data.Ga.Get("ga:" + id, "2012-10-01", "2012-11-01", "ga:visits,ga:bounces,ga:pageviews");
            data.Dimensions = "ga:source,ga:keyword,ga:pagePath,ga:city,ga:date,ga:landingPagePath,ga:visitorType";
               // data.MaxResults = 500;

            GaData garesults = data.Fetch();
            AnalyticsReport report = new AnalyticsReport();
            report.id = id;
            report.JSON = garesults.Rows;

            var test = garesults.TotalsForAllResults;
            report.TotalVisits = Convert.ToInt32(test["ga:visits"]);
            report.TotalPageViews = Convert.ToInt32(test["ga:pageviews"]);
            var bounces = Convert.ToInt32(test["ga:bounces"]);
            var visits = Convert.ToInt32(test["ga:visits"]);
            report.BounceRate = (bounces / visits);

            //Referral List
            List<string> reflinks = new List<string>();
            List<string> keyWordList = new List<string>();
            List<string> landingPages = new List<string>();
            List<string> pagePathList = new List<string>();
            List<string> cityList = new List<string>();

            List<string> visitorType = new List<string>();
            List<int> dayList = new List<int>();
            List<int> newVisitors = new List<int>();
            List<int> returningVisitors = new List<int>();
            int maxReturningVisitors = 0;
            int maxNewVisitors = 0;
            foreach (var a in garesults.Rows)
            {
            string visType = a[6];
            var day = Convert.ToInt32(a[4]);
            if (dayList.Count() == 0)
            {
                dayList.Add(day);
            }
            else
            {
                var lastday = dayList.Last();
                if (day != lastday)
                {
                    dayList.Add(day);
                    filltoSameSize(newVisitors, returningVisitors);
                }
            }
            int numVisits = Convert.ToInt32(a[7]);
            if(visType == "New Visitor"){
                newVisitors.Add(numVisits);
                report.TotalNewVisitors = (report.TotalNewVisitors + numVisits);
                maxNewVisitors = Math.Max(maxNewVisitors, numVisits);
            }
            else
            {
                returningVisitors.Add(numVisits);
                report.TotalReturningVisitors = (report.TotalReturningVisitors + numVisits);
                maxReturningVisitors = Math.Max(maxReturningVisitors, numVisits);
            }

            reflinks.Add(a[0]);
            keyWordList.Add(a[1]);
            pagePathList.Add(a[2]);
            cityList.Add(a[3]);
            dayList.Add(day);
            landingPages.Add(a[5]);
            visitorType.Add(a[6]);
            }
            filltoSameSize(newVisitors, returningVisitors);
            report.maxNewVisitors = maxNewVisitors;
            report.maxReturningVisitors = maxReturningVisitors;
            report.newVisitors = newVisitors;
            report.retVisitors = returningVisitors;
            report.keylist = keyWordList;
            report.reflist = reflinks;
            report.citylist = cityList;
            report.landingpagelist = pagePathList;
            report.daylist = dayList;

            //KeyWord Entrances
               //  report.newVisitors = (from pages in arrPage group pages by pages into p where p.Key != null && !p.Key.Contains("Error") orderby p.Count() descending select new { Key = p.Key, Count = p.Count() }).Take(7);

            return report;
        }
Beispiel #27
0
 public override void Init()
 {
     base.Init();
     var provider = new NativeApplicationClient(GoogleAuthenticationServer.Description);
     provider.ClientIdentifier = RequiredParams["client"].ToString();
     provider.ClientSecret = RequiredParams["secret"].ToString();
     var auth = new OAuth2Authenticator<NativeApplicationClient>(provider, GetAuthentication);
     analyticsService = new AnalyticsService(auth);
 }
        /// <summary>
        /// Lists web properties to which the user has access for a given account
        /// Documentation: https://developers.google.com/analytics/devguides/config/mgmt/v3/mgmtReference/management/webproperties/list
        /// </summary>
        /// <param name="service">Valid authenticated Analytics Service</param>
        /// <param name="accountId">Account Id </param>
        /// <returns>A Web property resource https://developers.google.com/analytics/devguides/config/mgmt/v3/mgmtReference/management/webproperties </returns>
        public static IList<Webproperty> WebpropertyList(AnalyticsService service, string accountId)
        {
            ManagementResource.WebpropertiesResource.ListRequest list = service.Management.Webproperties.List(accountId);
            list.MaxResults = 1000;

            Webproperties feed = list.Execute();

            List<Webproperty> returnList = new List<Webproperty>();
            //// Loop through until we arrive at an empty page
            while (feed.Items != null)
            {
                // Adding items to the list
                returnList.AddRange(feed.Items);

                // We will know we are on the last page when the next page token is
                // null.
                // If this is the case, break.
                if (feed.NextLink == null)
                {
                    break;
                }

                // Prepare the next page of results
                list.StartIndex = feed.StartIndex + list.MaxResults;
                // Execute and process the next page request
                feed = list.Execute();

            }
            return returnList;
        }
Beispiel #29
0
 private void auth()
 {
     credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                    new ClientSecrets
                    {
                        ClientId = "374992669151-gq3ge9ps7clrvdkr6r4kmqamlcbesqfp.apps.googleusercontent.com",
                        ClientSecret = "mIUGfAhjITR1qqv7CgAXK4BY"
                    },
                    new[] { AnalyticsService.Scope.AnalyticsReadonly },
                    "user", CancellationToken.None, new FileDataStore("ga")).Result;
     service = new AnalyticsService(
        new BaseClientService.Initializer()
        {
            HttpClientInitializer = credential,
            ApplicationName = "abc-analytics ga data exporter"
        });
     getAccounts();
 }
Beispiel #30
0
 public JsonResult Index()
 {
     IAuthenticator authenticator = Session["authenticator"] as IAuthenticator;
     AnalyticsService service = new AnalyticsService(new BaseClientService.Initializer() { Authenticator = authenticator });
     Profiles profiles = new Profiles();
     // profiles =
     profiles = service.Management.Profiles.List("~all", "~all").Fetch();
     JsonResult results = Json(profiles);
     results.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
     return results;
 }
        /// <summary>
        /// You query the Core Reporting API for Google Analytics report data. 
        /// Documentation: https://developers.google.com/analytics/devguides/reporting/core/v3/reference
        /// 
        /// Dimension and metric reference : https://developers.google.com/analytics/devguides/reporting/core/dimsmets
        /// </summary>
        /// <param name="service">Valid Authenticated AnalyticsServicve </param>
        /// <param name="ProfileId">The unique table ID of the form XXXX, where XXXX is the Analytics view (profile) ID for which the query will retrieve the data. </param>
        /// <param name="StartDate">Start date for fetching Analytics data. Requests can specify a start date formatted as YYYY-MM-DD, or as a relative date (e.g., today, yesterday, or NdaysAgo where N is a positive integer). </param>
        /// <param name="EndDate">End date for fetching Analytics data. Request can specify an end date formatted as YYYY-MM-DD, or as a relative date (e.g., today, yesterday, or NdaysAgo where N is a positive integer). </param>
        /// <param name="Metrics">A list of comma-separated metrics, such as ga:sessions,ga:bounces. </param>
        /// <param name="optionalValues">Optional values can be null </param>
        /// <returns></returns>
        public static GaData Get(AnalyticsService service, string profileId, string startDate, string endDate, string metrics, OptionalValues optionalValues)
        {
            
            ILog logger = LogManager.GetLogger(typeof(OptionalValues));
            try {
                DataResource.GaResource.GetRequest request = service.Data.Ga.Get(String.Format("ga:{0}", profileId), startDate, endDate, metrics);
                if (optionalValues == null)
                {
                    request.MaxResults = 1000;
                }
                else
                {
                    request.MaxResults = optionalValues.MaxResults;
                    request.Dimensions = optionalValues.Dimensions;
                    request.SamplingLevel = optionalValues.Sampling;
                    request.Segment = optionalValues.Segment;
                    request.Sort = optionalValues.Sort;
                    request.Filters = optionalValues.Filter;

                }
                return ProcessResults(request);
            }
            catch (Exception e) 
            {
                logger.Error(e.StackTrace);
                logger.Error(e.Message);
            }
            return null;
           
        }
        /// <summary>
        /// Update an existing web property. This method supports patch semantics 
        /// Documentation:https://developers.google.com/analytics/devguides/config/mgmt/v3/mgmtReference/management/webproperties/patch
        /// 
        /// Beta Access: https://developers.google.com/analytics/devguides/config/mgmt/v3/mgmtWebpropertyGuide#code
        /// Write operations in the Management API (e.g. create, update, delete, patch) for Web Property, View (Profile), 
        /// and Goal resources is currently available as a developer preview in limited beta. If you're interested in using these features, 
        /// request access to the beta.
        /// https://docs.google.com/forms/d/1xyjp6ca4YkGjh7TDi1Z3XyA3XHcRHkKzFentxzUrmPY/viewform
        /// 
        /// 
        /// </summary>
        /// <param name="service">Valid Authenticated Analytics Service </param>
        /// <param name="Body">relevant portions of a management.webproperty resource, according to the rules of patch semantics.</param>
        /// <param name="accountId">Account ID to which the web property belongs </param>
        /// <param name="webPropertyId">Web property ID</param>
        /// <returns>A Web property resource https://developers.google.com/analytics/devguides/config/mgmt/v3/mgmtReference/management/webproperties </returns>
        public static Webproperty WebpropertyUpdate(AnalyticsService service, Webproperty body, string accountId, string webPropertyId)
        {
            try
            {
                Webproperty wp = service.Management.Webproperties.Update(body, accountId, webPropertyId).Execute();
                return wp;
            }
            catch (Exception ex)
            {

                Console.WriteLine(ex.Message);
                return null;
            }
        }
        /// <summary>
        ///     <see cref="Authenticate" /> to Google Using Oauth2 Documentation
        ///     https://developers.google.com/accounts/docs/OAuth2
        /// </summary>
        /// <param name="clientId">
        ///     From Google Developer console https://console.developers.google.com
        /// </param>
        /// <param name="clientSecret">
        ///     From Google Developer console https://console.developers.google.com
        /// </param>
        /// <param name="userName">
        ///     A string used to identify a user (locally).
        /// </param>
        /// <param name="fileDataStorePath">
        ///     Name/Path where the Auth Token and refresh token are stored (usually
        ///     in %APPDATA%)
        /// </param>
        /// <param name="applicationName">Applicaiton Name</param>
        /// <param name="isFullPath">
        ///     <paramref name="fileDataStorePath" /> is completePath or Directory
        ///     Name
        /// </param>
        /// <returns>
        /// </returns>
        public AnalyticsService AuthenticateAnalyticsOauth(string clientId, string clientSecret, string userName,
            string fileDataStorePath, string applicationName, bool isFullPath = false)
        {
            try
            {
                var authTask = Authenticate(clientId, clientSecret, userName, fileDataStorePath, isFullPath);

                authTask.Wait(30000);

                if (authTask.Status == TaskStatus.WaitingForActivation)
                {
                    return null;
                }

                var service = new AnalyticsService(new BaseClientService.Initializer
                {
                    HttpClientInitializer = authTask.Result,
                    ApplicationName = applicationName
                });

                return service;
            }
            catch (AggregateException exception)
            {
                Logger.Error(exception);
                return null;
            }
            catch (Exception exception)
            {
                Logger.Error(exception);
                return null;
            }
        }
        public void Execute(AnalyticsService service, XML.Objects.Organisation.View view, Excel.Range currentCell)
        {
            String metrics = MetricsToString();

            Request = service.Data.Ga.Get(view.Tag, Start.ToString("yyyy-MM-dd"), End.ToString("yyyy-MM-dd"), metrics);
            SetDimensions(Request);
            SetSort(Request);
            SetFilters(Request);
            SetSegment(Request);

            Request.MaxResults = 10000;

            Request.PrettyPrint = true;

            //Send the query
            GaData result = null;
            try
            {
                result = Request.Execute();
                currentCell = Stubs.DisplayGaData(result, currentCell);
                currentCell.Select();
            }
            catch (Google.GoogleApiException exception)
            {
                MessageBox.Show(exception.Message, "Erreur", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }