private CurrentPrice getCurrentPrice(int id)
        {
            CurrentPrice currentPriceObject = new CurrentPrice();

            DatastoreDb db         = DatastoreDb.Create(projectId, "ProductNamespace", datastoreClient);
            KeyFactory  keyFactory = db.CreateKeyFactory(kind);
            string      name       = id + "";
            Key         key        = keyFactory.CreateKey(name);

            using (DatastoreTransaction transaction = db.BeginTransaction())
            {
                Entity currentProduct = transaction.Lookup(key);
                transaction.Commit();
                Value price, currency_code;
                if (currentProduct.Properties.TryGetValue("price", out price))
                {
                    currentPriceObject.value = price.DoubleValue;
                }
                if (currentProduct.Properties.TryGetValue("currency_code", out currency_code))
                {
                    currentPriceObject.currency_code = currency_code.StringValue;
                }
            }
            return(currentPriceObject);
        }
Exemple #2
0
        public void DeleteEntity()
        {
            string projectId   = _fixture.ProjectId;
            string namespaceId = _fixture.NamespaceId;

            // Copied from InsertEntity; we want to create a new one to delete.
            DatastoreDb insertClient = DatastoreDb.Create(projectId, namespaceId);
            KeyFactory  keyFactory   = insertClient.CreateKeyFactory("Task");
            Entity      entity       = new Entity
            {
                Key                  = keyFactory.CreateIncompleteKey(),
                ["category"]         = "Personal",
                ["done"]             = false,
                ["priority"]         = 4,
                ["description"]      = "Learn Cloud Datastore",
                ["percent_complete"] = 75.0
            };
            Key insertedKey = insertClient.Insert(entity);

            // Sample: DeleteEntity
            DatastoreDb db = DatastoreDb.Create(projectId, namespaceId);

            // If you have an entity instead of just a key, then entity.ToDelete() would work too.
            db.Delete(insertedKey);
            // End sample
        }
Exemple #3
0
        public void PaginateWithCursor()
        {
            string projectId   = _fixture.ProjectId;
            string namespaceId = _fixture.NamespaceId;

            ByteString pageCursor = null;
            int        pageSize   = 5;
            // Sample: PaginateWithCursor
            Query query = new Query("Task")
            {
                Limit = pageSize, StartCursor = pageCursor ?? ByteString.Empty
            };
            DatastoreDb db = DatastoreDb.Create(projectId, namespaceId);

            DatastoreQueryResults results = db.RunQueryLazily(query, ReadConsistency.Eventual).GetAllResults();

            foreach (Entity entity in results.Entities)
            {
                // Do something with the task entity
            }
            if (results.MoreResults == MoreResultsType.MoreResultsAfterLimit)
            {
                ByteString nextPageCursor = results.EndCursor;
                // Store nextPageCursor to get the next page later.
            }
            // End sample
        }
Exemple #4
0
        public async Task EagerGqlQueryAsync()
        {
            string projectId   = _fixture.ProjectId;
            string namespaceId = _fixture.NamespaceId;

            // Snippet: RunQueryAsync(GqlQuery,*,*)
            DatastoreDb db       = DatastoreDb.Create(projectId, namespaceId);
            GqlQuery    gqlQuery = new GqlQuery
            {
                QueryString   = "SELECT * FROM book WHERE author = @author",
                NamedBindings = { { "author", new GqlQueryParameter {
                                        Value = "Jane Austen"
                                    } } },
            };
            DatastoreQueryResults results = await db.RunQueryAsync(gqlQuery);

            // RunQuery fetches all the results into memory in a single call.
            // Constrast this with RunQueryLazily, which merely prepares an enumerable
            // query. Always specify a limit when you use RunQuery, to avoid running
            // out of memory.
            foreach (Entity entity in results.Entities)
            {
                Console.WriteLine(entity);
            }
            // End snippet

            // This will run the query again, admittedly...
            Assert.Equal(1, results.Entities.Count);
            Entity book = results.Entities[0];

            Assert.Equal("Jane Austen", (string)book["author"]);
            Assert.Equal("Pride and Prejudice", (string)book["title"]);
        }
Exemple #5
0
        public async Task AddEntity_NonTransactional_Async()
        {
            string projectId   = _fixture.ProjectId;
            string namespaceId = _fixture.NamespaceId;

            // Snippet: InsertAsync(*)
            DatastoreDb db         = DatastoreDb.Create(projectId, namespaceId);
            KeyFactory  keyFactory = db.CreateKeyFactory("book");
            Entity      book1      = new Entity
            {
                Key                  = keyFactory.CreateIncompleteKey(),
                ["author"]           = "Harper Lee",
                ["title"]            = "To Kill a Mockingbird",
                ["publication_date"] = new DateTime(1960, 7, 11, 0, 0, 0, DateTimeKind.Utc),
                ["genres"]           = new[] { "Southern drama", "Courtroom drama", "Bildungsroman" }
            };
            Entity book2 = new Entity
            {
                Key                  = keyFactory.CreateIncompleteKey(),
                ["author"]           = "Charlotte Brontë",
                ["title"]            = "Jane Eyre",
                ["publication_date"] = new DateTime(1847, 10, 16, 0, 0, 0, DateTimeKind.Utc),
                ["genres"]           = new[] { "Gothic", "Romance", "Bildungsroman" }
            };
            IReadOnlyList <Key> insertedKeys = await db.InsertAsync(book1, book2);

            Console.WriteLine($"Inserted keys: {string.Join(",", insertedKeys)}");
            // End snippet
        }
        private async Task CommitTest(Func <DatastoreTransaction, Task <CommitResponse> > commitCall)
        {
            var db            = DatastoreDb.Create(_fixture.ProjectId, _fixture.NamespaceId);
            var keyFactory    = db.CreateKeyFactory("book");
            var updatedEntity = new Entity {
                Key = keyFactory.CreateIncompleteKey(), ["description"] = "Inserted before transaction"
            };

            db.Insert(updatedEntity);

            Entity insertedEntity = new Entity {
                Key = keyFactory.CreateIncompleteKey(), ["description"] = "Inserted in transaction"
            };
            Entity upsertedEntity = new Entity {
                Key = keyFactory.CreateIncompleteKey(), ["description"] = "Upserted in transaction"
            };

            using (var transaction = db.BeginTransaction())
            {
                transaction.Insert(insertedEntity);
                transaction.Upsert(upsertedEntity);
                updatedEntity["description"] = "Updated in transaction";
                transaction.Update(updatedEntity);
                await commitCall(transaction);
            }

            // Check we can fetch with the newly allocated keys
            var entities     = db.Lookup(insertedEntity.Key, upsertedEntity.Key, updatedEntity.Key);
            var descriptions = entities.Select(e => (string)e["description"]);

            Assert.Equal(new[] { "Inserted in transaction", "Upserted in transaction", "Updated in transaction" }, descriptions);
        }
Exemple #7
0
        public async Task LazyGqlQueryAsync()
        {
            string projectId   = _fixture.ProjectId;
            string namespaceId = _fixture.NamespaceId;

            // Snippet: RunQueryLazilyAsync(GqlQuery,*,*)
            DatastoreDb db       = DatastoreDb.Create(projectId, namespaceId);
            GqlQuery    gqlQuery = new GqlQuery
            {
                QueryString   = "SELECT * FROM book WHERE author = @author",
                NamedBindings = { { "author", new GqlQueryParameter {
                                        Value = "Jane Austen"
                                    } } },
            };
            AsyncLazyDatastoreQuery results = db.RunQueryLazilyAsync(gqlQuery);
            // AsyncLazyDatastoreQuery implements IAsyncEnumerable<Entity>, but you can
            // call AsResponses() to see the raw RPC responses, or
            // GetAllResultsAsync() to get all the results into memory, complete with
            // the end cursor and the reason for the query finishing.
            await results.ForEachAsync(entity =>
            {
                Console.WriteLine(entity);
            });

            // End snippet

            // This will run the query again, admittedly...
            List <Entity> entities = await results.ToList();

            Assert.Equal(1, entities.Count);
            Entity book = entities[0];

            Assert.Equal("Jane Austen", (string)book["author"]);
            Assert.Equal("Pride and Prejudice", (string)book["title"]);
        }
Exemple #8
0
        public async Task AsyncQueries()
        {
            var db         = DatastoreDb.Create(_fixture.ProjectId, _fixture.NamespaceId);
            var keyFactory = db.CreateKeyFactory("asyncqueries");

            using (var transaction = await db.BeginTransactionAsync())
            {
                var entities = Enumerable.Range(0, 5)
                               .Select(x => new Entity {
                    Key = keyFactory.CreateIncompleteKey(), ["x"] = x
                })
                               .ToList();
                transaction.Insert(entities);
                await transaction.CommitAsync();
            }

            var query = new Query("asyncqueries")
            {
                Filter = Filter.LessThan("x", 3)
            };
            var gql = new GqlQuery {
                QueryString = "SELECT * FROM asyncqueries WHERE x < 3", AllowLiterals = true
            };

            ValidateQueryResults((await db.RunQueryAsync(gql)).Entities);
            ValidateQueryResults((await db.RunQueryAsync(query)).Entities);
            ValidateQueryResults(db.RunQueryLazilyAsync(query).ToEnumerable());
            ValidateQueryResults(db.RunQueryLazilyAsync(gql).ToEnumerable());
        }
Exemple #9
0
        public async Task InsertAsync_ResultKeys()
        {
            var db         = DatastoreDb.Create(_fixture.ProjectId, _fixture.NamespaceId);
            var keyFactory = db.CreateKeyFactory("insertasync_test");
            var entities   = new[]
            {
                new Entity {
                    Key = keyFactory.CreateKey("x"), ["description"] = "predefined_key"
                },
                new Entity {
                    Key = keyFactory.CreateIncompleteKey(), ["description"] = "incomplete_key"
                }
            };

            var keys = await db.InsertAsync(entities);

            Assert.Null(keys[0]);    // Insert with predefined key
            Assert.NotNull(keys[1]); // Insert with incomplete key

            // Inserted key is propagated into entity
            Assert.Equal(keys[1], entities[1].Key);

            var fetchedEntity = await db.LookupAsync(keys[1]);

            Assert.Equal("incomplete_key", fetchedEntity["description"]);
        }
Exemple #10
0
        public DatastoreDbProvider(IConfigurationService configurationService, IDataEntityObjectFactory dataEntityObjectFactory)
        {
            var project = configurationService.Get("DATASTOREDB_PROJECT");

            _db = DatastoreDb.Create(project);
            _dataEntityObjectFactory = dataEntityObjectFactory;
        }
        public static void Main(string[] args)
        {
            // Your Google Cloud Platform project ID
            string projectId = "YOUR-PROJECT-ID";

            // Instantiates a client
            DatastoreDb db = DatastoreDb.Create(projectId);

            // The kind for the new entity
            string kind = "Task";
            // The name/ID for the new entity
            string name = "sampletask1";
            KeyFactory keyFactory = db.CreateKeyFactory(kind);
            // The Cloud Datastore key for the new entity
            Key key = keyFactory.CreateKey(name);

            var task = new Entity
            {
                Key = key,
                ["description"] = "Buy milk"
            };
            using (DatastoreTransaction transaction = db.BeginTransaction())
            {
                // Saves the task
                transaction.Upsert(task);
                transaction.Commit();

                Console.WriteLine($"Saved {task.Key.Path[0].Name}: {(string)task["description"]}");
            }
        }
Exemple #12
0
        protected override void ProcessRecord()
        {
            base.ProcessRecord();
            var db = DatastoreDb.Create(Project);

            using (var transaction = db.BeginTransaction())
            {
                switch (Action)
                {
                case "Insert":
                    returnKey = db.Insert(Entity);
                    break;

                case "Update":
                    db.Update(Entity);
                    break;

                case "Upsert":
                    returnKey = db.Upsert(Entity);
                    break;

                default:
                    var e  = new ArgumentException();
                    var er = new ErrorRecord(e, "UnknownAction", ErrorCategory.InvalidArgument, Action);
                    ThrowTerminatingError(er);
                    break;
                }

                WriteObject(returnKey);
            }
        }
        public void TimestampFromProjection()
        {
            var    db         = DatastoreDb.Create(_fixture.ProjectId, _fixture.NamespaceId);
            string kind       = "projection_test";
            var    keyFactory = db.CreateKeyFactory(kind);

            DateTime sampleTimestamp = new DateTime(2018, 12, 3, 15, 8, 32, 123, DateTimeKind.Utc);

            using (var transaction = db.BeginTransaction())
            {
                transaction.Insert(new Entity {
                    Key = keyFactory.CreateIncompleteKey(), ["ts"] = sampleTimestamp, ["ignore"] = "ignore me"
                });
                transaction.Commit();
            }

            var query = new Query(kind)
            {
                Projection = { "ts" }
            };
            var results = db.RunQuery(query).Entities;

            Assert.Equal(1, results.Count);
            Assert.Equal(sampleTimestamp, results[0]["ts"].ToDateTimeFromProjection());
            Assert.Equal((DateTimeOffset)sampleTimestamp, results[0]["ts"].ToDateTimeOffsetFromProjection());
        }
Exemple #14
0
        public ActionResult Index()
        {
            var dbStore = DatastoreDb.Create("programming-for-the-cloud"); //getting an instance of the database

            Query q = new Query("Username");

            var            resultOfQuery = dbStore.RunQuery(q);
            List <UserLog> userlogs      = new List <UserLog>();

            foreach (var user in resultOfQuery.Entities)
            {
                UserLog log = new UserLog()
                {
                    Id       = user.Key.Path.First().Id,
                    Key      = user.Key.ToString(),
                    Email    = user["email"].StringValue,
                    LoggedOn = user["loggedOn"].TimestampValue.ToDateTime(),
                };
                try
                {
                    log.LoggedOut = user["loggedOut"].IsNull ? (DateTime?)null : user["loggedOut"].TimestampValue.ToDateTime();
                }
                catch
                {
                }
                userlogs.Add(log);
            }
            return(View(userlogs));
        }
Exemple #15
0
        public void Lookup()
        {
            string projectId   = _fixture.ProjectId;
            string namespaceId = _fixture.NamespaceId;

            // Snippet: Lookup(Key[])
            DatastoreDb db         = DatastoreDb.Create(projectId, namespaceId);
            KeyFactory  keyFactory = db.CreateKeyFactory("message");
            Entity      message    = new Entity {
                Key = keyFactory.CreateIncompleteKey(), ["text"] = "Original"
            };

            db.Insert(message);

            using (DatastoreTransaction transaction = db.BeginTransaction())
            {
                // Look the message up at the start of the transaction
                Entity fetched1 = transaction.Lookup(message.Key);
                Console.WriteLine((string)fetched1["text"]);  // "Original"

                // Update the message outside the transaction
                message["text"] = "Updated";
                db.Update(message);

                // Look up the message up again. We are guaranteed not to see the
                // update because it occurred after the start of the transaction.
                Entity fetched2 = transaction.Lookup(message.Key);
                Console.WriteLine((string)fetched2["text"]);  // Still "Original"
            }
            // End snippet
        }
Exemple #16
0
        public void Query_ImplicitlyUsesPartition()
        {
            var db         = DatastoreDb.Create(_fixture.ProjectId, _fixture.NamespaceId);
            var keyFactory = db.CreateKeyFactory("parent");
            var parent     = new Entity
            {
                Key = keyFactory.CreateIncompleteKey()
            };
            var parentKey = db.Insert(parent);

            var child = new Entity
            {
                Key = parentKey.WithElement(new PathElement {
                    Kind = "child"
                }),
            };

            db.Insert(child);
            using (var transaction = db.BeginTransaction())
            {
                var query = new Query("child")
                {
                    Filter = Filter.HasAncestor(parentKey)
                };
                var results = transaction.RunQueryLazily(query);
                Assert.Equal(1, results.Count());
            }
        }
Exemple #17
0
        static void CreateMovies()
        {
            //Project Id from the Project at GCP
            string projectId = "<your-project-id>";
            //We are storing movies. So this is a Movie kind.
            string kind = "Movie";

            //Create the datastore db
            var db = DatastoreDb.Create(projectId);

            //List of movies
            List <Entity> movieEntities = new List <Entity>();

            //I need 10 movies
            for (int i = 1; i <= 10; i++)
            {
                movieEntities.Add(
                    new Entity
                {
                    Key              = db.CreateKeyFactory(kind).CreateKey($"key{i}"),
                    ["title"]        = $"Movie Title {i}",
                    ["releasedYear"] = 2018,
                    ["director"]     = $"Director {i}"
                }
                    );
            }

            //Lets send the movies to the datastore
            using (var transction = db.BeginTransaction())
            {
                transction.Upsert(movieEntities);
                transction.Commit();
            }
        }
        public GcpDataStoreFixture()
        {
            var builder = new ConfigurationBuilder()
                          .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                          .AddEnvironmentVariables();
            var config = builder.Build();


            var services = new ServiceCollection();

            services.AddGcpDatastore();
            services.AddSingleton <IConfiguration>(config);
            var toRemove = services.Single(s => s.ServiceType == typeof(DataStoreKind));

            services.Remove(toRemove);
            services.AddSingleton(new DataStoreKind(Kind));

            var sp = services.BuildServiceProvider();

            var gcpConfig = sp.GetRequiredService <IOptions <GcpDatastoreConfig> >().Value;

            Db              = DatastoreDb.Create(gcpConfig.ProjectId);
            KeyFactory      = Db.CreateKeyFactory(Kind);
            MqttIntentStore = (GcpDatastoreMqttIntentStore)sp.GetRequiredService <IMqttIntentStore>();
        }
        private async Task AsyncQueries_ImplicityUsePartition()
        {
            var db        = DatastoreDb.Create(_fixture.ProjectId, _fixture.NamespaceId);
            var parentKey = PrepareQueryTest(db);

            using (var transaction = db.BeginTransaction())
            {
                var query = new Query("childKind")
                {
                    Filter = Filter.HasAncestor(parentKey)
                };
                var gql = new GqlQuery
                {
                    QueryString        = "SELECT * FROM childKind WHERE __key__ HAS ANCESTOR @1",
                    PositionalBindings = { new GqlQueryParameter {
                                               Value = parentKey
                                           } }
                };
                var lazyResults = transaction.RunQueryLazilyAsync(query);
                Assert.Equal(1, await lazyResults.Count());
                lazyResults = transaction.RunQueryLazilyAsync(gql);
                Assert.Equal(1, await lazyResults.Count());

                var eagerResults = await transaction.RunQueryAsync(query);

                Assert.Equal(1, eagerResults.Entities.Count);
                eagerResults = await transaction.RunQueryAsync(gql);

                Assert.Equal(1, eagerResults.Entities.Count);
            }
        }
Exemple #20
0
 public DataService(GcpConfiguration config)
 {
     _db         = DatastoreDb.Create(config.ProjectId);
     _storage    = StorageClient.Create();
     _keyFactory = _db.CreateKeyFactory(Kind);
     _bucketName = config.BucketName;
 }
Exemple #21
0
        public async Task EagerStructuredQueryAsync()
        {
            string projectId   = _fixture.ProjectId;
            string namespaceId = _fixture.NamespaceId;

            // Snippet: RunQueryAsync(Query,*,*)
            DatastoreDb db    = DatastoreDb.Create(projectId, namespaceId);
            Query       query = new Query("book")
            {
                Filter = Filter.Equal("author", "Jane Austen")
            };
            DatastoreQueryResults results = await db.RunQueryAsync(query);

            // RunQuery fetches all the results into memory in a single call.
            // Constrast this with RunQueryLazily, which merely prepares an enumerable
            // query. Always specify a limit when you use RunQuery, to avoid running
            // out of memory.
            foreach (Entity entity in results.Entities)
            {
                Console.WriteLine(entity);
            }
            // End snippet

            // This will run the query again, admittedly...
            Assert.Equal(1, results.Entities.Count);
            Entity book = results.Entities[0];

            Assert.Equal("Jane Austen", (string)book["author"]);
            Assert.Equal("Pride and Prejudice", (string)book["title"]);
        }
Exemple #22
0
        public void Upsert_ResultKeys()
        {
            var db          = DatastoreDb.Create(_fixture.ProjectId, _fixture.NamespaceId);
            var keyFactory  = db.CreateKeyFactory("upsert_test");
            var insertedKey = db.Insert(new Entity {
                Key = keyFactory.CreateIncompleteKey(), ["description"] = "original"
            });

            var revisedEntity = new Entity {
                Key = insertedKey, ["description"] = "changed"
            };
            var newEntity1 = new Entity {
                Key = keyFactory.CreateKey("x"), ["description"] = "predefined_key"
            };
            var newEntity2 = new Entity {
                Key = keyFactory.CreateIncompleteKey(), ["description"] = "incomplete_key"
            };

            var keys = db.Upsert(revisedEntity, newEntity1, newEntity2);

            Assert.Null(keys[0]);    // Update
            Assert.Null(keys[1]);    // Insert with predefined key
            Assert.NotNull(keys[2]); // Insert with incomplete key

            var fetchedEntity = db.Lookup(keys[2]);

            Assert.Equal("incomplete_key", fetchedEntity["description"]);
        }
Exemple #23
0
        public void AddEntity_Transactional()
        {
            string projectId   = _fixture.ProjectId;
            string namespaceId = _fixture.NamespaceId;

            // Sample: AddEntity
            DatastoreDb db         = DatastoreDb.Create(projectId, namespaceId);
            KeyFactory  keyFactory = db.CreateKeyFactory("book");
            Entity      book1      = new Entity
            {
                Key                  = keyFactory.CreateIncompleteKey(),
                ["author"]           = "Harper Lee",
                ["title"]            = "To Kill a Mockingbird",
                ["publication_date"] = new DateTime(1960, 7, 11, 0, 0, 0, DateTimeKind.Utc),
                ["genres"]           = new[] { "Southern drama", "Courtroom drama", "Bildungsroman" }
            };
            Entity book2 = new Entity
            {
                Key                  = keyFactory.CreateIncompleteKey(),
                ["author"]           = "Charlotte Brontë",
                ["title"]            = "Jane Eyre",
                ["publication_date"] = new DateTime(1847, 10, 16, 0, 0, 0, DateTimeKind.Utc),
                ["genres"]           = new[] { "Gothic", "Romance", "Bildungsroman" }
            };

            using (DatastoreTransaction transaction = db.BeginTransaction())
            {
                transaction.Insert(book1, book2);
                CommitResponse    response     = transaction.Commit();
                IEnumerable <Key> insertedKeys = response.MutationResults.Select(r => r.Key);
                Console.WriteLine($"Inserted keys: {string.Join(",", insertedKeys)}");
            }
            // End sample
        }
Exemple #24
0
        public void Lookup_NoPartition()
        {
            // Deliberately in the empty namespace, which won't be cleaned up automatically - hence the db.Delete call later.
            var db         = DatastoreDb.Create(_fixture.ProjectId);
            var keyFactory = db.CreateKeyFactory("test");
            var entity     = new Entity
            {
                Key     = keyFactory.CreateIncompleteKey(),
                ["foo"] = "bar"
            };
            var insertedKey = db.Insert(entity);

            try
            {
                var lookupKey = new Key {
                    Path = { insertedKey.Path }
                };
                var result = db.Lookup(lookupKey);
                Assert.NotNull(result);
                Assert.Equal("bar", (string)entity["foo"]);
            }
            finally
            {
                db.Delete(insertedKey);
            }
        }
Exemple #25
0
        public void InsertOverview()
        {
            string projectId   = _fixture.ProjectId;
            string namespaceId = _fixture.NamespaceId;
            // Sample: InsertOverview
            DatastoreDb db = DatastoreDb.Create(projectId, namespaceId);

            KeyFactory keyFactory = db.CreateKeyFactory("message");
            Entity     entity     = new Entity
            {
                Key         = keyFactory.CreateIncompleteKey(),
                ["created"] = DateTime.UtcNow,
                ["text"]    = "Text of the message",
                ["tags"]    = new[] { "tag1", "tag2" }
            };

            using (DatastoreTransaction transaction = db.BeginTransaction())
            {
                transaction.Insert(entity);
                CommitResponse commitResponse = transaction.Commit();
                Key            insertedKey    = commitResponse.MutationResults[0].Key;
                Console.WriteLine($"Inserted key: {insertedKey}");
                // The key is also propagated to the entity
                Console.WriteLine($"Entity key: {entity.Key}");
            }
            // End sample
        }
Exemple #26
0
        public void EagerGqlQuery()
        {
            string projectId   = _fixture.ProjectId;
            string namespaceId = _fixture.NamespaceId;

            // Snippet: RunQuery(GqlQuery,*)
            DatastoreDb db         = DatastoreDb.Create(projectId, namespaceId);
            KeyFactory  keyFactory = db.CreateKeyFactory("player");

            // Prepare the data: a player with two game child entities
            Entity player = new Entity
            {
                Key      = keyFactory.CreateIncompleteKey(),
                ["name"] = "Sophie"
            };
            Key    playerKey = db.Insert(player);
            Entity game1     = new Entity
            {
                Key = playerKey.WithElement(new PathElement {
                    Kind = "game"
                }),
                ["score"]     = 10,
                ["timestamp"] = new DateTime(2017, 2, 16, 8, 35, 0, DateTimeKind.Utc)
            };
            Entity game2 = new Entity
            {
                Key = playerKey.WithElement(new PathElement {
                    Kind = "game"
                }),
                ["score"]     = 25,
                ["timestamp"] = new DateTime(2017, 3, 15, 10, 35, 0, DateTimeKind.Utc)
            };

            db.Insert(game1, game2);

            // Perform a query within a transaction
            using (DatastoreTransaction transaction = db.BeginTransaction())
            {
                // Any query executed in a transaction must at least have an ancestor filter.
                GqlQuery query = new GqlQuery
                {
                    QueryString   = "SELECT * FROM game WHERE __key__ HAS ANCESTOR @player LIMIT @limit",
                    NamedBindings =
                    {
                        { "player", playerKey },
                        { "limit",         10 }
                    }
                };
                DatastoreQueryResults results = db.RunQuery(query);
                // RunQuery fetches all the results into memory in a single call.
                // Constrast this with RunQueryLazily, which merely prepares an enumerable
                // query. Always specify a limit when you use RunQuery, to avoid running
                // out of memory.
                foreach (Entity entity in results.Entities)
                {
                    Console.WriteLine(entity);
                }
            }
            // End snippet
        }
Exemple #27
0
        public void LazyStructuredQuery()
        {
            string projectId   = _fixture.ProjectId;
            string namespaceId = _fixture.NamespaceId;

            // Snippet: RunQueryLazily(Query,*,*)
            DatastoreDb db    = DatastoreDb.Create(projectId, namespaceId);
            Query       query = new Query("book")
            {
                Filter = Filter.Equal("author", "Jane Austen")
            };
            LazyDatastoreQuery results = db.RunQueryLazily(query);

            // LazyDatastoreQuery implements IEnumerable<Entity>, but you can
            // call AsResponses() to see the raw RPC responses, or
            // GetAllResults() to get all the results into memory, complete with
            // the end cursor and the reason for the query finishing.
            foreach (Entity entity in results)
            {
                Console.WriteLine(entity);
            }
            // End snippet

            // This will run the query again, admittedly...
            List <Entity> entities = results.ToList();

            Assert.Equal(1, entities.Count);
            Entity book = entities[0];

            Assert.Equal("Jane Austen", (string)book["author"]);
            Assert.Equal("Pride and Prejudice", (string)book["title"]);
        }
Exemple #28
0
        public void Commit()
        {
            string projectId   = _fixture.ProjectId;
            string namespaceId = _fixture.NamespaceId;

            // Snippet: Commit
            // Additional: Insert(Entity[])
            DatastoreDb db         = DatastoreDb.Create(projectId, namespaceId);
            KeyFactory  keyFactory = db.CreateKeyFactory("message");

            using (DatastoreTransaction transaction = db.BeginTransaction())
            {
                Entity entity = new Entity
                {
                    Key         = keyFactory.CreateIncompleteKey(),
                    ["message"] = "Hello"
                };
                // This adds the entity to a collection in memory: nothing
                // is sent to the server.
                transaction.Insert(entity);
                // Without the Commit call, the transaction will automatically
                // be rolled back. The Commit call performs all the mutations
                // within the transaction.
                transaction.Commit();
            }
            // End snippet
        }
Exemple #29
0
        public void TransactionReadAndWrite()
        {
            string projectId   = _fixture.ProjectId;
            string namespaceId = _fixture.NamespaceId;
            long   amount      = 1000L;
            Key    fromKey     = CreateAccount("Jill", 20000L);
            Key    toKey       = CreateAccount("Beth", 15500L);

            // Sample: TransactionReadAndWrite
            DatastoreDb db = DatastoreDb.Create(projectId, namespaceId);

            using (DatastoreTransaction transaction = db.BeginTransaction())
            {
                // The return value from DatastoreTransaction.Get contains the fetched entities
                // in the same order as they are in the call.
                IReadOnlyList <Entity> entities = transaction.Lookup(fromKey, toKey);
                Entity from = entities[0];
                Entity to   = entities[1];
                from["balance"] = (long)from["balance"] - amount;
                to["balance"]   = (long)to["balance"] - amount;
                transaction.Update(from);
                transaction.Update(to);
                transaction.Commit();
            }
            // End sample
        }
 public GroceryListController()
 {
     System.Environment.SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS", "E:\\Downloads\\My Project-5b01a7686bd6.json");
     projectId   = "cellular-datum-186719";
     _db         = DatastoreDb.Create(projectId);
     _keyFactory = _db.CreateKeyFactory("GroceryList");
 }