static void Main(string[] args)
        {
            log4net.Config.XmlConfigurator.Configure();
            //Bug? AnalyticsReadOnly scope does not work.
            //string Scope = AnalyticsService.Scopes.AnalyticsReadOnly.ToString().ToLower();
            string              Scope              = "analytics.readonly";
            string              scopeUrl           = "https://www.googleapis.com/auth/" + Scope;
            const string        ServiceAccountId   = "nnnnnnnnnnn.apps.googleusercontent.com";
            const string        ServiceAccountUser = "******";
            AssertionFlowClient client             = new AssertionFlowClient(
                GoogleAuthenticationServer.Description, new X509Certificate2(@"value-privatekey.p12", "notasecret", X509KeyStorageFlags.Exportable))
            {
                Scope            = scopeUrl,
                ServiceAccountId = ServiceAccountUser //Bug, why does ServiceAccountUser have to be assigned to ServiceAccountId
                                                      //,ServiceAccountUser = ServiceAccountUser
            };
            OAuth2Authenticator <AssertionFlowClient> authenticator = new OAuth2Authenticator <AssertionFlowClient>(client, AssertionFlowClient.GetState);
            AnalyticsService service   = new AnalyticsService(authenticator);
            string           profileId = "ga:nnnnnnnn";
            string           startDate = "2010-10-01";
            string           endDate   = "2010-10-31";
            string           metrics   = "ga:visits";

            DataResource.GaResource.GetRequest request = service.Data.Ga.Get(profileId, startDate, endDate, metrics);
            request.Dimensions = "ga:date";
            GaData data = request.Fetch();
        }
Beispiel #2
0
        private OAuth2Authenticator <AssertionFlowClient> ObjGetOAuth2(string thumb, string strServiceAccEmailId, string strScope)
        {
            string scopeUrl         = "https://www.googleapis.com/auth/" + strScope;
            string strSrvAccEmailId = strServiceAccEmailId;

            AuthorizationServerDescription objAuthServerDesc = GoogleAuthenticationServer.Description;

            var store = new X509Store(StoreName.My, StoreLocation.LocalMachine);

            store.Open(OpenFlags.ReadOnly);
            var cert = store.Certificates.Find(X509FindType.FindByThumbprint, thumb, false);

            if (cert.Count == 0)
            {
                Log.Error("GA Certificate not found by thumb '{0}'", thumb);
                throw new Exception("Certificate not found");
            }

            Log.Debug("certs found {0}, first: {1}", cert.Count, cert[0].FriendlyName);

            var objClient = new AssertionFlowClient(objAuthServerDesc, cert[0])
            {
                ServiceAccountId = strSrvAccEmailId, Scope = scopeUrl
            };

            var objAuth = new OAuth2Authenticator <AssertionFlowClient>(objClient, AssertionFlowClient.GetState);

            return(objAuth);
        }         // ObjGetOAuth2
Beispiel #3
0
 public void SetUp()
 {
     client = new AssertionFlowClient(
         GoogleAuthenticationServer.Description, new X509Certificate2(@"test-key.p12", "notasecret", X509KeyStorageFlags.Exportable))
     {
         Scope            = Scope,
         ServiceAccountId = ServiceAccountId
     };
     state   = new AuthorizationState(client.Scope.Split(' '));
     channel = new MockChannel()
     {
         ResponseMessage = new AssertionFlowMessage(GoogleAuthenticationServer.Description)
     };
 }
Beispiel #4
0
        private OAuth2Authenticator <AssertionFlowClient> GetAuthenticator(string userEmail)
        {
            var provider = new AssertionFlowClient(GoogleAuthenticationServer.Description, _Certificate)
            {
                ServiceAccountId = ServiceAccountEmail,
                // Scope = "https://www.googleapis.com/auth/userinfo.email",
                // Scope = "https://www.googleapis.com/auth/userinfo.profile",
                // Scope = "https://docs.google.com/feeds/",
                Scope = "https://www.googleapis.com/auth/drive", //drive
                ServiceAccountUser = userEmail,
            };

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

            return(auth);
        }
Beispiel #5
0
        public static CalendarService BuildCalendarService()
        {
            X509Certificate2 certificate = new X509Certificate2(SERVICE_ACCOUNT_PKCS12_FILE_PATH, "notasecret", X509KeyStorageFlags.Exportable);
            var provider = new AssertionFlowClient(GoogleAuthenticationServer.Description, certificate)
            {
                ServiceAccountId = SERVICE_ACCOUNT_EMAIL,
                Scope            = CalendarService.Scopes.Calendar.GetStringValue(),
            };
            var auth = new OAuth2Authenticator <AssertionFlowClient>(provider, AssertionFlowClient.GetState);

            return(new CalendarService(new BaseClientService.Initializer()
            {
                Authenticator = auth,
                ApplicationName = "Calendar API Sample",
            }));
        }
Beispiel #6
0
 /// <summary>
 /// Initializes a new instance of the <see cref="AnalyticsManager"/> class.
 /// </summary>
 /// <exception cref="StageBitz.Common.Exceptions.StageBitzException">0;Error occurred while initializing google analytics.</exception>
 public AnalyticsManager()
 {
     try
     {
         AuthorizationServerDescription desc = GoogleAuthenticationServer.Description;
         X509Certificate2    key             = new X509Certificate2(KeyFile, KeyPass, X509KeyStorageFlags.Exportable);
         AssertionFlowClient client          = new AssertionFlowClient(desc, key)
         {
             ServiceAccountId = ClientId, Scope = Scope
         };
         OAuth2Authenticator <AssertionFlowClient> auth =
             new OAuth2Authenticator <AssertionFlowClient>(client, AssertionFlowClient.GetState);
         GoogleAnalyticsService = new AnalyticsService(new BaseClientService.Initializer()
         {
             Authenticator = auth
         });
     }
     catch (Exception ex)
     {
         throw new StageBitzException(ExceptionOrigin.WebAnalytics, 0, "Error occurred while initializing google analytics.", ex);
     }
 }
Beispiel #7
0
        private GoogleAnaliticsStatisticModel GetAnaliticsDataMethod(string scope, string clientId, string keyPassword, Core.Domain.Media.Download download, DateTime startDate, DateTime endDate)
        {
            var model = new GoogleAnaliticsStatisticModel();
            AuthorizationServerDescription desc = GoogleAuthenticationServer.Description;

            //Create a certificate object to use when authenticating
            X509Certificate2 key = new X509Certificate2(download.DownloadBinary, keyPassword, X509KeyStorageFlags.Exportable);

            //Now, we will log in and authenticate, passing in the description
            //and key from above, then setting the accountId and scope
            AssertionFlowClient client = new AssertionFlowClient(desc, key)
            {
                ServiceAccountId = clientId,
                Scope            = scope,
            };

            //Finally, complete the authentication process
            //NOTE: This is the first change from the update above
            OAuth2Authenticator <AssertionFlowClient> auth =
                new OAuth2Authenticator <AssertionFlowClient>(client, AssertionFlowClient.GetState);

            //First, create a new service object
            //NOTE: this is the second change from the update
            //above. Thanks to James for pointing this out
            AnalyticsService gas = new AnalyticsService(new BaseClientService.Initializer()
            {
                Authenticator = auth
            });

            //Create our query
            //The Data.Ga.Get needs the parameters:
            //Analytics account id, starting with ga:
            //Start date in format YYYY-MM-DD
            //End date in format YYYY-MM-DD
            //A string specifying the metrics
            DataResource.GaResource.GetRequest r =
                gas.Data.Ga.Get("ga:" + _googleAnliticsSettings.AccountId, startDate.ToString("yyy-MM-dd"), endDate.ToString("yyy-MM-dd"), "ga:visitors,ga:uniquePageviews,ga:AvgTimeOnSite,ga:exitRate");

            //Specify some addition query parameters
            //r.Sort = "-ga:visitors";
            //r.Sort = "-ga:AvgTimeOnSite";
            //r.Sort = "-ga:uniquePageviews";
            //r.Sort = "-ga:exitRate";
            r.MaxResults = 50;

            //Execute and fetch the results of our query
            GaData d = r.Fetch();

            //Write the column headers
            //Write the data
            foreach (var row in d.Rows)
            {
                model.Visitors          = row[0];
                model.UniquePageViews   = row[1];
                model.AverageTimeOnSite = row[2];
                if (row[3].Length > 5)
                {
                    model.ExitRate = row[3].Substring(0, 5);
                }
                else
                {
                    model.ExitRate = row[3];
                }
            }

            r            = gas.Data.Ga.Get("ga:" + _googleAnliticsSettings.AccountId, startDate.ToString("yyy-MM-dd"), endDate.ToString("yyy-MM-dd"), "ga:visitors");
            r.Dimensions = "ga:visitorType";
            r.MaxResults = 50;

            //Execute and fetch the results of our query
            d = r.Fetch();
            if (d.Rows.Count == 1)
            {
                if (d.Rows[0][0] != "Returning Visitor")
                {
                    model.NewToOldVisitorsRate = "100%";
                }
                else
                {
                    model.NewToOldVisitorsRate = "0%";
                }
            }
            else
            {
                model.NewToOldVisitorsRate = (((double)(int.Parse(d.Rows[0][1])) / (int.Parse(d.Rows[1][1]))) * 100).ToString() + "%";
            }

            if (model.NewToOldVisitorsRate.Length > 5)
            {
                model.NewToOldVisitorsRate = model.NewToOldVisitorsRate.Substring(0, 5);
            }

            if (model.AverageTimeOnSite.Length - model.AverageTimeOnSite.IndexOf(".") > 3)
            {
                model.AverageTimeOnSite = model.AverageTimeOnSite.Substring(0, model.AverageTimeOnSite.IndexOf(".") + 3);
            }

            return(model);
        }