Exemplo n.º 1
0
        // Key - idContent
        // Value - Totals
        public async Task <IDictionary <string, Content> > GetPhotoTotalsByTopic(string topic)
        {
            // select All UserPhoto, where
            var   keyTopic = new Key().WithElement("TopicTotals", topic);
            Query query    = new Query("ContentTotals")
            {
                Filter = Filter.HasAncestor(keyTopic),
            };

            DatastoreQueryResults results = await Db.RunQueryAsync(query, ReadOptions.Types.ReadConsistency.Strong);

            var userPhotos = results.Entities.Select(x => x.ToContent());

            return(userPhotos.ToDictionary(x => x.IdContent, x => x));
        }
        public static async Task <IReadOnlyList <Entity> > GetAllUsersAsync()
        {
            var query = new Query("IcyWind");
            var data  = await db.RunQueryAsync(query);

            return(data.Entities);
        }
Exemplo n.º 3
0
        public async Task <TEntity[]> GetAllAsync(int limit = 1000)
        {
            var res = await _db.RunQueryAsync(new Query(_kind)
            {
                Limit = limit
            });

            return(res.Entities.Select(BuildDalEntity).ToArray());

            //var count = res.Entities.Count();
            ////UTF8Encoding encoder = new UTF8Encoding();
            ////encoder.GetString(res.EndCursor);

            //Query query = new Query("__Stat_Kind__")
            //{

            //    //Filter = new Filter
            //    //{
            //    //    PropertyFilter = new PropertyFilter
            //    //    {
            //    //        Op = PropertyFilter.Types.Operator.Equal,
            //    //        Value = "API-Version",
            //    //        Property = new PropertyReference("kind_name")
            //    //    }
            //    //}
            //};

            //var data = await _db.RunQueryAsync(query);


            //query.addFilter("kind_name", FilterOperator.EQUAL, kind);
            //Entity entityStat = datastore.prepare(query).asSingleEntity();
            //Long totalEntities = (Long)entityStat.getProperty("count");
        }
Exemplo n.º 4
0
        private async Task <(IEnumerable <Entity> Entities, string NextPageToken)> QueryGameState(ICriteria searchCriteria)
        {
            // Create our query
            var query = new Query(_tableName)
            {
                Limit  = searchCriteria.PageSize,
                Filter = Filter.And(Filter.Equal("PlayerId", searchCriteria.SearchFields["PlayerId"]),
                                    Filter.GreaterThanOrEqual("CurrentLevel", Convert.ToInt32(searchCriteria.SearchFields["CurrentLevel"]))),
                Projection = { "RecordId", "CurrentLevel", "Health", "Inventory", "GameId", "RecordCreatedAt" },
                Order      = { { "CurrentLevel",    PropertyOrder.Types.Direction.Descending },
                               { "RecordCreatedAt", PropertyOrder.Types.Direction.Descending } }
            };

            // Use NextPageState if specified
            if (!string.IsNullOrWhiteSpace(searchCriteria.NextPageState))
            {
                query.StartCursor = ByteString.FromBase64(searchCriteria.NextPageState);
            }

            // Run the query
            var results = await _db.RunQueryAsync(query);

            // Check for next page token
            var nextPageToken = results.Entities.Count == searchCriteria.PageSize ? results.EndCursor.ToBase64() : null;

            // Return the tuple
            return(results.Entities, nextPageToken);
        }
Exemplo n.º 5
0
        public async Task GqlQueryAsync()
        {
            string projectId   = _fixture.ProjectId;
            string namespaceId = _fixture.NamespaceId;

            // Snippet: RunQueryAsync(GqlQuery,*,*)
            DatastoreDb db       = DatastoreDb.Create(projectId, namespaceId);
            GqlQuery    gqlQuery = new GqlQuery
            {
                QueryString   = "SELECT * FROM book WHERE author = @author",
                NamedBindings = { { "author", new GqlQueryParameter {
                                        Value = "Jane Austen"
                                    } } },
            };
            DatastoreAsyncQueryResults results = db.RunQueryAsync(gqlQuery);
            // DatastoreAsyncQueryResults implements IAsyncEnumerable<Entity>, but you can
            // call AsEntityResults(), AsBatches() or AsResponses() to see the query
            // results in whatever way makes most sense for your application.
            await results.ForEachAsync(entity =>
            {
                Console.WriteLine(entity);
            });

            // End snippet

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

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

            Assert.Equal("Jane Austen", (string)book["author"]);
            Assert.Equal("Pride and Prejudice", (string)book["title"]);
        }
Exemplo n.º 6
0
        public async Task StructuredQueryAsync()
        {
            string projectId   = _fixture.ProjectId;
            string namespaceId = _fixture.NamespaceId;

            // Snippet: RunQueryAsync(Query,*,*)
            DatastoreDb db    = DatastoreDb.Create(projectId, namespaceId);
            Query       query = new Query("book")
            {
                Filter = Filter.Equal("author", "Jane Austen")
            };
            DatastoreAsyncQueryResults results = db.RunQueryAsync(query);
            // DatastoreAsyncQueryResults implements IAsyncEnumerable<Entity>, but you can
            // call AsEntityResults(), AsBatches() or AsResponses() to see the query
            // results in whatever way makes most sense for your application.
            await results.ForEachAsync(entity =>
            {
                Console.WriteLine(entity);
            });

            // End snippet

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

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

            Assert.Equal("Jane Austen", (string)book["author"]);
            Assert.Equal("Pride and Prejudice", (string)book["title"]);
        }
Exemplo n.º 7
0
        public async Task EagerStructuredQueryAsync()
        {
            string projectId   = _fixture.ProjectId;
            string namespaceId = _fixture.NamespaceId;

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

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

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

            Assert.Equal("Jane Austen", (string)book["author"]);
            Assert.Equal("Pride and Prejudice", (string)book["title"]);
        }
Exemplo n.º 8
0
        public async Task EagerGqlQueryAsync()
        {
            string projectId   = _fixture.ProjectId;
            string namespaceId = _fixture.NamespaceId;

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

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

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

            Assert.Equal("Jane Austen", (string)book["author"]);
            Assert.Equal("Pride and Prejudice", (string)book["title"]);
        }
Exemplo n.º 9
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]
            });
        }
        public async Task <IList <U> > GetUsersInRoleAsync(string roleName, CancellationToken cancellationToken)
        {
            var result = await _datastore.RunQueryAsync(new Query(USER_KIND)
            {
                Filter = Filter.Equal(ROLES, roleName)
            });

            return(result.Entities.Select(e => EntityToUser(e)).ToList());
        }
Exemplo n.º 11
0
        public async Task <ProjectsViewModel> Handle(GetProjectsQuery request, CancellationToken cancellationToken)
        {
            var projects = await db.RunQueryAsync(new Query("Project"));

            return(new ProjectsViewModel()
            {
                Projects = mapper.Map <IEnumerable <Entity>, List <WorkProject> >(projects.Entities)
            });
        }
        public async Task <R> FindByNameAsync(string normalizedRoleName, CancellationToken cancellationToken)
        {
            var result = await _datastore.RunQueryAsync(new Query(KIND)
            {
                Filter = Filter.Equal(NORMALIZED_NAME, normalizedRoleName)
            });

            return(EntityToRole(result.Entities.FirstOrDefault()));
        }
Exemplo n.º 13
0
        public override async Task ReplayMessagesAsync(IActorContext context, string persistenceId, long fromSequenceNr, long toSequenceNr, long max,
                                                       Action <IPersistentRepresentation> recoveryCallback)
        {
            Query query = new Query(_journalKind)
            {
                Filter = Filter.And(
                    Filter.HasAncestor(RootKey(persistenceId)),
                    Filter.GreaterThanOrEqual(JournalFields.SequenceNr, fromSequenceNr),
                    Filter.LessThanOrEqual(JournalFields.SequenceNr, toSequenceNr)
                    ),
                Order   = { { JournalFields.SequenceNr, PropertyOrder.Types.Direction.Ascending } }
                , Limit = max > Int32.MaxValue? (int?)null : (int)max
            };

            var results = await _db.RunQueryAsync(query).ConfigureAwait(false);

            results.Entities
            .Select(MapEntityToPersistentRepresentation)
            .ForEach(recoveryCallback);
        }
        public async Task <Role> Read(string name)
        {
            var query = new Query("Role")
            {
                Filter = Filter.Equal("name", name)
            };

            var results = await _db.RunQueryAsync(query);

            return(results.Entities.First()?.ToRole());
        }
        public async Task <User> Read(string username)
        {
            var query = new Query("User")
            {
                Filter = Filter.Equal("username", username)
            };

            var results = await _db.RunQueryAsync(query);

            return(results.Entities.First()?.ToUser());
        }
Exemplo n.º 16
0
        public async Task <List <Spot> > Read(Status status, int offset, int limit)
        {
            var query = new Query("Spot")
            {
                Filter = Filter.And(Filter.Equal("status", (int)status)),
                Order  = { { "date", PropertyOrder.Types.Direction.Descending } },
                Offset = offset,
                Limit  = limit
            };

            var results = await _db.RunQueryAsync(query);

            return(results.Entities.Select(entity => entity.ToSpot()).ToList());
        }
Exemplo n.º 17
0
        protected async Task <IEnumerable <Entity> > Get(Filter filter = null)
        {
            try
            {
                var query = new Query(_kind.GetDescription())
                {
                    Filter = filter,
                };

                return((await _db.RunQueryAsync(query)).Entities);
            }
            catch (Exception ex)
            {
                var exceptionMsg = $"{GetType().FullName}.Get experienced a {ex.GetType()}";
                _logger.LogError(ex, exceptionMsg);
                throw new Exception(exceptionMsg, ex);
            }
        }
        public async Task <IEnumerable <IDataEntityObject> > Select(string from)
        {
            var results = await _db.RunQueryAsync(new Query(from)).ConfigureAwait(false);

            var returnData = new List <IDataEntityObject>();

            foreach (var result in results.Entities)
            {
                var entity = _dataEntityObjectFactory.Create();

                foreach (var prop in result.Properties)
                {
                    //TODO: Get actually type from property
                    entity.Set(prop.Key, prop.Value.StringValue);
                }
                returnData.Add(entity);
            }

            return(returnData);
        }
        public async Task <IEnumerable <TEntity> > FindInAsync(IDictionary <string, dynamic> fieldComparisons)
        {
            var gqlFilters = new List <string>();

            foreach (var comparison in fieldComparisons)
            {
                var field           = comparison.Key;
                var values          = comparison.Value;
                var localGqlFilters = new List <string>();

                if (gqlFilters.Count == 0)
                {
                    if (values is Array)
                    {
                        foreach (var val in values)
                        {
                            localGqlFilters.Add(val is string?$"{field}='{val}'" : $"{field}={val}");
                        }
                    }
                    else
                    {
                        localGqlFilters.Add(values is string?$"{field}='{values}'" : $"{field}={values}");
                    }
                }
                else
                {
                    foreach (var gql in gqlFilters)
                    {
                        if (values is Array)
                        {
                            foreach (var val in values)
                            {
                                localGqlFilters.Add(val is string?$"{gql} AND {field}='{val}'" : $"{gql} AND {field}={val}");
                            }
                        }
                        else
                        {
                            localGqlFilters.Add(values is string?$"{gql} AND {field}='{values}'" : $"{gql} AND {field}={values}");
                        }
                    }
                }

                gqlFilters = localGqlFilters;
            }

            var entities = new List <TEntity>();

            foreach (var filter in gqlFilters)
            {
                var q = new GqlQuery
                {
                    QueryString   = $"SELECT * FROM {_kind} WHERE {filter}",
                    AllowLiterals = true
                };
                var results = await _database.RunQueryAsync(q);

                entities.AddRange(results.Entities.Select(BuildDalEntity));
            }

            return(entities);
        }