Beispiel #1
0
        public List <Notification> GetUnreadNotificationsForUser(string userId)
        {
            var query = new Query(Kind)
            {
                Filter = Filter.And(Filter.Equal("user_id", userId), Filter.Equal("is_read", false)),
                Order  = { { "created_at", PropertyOrder.Types.Direction.Descending } }
            };

            var results       = _db.RunQueryLazily(query).GetAllResults();
            var notifications = new List <Notification>();

            foreach (Entity entity in results.Entities)
            {
                notifications.Add(new Notification
                {
                    Key       = entity.Key,
                    CreatedAt = (DateTime)entity["created_at"],
                    IsRead    = (bool)entity["is_read"],
                    Text      = (string)entity["text"],
                    UserId    = (string)entity["user_id"]
                });
            }

            return(notifications);
        }
Beispiel #2
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
        }
Beispiel #3
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"]);
        }
Beispiel #4
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
        }
Beispiel #5
0
        public void OnGet()
        {
            DatastoreDb db = GoogleCloudDatastore.CreateDb();

            // 查詢現有貝工
            Query query       = new Query("Employee");
            var   allEmployee = db.RunQueryLazily(query);
            int   count       = allEmployee.Count();

            Employees = allEmployee.ToList();

            Message = "員工資料新增/修改/刪除作業";
        }
Beispiel #6
0
        public void NamespaceQuery()
        {
            string projectId = _fixture.ProjectId;

            // Sample: NamespaceQuery
            DatastoreDb db    = DatastoreDb.Create(projectId, "");
            Query       query = new Query(DatastoreConstants.NamespaceKind);

            foreach (Entity entity in db.RunQueryLazily(query))
            {
                Console.WriteLine(entity.Key.Path.Last().Name);
            }
            // End sample
        }
Beispiel #7
0
        public IEnumerable <Employee> Get()
        {
            List <Employee> EmployeeList = new List <Employee>();
            DatastoreDb     Db           = GoogleCloudDatastore.CreateDb();

            // 查詢現有貝工
            Query QueryInstance = new Query("Employee");
            var   AllEmployee   = Db.RunQueryLazily(QueryInstance);

            foreach (Entity EntityInstance in AllEmployee.ToList())
            {
                EmployeeList.Add(new Employee(EntityInstance));
            }

            return(EmployeeList);
        }
Beispiel #8
0
        public void ProjectionQuery()
        {
            string projectId   = _fixture.ProjectId;
            string namespaceId = _fixture.NamespaceId;

            // Sample: ProjectionQuery
            Query query = new Query("Task")
            {
                Projection = { "priority", "percentage_complete" }
            };
            DatastoreDb db = DatastoreDb.Create(projectId, namespaceId);

            foreach (Entity entity in db.RunQueryLazily(query))
            {
                Console.WriteLine($"{(int)entity["priority"]}: {(double?)entity["percentage_complete"]}");
            }
            // End sample
        }
Beispiel #9
0
        public void QueryOverview()
        {
            string projectId   = _fixture.ProjectId;
            string namespaceId = _fixture.NamespaceId;
            // Sample: QueryOverview
            DatastoreDb db = DatastoreDb.Create(projectId, namespaceId);

            // Print the messages created in the last 5 minutes, most recent first
            DateTime cutoff = DateTime.UtcNow.AddMinutes(-5);
            Query    query  = new Query("message")
            {
                Filter = Filter.GreaterThanOrEqual("created", cutoff),
                Order  = { { "created", Direction.Descending } }
            };

            foreach (Entity entity in db.RunQueryLazily(query))
            {
                DateTime created = (DateTime)entity["created"];
                string   text    = (string)entity["text"];
                Console.WriteLine($"{created:yyyy-MM-dd'T'HH:mm:ss}: {text}");
            }
            // End sample
        }
Beispiel #10
0
        public void CompositeFilterQuery()
        {
            string projectId   = _fixture.ProjectId;
            string namespaceId = _fixture.NamespaceId;

            // Sample: CompositeFilter
            Query query = new Query("Task")
            {
                Filter = Filter.And(
                    Filter.Equal("done", false),
                    Filter.GreaterThanOrEqual("priority", 4)
                    ),
                Order = { { "priority", Direction.Descending } },
            };

            DatastoreDb db = DatastoreDb.Create(projectId, namespaceId);

            foreach (Entity entity in db.RunQueryLazily(query))
            {
                Console.WriteLine((string)entity["description"]);
            }
            // TODO: Results beyond this batch?
            // End sample
        }
Beispiel #11
0
        public IActionResult QuestionList()
        {
            // Instantiates a client
            DatastoreDb     db        = DatastoreDb.Create(projectId);
            List <Question> questions = new List <Question>();
            // The kind for the new entity
            string     kind       = "Questions";
            KeyFactory keyFactory = db.CreateKeyFactory(kind);
            Query      query      = new Query("Questions");

            //{
            //    Projection = { "Author" }//, "Quiz", "Title", "Answer1", "Answer2", "Answer3" , "Answer4", "CorrectAnswer"}
            //};
            //{
            //    Filter = Filter.And(Filter.Equal("done", false),
            //    Filter.GreaterThanOrEqual("priority", 4)),
            //    Order = { { "priority", PropertyOrder.Types.Direction.Descending } }
            //};
            //DatastoreQueryResults tasks = db.RunQuery(query);
            foreach (var entity in db.RunQueryLazily(query))
            {
                Question ques = new Question
                {
                    Author        = entity["Author"].StringValue,
                    Quiz          = entity["Quiz"].StringValue,
                    Title         = entity["Title"].StringValue,
                    Answer1       = entity["Answer1"].StringValue,
                    Answer2       = entity["Answer2"].StringValue,
                    Answer3       = entity["Answer3"].StringValue,
                    Answer4       = entity["Answer4"].StringValue,
                    CorrectAnswer = entity["CorrectAnswer"].StringValue
                };
                questions.Add(ques);
            }
            return(View(questions));
        }
        /// <summary>
        /// The main loop of a Task that periodically cleans up expired sessions.
        /// Never returns.
        /// </summary>
        private async Task SweepTaskMain()
        {
            var random     = System.Security.Cryptography.RandomNumberGenerator.Create();
            var randomByte = new byte[1];

            while (true)
            {
                random.GetBytes(randomByte);
                // Not a perfect distrubution, but fine for our limited purposes.
                int randomMinute = randomByte[0] % 60;
                _log.DebugFormat("Delaying {0} minutes before checking sweep lock.", randomMinute);
                await Task.Delay(TimeSpan.FromMinutes(randomMinute));

                // Use a lock to make sure no clients are sweeping at the same time, or
                // sweeping more often than once per hour.
                try
                {
                    using (var transaction = await _datastore.BeginTransactionAsync(_callSettings))
                    {
                        const string SWEEP_BEGIN_DATE = "beginDate",
                                     SWEEPER          = "sweeper",
                                     SWEEP_LOCK_KIND  = "SweepLock";
                        var    key       = _datastore.CreateKeyFactory(SWEEP_LOCK_KIND).CreateKey(1);
                        Entity sweepLock = await transaction.LookupAsync(key, _callSettings) ??
                                           new Entity()
                        {
                            Key = key
                        };
                        bool sweep = true;
                        try
                        {
                            sweep =
                                DateTime.UtcNow - ((DateTime)sweepLock[SWEEP_BEGIN_DATE]) > TimeSpan.FromHours(1);
                        }
                        catch (Exception e)
                        {
                            _log.Error("Error reading sweep begin date.", e);
                        }
                        if (!sweep)
                        {
                            _log.Debug("Not yet time to sweep.");
                            continue;
                        }
                        sweepLock[SWEEP_BEGIN_DATE] = DateTime.UtcNow;
                        sweepLock[SWEEPER]          = Environment.MachineName;
                        transaction.Upsert(sweepLock);
                        await transaction.CommitAsync(_callSettings);
                    }
                }
                catch (Exception e)
                {
                    _log.Error("Error acquiring sweep lock.", e);
                    continue;
                }
                try
                {
                    _log.Info("Beginning sweep.");
                    // Find old sessions to clean up
                    var now   = DateTime.UtcNow;
                    var query = new Query(SESSION_LOCK_KIND)
                    {
                        Filter     = Filter.LessThan(EXPIRES, now),
                        Projection = { "__key__" }
                    };
                    foreach (Entity lockEntity in _datastore.RunQueryLazily(query))
                    {
                        try
                        {
                            using (var transaction = _datastore.BeginTransaction(_callSettings))
                            {
                                var sessionLock =
                                    SessionLockFromEntity(transaction.Lookup(lockEntity.Key, _callSettings));
                                if (sessionLock == null || sessionLock.ExpirationDate > now)
                                {
                                    continue;
                                }
                                transaction.Delete(lockEntity.Key,
                                                   _sessionKeyFactory.CreateKey(lockEntity.Key.Path.First().Name));
                                transaction.Commit(_callSettings);
                            }
                        }
                        catch (Exception e)
                        {
                            _log.Error("Failed to delete session.", e);
                        }
                    }
                    _log.Info("Done sweep.");
                }
                catch (Exception e)
                {
                    _log.Error("Failed to query expired sessions.", e);
                }
            }
        }
Beispiel #13
0
        public void OnGet()
        {
            /* *****************************************************************
            *  // Your Google Cloud Platform project ID
            *  string projectId = "howzgcp004";
            *
            *  // Instantiates a client
            *  DatastoreDb db = DatastoreDb.Create(projectId);
            ***************************************************************** */

            DatastoreDb db = GoogleCloudDatastore.CreateDb();

            /* *****************************************************************
            *  // 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"]}");
            *  }
            ***************************************************************** */



            Query query = new Query("Beer")
            {
                Filter = Filter.Equal("Brand", "TOOL")
            };

            foreach (Entity entity in db.RunQueryLazily(query))
            {
                string   beerBrand     = (string)entity["Brand"];
                string   beerName      = (string)entity["Name"];
                int      beerCost      = (int)entity["Cost"];
                int      beerPrice     = (int)entity["Price"];
                DateTime beerStockDate = (DateTime)entity["StockDate"];
                Console.WriteLine("Brand:{0} Name:{1} Cost:{2} Price:{3} StockDate:{4} ",
                                  beerBrand, beerName, beerCost, beerPrice, beerStockDate);

                entity.Key      = db.CreateKeyFactory("Beer").CreateIncompleteKey();
                entity["Brand"] = beerBrand + " again";
                var keys = db.Upsert(new[] { entity });
                Console.WriteLine("Beer Id: {0}", keys.First().Path.First().Id);
            }


            var task = new Entity
            {
                Key      = db.CreateKeyFactory("Task").CreateIncompleteKey(),
                ["memo"] = "買牛奶"
            };
            var taskkeys = db.Insert(new[] { task });

            Console.WriteLine("Task Id: {0}", taskkeys.First().Path.First().Id);

            var employee = new Entity
            {
                Key          = db.CreateKeyFactory("Employee").CreateIncompleteKey(),
                ["PersonId"] = "A123901930",
                ["Name"]     = "陳小寶"
            };
            var employeeKeys = db.Insert(new[] { employee });

            Console.WriteLine("Employee Id: {0}, Employee Kind: {1}", employeeKeys.First().Path.First().Id, employeeKeys.First().Path.First().Kind);

            Message = "Your Goole Cloud Platform Test page. (測試beer and task and employee)";
        }