コード例 #1
0
 public MeasurementService(IDynamoDBContext dbContext, IAmazonDynamoDB dbClient, DeviceAlarmRecorder alarmRecorder, ILogger <MeasurementService> logger) : base(dbContext)
 {
     _dbContext     = dbContext;
     _dbClient      = dbClient;
     _alarmRecorder = alarmRecorder;
     _logger        = logger;
 }
コード例 #2
0
        /// <summary>
        /// Queries for replies posted within a specific time period.
        /// </summary>
        /// <param name="context">The DynamoDB context used to perform the query.</param>
        /// <param name="forumName">The name of the ofrum we're interested in.</param>
        /// <param name="threadSubject">Information about the subject we are
        /// interested in.</param>
        public static async Task FindRepliesPostedWithinTimePeriod(
            IDynamoDBContext context,
            string forumName,
            string threadSubject)
        {
            string forumId = forumName + "#" + threadSubject;

            Console.WriteLine("\nReplies posted within time period:");

            DateTime startDate = DateTime.UtcNow - TimeSpan.FromDays(30);
            DateTime endDate   = DateTime.UtcNow - TimeSpan.FromDays(1);

            List <object> times = new List <object>();

            times.Add(startDate);
            times.Add(endDate);

            List <ScanCondition> scs = new List <ScanCondition>();
            var sc = new ScanCondition("LastPostedBy", ScanOperator.Between, times.ToArray());

            scs.Add(sc);

            var cfg = new DynamoDBOperationConfig
            {
                QueryFilter = scs
            };

            AsyncSearch <Reply> response         = context.QueryAsync <Reply>(forumId, cfg);
            IEnumerable <Reply> repliesInAPeriod = await response.GetRemainingAsync();

            foreach (Reply r in repliesInAPeriod)
            {
                Console.WriteLine("{r.Id}\t{r.PostedBy}\t{r.Message}\t{r.ReplyDateTime}");
            }
        }
コード例 #3
0
        public static async void AddRetrieveUpdateBook(IDynamoDBContext context)
        {
            // Create a book.
            DimensionType myBookDimensions = new DimensionType()
            {
                Length    = 8M,
                Height    = 11M,
                Thickness = 0.5M
            };

            Book myBook = new Book
            {
                Id          = 501,
                Title       = "AWS SDK for .NET Object Persistence Model Handling Arbitrary Data",
                Isbn        = "999-9999999999",
                BookAuthors = new List <string> {
                    "Author 1", "Author 2"
                },
                Dimensions = myBookDimensions
            };

            await context.SaveAsync(myBook);

            // Retrieve the book.
            Book bookRetrieved = await context.LoadAsync <Book>(501);

            // 3. Update property (book dimensions).
            bookRetrieved.Dimensions.Height    += 1;
            bookRetrieved.Dimensions.Length    += 1;
            bookRetrieved.Dimensions.Thickness += 0.2M;

            // Update the book.
            await context.SaveAsync(bookRetrieved);
        }
コード例 #4
0
 public UserResolverService(IHttpContextAccessor context, IDynamoDBContext dbContext,
                            ILogger <UserResolverService> log)
 {
     Log        = log;
     _context   = context;
     _dbContext = dbContext;
 }
コード例 #5
0
 //NOTE: Used by Unit Tests
 public ProcessKinesisEvents(IDynamoDBContext aeDbContext, IDynamoDBContext cfgDbContext, IAwsSqsFacade sqsFacade)
 {
     _aeDbContext    = aeDbContext;
     _cfgDbContext   = cfgDbContext;
     _sqsFacade      = sqsFacade;
     _ahgFilterLevel = 0;
 }
コード例 #6
0
ファイル: DynamoDbRepository.cs プロジェクト: imomou/LogFarm
        public DynamoDbRepository(string ddbTableName, string applicationName)
        {
            Contract.Requires(
                !string.IsNullOrEmpty(ddbTableName) &&
                !string.IsNullOrEmpty(applicationName)
                );

            _ddbTableName    = ddbTableName;
            _applicationName = applicationName;

            var awskey    = WebConfigurationManager.AppSettings["AWSAccessKey"] ?? string.Empty;
            var awsSecret = WebConfigurationManager.AppSettings["AWSSecretKey"] ?? string.Empty;
            var regionStr = WebConfigurationManager.AppSettings["AWSRegion"] ?? string.Empty;

            var region = RegionEndpoint.GetBySystemName(regionStr);

            if (region.DisplayName.ToLower().Contains("unknown"))
            {
                throw new ApplicationException(string.Format("Invalid region configured {0}", regionStr));
            }

            if (string.IsNullOrEmpty(awskey) && string.IsNullOrEmpty(awsSecret))
            {
                _ddbcontext = new DynamoDBContext(region);
            }
            else
            {
                _ddbcontext = new DynamoDBContext(new AmazonDynamoDBClient(awskey, awsSecret, region));
            }
        }
コード例 #7
0
 public DbIndex(IDynamoDBContext db, string indexName)
 {
     Db     = db;
     Config = new DynamoDBOperationConfig {
         IndexName = indexName
     };
 }
コード例 #8
0
        public override async Task Start(string _postJson, IDynamoDBContext _dynamoDBContext)
        {
            await base.Start(_postJson, _dynamoDBContext);

            User user          = JsonConvert.DeserializeObject <User>(_postJson);
            var  signUpRequest = new SignUpRequest
            {
                ClientId = ApiDefine.CognitoClientId,
                Password = user.Password,
                Username = user.Email
            };
            var emailAttribute = new AttributeType
            {
                Name  = "email",
                Value = user.Email
            };
            var nickNameAttribute = new AttributeType
            {
                Name  = "nickname",
                Value = user.Name
            };

            signUpRequest.UserAttributes.Add(emailAttribute);
            signUpRequest.UserAttributes.Add(nickNameAttribute);

            var client = new AmazonCognitoIdentityProviderClient(ApiDefine.Credentials, RegionEndpoint.USWest2);
            var result = await client.SignUpAsync(signUpRequest);

            JsPath = "cognito/sign.up.js";
            string json = JsonConvert.SerializeObject(result);

            await loadJs();

            ExecJs = ExecJs.Replace("JSON", json.Replace("\"", "\\\""));
        }
コード例 #9
0
        /// <summary>
        /// Update an item in a DynamoDB table that uses the modified
        /// data model described in the Entry class.
        /// </summary>
        /// <param name="context">The initialized DynamoDB context used
        /// to update the item in the DynamoDB table.</param>
        /// <param name="id">The id of the item to be updated.</param>
        /// <param name="status">The new status value to write to the
        /// existing item.</param>
        /// <returns>An Entry object containing the updated data.</returns>
        public static async Task <Entry> UpdateTableItemAsync(IDynamoDBContext context, string id, string status)
        {
            // Retrieve the existing order.
            Entry orderRetrieved = await context.LoadAsync <Entry>(id, "Order");

            // Trap any nulls.
            if (orderRetrieved is null)
            {
                throw new ArgumentException("The ID " + id + " did not identify any current order");
            }

            // Make sure it's an order.
            if (orderRetrieved.Area != "Order")
            {
                throw new ArgumentException("The ID " + id + " did NOT identify an order, but instead identified a " + orderRetrieved.Area);
            }

            // Update the status of the order.
            orderRetrieved.OrderStatus = status;
            await context.SaveAsync(orderRetrieved);

            // Retrieve the updated item.
            Entry updatedOrder = await context.LoadAsync <Entry>(id, "Order", new DynamoDBOperationConfig
            {
                ConsistentRead = true,
            });

            return(updatedOrder);
        }
コード例 #10
0
        public override async Task Start(string _postJson, IDynamoDBContext _dynamoDBContext)
        {
            await base.Start(_postJson, _dynamoDBContext);

            JsPath = "cognito/index.view.js";
            await loadJs();
        }
コード例 #11
0
 protected BaseScenario(TestServerFixture testServerFixture)
 {
     TestServer      = testServerFixture.Server;
     HttpClient      = testServerFixture.CreateClient();
     DynamoDbContext = TestServer.Services.GetRequiredService <IDynamoDBContext>();
     SqsClient       = TestServer.Services.GetRequiredService <IAmazonSQS>();
 }
コード例 #12
0
        public DataRepository(ILogger <DataRepository> logger)
        {
            _logger = logger;

            AWSConfigsDynamoDB.Context.TypeMappings[typeof(Church)] =
                new TypeMapping(typeof(Church), DdbTableNames.ChurchtableName);
            AWSConfigsDynamoDB.Context.TypeMappings[typeof(Family)] =
                new TypeMapping(typeof(Family), DdbTableNames.FamilytableName);
            AWSConfigsDynamoDB.Context.TypeMappings[typeof(Member)] =
                new TypeMapping(typeof(Member), DdbTableNames.MembertableName);

            var config = new Amazon.DynamoDBv2.DataModel.DynamoDBContextConfig
            {
                Conversion       = DynamoDBEntryConversion.V2,
                IgnoreNullValues = true
            };

            _ddbContext = new DynamoDBContext(new AmazonDynamoDBClient(), config);

            _churchesTable = _ddbContext.GetTargetTable <Church>(new DynamoDBOperationConfig {
                IgnoreNullValues = true
            });
            _familiesTable = _ddbContext.GetTargetTable <Family>(new DynamoDBOperationConfig {
                IgnoreNullValues = true
            });
            _membersTable = _ddbContext.GetTargetTable <Member>(new DynamoDBOperationConfig {
                IgnoreNullValues = true
            });
        }
コード例 #13
0
 public async void Create(CollectiveEF collectiveEF)
 {
     using (IDynamoDBContext context = _dbConnection.Context())
     {
         await context.SaveAsync(collectiveEF);
     }
 }
コード例 #14
0
        /// <summary>
        /// Creates a book, adds it to the DynamoDB ProductCatalog table, retrieves
        /// the new book from the table, updates the dimensions and writes the
        /// changed item back to the table.
        /// </summary>
        /// <param name="context">The DynamoDB context object used to write and
        /// read data from the table.</param>
        public static async Task AddRetrieveUpdateBook(IDynamoDBContext context)
        {
            // Create a book.
            DimensionType myBookDimensions = new DimensionType()
            {
                Length    = 8M,
                Height    = 11M,
                Thickness = 0.5M,
            };

            Book myBook = new Book
            {
                Id          = 501,
                Title       = "AWS SDK for .NET Object Persistence Model Handling Arbitrary Data",
                Isbn        = "999-9999999999",
                BookAuthors = new List <string> {
                    "Author 1", "Author 2"
                },
                Dimensions = myBookDimensions,
            };

            // Add the book to the DynamoDB table ProductCatalog.
            await context.SaveAsync(myBook);

            // Retrieve the book.
            Book bookRetrieved = await context.LoadAsync <Book>(501);

            // Update the book dimensions property.
            bookRetrieved.Dimensions.Height    += 1;
            bookRetrieved.Dimensions.Length    += 1;
            bookRetrieved.Dimensions.Thickness += 0.2M;

            // Write the changed item to the table.
            await context.SaveAsync(bookRetrieved);
        }
コード例 #15
0
        public static async Task <PagedResult <TEntity> > GetPagedQueryResultsAsync <TEntity>(
            this IDynamoDBContext dynamoDbContext, QueryOperationConfig queryConfig) where TEntity : class
        {
            var dbResults = new List <TEntity>();
            var table     = dynamoDbContext.GetTargetTable <TEntity>();

            var search     = table.Query(queryConfig);
            var resultsSet = await search.GetNextSetAsync().ConfigureAwait(false);

            var paginationToken = search.PaginationToken;

            if (resultsSet.Any())
            {
                dbResults.AddRange(dynamoDbContext.FromDocuments <TEntity>(resultsSet));

                // Look ahead for any more, but only if we have a token
                if (!string.IsNullOrEmpty(PaginationDetails.EncodeToken(paginationToken)))
                {
                    queryConfig.PaginationToken = paginationToken;
                    queryConfig.Limit           = 1;
                    search     = table.Query(queryConfig);
                    resultsSet = await search.GetNextSetAsync().ConfigureAwait(false);

                    if (!resultsSet.Any())
                    {
                        paginationToken = null;
                    }
                }
            }

            return(new PagedResult <TEntity>(dbResults, new PaginationDetails(paginationToken)));
        }
コード例 #16
0
        public string Retrieve(string userId, string firstName, DateTime weightDate)
        {
            try
            {
                using (IDynamoDBContext context = Factory.DynamoDBContext)
                {
                    WeighInUser user = context.LoadAsync <WeighInUser>(userId, firstName).Result;

                    if (user == null)
                    {
                        throw new WeighInException($"User \"{userId},{firstName}\" not found");
                    }

                    WeighInWeight weight = context.LoadAsync <WeighInWeight>(user.UserKey, weightDate).Result;

                    return(JsonConvert.SerializeObject(weight));
                }
            }
            catch (Exception ex)
            {
                Factory.Logger.Log($"Error getting WeighInWeight with userId=\"{userId}\" and firstName=\"{firstName}\" and weightDate=\"{weightDate}\"");
                Factory.Logger.Log(ex.Message);
                Factory.Logger.Log(ex.StackTrace);
                throw new WeighInException(ex.Message);
            }
        }
コード例 #17
0
        /// <summary>
        /// Queries a DynamoDB table to find replies posted within the last 15 days.
        /// </summary>
        /// <param name="context">The DynamoDB context used to perform the query.</param>
        /// <param name="forumName">The name of the forum we're interested in.</param>
        /// <param name="threadSubject">The thread object containing the query parameters.</param>
        public static async Task FindRepliesInLast15Days(
            IDynamoDBContext context,
            string forumName,
            string threadSubject)
        {
            string   replyId         = $"{forumName} #{threadSubject}";
            DateTime twoWeeksAgoDate = DateTime.UtcNow - TimeSpan.FromDays(15);

            List <object> times = new List <object>();

            times.Add(twoWeeksAgoDate);

            List <ScanCondition> scs = new List <ScanCondition>();
            var sc = new ScanCondition("LastPostedBy", ScanOperator.GreaterThan, times.ToArray());

            scs.Add(sc);

            var cfg = new DynamoDBOperationConfig
            {
                QueryFilter = scs,
            };

            AsyncSearch <Reply> response      = context.QueryAsync <Reply>(replyId, cfg);
            IEnumerable <Reply> latestReplies = await response.GetRemainingAsync();

            Console.WriteLine("\nReplies in last 15 days:");

            foreach (Reply r in latestReplies)
            {
                Console.WriteLine($"{r.Id}\t{r.PostedBy}\t{r.Message}\t{r.ReplyDateTime}");
            }
        }
コード例 #18
0
        public static async Task GetBook(IDynamoDBContext context, int productId)
        {
            Book bookItem = await context.LoadAsync <Book>(productId);

            Console.WriteLine("\nGetBook: Printing result.....");
            Console.WriteLine($"Title: {bookItem.Title} \n ISBN:{bookItem.Isbn} \n No. of pages: {bookItem.PageCount}");
        }
コード例 #19
0
 public DynamoDBAdvertStorageService(IMapper mapper, IAmazonDynamoDB amazonDynamoDB,
                                     IDynamoDBContext dynamoDBContext)
 {
     _mapper          = mapper;
     _amazonDynamoDB  = amazonDynamoDB;
     _dynamoDBContext = dynamoDBContext;
 }
コード例 #20
0
        public async static void SingleTableBatchWrite(IDynamoDBContext context)
        {
            Book book1 = new Book
            {
                Id              = 902,
                InPublication   = true,
                Isbn            = "902-11-11-1111",
                PageCount       = "100",
                Price           = 10,
                ProductCategory = "Book",
                Title           = "My book3 in batch write"
            };
            Book book2 = new Book
            {
                Id              = 903,
                InPublication   = true,
                Isbn            = "903-11-11-1111",
                PageCount       = "200",
                Price           = 10,
                ProductCategory = "Book",
                Title           = "My book4 in batch write"
            };

            var bookBatch = context.CreateBatchWrite <Book>();

            bookBatch.AddPutItems(new List <Book> {
                book1, book2
            });

            Console.WriteLine("Adding two books to ProductCatalog table.");
            await bookBatch.ExecuteAsync();
        }
コード例 #21
0
 public DataStoreProvider(IJWTHelper _myJWTHelper, IAmazonDynamoDB client)
 {
     this.Client      = client;
     this.context     = new DynamoDBContext(this.Client);
     dataStoreTable   = Table.LoadTable(this.Client, "BankServer_UserData");
     this.myJWTHelper = _myJWTHelper;
 }
コード例 #22
0
 public ProjectAccessor(IDynamoDBContext context, IAmazonS3 s3Client, IMapper mapper, ILogger <ProjectAccessor> logger, IOptions <AwsResourceConfig> options)
 {
     _context  = context;
     _s3Client = s3Client;
     _mapper   = mapper;
     _logger   = logger;
     _config   = options.Value;
 }
コード例 #23
0
ファイル: DynamoStorageHandler.cs プロジェクト: BAPostma/Loft
        public DynamoStorageHandler()
        {
            TableName = Configuration.DynamoDbTableName;

            _client  = new AmazonDynamoDBClient();
            _table   = Table.LoadTable(_client, TableName);
            _context = new DynamoDBContext(_client);
        }
コード例 #24
0
 public BrowserRepository(IAmazonDynamoDB client, string tableName)
 {
     this.config = new DynamoDBOperationConfig
     {
         OverrideTableName = tableName
     };
     this.context = new DynamoDBContext(client, this.config);
 }
コード例 #25
0
 public static async Task <IEnumerable <T> > WhereByIds <T>(this IDynamoDBContext context, IList <string> ids = null)
     where T : class
 {
     return(ids.IsNull()
         ? new List <T>()
         : await context.Where <T>(new ScanCondition(HashKeyConstants.Default, ScanOperator.In,
                                                     ids.Distinct().ToArray())));
 }
コード例 #26
0
        public static async void GetBook(IDynamoDBContext context, int productId)
        {
            Book bookItem = await context.LoadAsync <Book>(productId);

            Console.WriteLine("\nGetBook: Printing result.....");
            Console.WriteLine("Title: {0} \n No.Of threads:{1} \n No. of messages: {2}",
                              bookItem.Title, bookItem.Isbn, bookItem.PageCount);
        }
コード例 #27
0
        private async Task <Blog> LoadBlog(IDynamoDBContext context, Guid BlogId)
        {
            var blogDoc = await context.LoadAsync <BlogDocument>(BlogId.ToString());

            var blog = await BuildBlog(blogDoc);

            return(blog);
        }
コード例 #28
0
ファイル: DBDataService.cs プロジェクト: SerikM/optimiser
        public DbDataService(IAmazonDynamoDB dynamoDbClient)
        {
            AWSConfigsDynamoDB.Context.TypeMappings[typeof(T)] = new Amazon.Util.TypeMapping(typeof(T), typeof(T).Name);
            var conf = new DynamoDBContextConfig {
                Conversion = DynamoDBEntryConversion.V2
            };

            _ddbContext = new DynamoDBContext(dynamoDbClient, conf);
        }
コード例 #29
0
        public Fixture()
        {
            var clientConfig = new AmazonDynamoDBConfig {
                ServiceURL = "http://localhost:8000"
            };

            _amazonDynamoDb = new AmazonDynamoDBClient("local", "local", clientConfig);
            Context         = new DynamoDBContext(_amazonDynamoDb);
        }
コード例 #30
0
        public DynamoCrudRepository()
        {
            var config = new DynamoDBContextConfig {
                Conversion = DynamoDBEntryConversion.V2
            };

            client    = new AmazonDynamoDBClient();
            dbContext = new DynamoDBContext(client, config);
        }
コード例 #31
0
ファイル: Utils.cs プロジェクト: rossmas/aws-sdk-net
 public static object InstantiateConverter(Type objectType, IDynamoDBContext context)
 {
     return InstantiateHelper(objectType, validConverterConstructorInputs, new object[] { context });
 }