Пример #1
0
        public void DeleteAll <T>()
        {
            var query   = new Query(typeof(T).Name);
            var results = _db.RunQuery(query);

            _db.Delete(results.Entities);
        }
        public static Entity GetUserData(string userid)
        {
            var query = new Query("IcyWind")
            {
                Filter = Filter.Equal("uid", userid)
            };
            var data = db.RunQuery(query);

            return(data.Entities.First());
        }
        public IEnumerable <Key> FindKeys(Filter filter)
        {
            var query = new Query(_kind)
            {
                Filter     = filter,
                Projection = { "__key__" }
            };
            var results = _database.RunQuery(query);

            return(results.Entities.Select(x => x.Key));
        }
Пример #4
0
        public T ReadFirstOrDefault <T>(Filter filter) where T : class
        {
            Query query = new Query(GetKind <T>())
            {
                Filter = filter
            };

            var result = _db.RunQuery(query);

            return(result.Entities.Select(e => FromEntity <T>(e)).ToList().FirstOrDefault());
        }
Пример #5
0
        public void EagerStructuredQuery()
        {
            string projectId   = _fixture.ProjectId;
            string namespaceId = _fixture.NamespaceId;

            // Snippet: RunQuery(Query,*,*)
            DatastoreDb db    = DatastoreDb.Create(projectId, namespaceId);
            Query       query = new Query("book")
            {
                Filter = Filter.Equal("author", "Jane Austen"),
                Limit  = 10
            };
            // 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.
            DatastoreQueryResults results = db.RunQuery(query);

            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"]);
        }
        // [START list]
        public PlaceList List(int pageSize, string nextPageToken, string userId = null, GeoCoordinate coordinates = null)
        {
            var query = new Query("Place")
            {
                Limit = pageSize
            };

            if (userId != null)
            {
                query.Filter = Filter.Equal("CreatedById", userId);
            }
            if (coordinates != null)
            {
                query.Filter = Filter.And(
                    Filter.GreaterThan("Latitude", coordinates.MaxLatitude(100)),
                    Filter.GreaterThan("Latitude", coordinates.MinLatitude(100)),
                    Filter.GreaterThan("Longitude", coordinates.MaxLongitude(100)),
                    Filter.GreaterThan("Longitude", coordinates.MinLongitude(100))
                    );
            }
            if (!string.IsNullOrWhiteSpace(nextPageToken))
            {
                query.StartCursor = ByteString.FromBase64(nextPageToken);
            }
            var results = _db.RunQuery(query);

            return(new PlaceList()
            {
                Places = results.Entities.Select(entity => entity.ToPlace()),
                NextPageToken = results.Entities.Count == query.Limit ?
                                results.EndCursor.ToBase64() : null
            });
        }
    public void Dispose()
    {
        try
        {
            DatastoreDb datastoreDb  = DatastoreDb.Create(ProjectId, Namespace);
            var         deadEntities = datastoreDb.RunQuery(new Query(Kind));
            datastoreDb.Delete(deadEntities.Entities);
        }
        catch (Exception)
        {
            // Do nothing, we delete on a best effort basis.
        }

        try
        {
            var storage        = StorageClient.Create();
            var storageObjects = storage.ListObjects(BucketName);
            foreach (var storageObject in storageObjects)
            {
                storage.DeleteObject(BucketName, storageObject.Name);
            }
            storage.DeleteBucket(BucketName);
        }
        catch (Exception)
        {
            // Do nothing, we delete on a best effort basis.
        }
    }
Пример #8
0
        public void EagerGqlQuery()
        {
            string projectId   = _fixture.ProjectId;
            string namespaceId = _fixture.NamespaceId;

            // Snippet: RunQuery(GqlQuery,*,*)
            DatastoreDb db       = DatastoreDb.Create(projectId, namespaceId);
            GqlQuery    gqlQuery = new GqlQuery
            {
                QueryString   = "SELECT * FROM book WHERE author = @author LIMIT @limit",
                NamedBindings =
                {
                    { "author", "Jane Austen" },
                    { "limit",             10 }
                }
            };
            DatastoreQueryResults results = db.RunQuery(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"]);
        }
Пример #9
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);

            List <EntityResult> entityResults = db.RunQuery(query, ReadConsistency.Eventual).AsEntityResults().ToList();

            foreach (EntityResult result in entityResults)
            {
                Entity entity = result.Entity;
                // Do something with the task entity
            }
            // If we retrieved as many entities as we requested, there may be another page of results.
            // (There may not be any more results, but the query stopped executing when it had found
            // as many as we asked for.)
            // If we ran out of results, this is definitely the last page.
            if (entityResults.Count == pageSize)
            {
                ByteString nextPageCursor = entityResults.Last().Cursor;
                // Store nextPageCursor to get the next page later.
            }
            // End sample
        }
Пример #10
0
        public void StructuredQuery()
        {
            string projectId   = _fixture.ProjectId;
            string namespaceId = _fixture.NamespaceId;

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

            // DatastoreQueryResults implements IEnumerable<Entity>, but you can
            // call AsEntityResults(), AsBatches() or AsResponses() to see the query
            // results in whatever way makes most sense for your application.
            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"]);
        }
Пример #11
0
        public void GqlQuery()
        {
            string projectId   = _fixture.ProjectId;
            string namespaceId = _fixture.NamespaceId;

            // Snippet: RunQuery(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 = db.RunQuery(gqlQuery);

            // DatastoreQueryResults implements IEnumerable<Entity>, but you can
            // call AsEntityResults(), AsBatches() or AsResponses() to see the query
            // results in whatever way makes most sense for your application.
            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"]);
        }
Пример #12
0
        // [START list]
        public IEnumerable <T> List()
        {
            var query   = new Query(_kind);
            var results = _db.RunQuery(query);

            return(results.Entities.Select(entity => ToObject(entity)));
        }
Пример #13
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
        }
    public List <Item> ReadAll()
    {
        var query   = new Query(kind);
        var results = _db.RunQuery(query);

        return(results.Entities.Select(entity => entity.ToItem()).ToList());
    }
Пример #15
0
        // [END update_entity]

        // [START retrieve_entities]
        /// <summary>
        /// Returns a list of all task entities in ascending order of creation time.
        /// </summary>
        IEnumerable <Entity> ListTasks()
        {
            Query query = new Query("Task")
            {
                Order = { { "created", PropertyOrder.Types.Direction.Descending } }
            };

            return(_db.RunQuery(query).Entities);
        }
Пример #16
0
    public Model_Account FindAccount(string username, string discriminator)
    {
        Query query = new Query(Controller_Account.Enum.account)
        {
            Filter = Filter.And(Filter.Equal(Controller_Account.Enum.username, username),
                                Filter.Equal(Controller_Account.Enum.discriminator, discriminator))
        };
        DatastoreQueryResults results = db.RunQuery(query);

        if (results.Entities.Count == 0)
        {
            return(null);
        }
        else
        {
            return(Controller_Account.BuildController(results.Entities[0]).model);
        }
    }
Пример #17
0
        public Owner[] FindAll()
        {
            var query = new Query("owner")
            {
                Limit = 10
            };
            var results = db.RunQuery(query);

            return(results.Entities.Select(entity => entity.ToOwner()).ToArray());
        }
    static void Main(string[] args)
    {
        string      projectId = "YOUR-PROJECT-ID-HERE";
        DatastoreDb client    = DatastoreDb.Create(projectId);

        Entity shelf = new Entity
        {
            Key       = client.CreateKeyFactory("shelf").CreateIncompleteKey(),
            ["genre"] = "fiction"
        };
        Key shelfKey = client.Insert(shelf);

        // Insert a book specifying a complete key
        Entity book1 = new Entity
        {
            Key       = shelfKey.WithElement("book", "potter1"),
            ["title"] = "Harry Potter and the Philosopher's Stone"
        };
        Key book1Key = client.Insert(book1);
        // Insert a book by creating an incomplete key with the extension method
        Entity book2 = new Entity
        {
            Key       = shelfKey.WithIncompleteElement("book"),
            ["title"] = "Harry Potter and the Chamber of Secrets"
        };
        Key book2Key = client.Insert(book2);

        Console.WriteLine($"Inserted key: {book2Key}");

        // Insert a book by creating an incomplete key with a KeyFactory
        KeyFactory keyFactory = new KeyFactory(shelf, "book");
        Entity     book3      = new Entity
        {
            Key       = keyFactory.CreateIncompleteKey(),
            ["title"] = "Harry Potter and the Prisoner of Azkaban"
        };
        Key book3Key = client.Insert(book3);

        Console.WriteLine($"Inserted key: {book3Key}");
        Console.WriteLine();
        // List all the books
        var books = client.RunQuery(new Query {
            Kind = { new KindExpression {
                         Name = "book"
                     } }
        });

        Console.WriteLine("All books:");
        foreach (var book in books.Entities)
        {
            Console.WriteLine($"{(string) book["title"]}: Key={book.Key}");
        }
    }
        public ApiKey Get(string id)
        {
            Query query = new Query("ApiKey")
            {
                Filter = Filter.Equal("Id", id)
            };

            var results = _db.RunQuery(query);
            var apiKey  = results.Entities.Select(entity => entity.ToApiKey()).FirstOrDefault();

            return(apiKey);
        }
    public IActionResult OnGet()
    {
        Query query = new Query("Sports_db");
        IEnumerable <Entity> stores = _db.RunQuery(query).Entities;

        SportsStoreList = stores.Select(_ => new SportsStoreItem {
            Name  = (string)_["Name"],
            Price = (decimal)_["Price"]
        }).ToList();

        return(Page());
    }
Пример #21
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.RunQuery(query))
            {
                Console.WriteLine(entity.Key.Path.Last().Name);
            }
            // End sample
        }
Пример #22
0
        public ArrayList FindUsers(int offset, int limit)
        {
            Query query = new Query("User")
            {
                Limit  = limit,
                Offset = offset,
                Order  = { { "dob_timestamp", PropertyOrder.Types.Direction.Descending } }
            };

            IEnumerable <Entity> entities = _db.RunQuery(query).Entities;
            ArrayList            users    = new ArrayList();

            foreach (Entity entity in entities)
            {
                User user = new User();
                user.Name    = entity.Properties["name"].StringValue;
                user.Surname = entity.Properties["surname"].StringValue;
                user.Dob     = entity.Properties["dob"].StringValue;
                user.Gender  = entity.Properties["gender"].StringValue;
                users.Add(user);
            }
            return(users);
        }
        public IEnumerable <Movie> List()
        {
            var query = new Query("Movie");

            var results = _db.RunQuery(query);

            //return new MovieList()
            //{
            //    Movies = )

            //};

            return(results.Entities.Select(entity => entity.Tomovie()));
        }
Пример #24
0
    public IActionResult OnGet()
    {
        Query query = new Query("StoreList")
        {
            Order = { { "Name", PropertyOrder.Types.Direction.Descending } }
        };
        IEnumerable <Entity> stores = _db.RunQuery(query).Entities;

        SportsStoreList = stores.Select(_ => new SportsStoreItem {
            Name  = _["Name"],
            Price = _["Price"]
        }).ToList();

        return(Page());
    }
Пример #25
0
        public IActionResult GetAll()
        {
            Query query = new Query("GroceryList");

            List <GroceryList> GroceryLists = new List <GroceryList>();

            foreach (var entity in _db.RunQuery(query).Entities)
            {
                GroceryLists.Add(new GroceryList()
                {
                    GroceryListId = entity.Key.Path[0].Id.ToString(), UserId = (string)entity["UserId"], GroceryName = (string)entity["GroceryName"], Quantity = (string)entity["Quantity"], Shareable = (bool)entity["Shareable"]
                });
            }
            JsonResult jsonItem = new JsonResult(GroceryLists);

            return(jsonItem);
        }
Пример #26
0
        // [START list]
        public BookList List(int pageSize, string nextPageToken)
        {
            var query = _db.CreateQuery <Book>();

            query.Limit = pageSize;
            if (!string.IsNullOrWhiteSpace(nextPageToken))
            {
                query.StartCursor = ByteString.FromBase64(nextPageToken);
            }
            var results = _db.RunQuery(query);

            return(new BookList()
            {
                Books = results.Entities <Book>(),
                NextPageToken = results.Entities.Count == query.Limit ?
                                results.EndCursor.ToBase64() : null
            });
        }
Пример #27
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.RunQuery(query))
            {
                Console.WriteLine($"{(int)entity["priority"]}: {(double?)entity["percentage_complete"]}");
            }
            // End sample
        }
Пример #28
0
        protected virtual void Connect()
        {
            if (!isConnected)
            {
                isConnected = true;
                db          = DatastoreDb.Create(GetProjectId(), GetNamespace(), GetClient());

                // truncate the namespace ... aka remove all kinds
                var query = new Query("__kind__")
                {
                    Limit = int.MaxValue
                };

                foreach (var kindEntity in db.RunQuery(query).Entities)
                {
                    EnsureEmptyKind(kindEntity.Key.Path[0].Name);
                }
            }
        }
Пример #29
0
        // [START list]
        public BookList List(int pageSize, string nextPageToken)
        {
            var query = new Query("Book")
            {
                Limit = pageSize
            };

            if (!string.IsNullOrWhiteSpace(nextPageToken))
            {
                query.StartCursor = ByteString.FromBase64(nextPageToken);
            }
            var results = _db.RunQuery(query);

            return(new BookList()
            {
                Books = results.Entities.Select(entity => entity.ToBook()),
                NextPageToken = results.Entities.Count == query.Limit ?
                                results.EndCursor.ToBase64() : null
            });
        }
        // GET: Datastore
        public ActionResult Index()
        {
            DatastoreDb db = DatastoreDb.Create("progforthecloudt2020");

            Query query = new Query("users");

            List <Log> myLogs = new List <Log>();

            foreach (Entity entity in db.RunQuery(query).Entities)
            {
                Log myLog = new Log();
                myLog.Email        = entity["email"].StringValue;
                myLog.LastLoggedIn = entity["lastloggedin"].TimestampValue.ToDateTimeOffset().LocalDateTime;
                myLog.Id           = entity.Key.ToString();

                myLogs.Add(myLog);
            }

            return(View(myLogs));
        }