예제 #1
0
        public async Task <IActionResult> Get(string firstName, string lastName, string secondLastName, string curp)
        {
            var credentials = new BasicAWSCredentials(AWSAccessKeyId, AWSSecretAccessKey);
            var client      = new AmazonDynamoDBClient(credentials, RegionEndpoint.USWest2);

            ScanFilter scanFilter = new ScanFilter();

            scanFilter.AddCondition("FirstName", ScanOperator.Equal, firstName);
            scanFilter.AddCondition("LastName", ScanOperator.Equal, lastName);
            scanFilter.AddCondition("SecondLastName", ScanOperator.Equal, secondLastName);
            scanFilter.AddCondition("CURP", ScanOperator.Equal, curp);
            ScanOperationConfig soc = new ScanOperationConfig()
            {
                // AttributesToGet = new List { "Id", "Title", "ISBN", "Price" },
                Filter = scanFilter
            };
            DynamoDBContext            context      = new DynamoDBContext(client);
            AsyncSearch <EmployeesPTU> search       = context.FromScanAsync <EmployeesPTU>(soc, null);
            List <EmployeesPTU>        documentList = new List <EmployeesPTU>();

            do
            {
                documentList = await search.GetNextSetAsync(default(System.Threading.CancellationToken));
            } while (!search.IsDone);

            return(Ok(documentList));
        }
예제 #2
0
        public async Task <List <Model.ObjectCode> > List(string parentObjectCodeId)
        {
            ListTablesResponse existingTables = await client.ListTablesAsync();

            if (!existingTables.TableNames.Contains(TABLE_NAME))
            {
                await SetupTable(client, TABLE_NAME, "CodeId");
            }

            try
            {
                List <ScanCondition> filter = new List <ScanCondition>()
                {
                    new ScanCondition("ParentId", ScanOperator.Equal, parentObjectCodeId.ToUpper())
                };
                AsyncSearch <Model.ObjectCode> scan = DDBContext.ScanAsync <Model.ObjectCode>(filter);

                List <Model.ObjectCode> documentList = new List <Model.ObjectCode>();
                do
                {
                    documentList.AddRange(await scan.GetNextSetAsync());
                } while (!scan.IsDone);

                return(documentList);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error listing object codes: " + ex.Message);
            }
            return(null);
        }
예제 #3
0
        public async Task <IActionResult> GetAsync()
        {
            try
            {   // COGNITO SERVICE
                //AWSCredentials credentials = new CognitoAWSCredentials(cognitoID,RegionEndpoint.USEast1);
                //var client = new AmazonDynamoDBClient(credentials,RegionEndpoint.USEast1);

                // IAM SERVICE - Local
                //var credentials = new BasicAWSCredentials(AWSAccessKeyId, AWSSecretAccessKey);
                //var client = new AmazonDynamoDBClient(credentials, RegionEndpoint.USEast1);

                // This approach works when you are depending on a role
                var client = new AmazonDynamoDBClient(RegionEndpoint.USEast1);

                ScanFilter          scanFilter = new ScanFilter();
                ScanOperationConfig soc        = new ScanOperationConfig()
                {
                    Filter = scanFilter
                };
                DynamoDBContext    context      = new DynamoDBContext(client);
                AsyncSearch <lreb> search       = context.FromScanAsync <lreb>(soc, null);
                List <lreb>        documentList = new List <lreb>();
                do
                {
                    documentList = await search.GetNextSetAsync(default(System.Threading.CancellationToken));
                } while (!search.IsDone);

                return(Ok(documentList));
            }
            catch (Exception e)
            {
                return(StatusCode(500, e));
            }
        }
예제 #4
0
        public async Task <List <T> > GetAsyncSearchResult <T>(AsyncSearch <T> asyncSearch, CancellationToken cancellationToken)
        {
            var results = await asyncSearch.GetNextSetAsync(cancellationToken);

            while (!asyncSearch.IsDone && !cancellationToken.IsCancellationRequested)
            {
                results.AddRange(await asyncSearch.GetRemainingAsync(cancellationToken));
            }

            return(results);
        }
예제 #5
0
        /// <summary>
        /// Configures an async Query operation against DynamoDB, finding items that match the specified hash primary key.
        /// </summary>
        /// <param name="hashKeyValue">Hash key of the items to query.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <param name="take">The number of items to take.</param>
        /// <param name="queryFilter">Query filter for the Query operation operation.</param>
        /// <returns>The async task.</returns>
        private async Task <List <T> > QueryAsyncEx(object hashKeyValue, CancellationToken cancellationToken, int take = 100, List <ScanCondition> queryFilter = null)
        {
            List <T>        items        = new List <T>();
            AsyncSearch <T> result       = null;
            bool            foundEnought = false;

            // Add the filter.
            if (queryFilter != null)
            {
                // Add the query filter.
                DynamoDBOperationConfig operationConfig = new DynamoDBOperationConfig();
                operationConfig.QueryFilter = queryFilter;
                result = _context.QueryAsync <T>(hashKeyValue, operationConfig);
            }
            else
            {
                // Set the query.
                result = _context.QueryAsync <T>(hashKeyValue);
            }

            do
            {
                // Get the set of results.
                List <T> data = await result.GetNextSetAsync(cancellationToken);

                foreach (T entity in data)
                {
                    // Add the item found.
                    items.Add(entity);

                    // If we have enought.
                    if (items.Count >= take)
                    {
                        break;
                    }
                }

                // No more data.
                foundEnought = result.IsDone;

                // If we have enought.
                if (items.Count >= take)
                {
                    break;
                }
            }while (!foundEnought);

            // Return the list.
            return(items);
        }
예제 #6
0
        public async Task <List <MediaItem> > LoadByUniqueNameAsync(Guid accountId, string uniqueName, bool decending)
        {
            var stopwatch = Stopwatch.StartNew();

            try
            {
                var config = new DynamoDBContextConfig {
                    TableNamePrefix = _tablePrefix
                };
                var context = new DynamoDBContext(_client, config);

                var operationConfig = new DynamoDBOperationConfig
                {
                    IndexName           = "UniqueMediaKey-DateAdded-index",
                    TableNamePrefix     = _tablePrefix,
                    ConditionalOperator = ConditionalOperatorValues.And,
                    OverrideTableName   = TableName,
                    BackwardQuery       = decending
                };

                // Pagination doesn't work to well at present (or at-least not start/limit type for Dynamo).
                // Pagination needs to use datetime range.

                var hashKeyValue            = string.Format("{0}-{1}", accountId, uniqueName.ToLower());
                var operatorType            = QueryOperator.Between;
                IEnumerable <object> values = new List <object>
                {
                    DateTime.MinValue,
                    DateTime.UtcNow,
                };

                AsyncSearch <MediaItem> asyncSearch = context.QueryAsync <MediaItem>(hashKeyValue, operatorType, values, operationConfig);

                List <MediaItem> items = await asyncSearch.GetNextSetAsync();

                // Assume one batch of query items is enough.
                // really needs to be paginated on date range.
                return(items.ToList());
            }
            catch (Exception ex)
            {
                Logger.LogException(ex, "Exception loading media items");
                throw;
            }
            finally
            {
                stopwatch.Stop();
                Logger.LogMessage("LoadByUniqueNameAsync took: {0}ms", stopwatch.ElapsedMilliseconds);
            }
        }
예제 #7
0
        public async Task <List <MediaItem> > LoadByUserAsync(Guid userId, DateTime startDate, DateTime endDate)
        {
            var stopwatch = Stopwatch.StartNew();

            try
            {
                var config = new DynamoDBContextConfig {
                    TableNamePrefix = _tablePrefix
                };
                var context = new DynamoDBContext(_client, config);

                //QueryFilter filter = new QueryFilter();
                //filter.AddCondition("UserId", QueryOperator.Equal, userId);

                var operationConfig = new DynamoDBOperationConfig
                {
                    IndexName           = "UserId-DateAdded-index",
                    TableNamePrefix     = _tablePrefix,
                    ConditionalOperator = ConditionalOperatorValues.And,
                    OverrideTableName   = TableName,
                    BackwardQuery       = true,
                };

                var hashKeyValue            = userId;
                var operatorType            = QueryOperator.Between;
                IEnumerable <object> values = new List <object> {
                    startDate, endDate
                };
                AsyncSearch <MediaItem> asyncSearch = context.QueryAsync <MediaItem>(hashKeyValue, operatorType, values, operationConfig);

                List <MediaItem> items = await asyncSearch.GetNextSetAsync();

                Logger.LogMessage("LoadByUserAsync loaded {0} items", items.Count);

                return(items);
            }
            catch (Exception ex)
            {
                Logger.LogException(ex, "Exception loading media items (LoadByUserAsync)");
                throw;
            }
            finally
            {
                stopwatch.Stop();
                Logger.LogMessage("LoadByUserAsync took: {0} ms", stopwatch.ElapsedMilliseconds);
            }
        }
        public async Task <IEnumerable <Expense> > GetExpenses()
        {
            ScanFilter scanFilter = new ScanFilter();

            scanFilter.AddCondition("Id", ScanOperator.NotEqual, 0);

            ScanOperationConfig soc = new ScanOperationConfig()
            {
                Filter = scanFilter
            };
            AsyncSearch <Expense> search       = context.FromScanAsync <Expense>(soc, null);
            List <Expense>        documentList = new List <Expense>();

            do
            {
                documentList = await search.GetNextSetAsync(default(System.Threading.CancellationToken));
            } while (!search.IsDone);

            return(documentList);
        }
예제 #9
0
        public async Task <List <Coupon> > Get()
        {
            CreateTable();
            ScanFilter scanFilter = new ScanFilter();
            //scanFilter.AddCondition("StoreName", ScanOperator.Equal, storeName);

            ScanOperationConfig soc = new ScanOperationConfig()
            {
                Filter = scanFilter
            };
            DynamoDBContext      context      = new DynamoDBContext(dynamoDBClient);
            AsyncSearch <Coupon> search       = context.FromScanAsync <Coupon>(soc, null);
            List <Coupon>        documentList = new List <Coupon>();

            do
            {
                documentList = await search.GetNextSetAsync(default(System.Threading.CancellationToken));
            } while (!search.IsDone);

            return(documentList);
        }
        public List <TEntity> GetByList(List <FilterQuery> valuesAtributeScanOperator)
        {
            List <TEntity> listEntity;

            using (DynamoDBContext context = GetContext())
            {
                List <ScanCondition>  scanFilter          = GetScanCondition(valuesAtributeScanOperator);
                AsyncSearch <TEntity> query               = context.ScanAsync <TEntity>(scanFilter);
                List <TEntity>        partialResultDynamo = new List <TEntity>();
                List <TEntity>        totalResultDynamo   = new List <TEntity>();
                do
                {
                    partialResultDynamo.Clear();
                    partialResultDynamo = query.GetNextSetAsync().GetAwaiter().GetResult();
                    totalResultDynamo.AddRange(partialResultDynamo);
                } while (!query.IsDone);

                listEntity = totalResultDynamo;
            }
            return(listEntity);
        }
예제 #11
0
        public List <TEntity> GetAll()
        {
            List <TEntity> partialResultDynamo = new List <TEntity>();
            List <TEntity> totalResultDynamo   = new List <TEntity>();

            using DynamoDBContext context = GetContext();
            //Teniendo en cuenta la restricción de Dynamo en cuanto al límite de 1MB de los registros devueltos por cada consulta:
            AsyncSearch <TEntity> query = context.ScanAsync <TEntity>(null);

            do
            {
                partialResultDynamo.Clear();
                partialResultDynamo = query.GetNextSetAsync().Result.ToList();
                if (partialResultDynamo.Count > 0)                   //Si en la porción consultada obtuvo registros que cumplen con los filtros
                {
                    totalResultDynamo.AddRange(partialResultDynamo); //Añádalos.
                }
            } while (!query.IsDone);

            return(totalResultDynamo);
        }
예제 #12
0
        public static List <Goal> GetByEmail(string email)
        {
            List <Goal>         goals;
            AsyncSearch <Goal>  query     = context.QueryAsync <Goal>(email, QueryOperator.GreaterThan, new string[] { " " });
            Task <List <Goal> > taskQuery = query.GetNextSetAsync(default(CancellationToken));

            taskQuery.Wait();
            goals = taskQuery.Result;
            foreach (var goal in goals)
            {
                ScanOperationConfig config = new ScanOperationConfig();
                config.ConsistentRead = true;
                config.Filter         = new ScanFilter();
                config.Filter.AddCondition("GoalName", ScanOperator.Equal, goal.GoalName);
                var search = context.FromScanAsync <Goal>(config);
                Task <List <Goal> > taskScan = search.GetRemainingAsync();
                taskScan.Wait();
                goal.Members = taskScan.Result.Count;
            }
            return(goals);
        }
        public async Task <List <UniqueName> > ListAsync(Guid accountId, int start, int limit)
        {
            var stopwatch = Stopwatch.StartNew();

            try
            {
                var config = new DynamoDBContextConfig {
                    TableNamePrefix = _tablePrefix
                };
                var context = new DynamoDBContext(_client, config);

                var operationConfig = new DynamoDBOperationConfig
                {
                    IndexName           = "AccountId-index",
                    TableNamePrefix     = _tablePrefix,
                    ConditionalOperator = ConditionalOperatorValues.And,
                    OverrideTableName   = TableName,
                    BackwardQuery       = true,
                };

                // TODO: Figure out how to specify start and limit

                var hashKeyValue = accountId;
                AsyncSearch <UniqueName> asyncSearch = context.QueryAsync <UniqueName>(hashKeyValue, operationConfig);

                List <UniqueName> items = await asyncSearch.GetNextSetAsync();

                return(items);
            }
            catch (Exception ex)
            {
                Logger.LogException(ex, "Exception loading unique names: ");
                throw;
            }
            finally
            {
                stopwatch.Stop();
                Logger.LogMessage("Query unique names took: {0}ms", stopwatch.ElapsedMilliseconds);
            }
        }
예제 #14
0
        public async Task <List <Book> > GetBooksAsync()
        {
            ScanFilter scanFilter = new ScanFilter();

            scanFilter.AddCondition("Id", ScanOperator.NotEqual, 0);

            ScanOperationConfig soc = new ScanOperationConfig()
            {
                // AttributesToGet = new List { "Id", "Title", "ISBN", "Price" },
                Filter = scanFilter
            };
            DynamoDBContext    context      = new DynamoDBContext(dynamoDBClient);
            AsyncSearch <Book> search       = context.FromScanAsync <Book>(soc, null);
            List <Book>        documentList = new List <Book>();

            do
            {
                documentList = await search.GetNextSetAsync(default(System.Threading.CancellationToken));
            } while (!search.IsDone);

            return(documentList);
        }
예제 #15
0
        /// <summary>
        /// Configures an async Scan operation against DynamoDB, finding items that match the specified conditions.
        /// </summary>
        /// <param name="conditions">The scan conditions.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <param name="take">The number of items to take.</param>
        /// <returns>The async task.</returns>
        private async Task <List <T> > ScanAsyncEx(List <ScanCondition> conditions, CancellationToken cancellationToken, int take = 100)
        {
            List <T> items        = new List <T>();
            bool     foundEnought = false;

            // Set the query.
            AsyncSearch <T> result = _context.ScanAsync <T>(conditions);

            do
            {
                // Get the set of results.
                List <T> data = await result.GetNextSetAsync(cancellationToken);

                foreach (T entity in data)
                {
                    // Add the item found.
                    items.Add(entity);

                    // If we have enought.
                    if (items.Count >= take)
                    {
                        break;
                    }
                }

                // No more data.
                foundEnought = result.IsDone;

                // If we have enought.
                if (items.Count >= take)
                {
                    break;
                }
            }while (!foundEnought);

            // Return the list.
            return(items);
        }