示例#1
0
 /// <summary>Snippet for GetDocument</summary>
 public void GetDocument_RequestObject()
 {
     // Snippet: GetDocument(GetDocumentRequest,CallSettings)
     // Create client
     FirestoreClient firestoreClient = FirestoreClient.Create();
     // Initialize request argument(s)
     GetDocumentRequest request = new GetDocumentRequest
     {
         Name = new AnyPathName("[PROJECT]", "[DATABASE]", "[DOCUMENT]", "[ANY_PATH]").ToString(),
     };
     // Make the request
     Document response = firestoreClient.GetDocument(request);
     // End snippet
 }
示例#2
0
 public void BeginTransaction_RequestObject()
 {
     // Snippet: BeginTransaction(BeginTransactionRequest,CallSettings)
     // Create client
     FirestoreClient firestoreClient = FirestoreClient.Create();
     // Initialize request argument(s)
     BeginTransactionRequest request = new BeginTransactionRequest
     {
         Database = new DatabaseRootName("[PROJECT]", "[DATABASE]").ToString(),
     };
     // Make the request
     BeginTransactionResponse response = firestoreClient.BeginTransaction(request);
     // End snippet
 }
示例#3
0
        public static FirestoreDb Create()
        {
            var firestoreHost     = Environment.GetEnvironmentVariable("FIRESTORE_EMULATOR_HOST") ?? "localhost:8080";
            var matches           = Regex.Match(firestoreHost, "(?<host>.*):(?<port>\\d+)");
            var host              = matches.Groups["host"].Value;
            var port              = int.Parse(matches.Groups["port"].Value);
            var firestoreSettings = new FirestoreSettings
            {
                CallSettings = CallSettings.FromHeaderMutation(x => x.Add("Authorization", "Bearer owner"))
            };

            return(FirestoreDb.Create("na",
                                      FirestoreClient.Create(new Channel(host, port, ChannelCredentials.Insecure), firestoreSettings)));
        }
示例#4
0
        /// <summary>Snippet for PartitionQuery</summary>
        public void PartitionQueryRequestObject()
        {
            // Snippet: PartitionQuery(PartitionQueryRequest, CallSettings)
            // Create client
            FirestoreClient firestoreClient = FirestoreClient.Create();
            // Initialize request argument(s)
            PartitionQueryRequest request = new PartitionQueryRequest
            {
                Parent          = "",
                StructuredQuery = new StructuredQuery(),
                PartitionCount  = 0L,
            };
            // Make the request
            PagedEnumerable <PartitionQueryResponse, Cursor> response = firestoreClient.PartitionQuery(request);

            // Iterate over all response items, lazily performing RPCs as required
            foreach (Cursor 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 (PartitionQueryResponse page in response.AsRawResponses())
            {
                // Do something with each page of items
                Console.WriteLine("A page of results:");
                foreach (Cursor 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 <Cursor> 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 (Cursor 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
        }
示例#5
0
        /// <summary>Snippet for DeleteDocument</summary>
        public void DeleteDocument_RequestObject()
        {
            // Snippet: DeleteDocument(DeleteDocumentRequest,CallSettings)
            // Create client
            FirestoreClient firestoreClient = FirestoreClient.Create();
            // Initialize request argument(s)
            DeleteDocumentRequest request = new DeleteDocumentRequest
            {
                AnyPathName = new AnyPathName("[PROJECT]", "[DATABASE]", "[DOCUMENT]", "[ANY_PATH]"),
            };

            // Make the request
            firestoreClient.DeleteDocument(request);
            // End snippet
        }
示例#6
0
        /// <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>
        /// <param name="authFilePath">The path where to store the authentication file extracted from config.</param>
        /// <returns>
        /// The <see cref="IdentityBuilder" /> instance this method extends.
        /// </returns>
        public static IdentityBuilder AddFirestoreStores(this IdentityBuilder builder, Action <OAuthServiceAccountKey> configure, string authFilePath)
        {
            var services = builder.Services;

            services.Configure(configure)
            .AddScoped(provider =>
            {
                var authOptions = StoreAuthFile(provider, authFilePath);
                var client      = FirestoreClient.Create();

                return(FirestoreDb.Create(authOptions.Value.project_id, client: client));
            });
            AddStores(services, builder.UserType, builder.RoleType);
            return(builder);
        }
 /// <summary>Snippet for UpdateDocument</summary>
 public void UpdateDocument_RequestObject()
 {
     // Snippet: UpdateDocument(UpdateDocumentRequest,CallSettings)
     // Create client
     FirestoreClient firestoreClient = FirestoreClient.Create();
     // Initialize request argument(s)
     UpdateDocumentRequest request = new UpdateDocumentRequest
     {
         Document   = new Document(),
         UpdateMask = new DocumentMask(),
     };
     // Make the request
     Document response = firestoreClient.UpdateDocument(request);
     // End snippet
 }
 /// <summary>Snippet for Commit</summary>
 public void Commit_RequestObject()
 {
     // Snippet: Commit(CommitRequest,CallSettings)
     // Create client
     FirestoreClient firestoreClient = FirestoreClient.Create();
     // Initialize request argument(s)
     CommitRequest request = new CommitRequest
     {
         Database = new DatabaseRootName("[PROJECT]", "[DATABASE]").ToString(),
         Writes   = { },
     };
     // Make the request
     CommitResponse response = firestoreClient.Commit(request);
     // End snippet
 }
示例#9
0
 /// <summary>Snippet for BeginTransaction</summary>
 public void BeginTransactionRequestObject()
 {
     // Snippet: BeginTransaction(BeginTransactionRequest, CallSettings)
     // Create client
     FirestoreClient firestoreClient = FirestoreClient.Create();
     // Initialize request argument(s)
     BeginTransactionRequest request = new BeginTransactionRequest
     {
         Database = "",
         Options  = new TransactionOptions(),
     };
     // Make the request
     BeginTransactionResponse response = firestoreClient.BeginTransaction(request);
     // End snippet
 }
示例#10
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);
        }
示例#11
0
        public async Task <DocumentSnapshot> FetchData(string collectionName, string documentName)
        {
            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)
            {
                return(snapshot);
            }

            return(null);
        }
示例#12
0
        /// <summary>Snippet for DeleteDocument</summary>
        public void DeleteDocumentRequestObject()
        {
            // Snippet: DeleteDocument(DeleteDocumentRequest, CallSettings)
            // Create client
            FirestoreClient firestoreClient = FirestoreClient.Create();
            // Initialize request argument(s)
            DeleteDocumentRequest request = new DeleteDocumentRequest
            {
                Name            = "",
                CurrentDocument = new Precondition(),
            };

            // Make the request
            firestoreClient.DeleteDocument(request);
            // End snippet
        }
示例#13
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);
        }
示例#14
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);
        }
示例#15
0
 /// <summary>Snippet for BatchWrite</summary>
 public void BatchWriteRequestObject()
 {
     // Snippet: BatchWrite(BatchWriteRequest, CallSettings)
     // Create client
     FirestoreClient firestoreClient = FirestoreClient.Create();
     // Initialize request argument(s)
     BatchWriteRequest request = new BatchWriteRequest
     {
         Database = "",
         Writes   = { new Write(), },
         Labels   = { { "", "" }, },
     };
     // Make the request
     BatchWriteResponse response = firestoreClient.BatchWrite(request);
     // End snippet
 }
        /// <summary>Snippet for Rollback</summary>
        public void Rollback_RequestObject()
        {
            // Snippet: Rollback(RollbackRequest,CallSettings)
            // Create client
            FirestoreClient firestoreClient = FirestoreClient.Create();
            // Initialize request argument(s)
            RollbackRequest request = new RollbackRequest
            {
                Database    = new DatabaseRootName("[PROJECT]", "[DATABASE]").ToString(),
                Transaction = ByteString.CopyFromUtf8(""),
            };

            // Make the request
            firestoreClient.Rollback(request);
            // End snippet
        }
示例#17
0
        /// <summary>Snippet for Rollback</summary>
        public void RollbackRequestObject()
        {
            // Snippet: Rollback(RollbackRequest, CallSettings)
            // Create client
            FirestoreClient firestoreClient = FirestoreClient.Create();
            // Initialize request argument(s)
            RollbackRequest request = new RollbackRequest
            {
                Database    = "",
                Transaction = ByteString.Empty,
            };

            // Make the request
            firestoreClient.Rollback(request);
            // End snippet
        }
示例#18
0
 /// <summary>Snippet for Commit</summary>
 public void CommitRequestObject()
 {
     // Snippet: Commit(CommitRequest, CallSettings)
     // Create client
     FirestoreClient firestoreClient = FirestoreClient.Create();
     // Initialize request argument(s)
     CommitRequest request = new CommitRequest
     {
         Database    = "",
         Writes      = { new Write(), },
         Transaction = ByteString.Empty,
     };
     // Make the request
     CommitResponse response = firestoreClient.Commit(request);
     // End snippet
 }
示例#19
0
 /// <summary>Snippet for GetDocument</summary>
 public void GetDocumentRequestObject()
 {
     // Snippet: GetDocument(GetDocumentRequest, CallSettings)
     // Create client
     FirestoreClient firestoreClient = FirestoreClient.Create();
     // Initialize request argument(s)
     GetDocumentRequest request = new GetDocumentRequest
     {
         Name        = "",
         Mask        = new DocumentMask(),
         Transaction = ByteString.Empty,
     };
     // Make the request
     Document response = firestoreClient.GetDocument(request);
     // End snippet
 }
        /// <summary>Snippet for ListDocuments</summary>
        public void ListDocuments_RequestObject()
        {
            // Snippet: ListDocuments(ListDocumentsRequest,CallSettings)
            // Create client
            FirestoreClient firestoreClient = FirestoreClient.Create();
            // Initialize request argument(s)
            ListDocumentsRequest request = new ListDocumentsRequest
            {
                Parent       = new AnyPathName("[PROJECT]", "[DATABASE]", "[DOCUMENT]", "[ANY_PATH]").ToString(),
                CollectionId = "",
            };
            // Make the request
            PagedEnumerable <ListDocumentsResponse, Document> response =
                firestoreClient.ListDocuments(request);

            // Iterate over all response items, lazily performing RPCs as required
            foreach (Document 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 (ListDocumentsResponse page in response.AsRawResponses())
            {
                // Do something with each page of items
                Console.WriteLine("A page of results:");
                foreach (Document 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 <Document> 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 (Document item in singlePage)
            {
                Console.WriteLine(item);
            }
            // Store the pageToken, for when the next page is required.
            string nextPageToken = singlePage.NextPageToken;
            // End snippet
        }
        /// <summary>Snippet for Listen</summary>
        public async Task Listen()
        {
            // Snippet: Listen(CallSettings,BidirectionalStreamingSettings)
            // Create client
            FirestoreClient firestoreClient = FirestoreClient.Create();

            // Initialize streaming call, retrieving the stream object
            FirestoreClient.ListenStream duplexStream = firestoreClient.Listen();

            // Sending requests and retrieving responses can be arbitrarily interleaved.
            // Exact sequence will depend on client/server behavior.

            // Create task to do something with responses from server
            Task responseHandlerTask = Task.Run(async() =>
            {
                IAsyncEnumerator <ListenResponse> responseStream = duplexStream.ResponseStream;
                while (await responseStream.MoveNext())
                {
                    ListenResponse response = responseStream.Current;
                    // Do something with streamed response
                }
                // The response stream has completed
            });

            // Send requests to the server
            bool done = false;

            while (!done)
            {
                // Initialize a request
                ListenRequest request = new ListenRequest
                {
                    Database = new DatabaseRootName("[PROJECT]", "[DATABASE]").ToString(),
                };
                // Stream a request to the server
                await duplexStream.WriteAsync(request);

                // Set "done" to true when sending requests is complete
            }
            // Complete writing requests to the stream
            await duplexStream.WriteCompleteAsync();

            // Await the response handler.
            // This will complete once all server responses have been processed.
            await responseHandlerTask;
            // End snippet
        }
示例#22
0
        public async Task <DocumentReference> CloudHealthAsync()
        {
            FirestoreClient client = FirestoreClient.Create(channel);
            FirestoreDb     db     = await FirestoreDb.CreateAsync(configuration["GCPSetting:PROJECTNAME"], client);

            CollectionReference collection = db.Collection("tests");

            var testsData = new
            {
                TestsID    = Guid.NewGuid().ToString(),
                CreateTime = DateTimeOffset.UtcNow.ToUnixTimeSeconds()
            };

            DocumentReference document = await collection.AddAsync(testsData);

            return(document);
        }
 /// <summary>Snippet for CreateDocument</summary>
 public void CreateDocument_RequestObject()
 {
     // Snippet: CreateDocument(CreateDocumentRequest,CallSettings)
     // Create client
     FirestoreClient firestoreClient = FirestoreClient.Create();
     // 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 = firestoreClient.CreateDocument(request);
     // End snippet
 }
示例#24
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
 }
示例#25
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));
        }
示例#26
0
        /// <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 parent = "";
            // Make the request
            PagedEnumerable <ListCollectionIdsResponse, string> response = firestoreClient.ListCollectionIds(parent);

            // 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)
                {
                    // 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 = 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)
            {
                // 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 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);
        }
示例#28
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));
        }
示例#29
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);
        }