/// <summary>Snippet for ListCollectionIds</summary>
        public async Task ListCollectionIdsAsync()
        {
            // Snippet: ListCollectionIdsAsync(string, string, int?, CallSettings)
            // Create client
            FirestoreClient firestoreClient = await FirestoreClient.CreateAsync();

            // Initialize request argument(s)
            string parent = "";
            // Make the request
            PagedAsyncEnumerable <ListCollectionIdsResponse, string> response = firestoreClient.ListCollectionIdsAsync(parent);

            // Iterate over all response items, lazily performing RPCs as required
            await response.ForEachAsync((string item) =>
            {
                // Do something with each item
                Console.WriteLine(item);
            });

            // Or iterate over pages (of server-defined size), performing one RPC per page
            await response.AsRawResponses().ForEachAsync((ListCollectionIdsResponse page) =>
            {
                // Do something with each page of items
                Console.WriteLine("A page of results:");
                foreach (string item in page)
                {
                    // Do something with each item
                    Console.WriteLine(item);
                }
            });

            // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
            int           pageSize   = 10;
            Page <string> singlePage = await response.ReadPageAsync(pageSize);

            // Do something with the page of items
            Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
            foreach (string item in singlePage)
            {
                // Do something with each item
                Console.WriteLine(item);
            }
            // Store the pageToken, for when the next page is required.
            string nextPageToken = singlePage.NextPageToken;
            // End snippet
        }
        public FirebaseDocumentListener(FirestoreDb db)
        {
            // Create client
            FirestoreDb     = db;
            FirestoreClient = db.Client; //FirestoreClient.Create();
            ProjectId       = db.ProjectId;
            DatabaseId      = db.DatabaseId;

            //Setup no expiration for the listen
            ListenSettings = CallSettings.FromCallTiming(CallTiming.FromExpiration(Expiration.None));

            //Start our handler for writing requests to GCP
            RequestHanderTask = StartRequestHandlerTask();

            //Initialize a cancelation source so we can cancel tasks we create
            CancellationTokenSource = new CancellationTokenSource();
            CancellationToken       = CancellationTokenSource.Token;
        }
예제 #3
0
        /// <summary>Snippet for DeleteDocumentAsync</summary>
        public async Task DeleteDocumentRequestObjectAsync()
        {
            // Snippet: DeleteDocumentAsync(DeleteDocumentRequest, CallSettings)
            // Additional: DeleteDocumentAsync(DeleteDocumentRequest, CancellationToken)
            // Create client
            FirestoreClient firestoreClient = await FirestoreClient.CreateAsync();

            // Initialize request argument(s)
            DeleteDocumentRequest request = new DeleteDocumentRequest
            {
                Name            = "",
                CurrentDocument = new Precondition(),
            };
            // Make the request
            await firestoreClient.DeleteDocumentAsync(request);

            // End snippet
        }
예제 #4
0
        private FirestoreDb(string projectId, string databaseId, FirestoreClient client, Action <string> warningLogger, SerializationContext serializationContext)
        {
            ProjectId  = GaxPreconditions.CheckNotNull(projectId, nameof(projectId));
            DatabaseId = GaxPreconditions.CheckNotNull(databaseId, nameof(databaseId));
            Client     = GaxPreconditions.CheckNotNull(client, nameof(client));
            // TODO: Investigate using DatabaseName and DocumentPathName.
            RootPath      = $"projects/{ProjectId}/databases/{DatabaseId}";
            DocumentsPath = $"{RootPath}/documents";
            WarningLogger = warningLogger;

            // TODO: Validate these settings, and potentially make them configurable
            _batchGetCallSettings = CallSettings.FromCallTiming(CallTiming.FromRetry(new RetrySettings(
                                                                                         retryBackoff: new BackoffSettings(TimeSpan.FromMilliseconds(500), TimeSpan.FromSeconds(5), 2.0),
                                                                                         timeoutBackoff: new BackoffSettings(TimeSpan.FromMinutes(1), TimeSpan.FromMinutes(3), 2.0),
                                                                                         Expiration.FromTimeout(TimeSpan.FromMinutes(10)),
                                                                                         RetrySettings.FilterForStatusCodes(StatusCode.Unavailable))));
            SerializationContext = GaxPreconditions.CheckNotNull(serializationContext, nameof(serializationContext));
        }
예제 #5
0
        public static FirestoreDb CreateFirestoreDb(IServiceProvider provider)
        {
            var authOptions = provider.GetRequiredService <IOptions <OAuthServiceAccountKey> >();

            var path = Path.GetTempFileName();

            var json = JsonConvert.SerializeObject(authOptions.Value);

            using var writer = File.CreateText(path);
            writer.Write(json);
            writer.Flush();
            writer.Close();
            Environment.SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS", path);

            var client = FirestoreClient.Create();

            return(FirestoreDb.Create(authOptions.Value.project_id, client: client));
        }
예제 #6
0
        /// <summary>Snippet for RollbackAsync</summary>
        public async Task RollbackRequestObjectAsync()
        {
            // Snippet: RollbackAsync(RollbackRequest, CallSettings)
            // Additional: RollbackAsync(RollbackRequest, CancellationToken)
            // Create client
            FirestoreClient firestoreClient = await FirestoreClient.CreateAsync();

            // Initialize request argument(s)
            RollbackRequest request = new RollbackRequest
            {
                Database    = "",
                Transaction = ByteString.Empty,
            };
            // Make the request
            await firestoreClient.RollbackAsync(request);

            // End snippet
        }
        /// <summary>Snippet for UpdateDocumentAsync</summary>
        public async Task UpdateDocumentAsync_RequestObject()
        {
            // Snippet: UpdateDocumentAsync(UpdateDocumentRequest,CallSettings)
            // Additional: UpdateDocumentAsync(UpdateDocumentRequest,CancellationToken)
            // Create client
            FirestoreClient firestoreClient = await FirestoreClient.CreateAsync();

            // Initialize request argument(s)
            UpdateDocumentRequest request = new UpdateDocumentRequest
            {
                Document   = new Document(),
                UpdateMask = new DocumentMask(),
            };
            // Make the request
            Document response = await firestoreClient.UpdateDocumentAsync(request);

            // End snippet
        }
예제 #8
0
        /// <summary>Snippet for BeginTransactionAsync</summary>
        public async Task BeginTransactionRequestObjectAsync()
        {
            // Snippet: BeginTransactionAsync(BeginTransactionRequest, CallSettings)
            // Additional: BeginTransactionAsync(BeginTransactionRequest, CancellationToken)
            // Create client
            FirestoreClient firestoreClient = await FirestoreClient.CreateAsync();

            // Initialize request argument(s)
            BeginTransactionRequest request = new BeginTransactionRequest
            {
                Database = "",
                Options  = new TransactionOptions(),
            };
            // Make the request
            BeginTransactionResponse response = await firestoreClient.BeginTransactionAsync(request);

            // End snippet
        }
        /// <summary>Snippet for CommitAsync</summary>
        public async Task CommitAsync_RequestObject()
        {
            // Snippet: CommitAsync(CommitRequest,CallSettings)
            // Additional: CommitAsync(CommitRequest,CancellationToken)
            // Create client
            FirestoreClient firestoreClient = await FirestoreClient.CreateAsync();

            // Initialize request argument(s)
            CommitRequest request = new CommitRequest
            {
                Database = new DatabaseRootName("[PROJECT]", "[DATABASE]").ToString(),
                Writes   = { },
            };
            // Make the request
            CommitResponse response = await firestoreClient.CommitAsync(request);

            // End snippet
        }
        /// <summary>Snippet for RollbackAsync</summary>
        public async Task RollbackAsync_RequestObject()
        {
            // Snippet: RollbackAsync(RollbackRequest,CallSettings)
            // Additional: RollbackAsync(RollbackRequest,CancellationToken)
            // Create client
            FirestoreClient firestoreClient = await FirestoreClient.CreateAsync();

            // Initialize request argument(s)
            RollbackRequest request = new RollbackRequest
            {
                Database    = new DatabaseRootName("[PROJECT]", "[DATABASE]").ToString(),
                Transaction = Google.Protobuf.ByteString.CopyFromUtf8(""),
            };
            // Make the request
            await firestoreClient.RollbackAsync(request);

            // End snippet
        }
예제 #11
0
 /// <summary>Snippet for CreateDocument</summary>
 public void CreateDocumentRequestObject()
 {
     // Snippet: CreateDocument(CreateDocumentRequest, CallSettings)
     // Create client
     FirestoreClient firestoreClient = FirestoreClient.Create();
     // Initialize request argument(s)
     CreateDocumentRequest request = new CreateDocumentRequest
     {
         Parent       = "",
         CollectionId = "",
         DocumentId   = "",
         Document     = new Document(),
         Mask         = new DocumentMask(),
     };
     // Make the request
     Document response = firestoreClient.CreateDocument(request);
     // End snippet
 }
        /// <summary>Snippet for CreateDocumentAsync</summary>
        public async Task CreateDocumentAsync_RequestObject()
        {
            // Snippet: CreateDocumentAsync(CreateDocumentRequest,CallSettings)
            // Create client
            FirestoreClient firestoreClient = await FirestoreClient.CreateAsync();

            // Initialize request argument(s)
            CreateDocumentRequest request = new CreateDocumentRequest
            {
                Parent       = new AnyPathName("[PROJECT]", "[DATABASE]", "[DOCUMENT]", "[ANY_PATH]").ToString(),
                CollectionId = "",
                DocumentId   = "",
                Document     = new Document(),
            };
            // Make the request
            Document response = await firestoreClient.CreateDocumentAsync(request);

            // End snippet
        }
예제 #13
0
        /// <summary>Snippet for GetDocumentAsync</summary>
        public async Task GetDocumentRequestObjectAsync()
        {
            // Snippet: GetDocumentAsync(GetDocumentRequest, CallSettings)
            // Additional: GetDocumentAsync(GetDocumentRequest, CancellationToken)
            // Create client
            FirestoreClient firestoreClient = await FirestoreClient.CreateAsync();

            // Initialize request argument(s)
            GetDocumentRequest request = new GetDocumentRequest
            {
                Name        = "",
                Mask        = new DocumentMask(),
                Transaction = ByteString.Empty,
            };
            // Make the request
            Document response = await firestoreClient.GetDocumentAsync(request);

            // End snippet
        }
예제 #14
0
        /// <summary>Snippet for CommitAsync</summary>
        public async Task CommitRequestObjectAsync()
        {
            // Snippet: CommitAsync(CommitRequest, CallSettings)
            // Additional: CommitAsync(CommitRequest, CancellationToken)
            // Create client
            FirestoreClient firestoreClient = await FirestoreClient.CreateAsync();

            // Initialize request argument(s)
            CommitRequest request = new CommitRequest
            {
                Database    = "",
                Writes      = { new Write(), },
                Transaction = ByteString.Empty,
            };
            // Make the request
            CommitResponse response = await firestoreClient.CommitAsync(request);

            // End snippet
        }
예제 #15
0
        /// <summary>
        /// Fetches document data from firestore db
        /// </summary>
        /// <returns></returns>
        public async Task <ActionResult> Index()
        {
            string project    = "ainfirestoreproject";
            var    mappedPath = Server.MapPath("/Certificate/ainfirestoreproject-139fe45328fd.json");
            var    credential = GoogleCredential.FromFile(mappedPath);
            var    channel    = new Grpc.Core.Channel(
                FirestoreClient.DefaultEndpoint.ToString(),
                credential.ToChannelCredentials());
            var client = FirestoreClient.Create(channel);
            var db     = FirestoreDb.Create(project, client: client);

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

            CollectionReference usersRef = db.Collection("tests");
            var snapshot = await usersRef.GetSnapshotAsync();


            return(View(snapshot));
        }
예제 #16
0
        /// <summary>Snippet for BatchWriteAsync</summary>
        public async Task BatchWriteRequestObjectAsync()
        {
            // Snippet: BatchWriteAsync(BatchWriteRequest, CallSettings)
            // Additional: BatchWriteAsync(BatchWriteRequest, CancellationToken)
            // Create client
            FirestoreClient firestoreClient = await FirestoreClient.CreateAsync();

            // Initialize request argument(s)
            BatchWriteRequest request = new BatchWriteRequest
            {
                Database = "",
                Writes   = { new Write(), },
                Labels   = { { "", "" }, },
            };
            // Make the request
            BatchWriteResponse response = await firestoreClient.BatchWriteAsync(request);

            // End snippet
        }
        public FirestoreContext()
        {
            var path = Path.GetFullPath(Path.Combine(Environment.CurrentDirectory, @"Resources/Keys\gcloud_service_account.json"));

            /*
             * FirebaseApp.Create(new AppOptions()
             * {
             *  Credential = GoogleCredential.FromFile(path),
             * });*/

            var credential = GoogleCredential.FromFile(path);

            var projectID          = "tinglysning-b87b2";
            var channelCredentials = credential.ToChannelCredentials();
            var channel            = new Channel(FirestoreClient.DefaultEndpoint.ToString(), channelCredentials);
            var firestoreClient    = FirestoreClient.Create(channel);

            Database = FirestoreDb.Create(projectID, client: firestoreClient);
        }
        /// <summary>Snippet for ListCollectionIds</summary>
        public void ListCollectionIds()
        {
            // Snippet: ListCollectionIds(string,string,int?,CallSettings)
            // Create client
            FirestoreClient firestoreClient = FirestoreClient.Create();
            // Initialize request argument(s)
            string formattedParent = new AnyPathName("[PROJECT]", "[DATABASE]", "[DOCUMENT]", "[ANY_PATH]").ToString();
            // Make the request
            PagedEnumerable <ListCollectionIdsResponse, string> response =
                firestoreClient.ListCollectionIds(formattedParent);

            // Iterate over all response items, lazily performing RPCs as required
            foreach (string item in response)
            {
                // Do something with each item
                Console.WriteLine(item);
            }

            // Or iterate over pages (of server-defined size), performing one RPC per page
            foreach (ListCollectionIdsResponse page in response.AsRawResponses())
            {
                // Do something with each page of items
                Console.WriteLine("A page of results:");
                foreach (string item in page)
                {
                    Console.WriteLine(item);
                }
            }

            // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
            int           pageSize   = 10;
            Page <string> singlePage = response.ReadPage(pageSize);

            // Do something with the page of items
            Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
            foreach (string item in singlePage)
            {
                Console.WriteLine(item);
            }
            // Store the pageToken, for when the next page is required.
            string nextPageToken = singlePage.NextPageToken;
            // End snippet
        }
예제 #19
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();
        }
        /// <summary>
        /// Adds an Firebase implementation of identity stores.
        /// </summary>
        /// <param name="builder">The <see cref="IdentityBuilder"/> instance this method extends.</param>
        /// <param name="configure">Action to configure AuthTokenOptions</param>
        /// <returns>The <see cref="IdentityBuilder"/> instance this method extends.</returns>
        public static IdentityBuilder AddFirestoreStores(this IdentityBuilder builder, Action <OAuthServiceAccountKey> configure)
        {
            var services = builder.Services;

            services.Configure(configure)
            .AddScoped(provider =>
            {
                var authOptions = provider.GetRequiredService <IOptions <OAuthServiceAccountKey> >();
                var json        = JsonConvert.SerializeObject(authOptions.Value);
                var credentials = GoogleCredential.FromJson(json)
                                  .CreateScoped("https://www.googleapis.com/auth/datastore");
                var channel = new Grpc.Core.Channel(
                    FirestoreClient.DefaultEndpoint.ToString(),
                    credentials.ToChannelCredentials());
                var client = FirestoreClient.Create(channel);
                return(FirestoreDb.Create(authOptions.Value.project_id, client: client));
            });
            AddStores(services, builder.UserType, builder.RoleType);
            return(builder);
        }
예제 #21
0
        /// <summary>Snippet for CreateDocumentAsync</summary>
        public async Task CreateDocumentRequestObjectAsync()
        {
            // Snippet: CreateDocumentAsync(CreateDocumentRequest, CallSettings)
            // Additional: CreateDocumentAsync(CreateDocumentRequest, CancellationToken)
            // Create client
            FirestoreClient firestoreClient = await FirestoreClient.CreateAsync();

            // Initialize request argument(s)
            CreateDocumentRequest request = new CreateDocumentRequest
            {
                Parent       = "",
                CollectionId = "",
                DocumentId   = "",
                Document     = new Document(),
                Mask         = new DocumentMask(),
            };
            // Make the request
            Document response = await firestoreClient.CreateDocumentAsync(request);

            // End snippet
        }
예제 #22
0
        public async Task <FirestoreDb> DataBase()
        {
            FirebaseAuthService authService = new FirebaseAuthService();

            var auth = authService.LoadAuth();

            var firebaseToken = auth.FirebaseToken;

            if (auth.IsExpired())
            {
                firebaseToken = await authService.GetFreshTokenAsync();
            }

            var credential = GoogleCredential.FromAccessToken(firebaseToken);

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

            FirestoreClient client = FirestoreClient.Create(channel);

            return(FirestoreDb.Create(project, client));
        }
예제 #23
0
        public async Task <Google.Cloud.Firestore.WriteResult> AddFieldsbyDictionaryAsync(IDictionary <string, object> datas, string collectionName, string documentName)
        {
            FirestoreClient client = FirestoreClient.Create(channel);
            FirestoreDb     db     = await FirestoreDb.CreateAsync(configuration["GCPSetting:PROJECTNAME"], client);

            Google.Cloud.Firestore.WriteResult result;

            var document = db.Collection(collectionName).Document(documentName);
            var snapshot = await document.GetSnapshotAsync();

            if (snapshot.Exists)
            {
                result = await document.UpdateAsync(datas);
            }
            else
            {
                result = await document.CreateAsync(datas);
            }

            return(result);
        }
예제 #24
0
        /// <summary>
        ///
        /// </summary>
        /// <typeparam name="T">What kind of object are you sending me</typeparam>
        /// <param name="collection">Top folder</param>
        /// <param name="obj">The data</param>
        /// <param name="id">The collection in the document</param>
        /// <returns></returns>
        public async Task AddData <T>(string collection, T obj, string id)
        {
            try
            {
                var     serviceAcct = GoogleCredential.FromJson(_config.GetValue <string>("jsonCreds"));
                Channel channel     = new Channel(
                    FirestoreClient.DefaultEndpoint.Host, FirestoreClient.DefaultEndpoint.Port,
                    serviceAcct.ToChannelCredentials());
                FirestoreClient client = FirestoreClient.Create(channel);

                FirestoreDb db = FirestoreDb.Create(_config.GetValue <string>("projectId"), client);

                CollectionReference docRef = db.Collection(collection);

                await docRef.AddAsync(obj);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
예제 #25
0
        public static async Task Authenticate()
        {
            FirebaseAuthService authService = new FirebaseAuthService();
            //var firebaseAuthLink = await authService.LoginUser("*****@*****.**", "password");
            var firebaseToken = await authService.GetFreshToken();

            var project    = "firestoredemo-262aa";
            var credential = GoogleCredential.FromAccessToken(firebaseToken);


            Channel channel = new Channel(
                FirestoreClient.DefaultEndpoint.Host, FirestoreClient.DefaultEndpoint.Port,
                credential.ToChannelCredentials());
            FirestoreClient client = FirestoreClient.Create(channel);

            FirestoreDb db = FirestoreDb.Create(project, client);

            Tool tool = new Tool
            {
                Name   = "2.0MM BM LONG FINISH",
                Number = "4"
            };

            ExecutionData executionData = new ExecutionData
            {
                SelectedProgram = "Selected.program.running",
                ActiveProgram   = "Active.program.running"
            };

            Machine machine = new Machine
            {
                Name            = "Mikron HSM 200U LP",
                Ip              = "192.168.1.150",
                MachineName     = "Mikron 1",
                Tool            = tool,
                ExecutationData = executionData
            };

            SaveMachine(db, machine);
        }
예제 #26
0
        private FirestoreDb(string projectId, string databaseId, FirestoreClient client, Action <string> warningLogger, SerializationContext serializationContext)
        {
            ProjectId  = GaxPreconditions.CheckNotNull(projectId, nameof(projectId));
            DatabaseId = GaxPreconditions.CheckNotNull(databaseId, nameof(databaseId));
            Client     = GaxPreconditions.CheckNotNull(client, nameof(client));
            // TODO: Investigate using DatabaseName and DocumentPathName.
            RootPath      = $"projects/{ProjectId}/databases/{DatabaseId}";
            DocumentsPath = $"{RootPath}/documents";
            WarningLogger = warningLogger;

            // TODO: Validate these settings, and potentially make them configurable
            var batchGetRetry = RetrySettings.FromExponentialBackoff(
                maxAttempts: int.MaxValue,
                initialBackoff: TimeSpan.FromMilliseconds(500),
                maxBackoff: TimeSpan.FromSeconds(5),
                backoffMultiplier: 2.0,
                retryFilter: RetrySettings.FilterForStatusCodes(StatusCode.Unavailable));

            _batchGetCallSettings = CallSettings.FromRetry(batchGetRetry).WithTimeout(TimeSpan.FromMinutes(10));

            SerializationContext = GaxPreconditions.CheckNotNull(serializationContext, nameof(serializationContext));
        }
예제 #27
0
        private FirestoreDb CreateDb()
        {
            var builder       = new ConfigurationBuilder();
            var configuration = builder
                                .AddEnvironmentVariables()
                                .AddJsonFile(Path.Combine(Directory.GetCurrentDirectory(), "../../../../identityfirestore.json"))
                                .Build();
            var services = new ServiceCollection();

            services.Configure((Action <OAuthServiceAccountKey>)(options =>
            {
                configuration.GetSection("FirestoreAuthTokenOptions").Bind(options);
            }))
            .AddScoped(provider =>
            {
                CreateAuthFile(provider, out IOptions <OAuthServiceAccountKey> authOptions);

                var client = FirestoreClient.Create();
                return(FirestoreDb.Create(authOptions.Value.project_id, client: client));
            });

            return(services.BuildServiceProvider().GetRequiredService <FirestoreDb>());
        }
예제 #28
0
        private FirestoreDb(string projectId, string databaseId, FirestoreClient client, Action <string> warningLogger, SerializationContext serializationContext)
        {
            ProjectId  = GaxPreconditions.CheckNotNull(projectId, nameof(projectId));
            DatabaseId = GaxPreconditions.CheckNotNull(databaseId, nameof(databaseId));
            Client     = GaxPreconditions.CheckNotNull(client, nameof(client));
            // TODO: Investigate using DatabaseName and DocumentPathName.
            RootPath      = $"projects/{ProjectId}/databases/{DatabaseId}";
            DocumentsPath = $"{RootPath}/documents";
            WarningLogger = warningLogger;

            // TODO: Potentially make these configurable.
            // The retry settings are taken from firestore_grpc_service_config.json.
            var batchGetRetry = RetrySettings.FromExponentialBackoff(
                maxAttempts: 5,
                initialBackoff: TimeSpan.FromMilliseconds(100),
                maxBackoff: TimeSpan.FromSeconds(60),
                backoffMultiplier: 1.3,
                retryFilter: RetrySettings.FilterForStatusCodes(StatusCode.Unavailable, StatusCode.Internal, StatusCode.DeadlineExceeded));

            _batchGetCallSettings = CallSettings.FromRetry(batchGetRetry).WithTimeout(TimeSpan.FromMinutes(10));

            SerializationContext = GaxPreconditions.CheckNotNull(serializationContext, nameof(serializationContext));
        }
예제 #29
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);
        }
예제 #30
0
        public async Task <Google.Cloud.Firestore.WriteResult> DeleteFieldData(string collectionName, string documentName, List <string> keys)
        {
            FirestoreClient client = FirestoreClient.Create(channel);
            FirestoreDb     db     = await FirestoreDb.CreateAsync(configuration["GCPSetting:PROJECTNAME"], client);

            var document = db.Collection(collectionName).Document(documentName);

            var snapshot = await document.GetSnapshotAsync();

            if (snapshot.Exists)
            {
                Dictionary <string, object> updates = new Dictionary <string, object>();
                keys.ForEach(key =>
                {
                    updates.Add(key, FieldValue.Delete);
                });

                Google.Cloud.Firestore.WriteResult writeResult = await document.UpdateAsync(updates);

                return(writeResult);
            }

            return(null);
        }