Пример #1
0
        /// <summary>
        /// Create GoogleSheet with server parameters and database data.
        /// </summary>
        /// <param name="sheetName">name of the sheet</param>
        /// <param name="spreadsheetId">ID of google table</param>
        /// <param name="server">Object with server/database information</param>
        public GoogleSheet(string sheetName, string spreadsheetId, Server server)
        {
            this.sheetName     = sheetName;
            this.spreadsheetId = spreadsheetId;
            this.server        = server;

            using (var stream = new FileStream("configuration.json", FileMode.Open, FileAccess.Read))
            {
                this.credential = GoogleCredential.FromStream(stream).CreateScoped(Scopes);
            }

            service = new SheetsService(new Google.Apis.Services.BaseClientService.Initializer()
            {
                HttpClientInitializer = this.credential,
            });
        }
Пример #2
0
        public SpreadsheetConnector()
        {
            GoogleCredential credential;

            using (var stream = new FileStream("client_secrets.json", FileMode.Open, FileAccess.ReadWrite))
            {
                credential = GoogleCredential.FromStream(stream)
                             .CreateScoped(Scopes);
            }

            service = new SheetsService(new Google.Apis.Services.BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName       = ApplicationName,
            });
        }
Пример #3
0
        public HpgDocParser()
        {
            GoogleCredential credential;

            using (var stream = new FileStream("client_secrets.json", FileMode.Open, FileAccess.Read))
            {
                credential = GoogleCredential.FromStream(stream)
                             .CreateScoped(Scopes);
            }

            service = new SheetsService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName       = ApplicationName
            });
        }
Пример #4
0
        private void Init()
        {
            GoogleCredential credential;

            using (var stream = new FileStream("app_client_secret.json", FileMode.Open, FileAccess.Read))
            {
                credential = GoogleCredential.FromStream(stream)
                             .CreateScoped(Scopes);
            }
            // Creating Google Sheets API service...
            service = new SheetsService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName       = ApplicationName,
            });
        }
Пример #5
0
        private string AddNewPhotoBigQuery(Photo photo)
        {
            try
            {
                GoogleCredential credential;
                using (Stream stream = new FileStream(bigqueryFileKey, FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    credential = GoogleCredential.FromStream(stream);
                }

                string[] scopes = new string[] {
                    BigqueryService.Scope.Bigquery,
                    BigqueryService.Scope.CloudPlatform,
                };
                credential = credential.CreateScoped(scopes);
                BaseClientService.Initializer initializer = new BaseClientService.Initializer()
                {
                    HttpClientInitializer = (IConfigurableHttpClientInitializer)credential,
                    ApplicationName       = bigqueryApplicationName,
                    GZipEnabled           = true,
                };
                BigqueryService service = new BigqueryService(initializer);
                var             rowList = new List <TableDataInsertAllRequest.RowsData>();
                // Check @ https://developers.google.com/bigquery/streaming-data-into-bigquery for InsertId usage
                var row = new TableDataInsertAllRequest.RowsData();
                row.Json = new Dictionary <string, object>();
                row.Json.Add("Id", photo.Id);
                row.Json.Add("Title", photo.Title);
                row.Json.Add("Url", photo.Url);
                rowList.Add(row);

                var content = new TableDataInsertAllRequest();
                content.Rows = rowList;
                content.Kind = "bigquery#tableDataInsertAllRequest";
                content.IgnoreUnknownValues = true;
                content.SkipInvalidRows     = true;
                var requestResponse = service.Tabledata.InsertAll(content, bigqueryProjectId, "dsbigquery", "Photo").Execute();



                return("true");
            }
            catch (Exception ex)
            {
                return(ex.Message);
            }
        }
Пример #6
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers().AddNewtonsoftJson();

            FileStream serviceAccount = new FileStream(@"firebaseconfig.json", FileMode.Open, FileAccess.Read, FileShare.Read);

            FirebaseAdmin.AppOptions options = new FirebaseAdmin.AppOptions
            {
                Credential       = GoogleCredential.FromStream(serviceAccount),
                ServiceAccountId = "*****@*****.**",
            };

            FirebaseAdmin.FirebaseApp.Create(options);
            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options =>
            {
                options.Authority = "https://securetoken.google.com/vserve-app";
                options.Audience  = "https://securetoken.google.com/vserve-app";
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer   = true,
                    ValidIssuer      = "https://securetoken.google.com/vserve-app",
                    ValidateAudience = true,
                    ValidAudience    = "vserve-app",
                    ValidateLifetime = true
                };
            });

            services.Configure <MongoAppSettings>(Configuration.GetSection(nameof(MongoAppSettings)));
            services.AddSingleton <IMongoAppSettings>(sp => sp.GetRequiredService <IOptions <MongoAppSettings> >().Value);
            services.AddScoped <MongoContext>();
            services.AddScoped <JobDetailRepository>();
            services.AddScoped <AssignmentsRepository>();
            services.AddScoped <UserRepository>();
            services.AddScoped <UserDetailsRepo>();
            services.AddScoped <AuthenticationApi>();
            services.AddScoped <FireBaseRepo>();
            services.AddScoped <PlaceApi>();

            // In production, the Angular files will be served from this directory
            services.AddSpaStaticFiles(configuration =>
            {
                configuration.RootPath = "ClientApp/dist";
            });

            services.AddSwaggerDocument();
        }
Пример #7
0
        public Task <List <GridDraftDeckData> > GetCardData()
        {
            GoogleCredential credential;

            using (var stream =
                       new FileStream(_googleDocsInfo.GoogleKeyJsonFile, FileMode.Open, FileAccess.Read))
            {
                // The file token.json stores the user's access and refresh tokens, and is created
                // automatically when the authorization flow completes for the first time.
                string credPath = "token.json";
                credential = GoogleCredential.FromStream(stream).CreateScoped(Scopes);
                Console.WriteLine("Credential file saved to: " + credPath);
            }

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

            // Define request parameters.
            String spreadsheetId = _googleDocsInfo.SpreadSheetId;
            String range         = "Sheet1!A2:D";

            SpreadsheetsResource.ValuesResource.GetRequest request =
                service.Spreadsheets.Values.Get(spreadsheetId, range);

            ValueRange response            = request.Execute();
            IList <IList <Object> > values = response.Values;
            var result = new List <GridDraftDeckData>();

            if (values != null && values.Count > 0)
            {
                foreach (var row in values)
                {
                    // Print columns A and E, which correspond to indices 0 and 4.
                    result.Add(new GridDraftDeckData()
                    {
                        Name        = row[0].ToString(),
                        Description = row[1].ToString(),
                        Weight      = int.Parse(row[2].ToString())
                    });
                }
            }

            return(Task.FromResult(result));
        }
Пример #8
0
        public GoogleSS()
        {
            try
            {
                GoogleCredential credential;
                using (var stream = new FileStream("mlmcovid-8745379e99cd.json", FileMode.Open, FileAccess.Read))
                {
                    credential = GoogleCredential.FromStream(stream)
                                 .CreateScoped(Scopes);
                }

                //Ver luego para el uso con proxy.

                /*
                 * WebProxy proxy = (WebProxy)WebRequest.DefaultWebProxy;
                 * if (proxy.Address.AbsoluteUri != string.Empty)
                 * {
                 *  // Create Google Sheets API service.
                 *  service = new SheetsService(new BaseClientService.Initializer()
                 *  {
                 *      HttpClientInitializer = credential,
                 *      ApplicationName = ApplicationName,
                 *  });
                 * }
                 * else {
                 *
                 *  // Create Google Sheets API service.
                 *  service = new SheetsService(new BaseClientService.Initializer()
                 *  {
                 *      HttpClientInitializer = credential,
                 *      ApplicationName = ApplicationName,
                 *      HttpClientFactory = new ProxySupportedHttpClientFactory()
                 *
                 *  });
                 * } */

                service = new SheetsService(new BaseClientService.Initializer()
                {
                    HttpClientInitializer = credential,
                    ApplicationName       = ApplicationName,
                });
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Пример #9
0
        public List <string> getPokemonInfo(string input)
        {
            List <string> results = new List <string>();

            GoogleCredential credential;

            using (var stream = new FileStream("credentials.json", FileMode.Open, FileAccess.Read))
            {
                credential = GoogleCredential.FromStream(stream).CreateScoped(Scopes);
            }
            service = new SheetsService(new Google.Apis.Services.BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName       = ApplicationName,
            });

            getRow("Pokemon", input);

            var range   = $"Pokemon!C{rowNumber}:P{rowNumber}";
            var request = service.Spreadsheets.Values.Get(SpreadsheetId, range);

            var response = request.Execute();
            var values   = response.Values;

            if (values != null && values.Count > 0)
            {
                foreach (var col in values)
                {
                    results.Add(col[0].ToString()); //Name
                    results.Add(col[1].ToString()); //Type
                    results.Add(col[2].ToString()); //Weakness
                    results.Add(col[3].ToString()); //HP
                    results.Add(col[4].ToString()); //ATK
                    results.Add(col[5].ToString()); //DEF
                    results.Add(col[6].ToString()); //SATK
                    results.Add(col[7].ToString()); //SDEF
                    results.Add(col[8].ToString()); //SPD
                    //results.Add(col[9].ToString()); //Empty
                    //results.Add(col[10].ToString()); //Bulk
                    results.Add(col[11].ToString()); //Rank
                    //results.Add(col[12].ToString()); //Stat
                    results.Add(col[13].ToString()); //Rank
                }
            }

            return(results);
        }
Пример #10
0
        /// <summary>
        /// Creates a PublisherClient given a path to a downloaded json service
        /// credentials file.
        /// </summary>
        /// <param name="jsonPath">The path to the downloaded json file.</param>
        /// <returns>A new publisher client.</returns>
        public static PublisherServiceApiClient CreatePublisherWithServiceCredentials(
            string jsonPath)
        {
            GoogleCredential googleCredential = null;

            using (var jsonStream = new FileStream(jsonPath, FileMode.Open,
                                                   FileAccess.Read, FileShare.Read))
            {
                googleCredential = GoogleCredential.FromStream(jsonStream)
                                   .CreateScoped(PublisherServiceApiClient.DefaultScopes);
            }
            Channel channel = new Channel(PublisherServiceApiClient.DefaultEndpoint.Host,
                                          PublisherServiceApiClient.DefaultEndpoint.Port,
                                          googleCredential.ToChannelCredentials());

            return(PublisherServiceApiClient.Create(channel));
        }
Пример #11
0
        private GoogleCredential GetCredentials()
        {
            //Place Sheet in Root Directory
            var assembly     = typeof(GoogleSheetService).GetTypeInfo().Assembly;
            var assemblyName = assembly.GetName().Name;

            var path      = assembly + ".credentials.json";
            var doesExist = File.Exists(path);

            if (!doesExist)
            {
                return(null);
            }

            using var stream = assembly.GetManifestResourceStream($"{assemblyName}.credentials.json");
            return(GoogleCredential.FromStream(stream).CreateScoped(Scopes));
        }
Пример #12
0
        public static DriveService GetService(string keyFilePath)
        {
            // File existance check
            if (!System.IO.File.Exists(keyFilePath))
            {
                Console.WriteLine("File not found");
                return(null);
            }

            //var certificate = new X509Certificate2(keyFilePath, "", X509KeyStorageFlags.Exportable);
            GoogleCredential credential;

            using (var stream = new FileStream(keyFilePath, FileMode.Open, FileAccess.Read))
            {
                credential = GoogleCredential.FromStream(stream)
                             .CreateScoped(Scopes);
            }
            //UserCredential credential;

            //using(var stream = new FileStream(@"D:\credentials.json", FileMode.Open, FileAccess.Read))
            //{
            //    String folderPath = @"D:\";
            //    String filePath = Path.Combine(folderPath, "DriveServiceCredentials.json");

            //    credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
            //        GoogleClientSecrets.Load(stream).Secrets,
            //        Scopes,
            //        "user",
            //        CancellationToken.None,
            //        new FileDataStore(filePath, true)).Result;
            //}

            //ServiceAccountCredential credential = new ServiceAccountCredential(
            //    new ServiceAccountCredential.Initializer("*****@*****.**")
            //    {
            //        Scopes = Scopes
            //    }.FromCertificate(certificate));

            DriveService service = new DriveService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName       = "Prokoushol"
            });

            return(service);
        }
Пример #13
0
        /// <summary>
        /// Подключение к таблице
        /// </summary>
        private void Connect(string credentialPath)
        {
            GoogleCredential credential;

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

            // Создание Google Sheets API сервиса.
            service = new SheetsService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName       = "SpreadsheetBot",
            });
        }
Пример #14
0
        public ServiceAccountBase()
        {
            GoogleCredential credential;

            // Put your credentials json file in the root of the solution and make sure copy to output dir property is set to always copy
            using (var stream = GenerateStreamFromString(BuildConfigString()))
            {
                credential = GoogleCredential.FromStream(stream).CreateScoped(_scopes);
            }

            // Create Google Sheets API service.
            _service = new SheetsService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName       = _applicationName
            });
        }
Пример #15
0
        private void ConnectToGoogle()
        {
            GoogleCredential credential;

            // Put your credentials json file in the root of the solution and make sure copy to output dir property is set to always copy
            using (var stream = new FileStream(Path.Combine(Environment.CurrentDirectory, "FlashCardProject-120429ad768d.json"), FileMode.Open, FileAccess.Read))
            {
                credential = GoogleCredential.FromStream(stream).CreateScoped(_scopes);
            }

            // Create Google Sheets API service.
            _sheetsService = new SheetsService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName       = _applicationName
            });
        }
Пример #16
0
        public GoogleSheetsFactory()
        {
            GoogleCredential credential;

            using (var stream = new FileStream("google_client_secret.json", FileMode.Open, FileAccess.Read))
            {
                credential = GoogleCredential.FromStream(stream)
                             .CreateScoped(SCOPES);
            }

            // Create Google Sheets API service.
            this.Service = new SheetsService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName       = APPLICATION_NAME,
            });
        }
Пример #17
0
        private CloudDnsService CreateDnsService(ILogService log)
        {
            GoogleCredential credential;

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

            var dnsService = new DnsService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName       = "Win ACME",
            });

            return(new CloudDnsService(dnsService));
        }
Пример #18
0
        public Mp2Bot()
        {
            _spreadsheetId = (string)Prop.GetValue("mp2Sheet");
            _mp2Role       = (ulong)Prop.GetValue("mutinyPartDeux");
            // _mutinyRole = (ulong) Prop.GetValue("mutiny");
            _mutinyGuild = (ulong)Prop.GetValue("mutinyGuild");
            // _sithApprentices = (ulong) Prop.GetValue("sithApprentices");
            _knightsOfRen = (ulong)Prop.GetValue("knightsOfRen");
            // _td = (ulong) Prop.GetValue("td");
            _mp2General   = (ulong)Prop.GetValue("mp2General");
            _mp2Probation = (ulong)Prop.GetValue("mp2Probation");
            _mp2Mediation = (ulong)Prop.GetValue("mp2Mediation");
            _mp2Raider    = (ulong)Prop.GetValue("mp2Raider");

            var applicationName = (string)Prop.GetValue("sheetName");

            try
            {
                using var stream = new FileStream(@"credentials.json", FileMode.Open, FileAccess.Read);
                _credential      = GoogleCredential.FromStream(stream).CreateScoped(Scopes);

                // The file token.json stores the user's access and refresh tokens, and is created
                // automatically when the authorization flow completes for the first time.
            }
            catch (Exception e)
            {
                Console.Out.WriteLine("FAILED TO GET CREDENTIALS\n" + e.Message);
            }

            try
            {
                // Create Google Sheets API service.
                _service = new SheetsService(new BaseClientService.Initializer
                {
                    ApplicationName       = applicationName,
                    HttpClientInitializer = _credential
                                            // ApiKey = _apiKey
                });

                _logger.Info("API Successfully Retrieved");
            }
            catch (Exception e)
            {
                _logger.Info("FAILED TO GET API: \n" + e.Message);
            }
        }
Пример #19
0
        public static VisionService CreateAuthorizedClient(string filePath)
        {
            using (var fs = new FileStream(filePath, FileMode.Open))
            {
                var credential = GoogleCredential.FromStream(fs);

                if (credential.IsCreateScopedRequired)
                {
                    credential = credential.CreateScoped(new[] { VisionService.Scope.CloudPlatform });
                }
                return(new VisionService(new BaseClientService.Initializer()
                {
                    HttpClientInitializer = credential,
                    GZipEnabled = false
                }));
            }
        }
Пример #20
0
 private static void Init()
 {
     if (service == null)
     {
         string[]         scopes = new string[] { AnalyticsReportingService.Scope.Analytics };
         GoogleCredential credential;
         using (var stream = new FileStream(CachedData.AnalyticsCredentialFile, FileMode.Open, FileAccess.Read))
         {
             credential = GoogleCredential.FromStream(stream).CreateScoped(scopes);
         }
         BaseClientService.Initializer bi = new BaseClientService.Initializer()
         {
             ApplicationName = "StreamingLiveService", HttpClientInitializer = credential
         };
         service = new AnalyticsReportingService(bi);
     }
 }
Пример #21
0
        private GoogleCredential GetCredentials()
        {
            GoogleCredential credential;

            using (var stream =
                       new FileStream("client_secret.json", FileMode.Open, FileAccess.Read))
            {
                string credPath = System.Environment.GetFolderPath(
                    System.Environment.SpecialFolder.Personal);
                credPath = Path.Combine(credPath, ".credentials/sheets.googleapis.com-dotnet-quickstart.json");

                credential = GoogleCredential.FromStream(stream).CreateScoped(Scopes);

                Console.WriteLine("Credential file saved to: " + credPath);
            }
            return(credential);
        }
Пример #22
0
        public GoogleServices()
        {
            GoogleCredential credential;

            using (var stream = new FileStream("google-credentials.json", FileMode.Open, FileAccess.Read))
            {
                credential = GoogleCredential.FromStream(stream)
                             .CreateScoped(Scopes);
            }

            // Create Google Sheets API service.
            service = new SheetsService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName       = ApplicationName,
            });
        }
Пример #23
0
        //private PublisherClient.ClientCreationSettings clientCreationSettings = null;
        // private PublisherClient.Settings settings = new PublisherClient.Settings();

        public PubSub(ILogger <PubSub> logger, IConfiguration configuration)
        {
            this.logger        = logger ?? throw new ArgumentNullException(nameof(logger));
            this.configuration = configuration ?? throw new ArgumentNullException(nameof(configuration));

            string credentialsJsonFilePath = configuration["Application:GoogleApplicationCredentials"];

            using (FileStream jsonFileStream = new FileStream(credentialsJsonFilePath, FileMode.Open, FileAccess.Read, FileShare.Read))
            {
                this.googleCredential   = GoogleCredential.FromStream(jsonFileStream);
                this.channelCredentials = this.googleCredential.ToChannelCredentials();
            }

            //this.clientCreationSettings = new PublisherClient.ClientCreationSettings(credentials: this.channelCredentials);

            this.logger.LogInformation("PubSub init");
        }
        public async static Task <IList <IList <Object> > > GetDataFromGoogleSheetsAsync(string projectName, DataType datatype)
        //public static IList<IList<Object>> GetDataFromGoogleSheetsAsync(string projectName, DataType datatype)
        {
            if (credential == null)
            {
                //using (var stream =
                //    new FileStream(@"GoogleUtility\credentials.json", FileMode.Open, FileAccess.Read))
                //{
                //    string credPath = "token.json";
                //    credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                //        GoogleClientSecrets.Load(stream).Secrets,
                //        new[] { SheetsService.Scope.SpreadsheetsReadonly },
                //        "user",
                //        CancellationToken.None,
                //        new FileDataStore(credPath, true)).Result;

                //}

                using (var stream = new FileStream(@"GoogleUtility\client_secret.json", FileMode.Open, FileAccess.Read))
                {
                    credential = GoogleCredential.FromStream(stream)
                                 .CreateScoped(Scopes);
                }
            }

            // Create Google Sheets API service.
            if (service == null)
            {
                service = new SheetsService(new BaseClientService.Initializer()
                {
                    HttpClientInitializer = credential,
                    ApplicationName       = ApplicationName,
                });
            }
            // Define request parameters.

            String range = "Pricing!" + GetRangeFromXML(projectName, datatype);

            SpreadsheetsResource.ValuesResource.GetRequest request =
                service.Spreadsheets.Values.Get(spreadsheetId, range);

            //ValueRange response = request.ExecuteAsync().Result;
            ValueRange response = await request.ExecuteAsync();

            return(response.Values);
        }
Пример #25
0
        public static void Init()
        {
            GoogleCredential credential;

            //Reading Credentials File...
            using (var stream = new FileStream("sheet project-206c3def15da.json", FileMode.Open, FileAccess.Read))
            {
                credential = GoogleCredential.FromStream(stream)
                             .CreateScoped(Scopes);
            }
            // Creating Google Sheets API service...
            service = new SheetsService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName       = ApplicationName,
            });
        }
Пример #26
0
    static GoogleSheetsHelper()
    {
        GoogleCredential credential;

        using (var stream = new FileStream(System.IO.Path.Combine(JsonLocation, JsonFile), FileMode.Open, FileAccess.Read)) {
            credential = GoogleCredential.FromStream(stream)
                         .CreateScoped(Scopes);
        }

        service = new SheetsService(new Google.Apis.Services.BaseClientService.Initializer()
        {
            HttpClientInitializer = credential,
            ApplicationName       = ApplicationName
        }

                                    );
    }
        public void FromStream_UserCredential()
        {
            var stream     = new MemoryStream(Encoding.UTF8.GetBytes(DummyUserCredentialFileContents));
            var credential = GoogleCredential.FromStream(stream);

            Assert.IsType <UserCredential>(credential.UnderlyingCredential);
            Assert.False(credential.IsCreateScopedRequired);
            var userCred = (UserCredential)credential.UnderlyingCredential;

            Assert.Equal("REFRESH_TOKEN", userCred.Token.RefreshToken);
            var flow = (GoogleAuthorizationCodeFlow)userCred.Flow;

            Assert.Equal("CLIENT_ID", flow.ClientSecrets.ClientId);
            Assert.Equal("CLIENT_SECRET", flow.ClientSecrets.ClientSecret);
            Assert.Equal("PROJECT_ID", flow.ProjectId);
            Assert.Equal("QUOTA_PROJECT", userCred.QuotaProject);
        }
Пример #28
0
        string credentialsFileName         = "credentials.json"; // This file has to be generated in GCP, enable Google Sheet API



        public GoogleSheetsService()
        {
            string jsonFile = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, credentialsFileName);

            using (Stream stream = new FileStream(jsonFile, FileMode.Open, FileAccess.Read, FileShare.Read))
            {
                _credential = (ServiceAccountCredential)GoogleCredential.FromStream(stream).UnderlyingCredential;

                var initializer = new ServiceAccountCredential.Initializer(_credential.Id)
                {
                    User   = serviceAccountEmail,
                    Key    = _credential.Key,
                    Scopes = Scopes
                };
                _credential = new ServiceAccountCredential(initializer);
            }
        }
Пример #29
0
        private GoogleCredential CreateCredential()
        {
            if (_credential != null)
            {
                return(_credential);
            }
//            using (var stream = new FileStream(JsonKeypath, FileMode.Open, FileAccess.Read))
            using (var stream = GetGoogleOCRAPIKey())
            {
                string[] scopes     = { VisionService.Scope.CloudPlatform };
                var      credential = GoogleCredential.FromStream(stream);

                credential  = credential.CreateScoped(scopes);
                _credential = credential;
                return(credential);
            }
        }
Пример #30
0
        public void SstGooglesHeet()
        {
            GoogleCredential credential;

            using (var stream = new FileStream(System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "client_secret.json", FileMode.Open, FileAccess.Read))
            {
                credential = GoogleCredential.FromStream(stream)
                             .CreateScoped(Scopes);
            }

            // Create Google Sheets API service.
            service = new SheetsService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName       = ApplicationName,
            });
        }