Esempio n. 1
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
        }
Esempio n. 2
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
        }
Esempio n. 3
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
            // Additional: BeginTransaction(*)
            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 static void Main(string[] args)
        {
            // Your Google Cloud Platform project ID
            string projectId = "ordrcoffee";

            // 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"]}");
            }
        }
Esempio n. 5
0
 public void StoreEntity(Entity e)
 {
     e.Key.PartitionId = new PartitionId(projectId, namespaceId);
     using (DatastoreTransaction transaction = db.BeginTransaction())
     {
         transaction.Upsert(e);
         transaction.Commit();
     }
 }
Esempio n. 6
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
        }
Esempio n. 7
0
        public void EagerStructuredQuery()
        {
            string projectId   = _fixture.ProjectId;
            string namespaceId = _fixture.NamespaceId;

            // Snippet: RunQuery(Query,*)
            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.
                Query query = new Query("game")
                {
                    Filter = Filter.HasAncestor(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
        }
        private void upsert(DatastoreDb db, Entity entity)
        {
            GrpcEnvironment.SetLogger(new ConsoleLogger());

            using (DatastoreTransaction transaction = db.BeginTransaction())
            {
                transaction.Upsert(entity);
                transaction.Commit();
            }
        }
        public void Upsert(ApiKey apiKey)
        {
            var entity = apiKey.ToEntity();

            using (DatastoreTransaction transaction = _db.BeginTransaction())
            {
                entity.Key = _db.CreateKeyFactory("ApiKey").CreateKey(apiKey.Id);
                transaction.Upsert(entity);
                transaction.Commit();
            }
        }
Esempio n. 10
0
        // [END add_entity]

        // [START update_entity]
        /// <summary>
        /// Marks a task entity as done.
        /// </summary>
        /// <param name="id">The ID of the task entity as given by Key.</param>
        /// <returns>true if the task was found.</returns>
        bool MarkDone(long id)
        {
            using (var transaction = _db.BeginTransaction())
            {
                Entity task = transaction.Lookup(_keyFactory.CreateKey(id));
                if (task != null)
                {
                    task["done"] = true;
                    transaction.Update(task);
                }
                transaction.Commit();
                return(task != null);
            }
        }
        public ActionResult Put(int id, [FromBody] ProductObject product)
        {
            if (id != product.id)
            {
                return(BadRequest("PUT id is different from json body productid"));
            }            //ProductObject product = JsonConvert.DeserializeObject<ProductObject>(value);
            DatastoreDb db            = DatastoreDb.Create(projectId, "ProductNamespace", datastoreClient);
            string      name          = product.id + "";
            double      price         = product.current_price.value;
            string      currency_code = product.current_price.currency_code;
            KeyFactory  keyFactory    = db.CreateKeyFactory(kind);
            Key         key           = keyFactory.CreateKey(name);

            using (DatastoreTransaction transaction = db.BeginTransaction())
            {
                Entity currentProduct = transaction.Lookup(key);
                transaction.Commit();
                Value productid;
                if (currentProduct == null || !currentProduct.Properties.TryGetValue("productid", out productid))
                {
                    return(NotFound("Productid:" + name + " does not exist"));
                }
            }
            var task = new Entity
            {
                Key               = key,
                ["productid"]     = name,
                ["price"]         = price,
                ["currency_code"] = currency_code
            };

            try
            {
                upsert(db, task);
            }
            catch (Exception e) {
                if (Debugger.IsAttached)
                {
                    return(Content("Productid:" + name + " might not be updated.\n" + e.StackTrace));
                }
                else
                {
                    return(BadRequest("Productid:" + name + " might not be updated.\n"));
                }
            }

            return(Ok("Productid:" + name + " is updated"));
        }
Esempio n. 12
0
        public void InsertBD(string InsertTweet, string[] tweetScore, DateTime fecha, Tweetinvi.Models.IPlace lugar)
        {
            #region db access
            ///////////////////////////////////////////// db access ///////////////////////////////////
            string credential_path = @"C:\Users\Javier\Downloads\IMAPBD-Misc\Sentiment analisis\imapbd\IMAPBD\IMAPBD\OAuth\IMAPBD - Load-db-access.json";
            System.Environment.SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS", credential_path);

            string projectID = "imapbd-load";

            DatastoreDb db   = DatastoreDb.Create(projectID, "");
            string      kind = "Lugar_Tweet";

            KeyFactory keyFactory = db.CreateKeyFactory(kind);
            Key        key        = keyFactory.CreateIncompleteKey();

            Entity task = new Entity();
            task.Key = key;
            task.Properties.Add("tweet", InsertTweet);

            task.Properties.Add("tedioso", Convert.ToDouble(tweetScore[0]));
            task.Properties.Add("malo", Convert.ToDouble(tweetScore[1]));
            task.Properties.Add("bueno", Convert.ToDouble(tweetScore[2]));
            task.Properties.Add("regular", Convert.ToDouble(tweetScore[3]));

            task.Properties.Add("dia", fecha.DayOfWeek.ToString());
            task.Properties.Add("mes", fecha.Month);
            task.Properties.Add("anio", fecha.Year);
            if (string.IsNullOrEmpty(lugar.Name))
            {
                task.Properties.Add("lugar", "");
            }
            else
            {
                task.Properties.Add("lugar", lugar.Name);
            }

            task.Properties.Add("lugar", lugar.Name);
            task.Properties.Add("pais", lugar.Country);


            using (DatastoreTransaction transaction = db.BeginTransaction())
            {
                transaction.Upsert(task);
                transaction.Commit();
            }
            ///////////////////////////////////////////// db access ///////////////////////////////////
            #endregion
        }
Esempio n. 13
0
 public void UpdateGroceryItem(long id, [FromBody] GroceryList gl)
 {
     using (var transaction = _db.BeginTransaction())
     {
         Entity groceryItem = transaction.Lookup(_keyFactory.CreateKey(id));
         if (groceryItem != null)
         {
             groceryItem["GroceryName"] = gl.GroceryName;
             groceryItem["Quantity"]    = gl.Quantity;
             groceryItem["Shareable"]   = gl.Shareable;
             transaction.Update(groceryItem);
         }
         ;
         transaction.Commit();
     }     //end "using"
 }
Esempio n. 14
0
 // [START transactional_update]
 private void TransferFunds(Key fromKey, Key toKey, long amount)
 {
     using (var transaction = _db.BeginTransaction())
     {
         var entities = transaction.Lookup(fromKey, toKey);
         entities[0]["balance"].IntegerValue -= amount;
         entities[1]["balance"].IntegerValue += amount;
         transaction.Update(entities);
         transaction.Commit();
     }
 }
Esempio n. 15
0
        public void UpdateEntity()
        {
            string projectId   = _fixture.ProjectId;
            string namespaceId = _fixture.NamespaceId;
            Key    key         = _fixture.LearnDatastoreKey;

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

            using (DatastoreTransaction transaction = db.BeginTransaction())
            {
                Entity entity = transaction.Lookup(key);
                entity["priority"] = 5;
                transaction.Update(entity);
                transaction.Commit();
            }
            // End sample
        }
Esempio n. 16
0
        private async Task <bool> UpdateGameState(GameState item)
        {
            using (var transaction = _db.BeginTransaction())
            {
                Entity entity = _db.Lookup(_keyFactory.CreateKey(Convert.ToInt64(item.PlatformKey)));
                if (entity != null)
                {
                    entity["CurrentLevel"] = item.CurrentLevel;
                    entity["Health"]       = item.Health;
                    entity["Inventory"]    = JsonConvert.SerializeObject(item.Inventory, Formatting.None);

                    transaction.Update(entity);
                }
                await transaction.CommitAsync();

                return(entity != null);
            }
        }
Esempio n. 17
0
        public static void Main(string[] args)
        {
            // Your Google Cloud Platform project ID
            string projectId = "czreadbook";

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

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

            var contenttmp = @"这才多长时间过去,当年那个都不曾被他们注意、没有放在眼中的小土著,竟在短短的一年内从圣者层次突破到神级领域,位列神将之巅,震撼人心。

他们惶恐了,这种进化速度就是在阳间也吓死人,除非古代那几个特殊时期,不然的话怎能出现?

在阴间宇宙中,法则不全,天地残缺,此外还有“天花板”,最高不过映照级,他居然能走到这一步,逆天了吗?

噗!

楚风的剑翼扇动,如同一个十二羽翼的神王,呼啸天地间,再次将一位神祇的头颅斩落,根本就没有人能挡住他。";
            var task       = new Entity
            {
                Key                 = key,
                ["url"]             = "https://www.piaotian.com/html/8/8253/6290265.html",
                ["content"]         = contenttmp,
                ["create_date"]     = DateTimeOffset.Now,
                ["last_upate_date"] = DateTimeOffset.Now,
            };

            using (DatastoreTransaction transaction = db.BeginTransaction())
            {
                // Saves the task
                transaction.Upsert(task);
                transaction.Commit();

                Console.WriteLine($"Saved {task.Key.Path[0].Name}: {(string)task["url"]}");
            }
        }
Esempio n. 18
0
        public void Upsert()
        {
            string projectId   = _fixture.ProjectId;
            string namespaceId = _fixture.NamespaceId;

            // Snippet: Upsert(Entity[])
            DatastoreDb db         = DatastoreDb.Create(projectId, namespaceId);
            KeyFactory  keyFactory = db.CreateKeyFactory("book");
            Entity      book1      = 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(book1);

            using (DatastoreTransaction transaction = db.BeginTransaction())
            {
                // Correct the typo in memory
                book1["title"] = "To Kill a Mockingbird";

                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" }
                };

                // This adds the entities to a collection of mutations in memory: nothing
                // is sent to the server.
                transaction.Upsert(book1, book2);
                // 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
        }
Esempio n. 19
0
        public void DeleteEntity()
        {
            string projectId   = _fixture.ProjectId;
            string namespaceId = _fixture.NamespaceId;

            // Snippet: 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);

            using (DatastoreTransaction transaction = db.BeginTransaction())
            {
                // This adds the entity key to a collection of mutations in memory: nothing
                // is sent to the server. 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[]) or
                // a similar overload.
                transaction.Delete(message);
                // Without the Commit call, the transaction will automatically
                // be rolled back. The Commit call performs all the mutations
                // within the transaction.
                transaction.Commit();
            }

            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);
        }
 public override void CreateUninitializedItem(HttpContext context, string id, int timeout)
 {
     _log.DebugFormat("CreateUninitializedItem({0})", id);
     LogExceptions("CreateUninitializedItem()", () =>
     {
         var sessionLock              = new SessionLockEntity();
         sessionLock.Id               = id;
         sessionLock.ExpirationDate   = DateTime.UtcNow.AddMinutes(timeout);
         sessionLock.TimeOutInMinutes = timeout;
         sessionLock.DateLocked       = DateTime.UtcNow;
         sessionLock.LockCount        = 0;
         using (new LifetimeTimer(_log, "CreateUninitializedItem", 25))
             using (var transaction = _datastore.BeginTransaction(_callSettings))
             {
                 transaction.Upsert(ToEntity(sessionLock));
                 transaction.Delete(_sessionKeyFactory.CreateKey(id));
                 transaction.Commit(_callSettings);
             }
     });
 }
Esempio n. 21
0
        public ActionResult <object> Register([FromBody] User user)
        {
            Environment.SetEnvironmentVariable(
                "GOOGLE_APPLICATION_CREDENTIALS",
                Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "fsndigital-cred.json"));

            DatastoreDb db = DatastoreDb.Create("fsndigital", "Users", DatastoreClient.Create());

            string kind = "user";

            KeyFactory keyFactory = db.CreateKeyFactory(kind);
            Key        key        = keyFactory.CreateKey(user.Email);

            var task = new Entity
            {
                Key          = key,
                ["TypeId"]   = user.TypeId,
                ["UserName"] = user.UserName,
                ["Email"]    = user.Email,
                ["Password"] = user.Password,
            };

            Entity check = db.Lookup(task.Key);

            if (check != null)
            {
                return(Ok(new { succeeded = false, message = "An account with that email already exists." }));
            }



            using (DatastoreTransaction transaction = db.BeginTransaction())
            {
                transaction.Upsert(task);
                transaction.Commit();
            }

            return(Ok(new { succeeded = true }));
        }
Esempio n. 22
0
        public void Save(T obj)
        {
            DatastoreDb db = DatastoreDb.Create("fantasyfootball-204922", "default");

            KeyFactory keyFactory = db.CreateKeyFactory(obj.Kind);
            Entity     entity     = new Entity
            {
                Key         = keyFactory.CreateKey(obj.id),
                ["updated"] = DateTime.UtcNow,
                ["text"]    = JsonConvert.SerializeObject(obj),
                ["tags"]    = obj.Tags.ToArray()
            };

            using (DatastoreTransaction transaction = db.BeginTransaction())
            {
                transaction.Upsert(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}");
            }
        }
Esempio n. 23
0
        public void Update()
        {
            string projectId   = _fixture.ProjectId;
            string namespaceId = _fixture.NamespaceId;

            // Snippet: Update(Entity[])
            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);

            using (DatastoreTransaction transaction = db.BeginTransaction())
            {
                // Correct the typo in memory
                book["title"] = "To Kill a Mockingbird";
                // This adds the entity to a collection of mutations in memory: nothing
                // is sent to the server.
                transaction.Update(book);
                // 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

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

            Assert.Equal("To Kill a Mockingbird", (string)fetched["title"]);
        }
Esempio n. 24
0
        public void Firebase_Connection()
        {
            string path = AppDomain.CurrentDomain.BaseDirectory + @"safe-zone-child-firebase-adminsdk-mq2cq-8ea2101a36.json";

            Environment.SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS", path);

            // Your Google Cloud Platform project ID.
            string projectId = "safe-zone-child";

            // 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"] = "8888Buy 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"]}");
            }
        }
Esempio n. 25
0
        public IActionResult CreateQuestion(Question ques)
        {
            // Instantiates a client
            DatastoreDb db = DatastoreDb.Create(projectId);

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

            var task = new Entity
            {
                Key               = keyFactory.CreateIncompleteKey(),
                ["Author"]        = ques.Author,
                ["Quiz"]          = ques.Quiz,
                ["Title"]         = ques.Title,
                ["Answer1"]       = ques.Answer1,
                ["Answer2"]       = ques.Answer2,
                ["Answer3"]       = ques.Answer3,
                ["Answer4"]       = ques.Answer4,
                ["CorrectAnswer"] = ques.CorrectAnswer
            };

            using (DatastoreTransaction transaction = db.BeginTransaction())
            {
                // Saves the task
                task.Key = db.Insert(task);
                //transaction.Upsert(task);
                transaction.Commit();

                Console.WriteLine($"Saved {task.Key.Path[0].Name}: {(string)task["Quiz"]}");
            }

            return(RedirectToAction("QuestionList", "Home"));
        }