Exemplo n.º 1
0
 public async Task <List <T> > FromQueryAsync(QueryOperationConfig queryOperationConfig, string overrideTableName = null)
 {
     using (var dbcontext = new DynamoDBContext(client))
     {
         if (!string.IsNullOrEmpty(overrideTableName))
         {
             return(await dbcontext.FromQueryAsync <T>(queryOperationConfig, new DynamoDBOperationConfig { OverrideTableName = overrideTableName }).GetNextSetAsync());
         }
         else
         {
             return(await dbcontext.FromQueryAsync <T>(queryOperationConfig).GetNextSetAsync());
         }
     }
 }
        public IEnumerable <LeaderBoardEntry> GetLeaderBoard(string match, int duration)
        {
            DynamoDBContext context = new DynamoDBContext(_client);

            QueryFilter filter = new QueryFilter();

            filter.AddCondition("Match", QueryOperator.Equal, match);
            filter.AddCondition("TimeStamp", QueryOperator.GreaterThanOrEqual, DateTime.Now.AddHours(-duration));

            QueryOperationConfig queryOperationConfig = new QueryOperationConfig {
                Filter = filter, IndexName = "LeaderBoardIndex"
            };

            var playerStats = context.FromQueryAsync <PlayerStat>(queryOperationConfig).GetNextSetAsync().GetAwaiter().GetResult();

            playerStats.Sort((x, y) => { return(y.Score.CompareTo(x.Score)); });

            List <LeaderBoardEntry> leaderBoardEntries = new List <LeaderBoardEntry>();

            foreach (var playerStat in playerStats)
            {
                if (leaderBoardEntries.Find(item => item.UserName == playerStat.UserName) == null)
                {
                    leaderBoardEntries.Add(new LeaderBoardEntry
                    {
                        Kills    = playerStat.Kills,
                        Score    = playerStat.Score,
                        UserName = playerStat.UserName,
                        Rank     = leaderBoardEntries.FindAll(item => item.Score > playerStat.Score).Count + 1
                    });
                }
            }

            return(leaderBoardEntries);
        }
Exemplo n.º 3
0
        public static Task <List <T> > QueryItemAsync <T>(string columnName, QueryOperator queryOperator, string queryValue)
        {
            string indexName = null;

            foreach (var property in typeof(T).GetProperties())
            {
                if (property.CustomAttributes.Any(attribute =>
                                                  attribute.AttributeType == typeof(DynamoDBHashKeyAttribute)))
                {
                    indexName = property.Name;
                }

                if (!string.IsNullOrEmpty(indexName))
                {
                    break;
                }
            }

            Console.WriteLine();
            var search = Context.FromQueryAsync <T>(new QueryOperationConfig
            {
                IndexName = indexName,
                Filter    = new QueryFilter(columnName, queryOperator, queryValue)
            });

            return(search.GetRemainingAsync());
        }
        public async Task <List <Channel> > GetBotsByChannelId(string id)
        {
            var query = _context.QueryAsync <Channel>(id);

            var botQuery = new Amazon.DynamoDBv2.DocumentModel.QueryOperationConfig
            {
                IndexName = "BotId-ChannelId-index"
            };

            botQuery.KeyExpression = new Amazon.DynamoDBv2.DocumentModel.Expression
            {
                ExpressionStatement       = "BotId = :botId",
                ExpressionAttributeValues = new Dictionary <string, Amazon.DynamoDBv2.DocumentModel.DynamoDBEntry>
                {
                    { ":botId", id }
                }
            };
            var botresult = _context.FromQueryAsync <Channel>(botQuery);

            var data = await botresult.GetRemainingAsync();

            var data2 = await query.GetRemainingAsync();

            return(data.Union(data2).ToList());
        }
Exemplo n.º 5
0
        public async Task QueryByConditions()
        {
            Console.WriteLine("Query where name starts with 'M' for ID country sorted descending: ");
            QueryFilter filter = new QueryFilter();

            filter.AddCondition(nameof(Profile.CountryId), QueryOperator.Equal, "ID");
            filter.AddCondition(nameof(Profile.Name), QueryOperator.BeginsWith, "M");
            List <Profile> profiles = await _context.FromQueryAsync <Profile>(new QueryOperationConfig
            {
                BackwardSearch = true,
                Filter         = filter
            }).GetRemainingAsync();

            IterateList(profiles);

            Console.WriteLine("\n\nQuery where email in '*****@*****.**', '*****@*****.**' sorted descending");
            profiles = await _context.QueryAsync <Profile>("ID", new DynamoDBOperationConfig
            {
                QueryFilter = new List <ScanCondition>
                {
                    new ScanCondition(nameof(Profile.Email), ScanOperator.In, "*****@*****.**", "*****@*****.**")
                },
                BackwardQuery = true
            }).GetRemainingAsync();

            IterateList(profiles);
        }
Exemplo n.º 6
0
        public List <T> GetItem <T>(string filterType, string filterValue)
        {
            List <AttributeValue> eqListAvailable = new List <AttributeValue>();

            eqListAvailable.Add(new AttributeValue()
            {
                N = "1"
            });
            QueryFilter           queryFilter = new QueryFilter();
            List <AttributeValue> eqList      = new List <AttributeValue>();

            eqList.Add(new AttributeValue()
            {
                S = filterValue
            });
            queryFilter.AddCondition(filterType, new Condition()
            {
                ComparisonOperator = ComparisonOperator.EQ,
                AttributeValueList = eqList
            });
            queryFilter.AddCondition(pseudoDeleteAttributeName, new Condition()
            {
                AttributeValueList = eqListAvailable,
                ComparisonOperator = ComparisonOperator.EQ
            });

            QueryOperationConfig config = filterType == "Name" ? new QueryOperationConfig()
            {
                Filter = queryFilter
            } : new QueryOperationConfig()
            {
                IndexName = filterType, Filter = queryFilter
            };

            var list = _dynamoDBContext.FromQueryAsync <T>(config).GetRemainingAsync().Result;

            return(list);
            //Easy way to query by primary(hash) key
            //IEnumerable<T> list = _dynamoDBContext.QueryAsync<T>(name).GetRemainingAsync().Result;
            //return list;
        }
Exemplo n.º 7
0
        private async Task <IEnumerable <MessageItem> > PageAllMessagesAsync(QueryOperationConfig queryConfig)
        {
            var asyncSearch = _context.FromQueryAsync <MessageItem>(queryConfig);

            var messages = new List <MessageItem>();

            do
            {
                messages.AddRange(await asyncSearch.GetNextSetAsync().ConfigureAwait(ContinueOnCapturedContext));
            } while (!asyncSearch.IsDone);

            return(messages);
        }
Exemplo n.º 8
0
        private async Task <IEnumerable <CommandItem <T> > > PageAllMessagesAsync <T>(QueryOperationConfig queryConfig)
            where T : class, IRequest
        {
            var asyncSearch = _context.FromQueryAsync <CommandItem <T> >(queryConfig);

            var messages = new List <CommandItem <T> >();

            do
            {
                messages.AddRange(await asyncSearch.GetNextSetAsync().ConfigureAwait(false));
            } while (!asyncSearch.IsDone);

            return(messages);
        }
        public async Task <List <T> > Get <T>(object key)
        {
            using (var context = new DynamoDBContext(_client))
            {
                if (typeof(T) == typeof(Network))
                {
                    var queryOperation = context.FromQueryAsync <T>(new QueryOperationConfig()
                    {
                        IndexName     = "Network_Global_Index_01",
                        KeyExpression = new Expression()
                        {
                            ExpressionStatement = "MasterId = :mid", ExpressionAttributeValues = new Dictionary <string, DynamoDBEntry>()
                            {
                                { ":mid", key.ToString() }
                            }
                        },
                        AttributesToGet = new List <string>()
                        {
                            "Name", "Code", "Tags", "Id", "MasterId"
                        },
                        Select = SelectValues.SpecificAttributes
                    });

                    return(await queryOperation.GetRemainingAsync());
                }
                else
                {
                    var queryOperation = context.FromQueryAsync <T>(new QueryOperationConfig()
                    {
                        ConsistentRead = true,
                        Filter         = new QueryFilter("MasterId", QueryOperator.Equal, key.ToString())
                    });

                    return(await queryOperation.GetRemainingAsync());
                }
            }
        }
Exemplo n.º 10
0
        /// <summary>
        /// Multiple Query using Object Persistence Model
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task <List <Widget> > GetWidgetsByQueryUsingOP(string id)
        {
            if (string.IsNullOrEmpty(id))
            {
                id = "WDGT1";
            }
            var queryfilter = new QueryOperationConfig()
            {
                IndexName = "Id-Created-index",
                Filter    = new QueryFilter("Id", QueryOperator.Equal, id)
            };
            var query = _context.FromQueryAsync <Widget>(queryfilter);

            return(await query.GetRemainingAsync());
        }
        public IList <PlayerStat> GetPlayerStats(string id)
        {
            DynamoDBContext context = new DynamoDBContext(_client);

            QueryFilter filter = new QueryFilter();

            filter.AddCondition("UserName", QueryOperator.Equal, id);

            QueryOperationConfig queryOperationConfig = new QueryOperationConfig {
                Filter = filter
            };

            var result = context.FromQueryAsync <PlayerStat>(queryOperationConfig).GetNextSetAsync().GetAwaiter().GetResult();

            return(result);
        }
        public IList <PlayerStat> GetPlayerStats(string id, int duration)
        {
            DynamoDBContext context = new DynamoDBContext(_client);

            QueryFilter filter = new QueryFilter();

            filter.AddCondition("UserName", QueryOperator.Equal, id);
            filter.AddCondition("TimeStamp", QueryOperator.GreaterThanOrEqual, DateTime.Now.AddHours(-duration));

            QueryOperationConfig queryOperationConfig = new QueryOperationConfig {
                Filter = filter
            };

            var result = context.FromQueryAsync <PlayerStat>(queryOperationConfig).GetNextSetAsync().GetAwaiter().GetResult();

            return(result);
        }
Exemplo n.º 13
0
        public async Task <bool> Exists <T>(AttributeValue key) where T : IAwsDbItem, new()
        {
            var filter = new QueryFilter();

            filter.AddCondition(new T().GetIdFieldName(), ScanOperator.Equal, new List <AttributeValue>()
            {
                key
            });

            var iterator = _context.FromQueryAsync <T>(new QueryOperationConfig()
            {
                Filter = filter
            });

            var results = await iterator.GetRemainingAsync();

            return(results.Count > 0);
        }
Exemplo n.º 14
0
        public Task <List <User> > GetUsersByClientIdAsync(string id)
        {
            var userQuery = new Amazon.DynamoDBv2.DocumentModel.QueryOperationConfig
            {
                IndexName = "ClientId-index"
            };

            userQuery.KeyExpression = new Amazon.DynamoDBv2.DocumentModel.Expression
            {
                ExpressionStatement       = "ClientId = :clientId",
                ExpressionAttributeValues = new Dictionary <string, Amazon.DynamoDBv2.DocumentModel.DynamoDBEntry>
                {
                    { ":clientId", id }
                }
            };
            var botresult = _context.FromQueryAsync <User>(userQuery);

            return(botresult.GetRemainingAsync());
        }
Exemplo n.º 15
0
        protected virtual async Task <object> GetLastSortKey(string hashKeyFieldName, string hashKeyValue, string sortKeyFieldName)
        {
            var queryConfig = new QueryOperationConfig()
            {
                BackwardSearch = true,
                Limit          = 1,
                Filter         = new QueryFilter(hashKeyFieldName, QueryOperator.Equal, hashKeyValue)
            };
            var results = await Context.FromQueryAsync <TEntity>(queryConfig).GetNextSetAsync();

            var lastItem = results.FirstOrDefault();

            if (lastItem == null)
            {
                return(null);
            }
            var keyProperty = lastItem.GetType().GetProperty(sortKeyFieldName);

            if (keyProperty == null)
            {
                throw new ArgumentException($"Sort key name ({sortKeyFieldName}) is invalid for entity {lastItem.GetType().ToString()}");
            }
            return(keyProperty.GetValue(lastItem, null));
        }
        public async Task <IEnumerable <BackerListModel> > Handle(GetBackersListQuery request, CancellationToken cancellationToken)
        {
            var results = new List <Backer>();

            using var context = new DynamoDBContext(_dynamoDb);
            var response = context.FromQueryAsync <Backer>(new QueryOperationConfig
            {
                AttributesToGet = new List <string> {
                    nameof(Backer.Id), nameof(Backer.Name), nameof(Backer.EmailAddress), nameof(Backer.Amount)
                },
                Select        = SelectValues.SpecificAttributes,
                KeyExpression = new Expression
                {
                    ExpressionStatement       = "begins_with(Id,:eventId) AND DomainType = :domainType",
                    ExpressionAttributeValues = new Dictionary <string, DynamoDBEntry> {
                        { ":eventId", new Primitive($"{request.EventId}-{request.ParticipantId}") }, { ":domainType", new Primitive(nameof(Backer)) }
                    }
                }
            });

            results.AddRange(await response.GetRemainingAsync(cancellationToken));

            return(results.Select(x => _mapper.Map(x, new BackerListModel())));
        }
Exemplo n.º 17
0
        public async Task <IEnumerable <EventListModel> > Handle(GetEventsListQuery request, CancellationToken cancellationToken)
        {
            var results = new List <Event>();

            using var context = new DynamoDBContext(_dynamoDb);
            var response = context.FromQueryAsync <Event>(new QueryOperationConfig
            {
                AttributesToGet = new List <string> {
                    nameof(Event.Id), nameof(Event.Name), nameof(Event.StartDate), nameof(Event.City)
                },
                Select        = SelectValues.SpecificAttributes,
                KeyExpression = new Expression
                {
                    ExpressionStatement       = "Id > :id AND DomainType = :domainType",
                    ExpressionAttributeValues = new Dictionary <string, DynamoDBEntry> {
                        { ":id", new Primitive("0") }, { ":domainType", new Primitive(nameof(Event)) }
                    }
                }
            });

            results.AddRange(await response.GetRemainingAsync(cancellationToken));

            return(results.Select(x => _mapper.Map(x, new EventListModel())));
        }
Exemplo n.º 18
0
        //******

        //****** Adapted from the Query and Scan section in https://docs.aws.amazon.com/mobile/sdkforxamarin/developerguide/dynamodb-integration-objectpersistencemodel.html
        /// <summary>
        /// Reads items where the contents of the field is equal to the query string. This method is async.
        /// </summary>
        /// <returns>A List of items.</returns>
        /// <param name="fieldToQuery">Field to query.</param>
        /// <param name="queryString">Query string.</param>
        public async Task <List <Item> > ReadItemEqualAsync(string fieldToQuery, string queryString)
        {
            if (string.IsNullOrEmpty(queryString))
            {
                List <Item> blankResponse = new List <Item>
                {
                    new Item
                    {
                        Id             = "Nothing to retrieve",
                        SavedTimeStamp = "Nothing to retrieve",
                        Name           = "Nothing to retrieve",
                        Email          = "Nothing to retrieve",
                        Password       = "******"
                    }
                };

                RetrievedItemDataStore.Instance().retrievedName  = "Nothing to retrieve";                //Is it necessary to store the UserNameToRetrieveText?
                RetrievedItemDataStore.Instance().id             = "Nothing to retrieve";
                RetrievedItemDataStore.Instance().savedTimeStamp = "Nothing to retrieve";
                RetrievedItemDataStore.Instance().name           = "Nothing to retrieve";
                RetrievedItemDataStore.Instance().email          = "Nothing to retrieve";
                RetrievedItemDataStore.Instance().password       = "******";

                return(blankResponse);                //An error of "value cannot be null" will be thrown in the viewmodel if the queryString is null.
                                                      //So FromQueryAsync() isn't executed if queryString is null.
            }

            //var client = new AmazonDynamoDBClient(_credentials, RegionEndpoint.USEast2);
            //DynamoDBContext context = new DynamoDBContext(client);

            //QueryFilter queryFilter = null;

            //switch (queryOperator)
            //{
            //	case "Equal":
            //		queryFilter = new QueryFilter(fieldToQuery, QueryOperator.Equal, queryString);
            //		break;
            //	case "GreaterThan":
            //		queryFilter = new QueryFilter(fieldToQuery, QueryOperator.GreaterThan, queryString);
            //		break;
            //	case "GreaterThanOrEqual":
            //		queryFilter = new QueryFilter(fieldToQuery, QueryOperator.GreaterThanOrEqual, queryString);
            //		break;
            //	case "LessThan":
            //		queryFilter = new QueryFilter(fieldToQuery, QueryOperator.LessThan, queryString);
            //		break;
            //	case "LessThanOrEqual":
            //		queryFilter = new QueryFilter(fieldToQuery, QueryOperator.LessThanOrEqual, queryString);
            //		break;
            //	case "BeginsWith":
            //		queryFilter = new QueryFilter(fieldToQuery, QueryOperator.BeginsWith, queryString);
            //		break;
            //	case "Between":
            //		queryFilter = new QueryFilter(fieldToQuery, QueryOperator.Between, queryString);
            //		break;
            //}

            var search = _context.FromQueryAsync <Item>(new QueryOperationConfig()
            {
                //IndexName = "Name-index", //Taken from the DynamoDB dashboard when creating the Global Secondary Index.
                //Filter = new QueryFilter("Name", QueryOperator.Equal, "AwsDynamoDbTest app started")

                IndexName = fieldToQuery + "-index", //Taken from the DynamoDB dashboard when creating the Global Secondary Index.
                Filter    = new QueryFilter(fieldToQuery, QueryOperator.Equal, queryString)
            });

#if DEBUG
            //System.Diagnostics.Debug.WriteLine("QueryAsync() items retrieved:");

            int count          = 0;
            var searchResponse = await search.GetRemainingAsync();

            string itemData = null;

            searchResponse.ForEach((item) =>
            {
                count++;
                //System.Diagnostics.Debug.WriteLine(count + ". " + "Name = " + item.Name + ", Password = "******", Id = " + item.Id + ", SavedTimeStamp = " + item.SavedTimeStamp);
                itemData += count + ". " + "Name = " + item.Name + ", Password = "******", Id = " + item.Id + ", SavedTimeStamp = " + item.SavedTimeStamp + "\n";
            });

            System.Diagnostics.Debug.WriteLine("ReadItemEqualAsync() retrieved " + count + " items:\n" + itemData);
            count = 0;
#endif
            return(searchResponse);
        }