Exemplo n.º 1
0
        public GooglePubSubAdapter(
            AdapterConfiguration adapterConfiguration)
        {
            this.credential           = GoogleCredential.FromFile($"{Directory.GetCurrentDirectory()}\\{adapterConfiguration.GoogleCredentialFile}") ?? throw new ArgumentNullException(nameof(AdapterConfiguration));
            this.adapterConfiguration = adapterConfiguration ?? throw new ArgumentNullException(nameof(AdapterConfiguration));

            this.createSettingsPub = new PublisherClient.ClientCreationSettings(
                credentials: credential.ToChannelCredentials());

            this.createSettingsSub = new SubscriberClient.ClientCreationSettings(
                credentials: credential.ToChannelCredentials());
        }
Exemplo n.º 2
0
        public static string Recognize(string imagePath)
        {
            if (credential == null)
            {
                var googleCredsPath = System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(OSPlatform.Windows)
                    ? @"C:\mydev\My Project-77101559a6d3.json"
                    : "/Users/slav/Downloads/My Project-d1092d64586a.json";

                credential = GoogleCredential.FromFile(googleCredsPath)
                             .CreateScoped(ImageAnnotatorClient.DefaultScopes);
                channel = new Grpc.Core.Channel(
                    ImageAnnotatorClient.DefaultEndpoint.ToString(),
                    credential.ToChannelCredentials());

                var client = ImageAnnotatorClient.Create(channel);
            }

            var image    = Image.FromFile(imagePath);
            var response = client.DetectText(image);
            int count    = response.Count;

            foreach (var annotation in response)
            {
                if (annotation.Description != null)
                {
                    return(annotation.Description);
                }
            }
            return(null);
        }
Exemplo n.º 3
0
        public void CreateClientWithEmptyOptions()
        {
            GoogleCredential credential = GoogleCredential.GetApplicationDefault();

            invoker = new GcpCallInvoker(Target, credential.ToChannelCredentials());
            client  = new Bigtable.BigtableClient(invoker);

            MutateRowRequest mutateRowRequest = new MutateRowRequest
            {
                TableName = TableName,
                RowKey    = ByteString.CopyFromUtf8(RowKey)
            };

            Mutation mutation = new Mutation
            {
                SetCell = new Mutation.Types.SetCell
                {
                    FamilyName      = ColumnFamily,
                    ColumnQualifier = ByteString.CopyFromUtf8(ColumnQualifier),
                    Value           = ByteString.CopyFromUtf8(TestValue),
                }
            };

            mutateRowRequest.Mutations.Add(mutation);

            client.MutateRow(mutateRowRequest);
            Assert.AreEqual(1, invoker.GetChannelRefsForTest().Count);
        }
        /// <summary>
        /// The <see cref="ChannelCredentials"/> credential used to communicate with Spanner.
        /// If not set, then default application credentials will be used.
        /// Credentials can be retrieved from a file or obtained interactively.
        /// See Google Cloud documentation for more information.
        /// </summary>
        public ChannelCredentials GetCredentials()
        {
            // Check the ctor override.
            if (CredentialOverride != null)
            {
                return(CredentialOverride);
            }

            //Calculate it from the CredentialFile argument in the connection string.
            GoogleCredential credentials = null;
            string           jsonFile    = CredentialFile;

            if (!string.IsNullOrEmpty(jsonFile))
            {
                if (!string.Equals(Path.GetExtension(jsonFile), ".json", StringComparison.OrdinalIgnoreCase))
                {
                    throw new InvalidOperationException($"{nameof(CredentialFile)} should only be set to a JSON file.");
                }

                if (!File.Exists(jsonFile))
                {
                    //try some relative locations.
                    jsonFile = $"{GetApplicationFolder()}{Path.DirectorySeparatorChar}{jsonFile}";
                }
                if (!File.Exists(jsonFile))
                {
                    //throw a meaningful error that tells the developer where we looked.
                    throw new FileNotFoundException($"Could not find {nameof(CredentialFile)}. Also looked in {jsonFile}.");
                }
                credentials = GoogleCredential.FromFile(jsonFile).CreateScoped(SpannerClient.DefaultScopes);
            }
            return(credentials?.ToChannelCredentials());
        }
Exemplo n.º 5
0
        private void InitDefaultClient()
        {
            GoogleCredential credential = GoogleCredential.GetApplicationDefault();
            var channel = new Channel(Target, credential.ToChannelCredentials());

            client = new Bigtable.BigtableClient(channel);
        }
        //public async Task<List<string>> GetDatabases()
        //{
        //    var client = new MongoClient(_config.AtlasMongoConnection);
        //    List<string> databases = new List<string>();

        //    using (var cursor = await client.ListDatabasesAsync())
        //    {
        //        await cursor.ForEachAsync(d => databases.Add(d.ToString()));
        //    }
        //    return databases;
        //}
        //public async Task<List<string>> GetCollections(string database)
        //{
        //    var client = new MongoClient(_config.AtlasMongoConnection);
        //    List<string> collections = new List<string>();

        //    using (var cursor = await client.GetDatabase(database).ListCollectionsAsync())
        //    {
        //        await cursor.ForEachAsync(d => collections.Add( new JObject(new JProperty("name",d["name"].ToString())).ToString()));
        //    }
        //    return collections;
        //}
        public async Task <Repository> Create(string repository, string collection, Repository repoObject)
        {
            if (repoObject.validate)
            {
                ValidateInnerDataAgainstSchema(repoObject.schemaUri, repoObject.data);
            }

            GoogleCredential serviceAcct = GoogleCredential.FromJson(GetServiceAccountKey()); //hardcoded

            Channel channel = new Channel(
                FirestoreClient.DefaultEndpoint.Host, FirestoreClient.DefaultEndpoint.Port,
                serviceAcct.ToChannelCredentials());

            FirestoreClient client = FirestoreClient.Create(channel);

            FirestoreDb         db = FirestoreDb.Create("repositorynookproject", client);
            CollectionReference c  = GetCollection(db, collection);


            //convert times to UTC
            repoObject.createdDate  = DateTime.SpecifyKind(repoObject.createdDate, DateTimeKind.Utc);
            repoObject.modifiedDate = DateTime.SpecifyKind(repoObject.modifiedDate, DateTimeKind.Utc);

            DocumentReference document = await c.AddAsync(repoObject);

            return(repoObject);
        }
        private SessionsClient CreateDialogFlowClientSessions()
        {
            var dialogFlowConfigurationFilePath = _env.ContentRootPath + "/App_Data";
            GoogleCredential googleCredential   = GoogleCredential.FromFile(dialogFlowConfigurationFilePath + "/hr-joy-26ab70a34ae2.json");
            Channel          channel            = new Channel(SessionsClient.DefaultEndpoint.Host,
                                                              googleCredential.ToChannelCredentials());

            return(SessionsClient.Create(channel));
        }
        private SessionsClient CreateDialogFlowClientSessions()
        {
            var dialogFlowConfigurationFilePath = System.Web.Hosting.HostingEnvironment.MapPath(@"~/App_Data/hrone-wxhfau-221616b3f7be.json");
            GoogleCredential googleCredential   = GoogleCredential.FromFile(dialogFlowConfigurationFilePath);
            Channel          channel            = new Channel(SessionsClient.DefaultEndpoint.Host,
                                                              googleCredential.ToChannelCredentials());

            return(SessionsClient.Create(channel));
        }
Exemplo n.º 9
0
 public CloudFirestoreService(IConfiguration configuration)
 {
     this.configuration = configuration;
     googleCredential   = new CloudFirestoreHelper(configuration).GetGoogleCredential();
     channel            = new Channel(
         FirestoreClient.DefaultEndpoint.Host,
         FirestoreClient.DefaultEndpoint.Port,
         googleCredential.ToChannelCredentials()
         );
 }
Exemplo n.º 10
0
        private void InitClient()
        {
            GoogleCredential      credential = GoogleCredential.GetApplicationDefault();
            IList <ChannelOption> options    = new List <ChannelOption>()
            {
                new ChannelOption(GcpCallInvoker.ApiConfigChannelArg, config.ToString())
            };

            invoker = new GcpCallInvoker(Target, credential.ToChannelCredentials(), options);
            client  = new Spanner.SpannerClient(invoker);
        }
        public static void Authorize()
        {
            var fileStream = new FileStream(Path.Combine(GetAssemblyFolder(Assembly.GetExecutingAssembly()), @"google_auth.json"), FileMode.Open);

            Credential = GoogleCredential
                         .FromStream(fileStream)
                         .CreateScoped(SpeechClient.DefaultScopes);
            Channel = new Grpc.Core.Channel(SpeechClient.DefaultEndpoint.Host, Credential.ToChannelCredentials());

            Client = SpeechClient.Create(Channel);
        }
Exemplo n.º 12
0
        private void InitGcpClient()
        {
            InitApiConfig(100, 10);
            GoogleCredential      credential = GoogleCredential.GetApplicationDefault();
            IList <ChannelOption> options    = new List <ChannelOption>()
            {
                new ChannelOption(GcpCallInvoker.ApiConfigChannelArg, config.ToString())
            };
            var invoker = new GcpCallInvoker(Target, credential.ToChannelCredentials(), options);

            client = new Bigtable.BigtableClient(invoker);
        }
Exemplo n.º 13
0
        /// <summary>
        /// firebaseTest authenticates the database to connect to Google API
        /// </summary>
        public firebaseTest()
        {
            //from work desktop => @"C:\Users\rjvarona\Documents\GitHub\Laboratory.MVC\LaboratoryOperatorV1.0\Laboratory-836fc4d08141.json"
            //from home desktop => @"C:\Users\rjvar\Documents\GitHub\Laboratory.MVC\LaboratoryOperatorV1.0\Laboratory-836fc4d08141.json"
            GoogleCredential credential = GoogleCredential
                                          .FromFile(@"C:\Users\rjvar\Documents\GitHub\Laboratory.MVC\LaboratoryOperatorV1.0\Laboratory-836fc4d08141.json");
            ChannelCredentials channelCredentials = credential.ToChannelCredentials();
            Channel            channel            = new Channel(FirestoreClient.DefaultEndpoint.ToString(), channelCredentials);
            FirestoreClient    firestoreClient    = FirestoreClient.Create(channel);

            db = FirestoreDb.Create("laboratory-2letter", client: firestoreClient);
        }
Exemplo n.º 14
0
        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);
        }
Exemplo n.º 15
0
        /// <summary>
        /// Creates new Speech recognizer from appropriate google credentials and language code
        /// </summary>
        /// <param name="credential">Credential with access to Google Cloud Speech API</param>
        /// <param name="languageCode">Language for speech recognition. Default is 'fa'.</param>
        public GoogleSpeechRecognizer(GoogleCredential credential, string languageCode = "fa")
        {
            // create channel to connect to Google API
            var channel = new Grpc.Core.Channel(
                SpeechClient.DefaultEndpoint.Host,
                credential.ToChannelCredentials()
                );

            // create speech client for future use
            this.speechClient = SpeechClient.Create(channel);
            // set the language code to use when calling Google API
            this.languageCode = languageCode;
        }
Exemplo n.º 16
0
        // https://developers.google.com/admin-sdk/directory/v1/languages
        /// <summary>
        /// Transcribes the specified URL.
        /// </summary>
        /// <param name="url">The URL.</param>
        /// <param name="languageCode">The language code.</param>
        /// <returns></returns>
        public async Task <TranscriptionViewModel> Transcribe(string url, string languageCode = "en-US", List <string> altLanguages = null)
        {
            // Initialize GA Speech Client
            Channel channel = new Channel(
                SpeechClient.DefaultEndpoint.Host, _googleCredential.ToChannelCredentials());
            SpeechClient speech = SpeechClient.Create(channel);

            RecognitionAudio audio = await RecognitionAudio.FetchFromUriAsync(url);

            RecognitionConfig config = new RecognitionConfig
            {
                Encoding     = AudioEncoding.Linear16,
                LanguageCode = languageCode,
            };

            if (altLanguages != null)
            {
                foreach (string altLang in altLanguages)
                {
                    config.AlternativeLanguageCodes.Add(altLang);
                }
            }

            RecognizeResponse response = speech.Recognize(config, audio);

            string transcript = "";
            float  confidence = 0f;
            string language   = "";

            // Parse results
            foreach (var res in response.Results)
            {
                // Take only the highest confidence transcription
                foreach (var alternative in res.Alternatives)
                {
                    if (alternative.Confidence > confidence)
                    {
                        transcript = alternative.Transcript;
                        confidence = alternative.Confidence;
                    }
                }
                language = res.LanguageCode;
            }

            await channel.ShutdownAsync();

            return(new TranscriptionViewModel()
            {
                Transcript = transcript, Confidence = confidence, Language = language
            });
        }
Exemplo n.º 17
0
        public CloudLoggingServicecs(IConfiguration configuration)
        {
            _configuration = configuration;
            var helper = new CloudLoggingHelper(_configuration);

            googleCredential = helper.GetGoogleCredential();
            channel          = new Channel(
                LoggingServiceV2Client.DefaultEndpoint.Host,
                LoggingServiceV2Client.DefaultEndpoint.Port,
                googleCredential.ToChannelCredentials()
                );
            client    = LoggingServiceV2Client.Create(channel);
            projectId = helper.GetProjectId();
        }
Exemplo n.º 18
0
 /// <summary>
 /// Получает необходимые для использования Google API права.
 /// </summary>
 private void GetCredentials()
 {
     try
     {
         // Получение пути до файла.
         AssetManager assets = Android.App.Application.Context.Assets;
         var          stream = Android.App.Application.Context.Assets.Open("hseOcrPrivateKey.json");
         // Получение прав путём чтения json-файла с приватным ключом.
         credential = GoogleCredential.FromStream(stream);
         channel    = new Channel(ImageAnnotatorClient.DefaultEndpoint.Host,
                                  ImageAnnotatorClient.DefaultEndpoint.Port, credential.ToChannelCredentials());
     }
     catch (Exception) { }
 }
Exemplo n.º 19
0
        public CloudMonitoringServices(IConfiguration configuration)
        {
            this.configuration = configuration;
            var helper = new CloudMonitoringHelper(configuration);

            googleCredential = helper.GetGoogleCredential();
            channel          = new Channel(
                MetricServiceClient.DefaultEndpoint.Host,
                MetricServiceClient.DefaultEndpoint.Port,
                googleCredential.ToChannelCredentials()
                );
            client    = MetricServiceClient.Create(channel);
            projectId = helper.GetProjectId();
        }
Exemplo n.º 20
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();
            SecretInfo secretInfo = new SecretInfo();

            Configuration.Bind("LINE-Bot-Setting", secretInfo);
            services.AddSingleton <SecretInfo> (secretInfo);
            GoogleCredential   credential         = GoogleCredential.FromFile(HostEnvironment.ContentRootPath + "/auth.json");
            ChannelCredentials channelCredentials = credential.ToChannelCredentials();
            Channel            channel            = new Channel(FirestoreClient.DefaultEndpoint.ToString(), channelCredentials);
            FirestoreClient    firestoreClient    = FirestoreClient.Create(channel);
            FirestoreDb        db = FirestoreDb.Create(Configuration.GetSection("FirseBase:ProjectId").Value, firestoreClient);

            services.AddSingleton <FirestoreDb> (db);
        }
Exemplo n.º 21
0
        public EmberDatabase(string projectId, string credentialsFilePath)
        {
            GoogleCredential cred    = GoogleCredential.FromFile(credentialsFilePath);
            Channel          channel = new Channel(FirestoreClient.DefaultEndpoint.Host,
                                                   FirestoreClient.DefaultEndpoint.Port,
                                                   cred.ToChannelCredentials());

            firestoreClient = FirestoreClient.Create(channel);

            database = FirestoreDb.Create(projectId, client: firestoreClient);

            selectionGateway      = new SelectionGateway(database);
            insertionGateway      = new InsertionGateway(database);
            actualtizationGateway = new ActualizationGateway(database);
            deletionGateway       = new DeletionGateway(database);
        }
Exemplo n.º 22
0
        public FirestoreDb GetInstance()
        {
            if (database == null)
            {
                GoogleCredential cred = GoogleCredential
                                        .FromFile(Path.Combine(AppContext.BaseDirectory + "/credentials.json"));
                Channel channel = new Channel(
                    FirestoreClient.DefaultEndpoint.Host,
                    FirestoreClient.DefaultEndpoint.Port,
                    cred.ToChannelCredentials());
                FirestoreClient client = FirestoreClient.Create(channel);
                database = FirestoreDb.Create(_configuration["ProjectId"], client);
            }

            return(database);
        }
Exemplo n.º 23
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));
        }
Exemplo n.º 24
0
        private LoggingServiceV2Client BuildLoggingServiceClient()
        {
            GoogleCredential credential = GetCredentialFromConfiguration();

            if (credential == null)
            {
                return(LoggingServiceV2Client.Create());
            }

            if (credential.IsCreateScopedRequired)
            {
                credential = credential.CreateScoped(s_oAuthScopes);
            }

            return(new LoggingServiceV2ClientBuilder {
                ChannelCredentials = credential.ToChannelCredentials()
            }.Build());
        }
Exemplo n.º 25
0
        public Runner(RunnerArgs args, IReceiveMessageHandler handler)
        {
            string jsonpath       = args.ServiceAccountJsonFpath;
            string projectId      = args.PubSubProjectId;
            string subscriptionId = args.PubSubSubscriptionId;

            GoogleCredential           googleCredential   = GoogleCredential.FromFile(jsonpath).CreateScoped(SCOPES);
            ChannelCredentials         channelCredentials = googleCredential.ToChannelCredentials();
            Channel                    channel            = new Channel(SubscriberServiceApiClient.DefaultEndpoint.Host, SubscriberServiceApiClient.DefaultEndpoint.Port, channelCredentials);
            SubscriberServiceApiClient subscriberService  = SubscriberServiceApiClient.Create(channel);
            SubscriptionName           subscriptionName   = new SubscriptionName(projectId, subscriptionId);

            SubscriberClient.ClientCreationSettings settings = new SubscriberClient.ClientCreationSettings(credentials: channelCredentials);
            SubscriberClient subscriber = SubscriberClient.CreateAsync(subscriptionName, settings).Result;

            this._factory    = new MessageFactory(googleCredential);
            this._subscriber = subscriber;
            this._handler    = handler;
        }
        public static AnalyzeSyntaxResponse AnalyzeSyntax(string texto)
        {
            GoogleCredential   credential         = GoogleCredential.FromFile(JSON_PATH);
            ChannelCredentials channelCredentials = credential.ToChannelCredentials();
            var builder = new LanguageServiceClientBuilder();

            builder.ChannelCredentials = channelCredentials;
            var client = builder.Build();


            var syntax = client.AnalyzeSyntax(new Document()
            {
                Content  = texto,
                Type     = Document.Types.Type.PlainText,
                Language = "en-US"
            });

            return(syntax);
        }
Exemplo n.º 27
0
        static void Main(string[] args)
        {
            string project = "YOUR_PROJECT_ID";


            GoogleCredential cred    = GoogleCredential.FromFile(@"C:\[YOUR_PATH]\[YOUR_FILE].json");
            Channel          channel = new Channel(FirestoreClient.DefaultEndpoint.Host,
                                                   FirestoreClient.DefaultEndpoint.Port,
                                                   cred.ToChannelCredentials());
            FirestoreClient client = FirestoreClient.Create(channel);
            FirestoreDb     db     = FirestoreDb.Create(project, client);

            Console.WriteLine("Created Cloud Firestore client with project ID: {0}", project);

            //GoogleApiImplement.callAddDataHelper(db);
            FireStoreApiImplementation.callRetrieveDataHelper(db);


            Console.ReadLine();
        }
Exemplo n.º 28
0
        public static Task <IReadOnlyList <Google.Cloud.Vision.V1.EntityAnnotation> > TextDetectionAsync(byte[] img_byte)
        {
            var newTask = Task.Factory.StartNew(async() =>
            {
                IReadOnlyList <Google.Cloud.Vision.V1.EntityAnnotation> response;
                Channel channel = new Channel(
                    ImageAnnotatorClient.DefaultEndpoint.Host,
                    ImageAnnotatorClient.DefaultEndpoint.Port,
                    Credential.ToChannelCredentials());
                ImageAnnotatorClient client = ImageAnnotatorClient.Create(channel);
                using (MemoryStream imageStream = new MemoryStream(img_byte))
                {
                    var image = Google.Cloud.Vision.V1.Image.FromStream(imageStream);
                    response  = await client.DetectTextAsync(image);
                }
                return(response);
            });

            return(newTask.Result);
        }
        private static MetricServiceClient CreateMetricServiceClient(GoogleCredential credential, CancellationTokenSource tokenSource)
        {
            // Make sure to add Opencensus header to every outgoing call to Stackdriver APIs
            Action <Metadata> addOpencensusHeader = m => m.Add(USER_AGENT_KEY, USER_AGENT);
            var callSettings = new CallSettings(
                cancellationToken: tokenSource.Token,
                credentials: null,
                timing: null,
                headerMutation: addOpencensusHeader,
                writeOptions: WriteOptions.Default,
                propagationToken: null);

            var channel = new Channel(
                MetricServiceClient.DefaultEndpoint.ToString(),
                credential.ToChannelCredentials());

            var metricServiceSettings = new MetricServiceSettings()
            {
                CallSettings = callSettings
            };

            return(MetricServiceClient.Create(channel, settings: metricServiceSettings));
        }
Exemplo n.º 30
0
        public async Task <bool> LoginAsync(string email, string password)
        {
            GoogleCredential credential = GoogleCredential
                                          .FromFile("auth.json");
            ChannelCredentials channelCredentials = credential.ToChannelCredentials();
            Channel            channel            = new Channel(FirestoreClient.DefaultEndpoint.ToString(), channelCredentials);
            FirestoreClient    firestoreClient    = FirestoreClient.Create(channel);

            this.Client = firestoreClient;

            return(await Task.FromResult(true));

            //try
            //{
            //    UserCredential credential;
            //    using (var stream = new FileStream("client_secrets.json", FileMode.Open, FileAccess.Read))
            //    {
            //        credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
            //            GoogleClientSecrets.Load(stream).Secrets,
            //            new[] { BooksService.Scope.Books },
            //            "user", CancellationToken.None, new FileDataStore("Books.ListMyLibrary"));
            //    }

            //    //this._authResult = await CrossFirebaseAuth.Current
            //    //        .GetInstance(ApiKeys.FirebaseName)
            //    //        .SignInWithEmailAndPasswordAsync(email, password);
            //}
            //catch (Exception ex)
            //{
            //    throw;
            //}


            ////return this._authResult != null && this._authResult.User != null;

            //return await Task.FromResult(false);
        }