public async Task Initialize(bool createTables = false, ProvisionedThroughput provisionedThroughput = null, StreamSpecification streamSpecification = null)
        {
            if (createTables)
            {
                Table table = _dynamoDBContext.GetTargetTable <TReadModel>();

                var createTableRequest = new CreateTableRequest()
                {
                    ProvisionedThroughput = provisionedThroughput,
                    TableName             = table.TableName,
                    LocalSecondaryIndexes = table.LocalSecondaryIndexes
                                            .Select(kv => new LocalSecondaryIndex()
                    {
                        KeySchema  = kv.Value.KeySchema,
                        IndexName  = kv.Value.IndexName,
                        Projection = kv.Value.Projection
                    }).ToList(),
                    GlobalSecondaryIndexes = table.GlobalSecondaryIndexes.Select(kv => new GlobalSecondaryIndex()
                    {
                        KeySchema             = kv.Value.KeySchema,
                        Projection            = kv.Value.Projection,
                        IndexName             = kv.Value.IndexName,
                        ProvisionedThroughput = new ProvisionedThroughput(kv.Value.ProvisionedThroughput.ReadCapacityUnits, kv.Value.ProvisionedThroughput.WriteCapacityUnits)
                    }).ToList(),
                    AttributeDefinitions = table.Attributes,
                    StreamSpecification  = streamSpecification,
                    KeySchema            = table.Keys.Select(kv => new KeySchemaElement(kv.Key, kv.Value.IsHash ? KeyType.HASH : KeyType.RANGE)).ToList()
                };

                await _dynamoDBClient.CreateTableAsync(createTableRequest).ConfigureAwait(false);
            }
        }
Esempio n. 2
0
        public async Task <IEnumerable <Transaction> > AllTransactions()
        {
            var table          = _context.GetTargetTable <Transaction>();
            var scanConditions = new List <ScanCondition>()
            {
                new ScanCondition("id", ScanOperator.IsNotNull)
            };
            var searchResults = _context.ScanAsync <Transaction>(scanConditions, null);

            return((IEnumerable <Transaction>) await searchResults.GetNextSetAsync());
        }
Esempio n. 3
0
        public void Save(Driver driver)
        {
            var table = _ddbContext.GetTargetTable <Driver>();

            var doc = _ddbContext.ToDocument(driver);

            if (driver.ModifiedAt == null)
            {
                doc[nameof(Driver.ModifiedAt)] = DynamoDBNull.Null;
                table.PutItemAsync(doc).Wait();
            }
            else
            {
                table.UpdateItemAsync(doc).Wait();
            }
        }
Esempio n. 4
0
        public static Dictionary <string, AttributeValue> MakeKey <T>(this DynamoDBContext context, T item)
        {
            var doc   = context.ToDocument(item);
            var table = context.GetTargetTable <T>();
            var key   = table.MakeKey(doc);

            return(key);
        }
Esempio n. 5
0
        public static void Add <TModel>(AmazonDynamoDBClient client, TModel model)
        {
            DynamoDBContext context = new DynamoDBContext(client);
            var             table   = context.GetTargetTable <TModel>();

            JsonSerializerOptions options = new JsonSerializerOptions
            {
                IgnoreNullValues = true
            };
            var      modelJson = JsonSerializer.Serialize(model, options);
            Document item      = Document.FromJson(modelJson);

            table.PutItemAsync(item).GetAwaiter().GetResult();
        }
Esempio n. 6
0
        private FilterResponse <TEntity> GetAllByFiltersCurrentLimit(FilterRequest request)
        {
            string paginationToken;
            int    total;

            using DynamoDBContext context = GetContext();
            var table = context.GetTargetTable <TEntity>();

            Task <int> taskTotalElements = GetTotalRecords(table, (FilterRequest)request.Clone());

            List <TEntity> totalElements = GetElements(request, table, context, out Search search, out TEntity lastElementGeneral);

            #region GeneratePaginationToken Y TotalResults
            if (request.Limit > 0)
            {
                TEntity lastElementResult = totalElements.LastOrDefault();

                if (search.PaginationToken == "{}" && lastElementGeneral != lastElementResult) //Si encuentra {} es porque tomó un
                                                                                               //rango de búsqueda tan grande, que logró terminar la búsqueda (search.IsDone==true) y
                                                                                               //por lo tanto, no genera paginationToken.
                {
                    //Se hace una búsqueda con límite 1 para obtener el formato correcto de paginationToken
                    var searchForPagTokenFormat = GetFormatPaginationToken(table, request);
                    paginationToken = GeneratePaginationToken(searchForPagTokenFormat.PaginationToken, lastElementResult);
                }
                else if (search.PaginationToken != "{}")
                {
                    paginationToken = GeneratePaginationToken(search.PaginationToken, lastElementResult);
                }
                else
                {
                    paginationToken = search.PaginationToken;
                }

                total = taskTotalElements != null && taskTotalElements.Result > 0 ? taskTotalElements.Result : search.Count;
            }
            else
            {
                paginationToken = search.PaginationToken;
                total           = totalElements.Count;
            }
            #endregion

            return(new FilterResponse <TEntity>
            {
                Elements = totalElements,
                PaginationToken = paginationToken,
                Total = total
            });
        }
Esempio n. 7
0
        public async Task <ICollection <ZipCode> > Search()
        {
            using (var dynamoDbContext = new DynamoDBContext(dbClientFactory.Value, new DynamoDBContextConfig {
                Conversion = DynamoDBEntryConversion.V2
            }))
            {
                var zipCodeTable = dynamoDbContext.GetTargetTable <ZipCode>();

                var randZip = rand.Next(10).ToString("D5");

                var keyExpr = new Expression();
                keyExpr.ExpressionStatement       = "Code = :v_code";
                keyExpr.ExpressionAttributeValues = new Dictionary <string, DynamoDBEntry>
                {
                    [":v_code"] = new Primitive(randZip)
                };

                var pageSize = 25;

                var query = zipCodeTable.Query(new QueryOperationConfig()
                {
                    IndexName       = "Code-index",
                    KeyExpression   = keyExpr,
                    PaginationToken = "{}",
                    Limit           = 5 // let's limit this to cause more GetNextSetAsync calls, this is artificial ...
                });

                var bucket = new List <ZipCode>(pageSize); // 25 is our bucket or page size. After we fill it, we are good...

                var i = 0;
                do
                {
                    i++;

                    var docs = await query.GetNextSetAsync();

                    IEnumerable <ZipCode> zipCodes = dynamoDbContext.FromDocuments <ZipCode>(docs);

                    bucket.AddRange(zipCodes);

                    if (query.PaginationToken == "{}" || query.IsDone)
                    {
                        break; // BREAK!!! there are no more records
                    }
                } while (bucket.Count < pageSize);

                return(bucket);
            }
        }
Esempio n. 8
0
        public async Task <IList <T> > Get(string paginationToken = null, CancellationToken cancellationToken = default)
        {
            var table   = DynamoDBContext.GetTargetTable <T>();
            var scanOps = new ScanOperationConfig();

            if (!string.IsNullOrEmpty(paginationToken))
            {
                scanOps.PaginationToken = paginationToken;
            }

            var             results = table.Scan(scanOps);
            List <Document> data    = await results.GetNextSetAsync(cancellationToken).ConfigureAwait(false);

            return(DynamoDBContext.FromDocuments <T>(data).ToList());
        }
Esempio n. 9
0
        public async Task <WriterOutputModel> All(string paginationToken = "")
        {
            // Get the Table ref from the Model
            var table = _context.GetTargetTable <Writer>();

            // If there's a PaginationToken
            // Use it in the Scan options
            // to fetch the next set
            var scanOps = new ScanOperationConfig();

            if (!string.IsNullOrEmpty(paginationToken))
            {
                scanOps.PaginationToken = paginationToken;
            }

            // returns the set of Document objects
            // for the supplied ScanOptions
            var             results = table.Scan(scanOps);
            List <Document> data    = await results.GetNextSetAsync();

            // transform the generic Document objects
            // into our Entity Model
            IEnumerable <Writer> Writers = _context.FromDocuments <Writer>(data);

            // Pass the PaginationToken
            // if available from the Results
            // along with the Result set
            return(new WriterOutputModel
            {
                PaginationToken = results.PaginationToken,
                Writers = Writers,
                ResultsType = ResultsType.List
            });

            /* The Non-Pagination approach */
            //var scanConditions = new List<ScanCondition>() { new ScanCondition("Id", ScanOperator.IsNotNull) };
            //var searchResults = _context.ScanAsync<Writer>(scanConditions, null);
            //return await searchResults.GetNextSetAsync();
        }
Esempio n. 10
0
        public async Task <QuoteCollection> GetQuotes(string paginationToken = "")
        {
            var table = _context.GetTargetTable <Quote>();

            var scanOps = new ScanOperationConfig();

            if (!string.IsNullOrEmpty(paginationToken))
            {
                scanOps.PaginationToken = paginationToken;
            }

            var             results = table.Scan(scanOps);
            List <Document> data    = await results.GetNextSetAsync();

            IEnumerable <Quote> quotes = _context.FromDocuments <Quote>(data);

            return(new QuoteCollection
            {
                PaginationToken = results.PaginationToken,
                Quotes = quotes
            });
        }
Esempio n. 11
0
        public DynamoTableAccess(DynamoDBContext context)
        {
            Context = context;

            Table = Context.GetTargetTable <T>();
        }