Exemple #1
0
        /// <summary>
        /// Synchronously creates a <see cref="StorageClient"/>, using application default credentials if
        /// no credentials are specified.
        /// </summary>
        /// <remarks>
        /// The credentials are scoped as necessary.
        /// </remarks>
        /// <param name="credential">Optional <see cref="GoogleCredential"/>.</param>
        /// <returns>The created <see cref="StorageClient"/>.</returns>
        public static StorageClient Create(GoogleCredential credential = null)
        {
            try
            {
                credential = credential ?? Task.Run(() => GoogleCredential.GetApplicationDefaultAsync()).Result;
            }
            catch (AggregateException e)
            {
                // Unwrap the first exception, a bit like await would.
                // It's very unlikely that we'd ever see an AggregateException without an inner exceptions,
                // but let's handle it relatively gracefully.
                throw e.InnerExceptions.FirstOrDefault() ?? e;
            }
            if (credential.IsCreateScopedRequired)
            {
                credential = credential.CreateScoped(StorageService.Scope.DevstorageFullControl);
            }
            var service = new StorageService(new BaseClientService.Initializer
            {
                HttpClientInitializer = credential,
                ApplicationName       = StorageClientImpl.ApplicationName,
            });

            return(new StorageClientImpl(service));
        }
        public GoogleDriveCache(GoogleCredential creds)
        {
            var credential = creds.CreateScoped(Scopes);

            _retryPolicy = Policy.Handle <Exception>()
                           .WaitAndRetryForever(retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)));

            using (var service = new SheetsService(new BaseClientService.Initializer
            {
                HttpClientInitializer = credential,
                ApplicationName = ApplicationName,
                GZipEnabled = true
            }))
            {
                service.HttpClient.Timeout = TimeSpan.FromSeconds(30);

                // TODO make async
                var places         = GetCityPlaceNames(service, "1Dc77HLVn9YXgY1JkcqqaMh1Tm0cemwXxFfyHb7dP0Cs", "A2:C");
                var zips           = GetZipCodesInQuadrants(service, "1HX47abPQ24LqB8iUHu6HTSmTnbU1YN9WvxO6BDsHCLg", "A2:C");
                var deliveryPoints = GetUspsDeliveryPoints(service, "1rgqNweBxiqWVwxTlMWgX-sN8IJguvlUcY0yOvmI8JuQ", "A2:H");
                var corrections    = GetCorrections(service, "1ZqXyQflKQ8q-sBHCHLaYaQXY90aOFU0JPc4-M_41GM0", "A2:H");
                var poboxes        = GetPoBoxes(service, "1DX5w1UDeANyrjr0C-13lJVal2sRcZ3U67Im1loIaFog", "A2:C");

                PlaceGrids         = BuildGridLinkableLookup(places);
                ZipCodesGrids      = BuildGridLinkableLookup(zips);
                UspsDeliveryPoints = BuildGridLinkableLookup(deliveryPoints);
                PoBoxes            = poboxes;

                var exclusions = corrections.ToList();
                PoBoxZipCodesWithExclusions = exclusions.Select(x => x.Zip).Distinct();
                PoBoxExclusions             = exclusions.ToDictionary(x => x.ZipPlusFour, y => y);
            }
        }
        // [END auth_api_explicit]

        // [START auth_http_implicit]
        static object AuthHttpImplicit(string projectId)
        {
            GoogleCredential credential =
                GoogleCredential.GetApplicationDefaultAsync().Result;
            // Inject the Cloud Storage scope if required.
            if (credential.IsCreateScopedRequired)
            {
                credential = credential.CreateScoped(new[]
                {
                    "https://www.googleapis.com/auth/devstorage.read_only"
                });
            }
            HttpClient http = new Google.Apis.Http.HttpClientFactory()
                .CreateHttpClient(
                new Google.Apis.Http.CreateHttpClientArgs()
                {
                    ApplicationName = "Google Cloud Platform Auth Sample",
                    GZipEnabled = true,
                    Initializers = { credential },
                });
            UriBuilder uri = new UriBuilder(
                "https://www.googleapis.com/storage/v1/b");
            uri.Query = "project=" +
                System.Web.HttpUtility.UrlEncode(projectId);
            var resultText = http.GetAsync(uri.Uri).Result.Content
                .ReadAsStringAsync().Result;
            dynamic result = Newtonsoft.Json.JsonConvert
                .DeserializeObject(resultText);
            foreach (var bucket in result.items)
            {
                Console.WriteLine(bucket.name);
            }
            return null;
        }
Exemple #4
0
        public static void AuthExplicitComputeEngine(string projectId)
        {
            // Explicitly use service account credentials by specifying the
            // private key file.
            GoogleCredential credential =
                GoogleCredential.FromComputeCredential();

            // Inject the Cloud Storage scope if required.
            if (credential.IsCreateScopedRequired)
            {
                credential = credential.CreateScoped(new[]
                {
                    StorageService.Scope.DevstorageReadOnly
                });
            }
            var storage = new StorageService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName       = "clear-fusion",
            });
            var request       = new BucketsResource.ListRequest(storage, projectId);
            var requestResult = request.Execute();
            var folder        = "00012";

            foreach (var bucket in requestResult.Items)
            {
                if (bucket.Name == "cf-staging-storage")
                {
                    // AddFolder(folder, bucket.Name);
                }
            }
            //return null;
        }
Exemple #5
0
        static void Main(string[] args)
        {
            GoogleCredential credential =
                GoogleCredential.GetApplicationDefault();

            if (credential.IsCreateScopedRequired)
            {
                credential = credential.CreateScoped(new[]
                {
                    CloudResourceManagerService.Scope.CloudPlatformReadOnly
                });
            }
            var crmService = new CloudResourceManagerService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
            });
            var request = new ProjectsResource.ListRequest(crmService);

            while (true)
            {
                var result = request.Execute();
                foreach (var project in result.Projects)
                {
                    Console.WriteLine(project.ProjectId);
                }
                if (string.IsNullOrEmpty(result.NextPageToken))
                {
                    break;
                }
                request.PageToken = result.NextPageToken;
            }
        }
Exemple #6
0
 private void InitializeClassroomService()
 {
     _classroomService = new ClassroomService(new BaseClientService.Initializer()
     {
         HttpClientInitializer = _credential.CreateScoped(_scopes)
     });
 }
Exemple #7
0
        public object AuthImplicit(string projectId)
        {
            GoogleCredential credential =
                GoogleCredential.GetApplicationDefault();

            // Inject the Cloud Storage scope if required.
            if (credential.IsCreateScopedRequired)
            {
                credential = credential.CreateScoped(new[]
                {
                    StorageService.Scope.DevstorageReadOnly
                });
            }
            var storage = new StorageService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName       = "gcloud-dotnet/2.2.1",
            });
            var request       = new BucketsResource.ListRequest(storage, projectId);
            var requestResult = request.Execute();

            foreach (var bucket in requestResult.Items)
            {
                Console.WriteLine(bucket.Name);
            }
            return(null);
        }
        /// <summary>
        /// Get Access Token From JSON Key Async
        /// </summary>
        /// <param name="jsonKeyFilePath">Path to your JSON Key file</param>
        /// <param name="scopes">Scopes required in access token</param>
        /// <returns>Access token as string Task</returns>

        public static async Task <string> GetAccessTokenFromJSONKeyAsync(string jsonKeyFilePath, params string[] scopes)
        {
            try
            {
                // Get active credential
                using (var stream = new System.IO.FileStream(jsonKeyFilePath, System.IO.FileMode.Open, System.IO.FileAccess.Read))
                {
                    _cred   = GoogleCredential.FromStream(stream);
                    _cred   = _cred.CreateScoped(scopes);
                    service = new DriveService(new BaseClientService.Initializer()
                    {
                        HttpClientInitializer = _cred,
                        ApplicationName       = "Drive API Sample",
                    });
                    try
                    {
                        Task <string> task = ((ITokenAccess)_cred).GetAccessTokenForRequestAsync();
                        task.Wait();
                        string bearer = task.Result;
                        return(bearer);
                    }
                    catch (AggregateException ex)
                    {
                        throw ex.InnerException;
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        public static void Main(string[] args)
        {
            // Authorize the client using Application Default Credentials.
            // See: https://developers.google.com/identity/protocols/application-default-credentials
            GoogleCredential credential = GoogleCredential.GetApplicationDefaultAsync().Result;

            // Specify the Service scope.
            if (credential.IsCreateScopedRequired)
            {
                credential = credential.CreateScoped(new[]
                {
                    Google.Apis.JobService.v2.JobServiceService.Scope.Jobs
                });
            }
            // Instantiate the Cloud Key Management Service API.
            JobServiceService jobServiceClient = new JobServiceService(new BaseClientService.Initializer
            {
                HttpClientInitializer = credential,
                GZipEnabled           = false
            });

            // List companies.
            ListCompaniesResponse result = jobServiceClient.Companies.List().Execute();

            Console.WriteLine("Request Id: " + result.Metadata.RequestId);
            if (result.Companies != null)
            {
                Console.WriteLine("Companies: ");
                result.Companies.ToList().ForEach(company => Console.WriteLine(company.Name));
            }
            else
            {
                Console.WriteLine("No companies found.");
            }
        }
        // [END auth_api_explicit]

        // [START auth_api_explicit_compute_engine]
        public object AuthExplicitComputeEngine(string projectId)
        {
            // Explicitly use service account credentials by specifying the
            // private key file.
            GoogleCredential credential =
                GoogleCredential.FromComputeCredential();

            // Inject the Cloud Storage scope if required.
            if (credential.IsCreateScopedRequired)
            {
                credential = credential.CreateScoped(new[]
                {
                    StorageService.Scope.DevstorageReadOnly
                });
            }
            var storage = new StorageService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName       = "DotNet Google Cloud Platform Auth Sample",
            });
            var request       = new BucketsResource.ListRequest(storage, projectId);
            var requestResult = request.Execute();

            foreach (var bucket in requestResult.Items)
            {
                Console.WriteLine(bucket.Name);
            }
            return(null);
        }
Exemple #11
0
        // [END auth_api_implicit]

        // [START auth_api_explicit]
        public object AuthExplicit(string projectId, string jsonPath)
        {
            GoogleCredential credential = null;

            using (var jsonStream = new FileStream(jsonPath, FileMode.Open,
                                                   FileAccess.Read, FileShare.Read))
            {
                credential = GoogleCredential.FromStream(jsonStream);
            }
            // Inject the Cloud Storage scope if required.
            if (credential.IsCreateScopedRequired)
            {
                credential = credential.CreateScoped(new[]
                {
                    StorageService.Scope.DevstorageReadOnly
                });
            }
            var storage = new StorageService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName       = "DotNet Google Cloud Platform Auth Sample",
            });
            var request       = new BucketsResource.ListRequest(storage, projectId);
            var requestResult = request.Execute();

            foreach (var bucket in requestResult.Items)
            {
                Console.WriteLine(bucket.Name);
            }
            return(null);
        }
        public IConfigurableHttpClientInitializer GetApplicationDefaultCredentials()
        {
            Console.WriteLine(Directory.GetCurrentDirectory());

            var docPath = HttpContext.Current.Server.MapPath("/bin/wwwarchishainnovatorscom-eaed27291ff7.json");

            //var credentialsPath = Path.Combine(Directory.GetCurrentDirectory(), @".\wwwarchishainnovatorscom-eaed27291ff7.json");
            Environment.SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS", docPath, EnvironmentVariableTarget.Process);

            try {
                GoogleCredential credential =
                    GoogleCredential.GetApplicationDefaultAsync().Result;
                if (credential.IsCreateScopedRequired)
                {
                    credential = credential.CreateScoped(new[] {
                        StorageService.Scope.DevstorageReadWrite
                    });
                }
                return(credential);
            }
            catch (AggregateException exception)
            {
                throw new Exception(String.Join("\n", exception.Flatten().InnerExceptions.Select(t => t.Message)));
            }
        }
Exemple #13
0
        private async Task Run()
        {
            GoogleCredential credential = await GoogleCredential.GetApplicationDefaultAsync();

            if (credential.IsCreateScopedRequired)
            {
                credential = credential.CreateScoped(new string[] { "https://www.googleapis.com/auth/userinfo.email" });
            }
            String uc = await credential.UnderlyingCredential.GetAccessTokenForRequestAsync();

            Console.WriteLine("Done UserCredential " + uc);



            string CREDENTIAL_FILE_JSON = "/home/srashid/gcp_misc/certs/GCPNETAppID-e65deccae47b.json";

            //Environment.SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS", CREDENTIAL_FILE_JSON);
            using (var stream = new FileStream(CREDENTIAL_FILE_JSON, FileMode.Open, FileAccess.Read))
            {
                ServiceAccountCredential svc_credential = GoogleCredential.FromStream(stream)
                                                          .CreateScoped(new string[] { "https://www.googleapis.com/auth/userinfo.email" })
                                                          .UnderlyingCredential as ServiceAccountCredential;


                String sc = await svc_credential.GetAccessTokenForRequestAsync();

                Console.WriteLine("Done ServiceAccountCredential " + sc);

                //https://github.com/google/google-api-dotnet-client/blob/master/Src/Support/Google.Apis.Auth/GoogleJsonWebSignature.cs
                //var certs = await GoogleJsonWebSignature.GetGoogleCertsAsync(SystemClock.Default, false, null);
                //var validPayload = await GoogleJsonWebSignature.ValidateAsync(jwt);
            }
        }
Exemple #14
0
        /// <summary>
        /// Gets the user credentials used to access Google APIs
        /// </summary>
        /// <param name="credentialsFileName">Name of credentials .json file downloaded from Google including extension. This method expects the credentials file to be in the application execution path unless you specify the full path</param>
        /// <param name="scopes">Determines how the drive will be accessed. You can use one of the scope constants like ReadOnlyScope</param>
        /// <remarks>
        /// TESTED via UnitTestGoogleDriveViaConsole Step 1
        /// </remarks>
        public GoogleCredential GetUserCredential(string credentialsFileName, string[] scopes)
        {
            // if no credentials filename is supplied we cannot look up user credentials
            if (string.IsNullOrEmpty(credentialsFileName))
            {
                throw new ArgumentNullException("credentials JSON filename is required in order to get user credentials.");
            }

            // Scopes determine permissions so if we do not have a scope then not worth asking for access to nothing.
            if (scopes == null)
            {
                throw new ArgumentNullException("At least one scope is required to get user credentials.");
            }
            if (scopes.Length < 1)
            {
                throw new ArgumentNullException("At least one scope is required to get user credentials.");
            }

            // Read the credentials from the file in preparation for service creations.
            GoogleCredential credential = null;

            using (var stream = new FileStream(credentialsFileName, FileMode.Open, FileAccess.Read))
            {
                credential = GoogleCredential.FromStream(stream);
                credential = credential.CreateScoped(scopes);
            }

            return(credential);
        }
        // [END fs_count_indexes]

        // Creates an index for a given collection in a project.
        // [START fs_create_index]
        private static async Task CreateIndex(string project, string collectionId, string field1, string order1, string field2, string order2)
        {
            GoogleCredential credential =
                GoogleCredential.GetApplicationDefault();

            // Inject the Cloud Platform scope if required.
            if (credential.IsCreateScopedRequired)
            {
                credential = credential.CreateScoped(new[]
                {
                    "https://www.googleapis.com/auth/cloud-platform"
                });
            }
            HttpClient http = new Google.Apis.Http.HttpClientFactory()
                              .CreateHttpClient(
                new Google.Apis.Http.CreateHttpClientArgs()
            {
                ApplicationName = "Google Cloud Platform Firestore Sample",
                GZipEnabled     = true,
                Initializers    = { credential },
            });

            IndexContent indexContent = new IndexContent(collectionId, field1, order1, field2, order2);
            string       jsonRequest  = JsonConvert.SerializeObject(indexContent);
            string       uriString    = "https://firestore.googleapis.com/v1beta1/projects/" + project + "/databases/(default)/indexes";
            UriBuilder   uri          = new UriBuilder(uriString);
            await http.PostAsync(uri.Uri, new StringContent(jsonRequest, System.Text.Encoding.UTF8, "application/json"));
        }
        /// <summary>
        /// Synchronously creates a <see cref="BigqueryClient"/>, using application default credentials if
        /// no credentials are specified.
        /// </summary>
        /// <remarks>
        /// The credentials are scoped as necessary.
        /// </remarks>
        /// <param name="credential">Optional <see cref="GoogleCredential"/>.</param>
        /// <returns>The created <see cref="BigqueryClient"/>.</returns>
        public static BigqueryClient Create(string projectId, GoogleCredential credential = null)
        {
            GaxRestPreconditions.CheckNotNull(projectId, nameof(projectId));
            try
            {
                credential = credential ?? Task.Run(() => GoogleCredential.GetApplicationDefaultAsync()).Result;
            }
            catch (AggregateException e)
            {
                // Unwrap the first exception, a bit like await would.
                // It's very unlikely that we'd ever see an AggregateException without an inner exceptions,
                // but let's handle it relatively gracefully.
                throw e.InnerExceptions.FirstOrDefault() ?? e;
            }
            if (credential.IsCreateScopedRequired)
            {
                credential = credential.CreateScoped(
                    // FIXME: Work out which of these we actually need.
                    BigqueryService.Scope.Bigquery,
                    BigqueryService.Scope.BigqueryInsertdata,
                    BigqueryService.Scope.DevstorageFullControl,
                    BigqueryService.Scope.CloudPlatform);
            }
            var service = new BigqueryService(new BaseClientService.Initializer
            {
                HttpClientInitializer = credential,
                ApplicationName       = BigqueryClientImpl.ApplicationName,
            });

            return(new BigqueryClientImpl(projectId, service));
        }
Exemple #17
0
        /// <summary>
        /// Asynchronously creates a <see cref="StorageClient"/>, using application default credentials if
        /// no credentials are specified.
        /// </summary>
        /// <remarks>
        /// The credentials are scoped as necessary.
        /// </remarks>
        /// <param name="credential">Optional <see cref="GoogleCredential"/>.</param>
        /// <param name="encryptionKey">Optional <see cref="EncryptionKey"/> to use for all relevant object-based operations by default. May be null.</param>
        /// <returns>The task representing the created <see cref="StorageClient"/>.</returns>
        public static Task <StorageClient> CreateAsync(GoogleCredential credential = null, EncryptionKey encryptionKey = null) =>
        new StorageClientBuilder
        {
            Credential    = credential?.CreateScoped(s_scopes),
            EncryptionKey = encryptionKey
        }

        .BuildAsync();
        /// <summary>
        /// Synchronously creates a <see cref="TranslationClient"/>, using application default credentials if
        /// no credentials are specified.
        /// </summary>
        /// <remarks>
        /// The credentials are scoped as necessary.
        /// </remarks>
        /// <param name="credential">Optional <see cref="GoogleCredential"/>.</param>
        /// <param name="model">The default translation model to use. Defaults to <see cref="TranslationModel.ServiceDefault"/>.</param>
        /// <returns>The created <see cref="TranslationClient"/>.</returns>
        public static TranslationClient Create(GoogleCredential credential = null, TranslationModel model = TranslationModel.ServiceDefault) =>
        new TranslationClientBuilder
        {
            Credential       = credential?.CreateScoped(Scopes),
            TranslationModel = model
        }

        .Build();
        /// <summary>
        /// Asynchronously creates a <see cref="BigQueryClient"/>, using application default credentials if
        /// no credentials are specified.
        /// </summary>
        /// <remarks>
        /// The credentials are scoped as necessary.
        /// </remarks>
        /// <param name="projectId">The ID of the project containing the BigQuery data. Must not be null.</param>
        /// <param name="credential">Optional <see cref="GoogleCredential"/>.</param>
        /// <returns>The task representing the created <see cref="BigQueryClient"/>.</returns>
        public static Task <BigQueryClient> CreateAsync(string projectId, GoogleCredential credential = null) =>
        new BigQueryClientBuilder
        {
            ProjectId  = GaxPreconditions.CheckNotNull(projectId, nameof(projectId)),
            Credential = credential?.CreateScoped(s_scopes)
        }

        .BuildAsync();
Exemple #20
0
        /// <summary>
        /// Synchronously creates a <see cref="AdvancedTranslationClient"/>, using application default credentials if
        /// no credentials are specified.
        /// </summary>
        /// <remarks>
        /// The credentials are scoped as necessary.
        /// </remarks>
        /// <param name="credential">Optional <see cref="GoogleCredential"/>.</param>
        /// <param name="model">The default translation model to use. Defaults to null, indicating that by default no model is specified in requests.</param>
        /// <returns>The created <see cref="AdvancedTranslationClient"/>.</returns>
        public static AdvancedTranslationClient Create(GoogleCredential credential = null, string model = null) =>
        new AdvancedTranslationClientBuilder
        {
            Credential = credential?.CreateScoped(TranslationClient.Scopes),
            Model      = model
        }

        .Build();
Exemple #21
0
        /// <summary>
        /// Synchronously creates a <see cref="StorageClient"/>, using application default credentials if
        /// no credentials are specified.
        /// </summary>
        /// <remarks>
        /// The credentials are scoped as necessary.
        /// </remarks>
        /// <param name="credential">Optional <see cref="GoogleCredential"/>.</param>
        /// <param name="encryptionKey">Optional <see cref="EncryptionKey"/> to use for all relevant object-based operations by default. May be null.</param>
        /// <returns>The created <see cref="StorageClient"/>.</returns>
        public static StorageClient Create(GoogleCredential credential = null, EncryptionKey encryptionKey = null) =>
        new StorageClientBuilder
        {
            Credential    = credential?.CreateScoped(s_scopes),
            EncryptionKey = encryptionKey,
            BaseUri       = EndpointOverride
        }

        .Build();
Exemple #22
0
        public async Task SignedUrlWithIamServiceBlobSigner()
        {
            _fixture.SkipIf(Platform.Instance().Type == PlatformType.Unknown);

            var bucketName = _fixture.BucketName;
            var objectName = _fixture.HelloStorageObjectName;
            var credential = (await GoogleCredential.GetApplicationDefaultAsync()).UnderlyingCredential as ServiceAccountCredential;
            var httpClient = new HttpClient();

            // Sample: IamServiceBlobSignerUsage
            // First obtain the email address of the default service account for this instance from the metadata server.
            HttpRequestMessage serviceAccountRequest = new HttpRequestMessage
            {
                // Note: you could use 169.254.169.254 as the address to avoid a DNS lookup.
                RequestUri = new Uri("http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/email"),
                Headers    = { { "Metadata-Flavor", "Google" } }
            };
            HttpResponseMessage serviceAccountResponse = await httpClient.SendAsync(serviceAccountRequest).ConfigureAwait(false);

            serviceAccountResponse.EnsureSuccessStatusCode();
            string serviceAccountId = await serviceAccountResponse.Content.ReadAsStringAsync();

            // Create an IAM service client object using the default application credentials.
            GoogleCredential iamCredential = await GoogleCredential.GetApplicationDefaultAsync();

            iamCredential = iamCredential.CreateScoped(IamService.Scope.CloudPlatform);
            IamService iamService = new IamService(new BaseClientService.Initializer
            {
                HttpClientInitializer = iamCredential
            });

            // Create a request template that will be used to create the signed URL.
            UrlSigner.RequestTemplate requestTemplate = UrlSigner.RequestTemplate
                                                        .FromBucket(bucketName)
                                                        .WithObjectName(objectName)
                                                        .WithHttpMethod(HttpMethod.Get);
            // Create options specifying for how long the signer URL will be valid.
            UrlSigner.Options options = UrlSigner.Options.FromDuration(TimeSpan.FromHours(1));

            // Create a URL signer that will use the IAM service for signing. This signer is thread-safe,
            // and would typically occur as a dependency, e.g. in an ASP.NET Core controller, where the
            // same instance can be reused for each request.
            IamServiceBlobSigner blobSigner = new IamServiceBlobSigner(iamService, serviceAccountId);
            UrlSigner            urlSigner  = UrlSigner.FromBlobSigner(blobSigner);

            // Use the URL signer to sign a request for the test object for the next hour.
            string url = await urlSigner.SignAsync(requestTemplate, options);

            // Prove we can fetch the content of the test object with a simple unauthenticated GET request.
            HttpResponseMessage response = await httpClient.GetAsync(url);

            string content = await response.Content.ReadAsStringAsync();

            // End sample

            Assert.Equal(_fixture.HelloWorldContent, content);
        }
        public static GoogleCredential GetCredential()
        {
            GoogleCredential credential = Task.Run(() => GoogleCredential.GetApplicationDefaultAsync()).Result;

            if (credential.IsCreateScopedRequired)
            {
                credential = credential.CreateScoped("https://www.googleapis.com/auth/cloud-platform");
            }
            return(credential);
        }
Exemple #24
0
        public static GoogleCredential GetCredential(string adminUserName, string serviceAccountKey, string scope)
        {
            GoogleCredential credential = GoogleCredential.FromJson(serviceAccountKey);

            if (credential.IsCreateScopedRequired)
            {
                credential = credential.CreateScoped(scope).CreateWithUser(adminUserName);
            }

            return(credential);
        }
Exemple #25
0
        /// <summary>
        /// Attempts to load the application default credentials
        /// </summary>
        /// <returns>The application default credentials, or null if none were found.</returns>
        private static ICredential LoadApplicationDefaultCredentials()
        {
            try {
                GoogleCredential credential = GoogleCredential.GetApplicationDefaultAsync().Result;
                return(credential.CreateScoped(scopes));
            } catch (Exception) {
                // No application default credentials, continue to try other options.
            }

            return(null);
        }
Exemple #26
0
        public WebAPI()
        {
            //authenticate
            GoogleCredential cred = GoogleCredential.FromStream(new FileStream("client_secrets.json", FileMode.Open, FileAccess.Read));

            gdrive = new DriveService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = cred.CreateScoped(Scopes),
                ApplicationName       = ApplicationName,
            });
        }
        /// <summary>
        /// Applies scopes when they're available, and potentially specifies a preference for
        /// using self-signed JWTs.
        /// </summary>
        private GoogleCredential ApplyScopes(GoogleCredential original)
        {
            if (!original.IsCreateScopedRequired || _scopes.Count == 0)
            {
                return(original);
            }
            var scoped = original.CreateScoped(_scopes);

            return(_useJwtWithScopes && scoped.UnderlyingCredential is ServiceAccountCredential serviceCredential
                ? GoogleCredential.FromServiceAccountCredential(serviceCredential.WithUseJwtAccessWithScopes(true))
                : scoped);
        }
Exemple #28
0
        GetApplicationDefaultCredentials()
        {
            GoogleCredential credential =
                GoogleCredential.GetApplicationDefaultAsync().Result;

            if (credential.IsCreateScopedRequired)
            {
                credential = credential.CreateScoped(new[] {
                    StorageService.Scope.DevstorageReadWrite
                });
            }
            return(credential);
        }
        private void InitializeSpeechClient()
        {
            GoogleCredential credential = Task.Run(GoogleCredential.GetApplicationDefaultAsync).Result;

            if (credential.IsCreateScopedRequired)
            {
                credential = credential.CreateScoped("https://www.googleapis.com/auth/cloud-platform");
            }

            Channel channel = new Channel("speech.googleapis.com", 443, credential.ToChannelCredentials());

            _client = new Speech.SpeechClient(channel);
        }
Exemple #30
0
        // [END fs_create_index]

        // Retrieves all indexes for a given collection in a project and deletes them.
        // [START fs_delete_indexes]
        private static async Task DeleteIndexes(string project, string collectionId)
        {
            GoogleCredential credential =
                GoogleCredential.GetApplicationDefault();

            // Inject the Cloud Platform scope if required.
            if (credential.IsCreateScopedRequired)
            {
                credential = credential.CreateScoped(new[]
                {
                    "https://www.googleapis.com/auth/cloud-platform"
                });
            }
            HttpClient http = new Google.Apis.Http.HttpClientFactory()
                              .CreateHttpClient(
                new Google.Apis.Http.CreateHttpClientArgs()
            {
                ApplicationName = "Google Cloud Platform Firestore Sample",
                GZipEnabled     = true,
                Initializers    = { credential },
            });

            string     uriString  = "https://firestore.googleapis.com/v1beta1/projects/" + project + "/databases/(default)/indexes";
            UriBuilder uri        = new UriBuilder(uriString);
            var        resultText = http.GetAsync(uri.Uri).Result.Content
                                    .ReadAsStringAsync().Result;
            dynamic result = Newtonsoft.Json.JsonConvert
                             .DeserializeObject(resultText);

            List <string> indexesToBeDeleted = new List <string>();

            if (result.indexes != null)
            {
                foreach (var index in result.indexes)
                {
                    if (index.collectionId == collectionId)
                    {
                        string name = index.name;
                        indexesToBeDeleted.Add(name);
                    }
                }
            }

            foreach (string indexToBeDeleted in indexesToBeDeleted)
            {
                uriString = "https://firestore.googleapis.com/v1beta1/" + indexToBeDeleted;
                UriBuilder deleteUri = new UriBuilder(uriString);
                await http.DeleteAsync(deleteUri.Uri);
            }
            Console.WriteLine("Index deletion completed!");
        }