コード例 #1
0
ファイル: DatastoreFixture.cs プロジェクト: greggaba/GCDotNet
        public void Dispose()
        {
            var client = DatastoreClient.Create();
            // Delete all the entities in our partition.
            // TODO: Transactions? Paging?
            var query = new Query {
                Projection = { DatastoreConstants.KeyProperty }
            };
            var response = client.RunQuery(new RunQueryRequest {
                ProjectId = ProjectId, PartitionId = PartitionId, Query = query
            });
            var deletions = response.Batch.EntityResults.Select(entityResult => entityResult.Entity.ToDelete());

            client.Commit(ProjectId, CommitRequest.Types.Mode.NonTransactional, deletions);
        }
コード例 #2
0
        /// <summary>Snippet for AllocateIdsAsync</summary>
        public async Task AllocateIdsAsync()
        {
            // Snippet: AllocateIdsAsync(string,IEnumerable<Key>,CallSettings)
            // Additional: AllocateIdsAsync(string,IEnumerable<Key>,CancellationToken)
            // Create client
            DatastoreClient datastoreClient = await DatastoreClient.CreateAsync();

            // Initialize request argument(s)
            string            projectId = "";
            IEnumerable <Key> keys      = new List <Key>();
            // Make the request
            AllocateIdsResponse response = await datastoreClient.AllocateIdsAsync(projectId, keys);

            // End snippet
        }
コード例 #3
0
        /// <summary>
        /// Creates a <see cref="DatastoreDb"/>, using environment variables to support
        /// the Datastore Emulator if they have been set.
        /// </summary>
        /// <remarks>
        /// <para>
        /// If the DATASTORE_EMULATOR_HOST environment variable is set and not empty,
        /// this method will use the value to connect to the emulator. Otherwise, the default
        /// endpoint (and credentials) will be used.
        /// </para>
        /// <para>
        /// If the DATASTORE_PROJECT_ID environment variable is set and not empty, this
        /// overrides the value of <paramref name="projectId"/>.
        /// </para>
        /// </remarks>
        /// <param name="projectId">The project ID to use, unless overridden by DATASTORE_PROJECT_ID</param>
        /// <param name="namespaceId">The namespace ID to use in operations requiring a partition.</param>
        /// <returns>A <see cref="DatastoreDb"/> connected to either an emulator or production servers.</returns>
        public static DatastoreDb CreateDatastoreDb(string projectId, string namespaceId = "")
        {
            string emulatorHost      = Environment.GetEnvironmentVariable(EmulatorHostVariable);
            string projectIdOverride = Environment.GetEnvironmentVariable(ProjectIdVariable);

            if (!string.IsNullOrEmpty(projectIdOverride))
            {
                projectId = projectIdOverride;
            }
            DatastoreClient client = string.IsNullOrEmpty(emulatorHost)
                ? DatastoreClient.Create()
                : DatastoreClient.Create(new Channel(emulatorHost, ChannelCredentials.Insecure));

            return(DatastoreDb.Create(projectId, namespaceId, client));
        }
コード例 #4
0
 /// <summary>Snippet for Rollback</summary>
 public void Rollback_RequestObject()
 {
     // Snippet: Rollback(RollbackRequest,CallSettings)
     // Create client
     DatastoreClient datastoreClient = DatastoreClient.Create();
     // Initialize request argument(s)
     RollbackRequest request = new RollbackRequest
     {
         ProjectId   = "",
         Transaction = ByteString.Empty,
     };
     // Make the request
     RollbackResponse response = datastoreClient.Rollback(request);
     // End snippet
 }
コード例 #5
0
        /// <summary>Snippet for Commit</summary>
        public void Commit1()
        {
            // Snippet: Commit(string,CommitRequest.Types.Mode,ByteString,IEnumerable<Mutation>,CallSettings)
            // Create client
            DatastoreClient datastoreClient = DatastoreClient.Create();
            // Initialize request argument(s)
            string projectId = "";

            CommitRequest.Types.Mode mode      = CommitRequest.Types.Mode.Unspecified;
            ByteString             transaction = ByteString.Empty;
            IEnumerable <Mutation> mutations   = new List <Mutation>();
            // Make the request
            CommitResponse response = datastoreClient.Commit(projectId, mode, transaction, mutations);
            // End snippet
        }
コード例 #6
0
        /// <summary>Snippet for RollbackAsync</summary>
        public async Task RollbackAsync()
        {
            // Snippet: RollbackAsync(string,ByteString,CallSettings)
            // Additional: RollbackAsync(string,ByteString,CancellationToken)
            // Create client
            DatastoreClient datastoreClient = await DatastoreClient.CreateAsync();

            // Initialize request argument(s)
            string     projectId   = "";
            ByteString transaction = ByteString.Empty;
            // Make the request
            RollbackResponse response = await datastoreClient.RollbackAsync(projectId, transaction);

            // End snippet
        }
コード例 #7
0
        public async Task LookupAsync()
        {
            // Snippet: LookupAsync(string,ReadOptions,IEnumerable<Key>,CallSettings)
            // Additional: LookupAsync(string,ReadOptions,IEnumerable<Key>,CancellationToken)
            // Create client
            DatastoreClient datastoreClient = DatastoreClient.Create();
            // Initialize request argument(s)
            string            projectId   = "";
            ReadOptions       readOptions = new ReadOptions();
            IEnumerable <Key> keys        = new List <Key>();
            // Make the request
            LookupResponse response = await datastoreClient.LookupAsync(projectId, readOptions, keys);

            // End snippet
        }
コード例 #8
0
 /// <summary>Snippet for RunQuery</summary>
 public void RunQuery_RequestObject()
 {
     // Snippet: RunQuery(RunQueryRequest,CallSettings)
     // Create client
     DatastoreClient datastoreClient = DatastoreClient.Create();
     // Initialize request argument(s)
     RunQueryRequest request = new RunQueryRequest
     {
         ProjectId   = "",
         PartitionId = new PartitionId(),
     };
     // Make the request
     RunQueryResponse response = datastoreClient.RunQuery(request);
     // End snippet
 }
コード例 #9
0
 /// <summary>Snippet for BeginTransaction</summary>
 public void BeginTransactionRequestObject()
 {
     // Snippet: BeginTransaction(BeginTransactionRequest, CallSettings)
     // Create client
     DatastoreClient datastoreClient = DatastoreClient.Create();
     // Initialize request argument(s)
     BeginTransactionRequest request = new BeginTransactionRequest
     {
         ProjectId          = "",
         TransactionOptions = new TransactionOptions(),
     };
     // Make the request
     BeginTransactionResponse response = datastoreClient.BeginTransaction(request);
     // End snippet
 }
コード例 #10
0
 public void Lookup_RequestObject()
 {
     // Snippet: Lookup(LookupRequest,CallSettings)
     // Create client
     DatastoreClient datastoreClient = DatastoreClient.Create();
     // Initialize request argument(s)
     LookupRequest request = new LookupRequest
     {
         ProjectId = "",
         Keys      = { },
     };
     // Make the request
     LookupResponse response = datastoreClient.Lookup(request);
     // End snippet
 }
コード例 #11
0
        private void AddSampleBooks()
        {
            var client     = DatastoreClient.Create();
            var keyFactory = new KeyFactory(ProjectId, NamespaceId, BookKind);
            var entity     = new Entity
            {
                Key                  = keyFactory.CreateKey("pride_and_prejudice"),
                ["title"]            = "Pride and Prejudice",
                ["publication_date"] = new DateTime(1813, 1, 28, 0, 0, 0, DateTimeKind.Utc),
                ["author"]           = "Jane Austen"
            };
            var response = client.Commit(ProjectId, CommitRequest.Types.Mode.NonTransactional, new[] { entity.ToInsert() });

            _prideAndPrejudiceKey = response.MutationResults[0].Key;
        }
コード例 #12
0
 /// <summary>Snippet for AllocateIds</summary>
 public void AllocateIds_RequestObject()
 {
     // Snippet: AllocateIds(AllocateIdsRequest,CallSettings)
     // Create client
     DatastoreClient datastoreClient = DatastoreClient.Create();
     // Initialize request argument(s)
     AllocateIdsRequest request = new AllocateIdsRequest
     {
         ProjectId = "",
         Keys      = { },
     };
     // Make the request
     AllocateIdsResponse response = datastoreClient.AllocateIds(request);
     // End snippet
 }
コード例 #13
0
        public async Task <IEnumerable <WeatherForecast> > Get()
        {
            var host    = _configuration.GetValue <string>("EMULATOR_HOST");
            var project = _configuration.GetValue <string>("PROJECT_ID");

            var channel = new Channel(host, 8081, ChannelCredentials.Insecure);
            var client  = DatastoreClient.Create(channel); //FirestoreClient.Create(channel);
            //var db = FirestoreDb.Create("test-project", client);

            var db = DatastoreDb.Create(project, "", client);

            var rng      = new Random();
            var forecast = new WeatherForecast
            {
                Date         = DateTime.UtcNow,
                TemperatureC = rng.Next(-20, 55),
                Summary      = Summaries[rng.Next(Summaries.Length)]
            };

            var entity = new Entity()
            {
                Key              = db.CreateKeyFactory("Forecast").CreateIncompleteKey(),
                ["Date"]         = forecast.Date,
                ["TemperatureC"] = forecast.TemperatureC,
                ["Summary"]      = forecast.Summary
            };

            entity.Key = db.CreateKeyFactory("Forecast").CreateIncompleteKey();
            var keys = db.Insert(new[] { entity });


            var results = await db.RunQueryAsync(new Query("Forecast"));

            var forecasts = new List <WeatherForecast>();

            foreach (var result in results.Entities)
            {
                forecasts.Add(new WeatherForecast
                {
                    Date         = result.Properties["Date"].TimestampValue.ToDateTime(),
                    TemperatureC = (int)result.Properties["TemperatureC"].IntegerValue,
                    Summary      = result.Properties["Summary"].StringValue
                });
            }


            return(forecasts);
        }
コード例 #14
0
        public void NamespaceQuery()
        {
            string projectId = _fixture.ProjectId;

            // Sample: NamespaceQuery
            DatastoreClient  client      = DatastoreClient.Create();
            PartitionId      partitionId = new PartitionId(projectId);
            RunQueryResponse response    = client.RunQuery(projectId, partitionId, null,
                                                           new Query(DatastoreConstants.NamespaceKind));

            foreach (EntityResult result in response.Batch.EntityResults)
            {
                Console.WriteLine(result.Entity.Key.Path.Last().Name);
            }
            // End sample
        }
コード例 #15
0
        public async Task RunQueryAsync2()
        {
            // Snippet: RunQueryAsync(string,PartitionId,ReadOptions,GqlQuery,CallSettings)
            // Additional: RunQueryAsync(string,PartitionId,ReadOptions,GqlQuery,CancellationToken)
            // Create client
            DatastoreClient datastoreClient = DatastoreClient.Create();
            // Initialize request argument(s)
            string      projectId   = "";
            PartitionId partitionId = new PartitionId();
            ReadOptions readOptions = new ReadOptions();
            GqlQuery    gqlQuery    = new GqlQuery();
            // Make the request
            RunQueryResponse response = await datastoreClient.RunQueryAsync(projectId, partitionId, readOptions, gqlQuery);

            // End snippet
        }
コード例 #16
0
        // Used by TransactionReadAndWrite. Could promote to the fixture.
        private Key CreateAccount(string name, long balance)
        {
            string          projectId   = _fixture.ProjectId;
            string          namespaceId = _fixture.NamespaceId;
            DatastoreClient client      = DatastoreClient.Create();
            KeyFactory      factory     = new KeyFactory(projectId, namespaceId, "Account");
            Entity          entity      = new Entity
            {
                Key         = factory.CreateIncompleteKey(),
                ["name"]    = name,
                ["balance"] = balance
            };
            CommitResponse response = client.Commit(projectId, Mode.NonTransactional, new[] { entity.ToInsert() });

            return(response.MutationResults[0].Key);
        }
コード例 #17
0
        public async Task CommitAsync2()
        {
            // Snippet: CommitAsync(string,CommitRequest.Types.Mode,IEnumerable<Mutation>,CallSettings)
            // Additional: CommitAsync(string,CommitRequest.Types.Mode,IEnumerable<Mutation>,CancellationToken)
            // Create client
            DatastoreClient datastoreClient = DatastoreClient.Create();
            // Initialize request argument(s)
            string projectId = "";

            CommitRequest.Types.Mode mode      = CommitRequest.Types.Mode.Unspecified;
            IEnumerable <Mutation>   mutations = new List <Mutation>();
            // Make the request
            CommitResponse response = await datastoreClient.CommitAsync(projectId, mode, mutations);

            // End snippet
        }
コード例 #18
0
 public void Commit_RequestObject()
 {
     // Snippet: Commit(CommitRequest,CallSettings)
     // Create client
     DatastoreClient datastoreClient = DatastoreClient.Create();
     // Initialize request argument(s)
     CommitRequest request = new CommitRequest
     {
         ProjectId = "",
         Mode      = CommitRequest.Types.Mode.Unspecified,
         Mutations = { },
     };
     // Make the request
     CommitResponse response = datastoreClient.Commit(request);
     // End snippet
 }
コード例 #19
0
        public async Task BeginTransactionAsync_RequestObject()
        {
            // Snippet: BeginTransactionAsync(BeginTransactionRequest,CallSettings)
            // Create client
            DatastoreClient datastoreClient = await DatastoreClient.CreateAsync();

            // Initialize request argument(s)
            BeginTransactionRequest request = new BeginTransactionRequest
            {
                ProjectId = "",
            };
            // Make the request
            BeginTransactionResponse response = await datastoreClient.BeginTransactionAsync(request);

            // End snippet
        }
コード例 #20
0
 /// <summary>Snippet for ReserveIds</summary>
 public void ReserveIdsRequestObject()
 {
     // Snippet: ReserveIds(ReserveIdsRequest, CallSettings)
     // Create client
     DatastoreClient datastoreClient = DatastoreClient.Create();
     // Initialize request argument(s)
     ReserveIdsRequest request = new ReserveIdsRequest
     {
         Keys       = { new Key(), },
         ProjectId  = "",
         DatabaseId = "",
     };
     // Make the request
     ReserveIdsResponse response = datastoreClient.ReserveIds(request);
     // End snippet
 }
コード例 #21
0
        public void RunQuery()
        {
            string      projectId   = _fixture.ProjectId;
            PartitionId partitionId = _fixture.PartitionId;

            // Snippet: RunQuery(RunQueryRequest,*)
            DatastoreClient client = DatastoreClient.Create();

            RunQueryRequest request = new RunQueryRequest
            {
                ProjectId   = projectId,
                PartitionId = partitionId,
                ReadOptions = new ReadOptions {
                    ReadConsistency = ReadConsistency.Eventual
                },
            };

            // Structured query
            request.Query = new Query("book")
            {
                Filter = Filter.Equal("author", "Jane Austen")
            };
            RunQueryResponse response = client.RunQuery(request);

            foreach (EntityResult result in response.Batch.EntityResults)
            {
                Console.WriteLine(result.Entity);
            }

            // Equivalent GQL query
            request.GqlQuery = new GqlQuery
            {
                QueryString   = "SELECT * FROM book WHERE author = @author",
                NamedBindings = { { "author", "Jane Austen" } },
            };
            foreach (EntityResult result in response.Batch.EntityResults)
            {
                Console.WriteLine(result.Entity);
            }
            // End snippet

            Assert.Equal(1, response.Batch.EntityResults.Count);
            Entity entity = response.Batch.EntityResults[0].Entity;

            Assert.Equal("Jane Austen", (string)entity["author"]);
            Assert.Equal("Pride and Prejudice", (string)entity["title"]);
        }
コード例 #22
0
        public void LookupEntity()
        {
            string projectId = _fixture.ProjectId;
            Key    key       = _fixture.LearnDatastoreKey;

            // Sample: LookupEntity
            DatastoreClient client   = DatastoreClient.Create();
            LookupResponse  response = client.Lookup(
                projectId,
                new ReadOptions {
                ReadConsistency = ReadConsistency.Eventual
            },
                new[] { key });

            Entity entity = response.Found[0].Entity;
            // End sample
        }
コード例 #23
0
        public async Task LookupAsync_RequestObject()
        {
            // Snippet: LookupAsync(LookupRequest,CallSettings)
            // Create client
            DatastoreClient datastoreClient = await DatastoreClient.CreateAsync();

            // Initialize request argument(s)
            LookupRequest request = new LookupRequest
            {
                ProjectId = "",
                Keys      = { },
            };
            // Make the request
            LookupResponse response = await datastoreClient.LookupAsync(request);

            // End snippet
        }
コード例 #24
0
        public void Dispose()
        {
            var client = DatastoreClient.Create();
            // Delete all the entities in our partition.
            // TODO: Transactions? Paging?
            var query = new Query {
                Projection = { new Projection {
                                   Property = new PropertyReference{
                                       Name = "__key__"
                                   }
                               } }
            };
            var response  = client.RunQuery(ProjectId, PartitionId, null, query);
            var deletions = response.Batch.EntityResults.Select(entityResult => entityResult.Entity.ToDelete());

            client.Commit(ProjectId, CommitRequest.Types.Mode.NonTransactional, deletions);
        }
コード例 #25
0
        private void AddSampleTasks()
        {
            var client     = DatastoreClient.Create();
            var keyFactory = new KeyFactory(ProjectId, NamespaceId, TaskKind);
            var entity     = new Entity
            {
                Key                  = keyFactory.CreateIncompleteKey(),
                ["category"]         = "Personal",
                ["done"]             = false,
                ["priority"]         = 4,
                ["description"]      = "Learn Cloud Datastore",
                ["percent_complete"] = 75.0
            };
            var response = client.Commit(ProjectId, CommitRequest.Types.Mode.NonTransactional, new[] { entity.ToInsert() });

            _learnDatastoreKey = response.MutationResults[0].Key;
        }
コード例 #26
0
        public async Task AllocateIdsAsync_RequestObject()
        {
            // Snippet: AllocateIdsAsync(AllocateIdsRequest,CallSettings)
            // Create client
            DatastoreClient datastoreClient = await DatastoreClient.CreateAsync();

            // Initialize request argument(s)
            AllocateIdsRequest request = new AllocateIdsRequest
            {
                ProjectId = "",
                Keys      = { },
            };
            // Make the request
            AllocateIdsResponse response = await datastoreClient.AllocateIdsAsync(request);

            // End snippet
        }
コード例 #27
0
        public async Task RollbackAsync_RequestObject()
        {
            // Snippet: RollbackAsync(RollbackRequest,CallSettings)
            // Create client
            DatastoreClient datastoreClient = await DatastoreClient.CreateAsync();

            // Initialize request argument(s)
            RollbackRequest request = new RollbackRequest
            {
                ProjectId   = "",
                Transaction = ByteString.CopyFromUtf8(""),
            };
            // Make the request
            RollbackResponse response = await datastoreClient.RollbackAsync(request);

            // End snippet
        }
コード例 #28
0
        public async Task RunQueryAsync_RequestObject()
        {
            // Snippet: RunQueryAsync(RunQueryRequest,CallSettings)
            // Create client
            DatastoreClient datastoreClient = await DatastoreClient.CreateAsync();

            // Initialize request argument(s)
            RunQueryRequest request = new RunQueryRequest
            {
                ProjectId   = "",
                PartitionId = new PartitionId(),
            };
            // Make the request
            RunQueryResponse response = await datastoreClient.RunQueryAsync(request);

            // End snippet
        }
コード例 #29
0
        /// <summary>Snippet for AllocateIdsAsync</summary>
        public async Task AllocateIdsRequestObjectAsync()
        {
            // Snippet: AllocateIdsAsync(AllocateIdsRequest, CallSettings)
            // Additional: AllocateIdsAsync(AllocateIdsRequest, CancellationToken)
            // Create client
            DatastoreClient datastoreClient = await DatastoreClient.CreateAsync();

            // Initialize request argument(s)
            AllocateIdsRequest request = new AllocateIdsRequest
            {
                Keys      = { new Key(), },
                ProjectId = "",
            };
            // Make the request
            AllocateIdsResponse response = await datastoreClient.AllocateIdsAsync(request);

            // End snippet
        }
コード例 #30
0
        /// <summary>Snippet for RollbackAsync</summary>
        public async Task RollbackRequestObjectAsync()
        {
            // Snippet: RollbackAsync(RollbackRequest, CallSettings)
            // Additional: RollbackAsync(RollbackRequest, CancellationToken)
            // Create client
            DatastoreClient datastoreClient = await DatastoreClient.CreateAsync();

            // Initialize request argument(s)
            RollbackRequest request = new RollbackRequest
            {
                Transaction = ByteString.Empty,
                ProjectId   = "",
            };
            // Make the request
            RollbackResponse response = await datastoreClient.RollbackAsync(request);

            // End snippet
        }