/// <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);
        }
Ejemplo n.º 2
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);
            }
        }
Ejemplo n.º 3
0
        public async Task <Person> GetPersonByIdAsync(PersonQueryObject query)
        {
            _logger.LogDebug($"Calling IDynamoDBContext.LoadAsync for id {query.Id}");

            var result = await _dynamoDbContext.LoadAsync <PersonDbEntity>(query.Id).ConfigureAwait(false);

            return(result?.ToDomain());
        }
Ejemplo n.º 4
0
        public async Task <string> FetchLongUrl(string shortUrlKey)
        {
            //var context = new DynamoDBContext(amazonDynamoDB);

            var record = await context.LoadAsync <FromShortUrl>(shortUrlKey);

            return(record?.LongUrl);
        }
Ejemplo n.º 5
0
        Task <Family> IDataRepository.GetFamily(string churchId, string familyId)
        {
            _logger.LogInformation($"Looking up details of family with ChurchId:{churchId} and FamilyId:{familyId}");

            var family = _ddbContext.LoadAsync <Family>(churchId, familyId);

            _logger.LogInformation($"Found family with ChurchId:{churchId} and FamilyId:{familyId} = {family != null}");
            return(family);
        }
        public static async Task PerformCRUDOperations(IDynamoDBContext context)
        {
            int  bookId = 1001; // Some unique value.
            Book myBook = new Book
            {
                Id          = bookId,
                Title       = "object persistence-AWS SDK for.NET SDK-Book 1001",
                Isbn        = "111-1111111001",
                BookAuthors = new List <string> {
                    "Author 1", "Author 2"
                },
            };

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

            // Retrieve the book from the ProductCatalog table.
            Book bookRetrieved = await context.LoadAsync <Book>(bookId);

            // Update some properties.
            bookRetrieved.Isbn = "222-2222221001";

            // Update existing authors list with the following values.
            bookRetrieved.BookAuthors = new List <string> {
                " Author 1", "Author x"
            };
            await context.SaveAsync(bookRetrieved);

            // Retrieve the updated book. This time, add the optional
            // ConsistentRead parameter using DynamoDBContextConfig object.
            await context.LoadAsync <Book>(bookId, new DynamoDBContextConfig
            {
                ConsistentRead = true,
            });

            // Delete the book.
            await context.DeleteAsync <Book>(bookId);

            // Try to retrieve deleted book. It should return null.
            Book deletedBook = await context.LoadAsync <Book>(bookId, new DynamoDBContextConfig
            {
                ConsistentRead = true,
            });

            if (deletedBook == null)
            {
                Console.WriteLine("Book is deleted");
            }
        }
Ejemplo n.º 7
0
        public async Task <string> Authorize(string username, string password)
        {
            if (String.IsNullOrEmpty(username) ||
                String.IsNullOrEmpty(password))
            {
                return(null);
            }

            var user = await _dbContext.LoadAsync <User>(username);

            if (user is null)
            {
                return(null);
            }
            else
            {
                if (String.Equals(HashPassword(password), user.Password))
                {
                    var tokenString = JWTHelper.GenerateJWTToken(_options);

                    return(tokenString);
                }
                else
                {
                    _logger.LogInformation(string.Format("Authorization Failed. Bad Password for {0}", username));
                    throw new AuthZException();
                }
            }
        }
        /// <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);
        }
Ejemplo n.º 9
0
        public async Task <Project> GetProject(Guid id)
        {
            var project = await _context.LoadAsync <Models.Project>(id, BaseVersion);

            if (project == null)
            {
                return(default);
Ejemplo n.º 10
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public byte[] Get(string key)
        {
            var cacheItem = _dynamoDbContext.LoadAsync <T>(key).GetAwaiter().GetResult();

            if (cacheItem == null)
            {
                return(null);
            }

            if (cacheItem.Ttl >= _cacheTtlManager.ToUnixTime(DateTime.UtcNow))
            {
                return(_dynamoDbContext.LoadAsync <T>(key).GetAwaiter().GetResult().Value);
            }

            Remove(cacheItem.CacheId);
            return(default);
Ejemplo n.º 11
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);
        }
Ejemplo n.º 12
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}");
        }
        private async Task <bool> ReadWriteEventsToQueueFlag()
        {
            _logger.Trace("Beginning ReadWriteEventsToQueueFlag");
            string flagStr = null;

            if (_cfgDbContext == null)
            {
                flagStr = Environment.GetEnvironmentVariable(WRITE_EVENTS_TO_QUEUE_ENVIRONMENT_VARIABLE_LOOKUP);
                _logger.Debug($"Read environment variable: {flagStr}");
            }
            else
            {
                var dynamoRecord = await _cfgDbContext.LoadAsync <ConfigRecord>(WRITE_EVENTS_TO_QUEUE_ENVIRONMENT_VARIABLE_LOOKUP);

                flagStr = dynamoRecord?.Value;
                _logger.Debug($"Read config table: {flagStr}");
                if (string.IsNullOrEmpty(flagStr))
                {
                    _logger.Debug("Config table row is missing, defaulting flag to false.");
                    flagStr = false.ToString();
                }
            }

            var flagValue = Convert.ToBoolean(flagStr);

            _logger.Trace("Ending ReadWriteEventsToQueueFlag");
            return(flagValue);
        }
        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);
        }
Ejemplo n.º 15
0
        public async Task <Person> GetPerson(int personId)
        {
            var personDynamoDb = await _context.LoadAsync <PersonDynamoDb>(personId);

            var person = new Person(personDynamoDb);

            return(person);
        }
Ejemplo n.º 16
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);
        }
Ejemplo n.º 17
0
        public static async void TestCrudOperations(IDynamoDBContext context)
        {
            int  bookId = 1001; // Some unique value.
            Book myBook = new Book
            {
                Id          = bookId,
                Title       = "object persistence-AWS SDK for.NET SDK-Book 1001",
                Isbn        = "111-1111111001",
                BookAuthors = new List <string> {
                    "Author 1", "Author 2"
                },
            };

            // Save the book.
            await context.SaveAsync(myBook);

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

            // Update few properties.
            bookRetrieved.Isbn        = "222-2222221001";
            bookRetrieved.BookAuthors = new List <string> {
                " Author 1", "Author x"
            };                                                                        // Replace existing authors list with this.
            await context.SaveAsync(bookRetrieved);

            // Retrieve the updated book. This time add the optional ConsistentRead parameter using DynamoDBContextConfig object.
            await context.LoadAsync <Book>(bookId, new DynamoDBContextConfig
            {
                ConsistentRead = true
            });

            // Delete the book.
            await context.DeleteAsync <Book>(bookId);

            // Try to retrieve deleted book. It should return null.
            Book deletedBook = await context.LoadAsync <Book>(bookId, new DynamoDBContextConfig
            {
                ConsistentRead = true
            });

            if (deletedBook == null)
            {
                Console.WriteLine("Book is deleted");
            }
        }
Ejemplo n.º 18
0
        public async Task <Entity> GetEntityById(int id)
        {
            _logger.LogDebug($"Calling IDynamoDBContext.LoadAsync for id parameter {id}");

            var result = await _dynamoDbContext.LoadAsync <DatabaseEntity>(id).ConfigureAwait(false);

            return(result?.ToDomain());
        }
Ejemplo n.º 19
0
        public async Task <ServiceResult> UpdateItem(TDataType dataEntity)
        {
            var hashKeyProperty = typeof(TDataType).GetProperties()
                                  .Single(prop => prop.IsDefined(typeof(DynamoDBHashKeyAttribute), false));

            var partitionKey = hashKeyProperty.GetValue(dataEntity) as string;

            var record = await _dynamoDbContext.LoadAsync <TDataType>(partitionKey);

            if (record == null)
            {
                return(ServiceResult.Failed(ErrorCodes.Status.NotFound));
            }

            await _dynamoDbContext.SaveAsync <TDataType>(dataEntity);

            return(ServiceResult.Succeeded());
        }
Ejemplo n.º 20
0
            public async Task <Unit> Handle(Command request, CancellationToken cancellationToken)
            {
                var book = await _dataContext.LoadAsync <Book>(request.Book.ISBN, cancellationToken);

                book.Description = request.Book.Description;
                book.Title       = request.Book.Title;
                await _dataContext.SaveAsync(book, cancellationToken);

                return(Unit.Value);
            }
Ejemplo n.º 21
0
        /// <inheritdoc/>
        public async Task UpdateChatInfo(long id, bool isEnabled)
        {
            var chatInfo = await _dynamoDBContext.LoadAsync <TelegramChatInfo>(ChatInfoType.Chat.ToString(), id);

            if (chatInfo == null)
            {
                if (!isEnabled)
                {
                    _logger.LogWarning($"Trying to pause unknown chat ({id})");
                    return;
                }
                chatInfo = new TelegramChatInfo {
                    Id = id
                };
            }

            chatInfo.IsEnabled = isEnabled;
            await SaveEntityAsync(chatInfo);
        }
Ejemplo n.º 22
0
        public async Task <Book> Get(string isbn)
        {
            var book = await _dbContext.LoadAsync <RepositoryBook>(isbn);

            if (book == null)
            {
                throw new NotFoundException(isbn);
            }
            return(ConvertToBook(book));
        }
Ejemplo n.º 23
0
        public async Task <DeviceServiceResponse> GetDeviceBySerialNumber(string serialNumber)
        {
            try
            {
                var device = await _dbContext.LoadAsync <Device>(serialNumber);

                if (device != null)
                {
                    //create and map a service object to hide the device's secret
                    return(DeviceMapper.MapDevice(device));
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, string.Format("An error occured fetching device for serial number: {0}", serialNumber));
                throw ex;
            }

            return(null);
        }
Ejemplo n.º 24
0
        public Task <TAuthorization> FindByIdAsync(string identifier, CancellationToken cancellationToken)
        {
            if (identifier == null)
            {
                throw new ArgumentNullException(nameof(identifier));
            }

            cancellationToken.ThrowIfCancellationRequested();

            return(_context.LoadAsync <TAuthorization>(identifier, cancellationToken));
        }
Ejemplo n.º 25
0
        public async Task <StarWarsPun> Load(int id)
        {
            if (id < 0)
            {
                throw new ArgumentOutOfRangeException("id");
            }

            StarWarsPun pun = await _context.LoadAsync <StarWarsPun>(id);

            return(pun);
        }
Ejemplo n.º 26
0
        public async Task <TokenUser> Load(string id)
        {
            if (String.IsNullOrWhiteSpace(id))
            {
                throw new ArgumentNullException("id");
            }

            TokenUser user = await _context.LoadAsync <TokenUser>(id);

            return(user);
        }
Ejemplo n.º 27
0
        public async Task Confirm(ConfirmAdvertModel model)
        {
            //using (var context = new DynamoDBContext(_amazonDynamoDB))
            //{
            var record = await _dynamoDBContext.LoadAsync <AdvertDbModel>(model.Id);

            if (record == null)
            {
                throw new KeyNotFoundException($"A record with ID={model.Id} was not found.");
            }

            if (model.AdvertStatus == AdvertStatus.Active)
            {
                record.AdvertStatus = AdvertStatus.Active;
                await _dynamoDBContext.SaveAsync(record);
            }
            else
            {
                await _dynamoDBContext.DeleteAsync(record);
            }
            //}
        }
Ejemplo n.º 28
0
        public async Task <TUser> FindByIdAsync(string userId, CancellationToken cancellationToken)
        {
            if (userId == null)
            {
                throw new ArgumentNullException(nameof(userId));
            }

            cancellationToken.ThrowIfCancellationRequested();

            var user = await _context.LoadAsync <TUser>(userId, default(DateTimeOffset), cancellationToken);

            return(user?.DeletedOn == default(DateTimeOffset) ? user : null);
        }
        public async Task <TRole> FindByIdAsync(string roleId, CancellationToken cancellationToken)
        {
            if (roleId == null)
            {
                throw new ArgumentNullException(nameof(roleId));
            }

            cancellationToken.ThrowIfCancellationRequested();

            var role = await _context.LoadAsync <TRole>(roleId, default(DateTimeOffset), cancellationToken);

            return(role?.DeletedOn == default(DateTimeOffset) ? role : null);
        }
        public Incident GetIncidentById(Guid incidentId)
        {
            Console.WriteLine($"Getting blog {incidentId}");
            var incident = _dynamoDbContext.LoadAsync <Incident>(incidentId).Result;

            Console.WriteLine($"Found Incident: {incident != null}");

            if (incident == null)
            {
                throw new IncidentNotFoundException($"Could not locate {incidentId} in table {_tableName}");
            }

            return(incident);
        }