public async Task <List <Reading> > GetLatestReadings(string deviceID = "")
        {
            // Generate a timestamp
            var sevenDaysAgo = (DateTimeOffset)DateTime.Today - TimeSpan.FromDays(6);
            var timeStamp    = sevenDaysAgo.ToUnixTimeSeconds();

            // Create a query for last 7 days of data
            Search search;

            if (!string.IsNullOrEmpty(deviceID))
            {
                var queryFilter = new QueryFilter();
                queryFilter.AddCondition("device_id", QueryOperator.Equal, deviceID);
                queryFilter.AddCondition("timestamp", QueryOperator.GreaterThanOrEqual, timeStamp);

                search = _table.Query(queryFilter);
            }
            else
            {
                var scanFilter = new ScanFilter();
                scanFilter.AddCondition("timestamp", ScanOperator.GreaterThanOrEqual, timeStamp);

                search = _table.Scan(scanFilter);
            }

            var documentList = await search.GetRemainingAsync();

            var readingsList = JsonConvert.DeserializeObject <List <Reading> >(documentList.ToJson());

            // Parse and return readings
            return(readingsList);
        }
Example #2
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);
        }
        private QueryOperationConfig GetQueryOperationConfig(List <QueryFilterCondition> QueryFilterConditions, bool consistentRead = true, List <string> attributesToGet = null)
        {
            QueryFilter queryFilter = new QueryFilter();

            foreach (var queryFilterCondition in QueryFilterConditions)
            {
                if (queryFilterCondition.Type == QueryFilterConditionType.one)
                {
                    queryFilter.AddCondition(queryFilterCondition.AttributeName, queryFilterCondition.Condition);
                }
                if (queryFilterCondition.Type == QueryFilterConditionType.two)
                {
                    queryFilter.AddCondition(queryFilterCondition.AttributeName, queryFilterCondition.QueryOperator, queryFilterCondition.AttributeValues);
                }
                if (queryFilterCondition.Type == QueryFilterConditionType.three)
                {
                    queryFilter.AddCondition(queryFilterCondition.AttributeName, queryFilterCondition.QueryOperator, queryFilterCondition.DynamoDBEntry);
                }
            }

            QueryOperationConfig queryOperationConfig = new QueryOperationConfig()
            {
                ConsistentRead = consistentRead,
                Filter         = queryFilter
            };

            if (attributesToGet != null)
            {
                queryOperationConfig.AttributesToGet = attributesToGet;
            }

            return(queryOperationConfig);
        }
        public QueryFilter GetCriteriaQueryFilterForQueryFilter()
        {
            if (QueryCriteria == null || QueryCriteria.Count == 0)
            {
                return(new QueryFilter());
            }

            var result = new QueryFilter();

            foreach (var item in QueryCriteria)
            {
                if (item.SecondValue != null)
                {
                    result.AddCondition(item.PropertyName, item.QueryOperator, new List <AttributeValue> {
                        new AttributeValue {
                            S = item.Value.ToString()
                        }, new AttributeValue {
                            S = item.SecondValue.ToString()
                        }
                    });
                }
                else
                {
                    result.AddCondition(item.PropertyName, item.QueryOperator, item.Value.ToString());
                }
            }

            return(result);
        }
Example #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<Document> documents = await _table.Query("ID", filter).GetRemainingAsync();
            List <Document> documents = await _table.Query(new QueryOperationConfig
            {
                BackwardSearch = true,
                Filter         = filter
            }).GetRemainingAsync();

            if (documents.Count > 0)
            {
                IterateList(documents.Select(ConvertToProfile));
            }

            Console.WriteLine("\n\nQuery where email equals to '*****@*****.**'");
            filter    = new QueryFilter(nameof(Profile.Email), QueryOperator.Equal, "*****@*****.**");
            documents = await _table.Query("ID", filter).GetRemainingAsync();

            if (documents.Count > 0)
            {
                IterateList(documents.Select(ConvertToProfile));
            }
        }
        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);
        }
Example #7
0
        //--- Extension Methods ---
        public static Search QueryBeginsWith(this Table table, Primitive hashKey, Primitive rangeKeyPrefix)
        {
            var filter = new QueryFilter();

            filter.AddCondition("PK", QueryOperator.Equal, new DynamoDBEntry[] { hashKey });
            filter.AddCondition("SK", QueryOperator.BeginsWith, new DynamoDBEntry[] { rangeKeyPrefix });
            return(table.Query(new QueryOperationConfig {
                Filter = filter
            }));
        }
Example #8
0
        protected Task <IEnumerable <Document> > Search(string pk, QueryOperator skOperator, string skValue, CancellationToken cancellationToken)
        {
            var filter = new QueryFilter();

            filter.AddCondition("PK", QueryOperator.Equal, new DynamoDBEntry[] { pk });
            filter.AddCondition("SK", skOperator, new DynamoDBEntry[] { skValue });
            var search = Table.Query(new QueryOperationConfig {
                Filter = filter
            });

            return(DoSearchAsync(search, cancellationToken));
        }
Example #9
0
        /// <summary>
        /// Returns all player's decklist
        /// </summary>
        /// <param name="request">Request from gateway</param>
        /// <param name="context"></param>
        /// <returns>All deck list</returns>
        public List <Deck> FunctionHandler(AwsGetRequest <RequestFilter> request, ILambdaContext context)
        {
            //context.Logger.LogLine($"Context: {JsonConvert.SerializeObject(context)}");
            //context.Logger.LogLine($"Filter: {JsonConvert.SerializeObject(filter)}");

            var userUid = request.context.userId;

            context.Logger.LogLine($"Beginning to get all deck of user {userUid}.");

            using var client = new AmazonDynamoDBClient(Amazon.RegionEndpoint.EUWest1);
            Table       deckListTable = Table.LoadTable(client, Constantes.TableName);
            QueryFilter playerFilter  = new QueryFilter();

            playerFilter.AddCondition(Constantes.DynamoCol.PK, QueryOperator.Equal, new List <AttributeValue> {
                new AttributeValue($"{Constantes.DynamoKey.USER}{userUid}")
            });
            playerFilter.AddCondition(Constantes.DynamoCol.SK, QueryOperator.BeginsWith, new List <AttributeValue> {
                new AttributeValue($"{Constantes.DynamoKey.DECK}")
            });
            Search search = deckListTable.Query(playerFilter);

            List <Deck> decks = new List <Deck>();

            do
            {
                var set = search.GetNextSetAsync();
                set.Wait();
                foreach (var deckDoc in set.Result)
                {
                    var deck = new Deck
                    {
                        Id            = deckDoc[Constantes.DynamoCol.DECK_ID],
                        Name          = deckDoc[Constantes.DynamoCol.DECK_NAME],
                        Format        = deckDoc[Constantes.DynamoCol.FORMAT],
                        Author        = deckDoc[Constantes.DynamoCol.AUTHOR],
                        LastUpdatedAt = deckDoc[Constantes.DynamoCol.DATE].AsDateTime(),
                        MainDeck      = JsonConvert.DeserializeObject <List <CardInfo> >(deckDoc[Constantes.DynamoCol.MAIN_DECK]),
                        SideDeck      = JsonConvert.DeserializeObject <List <CardInfo> >(deckDoc[Constantes.DynamoCol.SIDE_DECK]),
                    };

                    decks.Add(deck);
                }
            } while (!search.IsDone);

            context.Logger.LogLine("Stream processing complete.");

            var headersDic = new Dictionary <string, string> {
                { "Content-type", "application/json" }
            };

            return(decks);
        }
        private static QueryFilter ComposeQueryFilterHelper(Document hashKey, IEnumerable <QueryCondition> conditions, ItemStorageConfig storageConfig, DynamoDBFlatConfig currentConfig, out List <string> indexNames)
        {
            if (hashKey == null)
            {
                throw new ArgumentNullException("hashKey");
            }

            if (storageConfig.HashKeyPropertyNames.Count != 1)
            {
                throw new InvalidOperationException("Must have one hash key defined for the table " + storageConfig.TableName);
            }
            if (storageConfig.RangeKeyPropertyNames.Count != 1 && storageConfig.IndexNameToGSIMapping.Count == 0)
            {
                throw new InvalidOperationException("Must have one range key or a GSI index defined for the table " + storageConfig.TableName);
            }

            QueryFilter filter = new QueryFilter();

            // Configure hash-key equality condition
            string hashKeyProperty = storageConfig.HashKeyPropertyNames[0];

            hashKeyProperty = storageConfig.GetCorrectHashKeyProperty(currentConfig, hashKeyProperty);
            PropertyStorage propertyStorage = storageConfig.GetPropertyStorage(hashKeyProperty);
            string          attributeName   = propertyStorage.AttributeName;
            DynamoDBEntry   hashValue       = hashKey[attributeName];

            filter.AddCondition(attributeName, QueryOperator.Equal, hashValue);

            indexNames = new List <string>();
            if (conditions != null)
            {
                foreach (QueryCondition condition in conditions)
                {
                    object[]        conditionValues   = condition.Values;
                    PropertyStorage conditionProperty = storageConfig.GetPropertyStorage(condition.PropertyName);
                    if (conditionProperty.IsLSIRangeKey || conditionProperty.IsGSIKey)
                    {
                        indexNames.AddRange(conditionProperty.Indexes);
                    }
                    List <AttributeValue> attributeValues = new List <AttributeValue>();
                    foreach (var conditionValue in conditionValues)
                    {
                        DynamoDBEntry  entry          = ToDynamoDBEntry(conditionProperty, conditionValue);
                        AttributeValue attributeValue = entry.ConvertToAttributeValue();
                        attributeValues.Add(attributeValue);
                    }
                    filter.AddCondition(conditionProperty.AttributeName, condition.Operator, attributeValues);
                }
            }
            return(filter);
        }
Example #11
0
        public async Task DeleteItem(string id, string item_id)
        {
            var table = Table.LoadTable(dbClient, "carts_id_cid");

            var filter = new QueryFilter();

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

            var queryConfig = new QueryOperationConfig
            {
                Filter = filter,
                Limit  = 1
            };

            var result = table.Query(queryConfig);

            if (result.IsDone)
            {
                throw new ArgumentException("id");
            }
            else
            {
                var querySet = await result.GetNextSetAsync();

                var document = querySet.First();

                var items = JsonConvert.DeserializeObject <List <CartItem> >(document["items"].AsString());
                var item  = items.FirstOrDefault(x => x.id.ToString() == item_id);
                items.Remove(item);

                await table.UpdateItemAsync(document);
            }
        }
Example #12
0
        public async Task <IEnumerable <Moment> > GetLatestMomentsAsync()
        {
            List <Moment> moments = new List <Moment>();

            var filter = new QueryFilter();

            filter.AddCondition("date", QueryOperator.LessThanOrEqual, DateTime.UtcNow.ToDateString());

            var query = DBContext.FromQueryAsync <Moment>(new QueryOperationConfig()
            {
                IndexName      = "date-time-index",
                Filter         = filter,
                BackwardSearch = true,
            });

            var result = await query.GetRemainingAsync();

            moments.AddRange(result);

            //filter = new QueryFilter();
            //filter.AddCondition("date", QueryOperator.Equal, DateTime.UtcNow.AddDays(-1).ToDateString());
            //filter.AddCondition("time", QueryOperator.GreaterThanOrEqual, DateTime.UtcNow.AddDays(-1).ToDateString());

            //query = DBContext.FromQueryAsync<Moment>(new QueryOperationConfig()
            //{
            //    IndexName = "date-time-index",
            //    Filter = filter,
            //    BackwardSearch = true,
            //});

            //result = await query.GetRemainingAsync();
            //moments.AddRange(result);

            return(moments);
        }
Example #13
0
        /// <summary>
        /// Fetch the specified metadata field from the metadata DynamoDB table
        /// </summary>
        /// <param name="searchkey"></param>
        /// <returns></returns>
        public string FetchMetadata(string searchkey)
        {
            QueryFilter filter = new QueryFilter();

            filter.AddCondition(Constants.KEY, QueryOperator.Equal, searchkey);

            QueryOperationConfig config = new QueryOperationConfig();

            config.Select = SelectValues.AllAttributes;
            config.Filter = filter;

            Search          searchRes   = metadataTable.Query(config);
            List <Document> documentSet = new List <Document>();

            do
            {
                try
                {
                    // We can assume there is only one entry per key.
                    // Hence, we are fetching the first item as required
                    documentSet = searchRes.GetNextSetAsync().Result;
                    Console.WriteLine("\nFindRepliesInLast15DaysWithConfig: printing ............");
                    return(documentSet[0][Constants.VALUE]);
                }
                catch (Exception ex)
                {
                    Logger.AddLog(ex.ToString());
                }
            } while (!searchRes.IsDone);

            return(String.Empty);
        }
        public List <Song> DbGetSongs(Album album)
        {
            try
            {
                //Load songs table
                var table = Table.LoadTable(Client, "Song");

                //Filter for query. AlbumName column matches album input
                var filter = new QueryFilter();
                filter.AddCondition("AlbumName", QueryOperator.Equal, album.AlbumName);

                //Response
                var response = table.Query(filter).GetNextSet();

                //List to contain found songs
                var foundSongs = new List <Song>();

                //Loop through each item in the response and map it to a new Song in the song list
                foreach (var item in response)
                {
                    foundSongs.Add(new Song()
                    {
                        SongName = item["SongName"]
                    });
                }

                return(foundSongs);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return(null);
            }
        }
        public List <Album> DbGetAlbums(Artist artist)
        {
            try
            {
                //Load albums table
                var table = Table.LoadTable(Client, "Album");

                //Filter for query. Artist column matches artist input
                var filter = new QueryFilter();
                filter.AddCondition("ArtistName", QueryOperator.Equal, artist.ArtistName);

                //Response
                var response = table.Query(filter).GetNextSet();

                //List to contain found artists
                var foundAlbums = new List <Album>();

                //Loop through each item in the response and map it to a new Artist in the artist list
                foreach (var item in response)
                {
                    foundAlbums.Add(new Album()
                    {
                        AlbumName = item["AlbumName"]
                    });
                }

                return(foundAlbums);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return(null);
            }
        }
        public async Task <IEnumerable <Document> > GetUsersRankedMoviesByMovieTitleAsync(int userId, string movieName)
        {
            var filter = new QueryFilter("UserId", QueryOperator.Equal, userId);

            filter.AddCondition("MovieName", QueryOperator.BeginsWith, movieName);
            return(await table.Query(filter).GetRemainingAsync());
        }
Example #17
0
        public Task <List <Document> > QueryOnTimestampRange(string tableName,
                                                             string partionKey,
                                                             string partitionValue,
                                                             int days)
        {
            using var client = new AmazonDynamoDBClient(RegionEndpoint.EUWest1);

            var table = Table.LoadTable(client, tableName);

            var queryFilter =
                new QueryFilter(partionKey, QueryOperator.Equal, partitionValue);

            var fromDateTime = DateTime.UtcNow
                               .AddDays(-days)
                               .ToString("yyyy-MM-dd HH:mm:ss", _culture);

            queryFilter.AddCondition("timestamp",
                                     QueryOperator.GreaterThanOrEqual,
                                     fromDateTime);

            var queryResult = table
                              .Query(queryFilter)
                              .GetRemainingAsync();

            return(queryResult);
        }
Example #18
0
        public async Task Checkout(string id)
        {
            var table = Table.LoadTable(dbClient, "carts_id_cid");

            var filter = new QueryFilter();

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

            var queryConfig = new QueryOperationConfig
            {
                Filter = filter,
                Limit  = 1
            };

            var result = table.Query(queryConfig);

            if (result.IsDone)
            {
                throw new ArgumentException("id");
            }
            else
            {
                var querySet = await result.GetNextSetAsync();

                var document = querySet.First();

                document["status"] = "DONE";

                await table.UpdateItemAsync(document);
            }
        }
Example #19
0
        private static void FindRepliesPostedWithinTimePeriod(Table table, string forumName, string threadSubject)
        {
            DateTime startDate = DateTime.UtcNow.Subtract(new TimeSpan(21, 0, 0, 0));
            DateTime endDate = DateTime.UtcNow.Subtract(new TimeSpan(1, 0, 0, 0));

            QueryFilter filter = new QueryFilter("Id", QueryOperator.Equal, forumName + "#" + threadSubject);
            filter.AddCondition("ReplyDateTime", QueryOperator.Between, startDate, endDate);

            QueryOperationConfig config = new QueryOperationConfig()
            {
                Limit = 2, // 2 items/page.
                Select = SelectValues.SpecificAttributes,
                AttributesToGet = new List<string> { "Message",
                                 "ReplyDateTime",
                                 "PostedBy" },
                ConsistentRead = true,
                Filter = filter
            };

            Search search = table.Query(config);

            List<Document> documentList = new List<Document>();

            do
            {
                documentList = search.GetNextSet();
                Console.WriteLine("\nFindRepliesPostedWithinTimePeriod: printing replies posted within dates: {0} and {1} ............", startDate, endDate);
                foreach (var document in documentList)
                {
                    PrintDocument(document);
                }
            } while (!search.IsDone);
        }
Example #20
0
        private static void FindRepliesInLast15DaysWithConfig(Table table, string forumName, string threadName)
        {
            DateTime twoWeeksAgoDate = DateTime.UtcNow - TimeSpan.FromDays(15);
            QueryFilter filter = new QueryFilter("Id", QueryOperator.Equal, forumName + "#" + threadName);
            filter.AddCondition("ReplyDateTime", QueryOperator.GreaterThan, twoWeeksAgoDate);
            // You are specifying optional parameters so use QueryOperationConfig.
            QueryOperationConfig config = new QueryOperationConfig()
            {
                Filter = filter,
                // Optional parameters.
                Select = SelectValues.SpecificAttributes,
                AttributesToGet = new List<string> { "Message", "ReplyDateTime",
                                 "PostedBy" },
                ConsistentRead = true
            };

            Search search = table.Query(config);

            List<Document> documentSet = new List<Document>();
            do
            {
                documentSet = search.GetNextSet();
                Console.WriteLine("\nFindRepliesInLast15DaysWithConfig: printing ............");
                foreach (var document in documentSet)
                    PrintDocument(document);
            } while (!search.IsDone);
        }
        public async Task <IAggregateSnapshot <TKey> > FindLastSnapshotAsync(TKey aggregateId, int maxVersion,
                                                                             CancellationToken cancellationToken = default)
        {
            var filter = new QueryFilter("aggregateId", QueryOperator.Equal, aggregateId as dynamic);

            filter.AddCondition("aggregateVersion", QueryOperator.LessThanOrEqual, maxVersion);
            Search search = _table.Query(new QueryOperationConfig
            {
                Filter         = filter,
                Limit          = 1,
                BackwardSearch = true,
            });

            List <Document> documents = await search.GetNextSetAsync(cancellationToken).ConfigureAwait(false);

            if (documents.Count == 0)
            {
                return(null);
            }

            string json = documents.First().ToJson();
            IAggregateSnapshot <TKey> snapshot = JsonConvert.DeserializeObject <IAggregateSnapshot <TKey> >(json, Defaults.JsonSerializerSettings);

            return(snapshot);
        }
        public async Task <Product> GetById(string id)
        {
            var table = Table.LoadTable(dbClient, "products_id_sku");

            var filter = new QueryFilter();

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

            var queryConfig = new QueryOperationConfig
            {
                Filter = filter,
                Limit  = 1
            };

            var result = table.Query(queryConfig);

            if (result.IsDone)
            {
                throw new ArgumentException("sku");
            }
            else
            {
                var querySet = await result.GetNextSetAsync();

                var document = querySet.First();

                Product product = ProductFromDocument(document);

                return(product);
            }
        }
Example #23
0
        /// <summary>
        /// Retrieves replies from the passed DynamoDB table object.
        /// </summary>
        /// <param name="table">The table we want to query.</param>
        /// <param name="forumName">The name of the forum we are interested in.</param>
        /// <param name="threadSubject">The subject of the thread for which we are
        /// looking for replies.</param>
        public static async Task FindRepliesInLast15Days(
            Table table,
            string forumName,
            string threadSubject)
        {
            DateTime    twoWeeksAgoDate = DateTime.UtcNow - TimeSpan.FromDays(15);
            QueryFilter filter          = new QueryFilter("Id", QueryOperator.Equal, "Id");

            filter.AddCondition("ReplyDateTime", QueryOperator.GreaterThan, twoWeeksAgoDate);

            // Use Query overloads that takes the minimum required query parameters.
            Search search = table.Query(filter);

            do
            {
                var documentSet = await search.GetNextSetAsync();

                Console.WriteLine("\nFindRepliesInLast15Days: printing ............");

                foreach (var document in documentSet)
                {
                    PrintDocument(document);
                }
            } while (!search.IsDone);
        }
        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);
        }
    private void FindRepliesPostedWithinTimePeriod(Table table, string forumName, string threadSubject)
    {
        this.displayMessage += "\n***FindRepliesPostedWithinTimePeriod***\n";
        if (replyTable == null)
        {
            this.displayMessage += "\nLoad table before running query";
            return;
        }
        ThreadPool.QueueUserWorkItem((s) =>
        {
            try
            {
                this.displayMessage = "\nRunning on background thread";


                DateTime startDate = DateTime.UtcNow.Subtract(new TimeSpan(21, 0, 0, 0));
                DateTime endDate   = DateTime.UtcNow.Subtract(new TimeSpan(1, 0, 0, 0));

                QueryFilter filter = new QueryFilter("Id", QueryOperator.Equal, forumName + "#" + threadSubject);
                filter.AddCondition("ReplyDateTime", QueryOperator.Between, startDate, endDate);

                QueryOperationConfig config = new QueryOperationConfig()
                {
                    Limit           = 2, // 2 items/page.
                    Select          = SelectValues.SpecificAttributes,
                    AttributesToGet = new List <string> {
                        "Message",
                        "ReplyDateTime",
                        "PostedBy"
                    },
                    ConsistentRead = true,
                    Filter         = filter
                };

                Search search = table.Query(config);

                List <Document> documentList = new List <Document>();

                do
                {
                    documentList         = search.GetNextSet();
                    this.displayMessage += String.Format("\nFindRepliesPostedWithinTimePeriod: printing replies posted within dates: {0} and {1} ............", startDate, endDate);
                    foreach (var document in documentList)
                    {
                        PrintDocument(document);
                    }
                } while (!search.IsDone);
                this.displayMessage += "\nCompleted !\n";
            }
            catch (Exception ex)
            {
                this.displayMessage += "\nFindRepliesPostedWithinTimePeriod:" + ex.Message;
                Debug.LogException(ex);
            }
        });
    }
Example #26
0
        public async Task <List <MovieResponse> > GetUsersRankedMoviesByMovieTitle(int userId, string movieName, CancellationToken cancellationToken)
        {
            var filter = new QueryFilter(attributeName: UserIdAttributeName, QueryOperator.Equal, userId);

            filter.AddCondition(keyAttributeName: MovieNameAttributeName, QueryOperator.BeginsWith, movieName);

            var rankedMoviesByMovieTitle = await _table.Query(filter).GetRemainingAsync(cancellationToken);

            return(_documentMapper.ToMovieContract(rankedMoviesByMovieTitle));
        }
        /// <summary>
        /// Updates a user
        /// </summary>
        /// <param name="usertId"></param>
        /// <param name="userEntity"></param>
        /// <returns></returns>
        //public bool UpdateUser(Guid userId, BusinessEntities.CustomerAPI userEntity)
        //{
        //    var success = false;
        //    if (userEntity != null)
        //    {
        //        using (var scope = new TransactionScope())
        //        {
        //            var user = _unitOfWork.UserRepository.GetByID(userId);
        //            if (user != null)
        //            {
        //                user.SID = userEntity.SID;
        //                _unitOfWork.UserRepository.Update(user);
        //                _unitOfWork.Save();
        //                scope.Complete();
        //                success = true;
        //            }
        //        }
        //    }
        //    return success;
        //}

        /// <summary>
        /// Deletes a particular user
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        //public bool DeleteUser(Guid userId)
        //{
        //    var success = false;
        //    if (userId != null && userId != Guid.Empty)
        //    {
        //        using (var scope = new TransactionScope())
        //        {
        //            var product = _unitOfWork.UserRepository.GetByID(userId);
        //            if (product != null)
        //            {

        //                _unitOfWork.UserRepository.Delete(product);
        //                _unitOfWork.Save();
        //                scope.Complete();
        //                success = true;
        //            }
        //        }
        //    }
        //    return success;
        //}

        /// <summary>
        /// Fetches product details by id
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public UserEntity GetUserById(string userId, string userType)
        {
            // UserEntity responseUser = new UserEntity();
            QueryFilter filter = new QueryFilter();
            filter.AddCondition("EmailAddress", QueryOperator.Equal, userType); //company is a parameter
            filter.AddCondition("UserType", QueryOperator.Equal, userType); //company is a parameter
            QueryOperationConfig config = new QueryOperationConfig()
            {
                Filter = filter,
                //Select = SelectValues.SpecificAttributes,
                //AttributesToGet = new List<string> { "AuthData", "Password", "FirstName", "LastName", "EmailAddress" },
                ConsistentRead = true
            };

            // var userData = _dynamoDataService.QueryItem<CustomerAPI>(userId, userType, config).FirstOrDefault();
            var userData = _dynamoDataService.GetEnumerable<CustomerAPI>(userId, userType).FirstOrDefault();
            if (userData != null)
            {
                // Mapper.CreateMap<hmis_user_base, hmisUserBase>();
                //Mapper.Reset();
                //Mapper.Initialize(cfg =>
                //{
                //    cfg.CreateMap<hmis_user_base, hmisUserBase>();
                //    //cfg.CreateMap<hmis_link_role_persmissions, hmisRolePermissions>();
                //    //cfg.CreateMap<hmis_permission_base, hmisPermisionBase>();

                //});
                //var userModel = Mapper.Map<hmis_user_base, hmisUserBase>(user);

                var responseUser = new UserEntity
                {
                    UserId = userData.EmailAddress,
                    UserName = userData.EmailAddress,
                    Password = userData.Password,
                    FirstName = userData.FirstName,
                    LastName = userData.LastName
                };

                return responseUser;
            }
            return null;
        }
Example #28
0
        public async Task <bool> ExistsById(string id)
        {
            var filter = new QueryFilter();

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

            var search   = _table.Query(filter);
            var querySet = await search.GetNextSetAsync();

            return(querySet.Count > 0);
        }
Example #29
0
        // Querying a Global Secondary Index
        // https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/GSI.html#GSI.Querying
        public static QueryOperationConfig pubDate(string date, int limit = 1)
        {
            var filter = new QueryFilter();

            filter.AddCondition("pubDate", QueryOperator.Equal, date);
            return(new QueryOperationConfig
            {
                Filter = filter,
                Limit = limit
            });
        }
Example #30
0
        public async Task QueryItems()
        {
            #region Query based on partition key: 'ID' in asc order
            QueryFilter queryFilter = new QueryFilter(nameof(Profile.CountryId), QueryOperator.Equal, "ID");
            var         rawDocList  = await _table.Query(queryFilter).GetRemainingAsync();

            List <Profile> profiles = rawDocList != null && rawDocList.Count > 0 ? rawDocList.Select(ConvertToProfile).ToList() : new List <Profile>();
            Console.WriteLine("\nQuery based on partition key: 'ID' in asc order");
            foreach (var item in profiles)
            {
                Console.WriteLine(item.ToString());
            }
            #endregion

            #region Query based on partition key: 'ID' in desc order
            queryFilter = new QueryFilter(nameof(Profile.CountryId), QueryOperator.Equal, "ID");
            rawDocList  = await _table.Query(new QueryOperationConfig
            {
                Filter         = queryFilter,
                BackwardSearch = true
            }).GetRemainingAsync();

            profiles = rawDocList != null && rawDocList.Count > 0 ? rawDocList.Select(ConvertToProfile).ToList() : new List <Profile>();
            Console.WriteLine("\nQuery based on partition key: 'ID' in desc order");
            foreach (var item in profiles)
            {
                Console.WriteLine(item.ToString());
            }
            #endregion


            #region Query based on partition key: 'ID' and the name must start with string 'Ra'
            try
            {
                queryFilter = new QueryFilter(nameof(Profile.CountryId), QueryOperator.Equal, "ID");
                queryFilter.AddCondition(nameof(Profile.Name), QueryOperator.BeginsWith, "Ra");
                rawDocList = await _table.Query(new QueryOperationConfig
                {
                    Filter = queryFilter
                }).GetRemainingAsync();

                profiles = rawDocList != null && rawDocList.Count > 0 ? rawDocList.Select(ConvertToProfile).ToList() : new List <Profile>();
                Console.WriteLine("\nQuery based on partition key: 'ID' and the name must contain string 'Ra'");
                foreach (var item in profiles)
                {
                    Console.WriteLine(item.ToString());
                }
            }
            catch (AmazonDynamoDBException ex)
            {
                Console.WriteLine(ex);
            }
            #endregion
        }