private Key BuildKey(TKey id)
        {
            var keyFactory = _database.CreateKeyFactory(_kind);

            return(typeof(TKey) == typeof(long)
                ? keyFactory.CreateKey(Convert.ToInt64(id))
                : keyFactory.CreateKey(Convert.ToString(id)));
        }
        private void SetKey(string id, string kind, DatastoreDb datastoreDb, Entity entity)
        {
            if (long.TryParse(id, out var idLong))
            {
                entity.Key = datastoreDb.CreateKeyFactory(kind).CreateKey(idLong);
                return;
            }

            entity.Key = datastoreDb.CreateKeyFactory(kind).CreateKey(id);
        }
Exemplo n.º 3
0
        // [START create]
        public long Create(T item)
        {
            KeyFactory factory = _db.CreateKeyFactory(_kind);
            var        entity  = item.ToEntity(factory);

            entity.Key = factory.CreateIncompleteKey();
            var keys = _db.Insert(new[] { entity });

            item.Id = keys.First().Path.First().Id;
            return(item.Id);
        }
Exemplo n.º 4
0
 public GroceryListController()
 {
     System.Environment.SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS", "C:\\Users\\arlin\\Desktop\\what-am-i-calling-this-project-e1c237c4aa27.json");
     projectId   = "what-am-i-calling-this-project";
     _db         = DatastoreDb.Create(projectId);
     _keyFactory = _db.CreateKeyFactory("GroceryList");
 }
Exemplo n.º 5
0
        //Main function
        static void Main()
        {
            KeyFactory _keyFactory = _db.CreateKeyFactory(entity_kind);

            //Use this code to CREATE a new KIND and KEY

            /*Entity task = new Entity()
             * {
             *  Key = _db.CreateKeyFactory(entity_kind).CreateKey(entity_key),
             *  ["UpdatedDate"] = currentDateTimeTimestampUTC
             * };
             *
             * //Insert the new Entity to Datastore
             * task.Key = _db.Insert(task);*/

            //Use this code to update a specific KIND and KEY
            Entity _sampleTask = new Entity()
            {
                Key = _keyFactory.CreateKey(entity_key),
            };

            _sampleTask["UpdatedDate"] = currentDateTimeTimestampUTC;
            _db.Update(_sampleTask);

            Console.WriteLine("Application was executed!");
        }
Exemplo n.º 6
0
        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"]}");
            }
        }
Exemplo n.º 7
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
        }
Exemplo n.º 8
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
        }
        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);
        }
Exemplo n.º 10
0
 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");
 }
Exemplo n.º 11
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
        }
Exemplo n.º 12
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
        }
Exemplo n.º 13
0
        public void DeleteKey()
        {
            string projectId   = _fixture.ProjectId;
            string namespaceId = _fixture.NamespaceId;

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

            Entity fetchedBeforeDeletion = db.Lookup(key);

            // Only the key is required to determine what to delete.
            // If you have an entity with the right key, you can use Delete(Entity, CallSettings)
            // or a similar overload for convenience.
            db.Delete(key);

            Entity fetchedAfterDeletion = db.Lookup(key);

            Console.WriteLine($"Entity exists before deletion? {fetchedBeforeDeletion != null}");
            Console.WriteLine($"Entity exists after deletion? {fetchedAfterDeletion != null}");
            // End snippet

            Assert.NotNull(fetchedBeforeDeletion);
            Assert.Null(fetchedAfterDeletion);
        }
Exemplo n.º 14
0
        public void DeleteEntity()
        {
            string projectId   = _fixture.ProjectId;
            string namespaceId = _fixture.NamespaceId;

            // Sample: DeleteEntity
            // Additional: Delete(Entity, *)
            DatastoreDb db         = DatastoreDb.Create(projectId, namespaceId);
            KeyFactory  keyFactory = db.CreateKeyFactory("message");
            Entity      message    = new Entity
            {
                Key      = keyFactory.CreateIncompleteKey(),
                ["text"] = "Hello",
            };

            db.Insert(message);

            Entity fetchedBeforeDeletion = db.Lookup(message.Key);

            // Only the key from the entity is used to determine what to delete.
            // If you already have the key but not the entity, use Delete(Key, CallSettings) or
            // a similar overload.
            db.Delete(message);

            Entity fetchedAfterDeletion = db.Lookup(message.Key);

            Console.WriteLine($"Entity exists before deletion? {fetchedBeforeDeletion != null}");
            Console.WriteLine($"Entity exists after deletion? {fetchedAfterDeletion != null}");
            // End snippet

            Assert.NotNull(fetchedBeforeDeletion);
            Assert.Null(fetchedAfterDeletion);
        }
Exemplo n.º 15
0
        public void Update()
        {
            string projectId   = _fixture.ProjectId;
            string namespaceId = _fixture.NamespaceId;

            // Snippet: Update(Entity, CallSettings)
            DatastoreDb db         = DatastoreDb.Create(projectId, namespaceId);
            KeyFactory  keyFactory = db.CreateKeyFactory("book");
            Entity      book       = new Entity
            {
                Key                  = keyFactory.CreateIncompleteKey(),
                ["author"]           = "Harper Lee",
                ["title"]            = "Tequila Mockingbird",
                ["publication_date"] = new DateTime(1960, 7, 11, 0, 0, 0, DateTimeKind.Utc),
                ["genres"]           = new[] { "Southern drama", "Courtroom drama", "Bildungsroman" }
            };

            db.Insert(book);

            // Correct the typo in memory
            book["title"] = "To Kill a Mockingbird";
            // Then update the entity in Datastore
            db.Update(book);
            // End snippet

            var fetched = db.Lookup(book.Key);

            Assert.Equal("To Kill a Mockingbird", (string)fetched["title"]);
        }
Exemplo n.º 16
0
 public DataService(GcpConfiguration config)
 {
     _db         = DatastoreDb.Create(config.ProjectId);
     _storage    = StorageClient.Create();
     _keyFactory = _db.CreateKeyFactory(Kind);
     _bucketName = config.BucketName;
 }
Exemplo n.º 17
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
        }
Exemplo n.º 18
0
        public static void CreateUser(string username, string uid, string passhash, string email, byte[] salt)
        {
            KeyFactory keyFactory = db.CreateKeyFactory("IcyWind");
            Key        key        = keyFactory.CreateKey(username);

            var task = new Entity
            {
                Key              = key,
                ["data"]         = string.Empty,
                ["salt"]         = ByteArrayToString(salt),
                ["passhash"]     = passhash,
                ["uid"]          = uid,
                ["email"]        = email,
                ["IsAdmin"]      = false,
                ["IsDonator"]    = false,
                ["Banned"]       = false,
                ["DonateAmount"] = 0
            };

            using (DatastoreTransaction transaction = db.BeginTransaction())
            {
                // Saves the task
                transaction.Upsert(task);
                transaction.Commit();
            }
        }
Exemplo n.º 19
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
        }
Exemplo n.º 20
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
        }
Exemplo n.º 21
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            string projectId = Configuration["GoogleProjectId"];

            if (new string[] { "your-project-id", "", null }.Contains(projectId))
            {
                app.Run(async(context) =>
                {
                    await context.Response.WriteAsync(@"<html>
                        <head><title>Error</title></head>
                        <body><p>Set GoogleProjectId to your project id in appsettings.json.
                              <p>See the README.md in the project directory for more information.</p>
                        </body>
                        </html>");
                });
                return;
            }

            // [START example]
            DatastoreDb datastore       = DatastoreDb.Create(projectId);
            var         visitKeyFactory = datastore.CreateKeyFactory("visit");

            // [END example]
            app.Run(async(HttpContext context) =>
            {
                // [START example]
                // Insert a visit into Datastore:
                Entity newVisit        = new Entity();
                newVisit.Key           = visitKeyFactory.CreateIncompleteKey();
                newVisit["time_stamp"] = DateTime.UtcNow;
                newVisit["ip_address"] = FormatAddress(
                    context.Connection.RemoteIpAddress);
                await datastore.InsertAsync(newVisit);

                // Look up the last 10 visits.
                var results = await datastore.RunQueryAsync(new Query("visit")
                {
                    Order = { { "time_stamp", PropertyOrder.Types.Direction.Descending } },
                    Limit = 10
                });
                await context.Response.WriteAsync(@"<html>
                    <head><title>Visitor Log</title></head>
                    <body>Last 10 visits:<br>");
                foreach (Entity visit in results.Entities)
                {
                    await context.Response.WriteAsync(string.Format("{0} {1}<br>",
                                                                    visit["time_stamp"].TimestampValue,
                                                                    visit["ip_address"].StringValue));
                }
                await context.Response.WriteAsync(@"</body></html>");
                // [END example]
            });
        }
Exemplo n.º 22
0
        // [START create]
        public void Create(Team team)
        {
            var entity = team.ToEntity();

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

            team.TeamId = keys.First().Path.First().Id;
        }
Exemplo n.º 23
0
        // [START create]
        public void Create(Place place)
        {
            var entity = place.ToEntity();

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

            place.Id = keys.First().Path.First().Id;
        }
        // [START create]
        public void Create(Movie movie)
        {
            var entity = movie.ToEntity();

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

            movie.Id = keys.First().Path.First().Id;
        }
Exemplo n.º 25
0
        public T Get(int id)
        {
            DatastoreDb db = DatastoreDb.Create("fantasyfootball-204922", "default");

            KeyFactory keyFactory = db.CreateKeyFactory("fpl_player");
            var        result     = db.Lookup(keyFactory.CreateKey(id));

            return(JsonConvert.DeserializeObject <T>(result["text"].StringValue));
        }
    public void Create(Item item)
    {
        var entity = item.ToEntity();

        entity.Key = _db.CreateKeyFactory(kind).CreateIncompleteKey();
        var keys = _db.Insert(new[] { entity });

        item.Id = keys.First().Path.First().Id;
    }
Exemplo n.º 27
0
 TaskList(string projectId)
 {
     // [START build_service]
     // Create an authorized Datastore service using Application Default Credentials.
     _db = DatastoreDb.Create(projectId);
     // Create a Key factory to construct keys associated with this project.
     _keyFactory = _db.CreateKeyFactory("Task");
     // [END build_service]
 }
Exemplo n.º 28
0
        // [START create]
        public void Create(Book book)
        {
            var entity = book.ToEntity();

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

            book.Id = keys.First().Path.First().Id;
        }
Exemplo n.º 29
0
        public void LazyGqlQuery()
        {
            string projectId   = _fixture.ProjectId;
            string namespaceId = _fixture.NamespaceId;

            // Snippet: RunQueryLazily(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",
                    NamedBindings = { { "player", playerKey } }
                };
                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
        }
Exemplo n.º 30
0
 public DatastoreTest()
 {
     _projectId  = Environment.GetEnvironmentVariable("GOOGLE_PROJECT_ID");
     _db         = DatastoreDb.Create(_projectId, TestUtil.RandomName());
     _keyFactory = _db.CreateKeyFactory("Task");
     _sampleTask = new Entity()
     {
         Key = _keyFactory.CreateKey("sampleTask"),
     };
 }