public async Task TransactWriteItemsAsync()
        {
            var request = new TransactWriteItemsRequest();

            request.TransactItems = new List <TransactWriteItem>();
            request.TransactItems.AddRange(_putItems);
            request.TransactItems.AddRange(_deleteItems);
            await _client.TransactWriteItemsAsync(request);
        }
Esempio n. 2
0
        public async Task CommitWriteTransaction()
        {
            var request = new TransactWriteItemsRequest
            {
                TransactItems          = writeActions,
                ReturnConsumedCapacity = ReturnConsumedCapacity.TOTAL
            };

            var response = await amazonDynamoDB.TransactWriteItemsAsync(request);
        }
Esempio n. 3
0
        private void BatchDynamo(List <TransactWriteItem> items)
        {
            var trans = new TransactWriteItemsRequest()
            {
                TransactItems          = items,
                ReturnConsumedCapacity = ReturnConsumedCapacity.TOTAL
            };

            var response = base.GetDynamo().TransactWriteItemsAsync(trans).Result;
        }
Esempio n. 4
0
        public void Handle(Event @event)
        {
            var request            = new TransactWriteItemsRequest();
            var transactWriteItems = new List <TransactWriteItem>
            {
                GetInsertEvent(@event),
                GetUpdateState(@event)
            };

            request.TransactItems = transactWriteItems;
            var response = _dbClient.TransactWriteItemsAsync(request);

            response.Wait();
        }
Esempio n. 5
0
        public void Handle(Event _event)
        {
            TransactWriteItemsRequest request            = new TransactWriteItemsRequest();
            List <TransactWriteItem>  transactWriteItems = new List <TransactWriteItem>();

            transactWriteItems.Add(GetInsertEvent(_event));
            transactWriteItems.Add(GetUpdateState(_event));
            request.TransactItems = transactWriteItems;

            var response = _dbClient.TransactWriteItemsAsync(request);

            response.Wait();

            // TODO: Handle exceptions
        }
        public async Task <TransactWriteItemsResponse> Commit(string clientRequestToken, CancellationToken cancellationToken = default)
        {
            if (_uoWState != UoWState.Started)
            {
                throw new UnitOfWorkNotStartedException();
            }

            var request = new TransactWriteItemsRequest
            {
                TransactItems      = _operations.ToList(),
                ClientRequestToken = clientRequestToken
            };

            _uoWState = UoWState.Committed;
            return(await _client.TransactWriteItemsAsync(request, cancellationToken).ConfigureAwait(false));
        }
Esempio n. 7
0
        public bool FreezeMoney(Order order)
        {
            Console.WriteLine("Aca voy");
            Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));
            TransactWriteItemsRequest request            = new TransactWriteItemsRequest();
            List <TransactWriteItem>  transactWriteItems = new List <TransactWriteItem>();

            transactWriteItems.Add(GetInsertOrderFlow(order));
            transactWriteItems.Add(GetUpdateContract(order));

            request.TransactItems = transactWriteItems;

            var response = DbClient.TransactWriteItemsAsync(request);

            response.Wait();
            Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));
            return(response.IsCompletedSuccessfully);
        }
Esempio n. 8
0
        public async Task <Customer> Get(
            CustomerDTO inboundCustomer)
        {
            var customer = new Customer(
                inboundCustomer.Username,
                inboundCustomer.EmailAddress,
                inboundCustomer.Name);
            var customerEmail = new CustomerEmail(inboundCustomer.EmailAddress);

            var transactWriteItemRequest = new TransactWriteItemsRequest
            {
                TransactItems = new List <TransactWriteItem>(2)
                {
                    new TransactWriteItem
                    {
                        Put = new Put
                        {
                            TableName           = "OnlineStore-dd006eb",
                            ConditionExpression = "attribute_not_exists(PK)",
                            Item = customer.AsTableItem()
                        }
                    },
                    new TransactWriteItem
                    {
                        Put = new Put
                        {
                            TableName           = "OnlineStore-dd006eb",
                            ConditionExpression = "attribute_not_exists(PK)",
                            Item = customerEmail.AsTableItem()
                        }
                    }
                }
            };

            var response = await this._client.TransactWriteItemsAsync(transactWriteItemRequest).ConfigureAwait(false);

            return(customer);
        }
Esempio n. 9
0
        private static async Task PublishEventsToDynamoTable(List <Transaction> transactions)
        {
            IAmazonDynamoDB client = CreateDynamoDbClient();

            foreach (Transaction transaction in transactions)
            {
                var request = new TransactWriteItemsRequest()
                {
                    TransactItems = transaction.Events.Select(x => new TransactWriteItem()
                    {
                        Put = new Put()
                        {
                            TableName = TableName,
                            Item      = new Dictionary <string, AttributeValue>
                            {
                                { "AggregateId", new AttributeValue {
                                      S = x.AggregateId.ToString()
                                  } },
                                { "Version", new AttributeValue {
                                      N = x.Version.ToString()
                                  } },
                                { "SequenceNumber", new AttributeValue {
                                      N = x.SequenceNumber.ToString()
                                  } },
                                { "Payload", new AttributeValue {
                                      S = System.Text.Encoding.UTF8.GetString(x.Payload)
                                  } }
                            }
                        }
                    }).ToList()
                };

                var response = await client.TransactWriteItemsAsync(request);

                Console.WriteLine($"Transaction sent with {request.TransactItems.Count} PUTs - {response.HttpStatusCode}");
            }
        }
Esempio n. 10
0
        public async Task Test1()
        {
            // Transaction put with an outbox message.
            var transactWriteItems = new List <TransactWriteItem>();

            for (int i = 0; i < 5; i++)
            {
                var orgDoc = new Document
                {
                    ["Id"]   = 123,
                    ["Name"] = $"org-123-{i}",
                    ["Foo"]  = Document.FromJson("{\"plot\" : \"Nothing happens at all.\",\"rating\" : 0}")
                };

                transactWriteItems.Add(new TransactWriteItem
                {
                    Put = new Put
                    {
                        TableName = OrgsTableName,
                        Item      = orgDoc.ToAttributeMap()
                    }
                });

                var outboxDoc = new Document
                {
                    ["Id"]      = $"123-{i}",
                    ["Created"] = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
                    ["Body"]    = Document.FromJson("{\"plot\" : \"Nothing happens at all.\",\"rating\" : 0}")
                };

                transactWriteItems.Add(new TransactWriteItem
                {
                    Put = new Put
                    {
                        TableName = OutboxTableName,
                        Item      = outboxDoc.ToAttributeMap()
                    }
                });
            }

            var transactWriteItemsRequest = new TransactWriteItemsRequest
            {
                TransactItems = transactWriteItems,
            };
            await _client.TransactWriteItemsAsync(transactWriteItemsRequest);


            // Read the changes to outbox change stream
            string lastEvaluatedShardId = null;

            do
            {
                var describeStreamRequest = new DescribeStreamRequest
                {
                    StreamArn             = _tableLatestStreamArn,
                    ExclusiveStartShardId = lastEvaluatedShardId
                };

                var describeStreamResponse = await _streamsClient.DescribeStreamAsync(describeStreamRequest);

                foreach (var shard in describeStreamResponse.StreamDescription.Shards)
                {
                    var getShardIteratorRequest = new GetShardIteratorRequest
                    {
                        StreamArn         = _tableLatestStreamArn,
                        ShardId           = shard.ShardId,
                        ShardIteratorType = ShardIteratorType.TRIM_HORIZON
                    };
                    var getShardIteratorResponse = await _streamsClient.GetShardIteratorAsync(getShardIteratorRequest);

                    var currentShardIterator = getShardIteratorResponse.ShardIterator;

                    var iterations = 0; // loop will continue for some time until the stream shard is closed, this just short circuits things for the test.
                    while (currentShardIterator != null && iterations < 10)
                    {
                        var getRecordsRequest = new GetRecordsRequest
                        {
                            ShardIterator = currentShardIterator,
                        };
                        var getRecordsResponse = await _streamsClient.GetRecordsAsync(getRecordsRequest);

                        foreach (var record in getRecordsResponse.Records)
                        {
                            _testOutputHelper.WriteLine($"{record.EventID} {record.EventName} {record.EventSource} {record.Dynamodb.NewImage.StreamViewType}");
                        }

                        currentShardIterator = getRecordsResponse.NextShardIterator;
                        iterations++;
                    }
                }

                lastEvaluatedShardId = describeStreamResponse.StreamDescription.LastEvaluatedShardId;
            } while (lastEvaluatedShardId != null);
        }
Esempio n. 11
0
        async Task <TransactWriteItemsResponse> IAmazonDynamoDB.TransactWriteItemsAsync(TransactWriteItemsRequest request, CancellationToken cancellationToken)
        {
            try {
                var response = await _dynamoDBClient.TransactWriteItemsAsync(request, cancellationToken);

                _callback?.Invoke(new {
                    Action   = nameof(IAmazonDynamoDB.TransactWriteItemsAsync),
                    Request  = request,
                    Response = response
                });
                return(response);
            } catch (Exception e) {
                _callback?.Invoke(new {
                    Action    = nameof(IAmazonDynamoDB.TransactWriteItemsAsync),
                    Request   = request,
                    Exception = new {
                        Type    = e.GetType().FullName,
                        Message = e.Message
                    }
                });
                throw;
            }
        }
Esempio n. 12
0
        /// <summary>
        /// Example that writes items in a transaction to a DynamoDB
        /// </summary>
        /// <returns></returns>
        public static async Task TransactWriteItemsExample()
        {
            var client = new AmazonDynamoDBClient(RegionEndpoint.USWest2);

            //Creation of the request. As an example, we will put an item on a secondary table, delete it from the original table and update the status on a third table if the current status is active
            var request = new TransactWriteItemsRequest()
            {
                TransactItems = new List <TransactWriteItem>()
                {
                    //Put
                    new TransactWriteItem()
                    {
                        Put = new Put()
                        {
                            TableName = "RetailDatabase2",
                            Item      = new Dictionary <string, AttributeValue>
                            {
                                { "pk", new AttributeValue("*****@*****.**") },
                                { "sk", new AttributeValue("metadata") },
                                { "attribute1", new AttributeValue("Attribute1 value") }
                                //Add more attributes
                            }
                        }
                    },
                    //Delete
                    new TransactWriteItem()
                    {
                        Delete = new Delete()
                        {
                            TableName = "RetailDatabase",
                            Key       = new Dictionary <string, AttributeValue>
                            {
                                { "pk", new AttributeValue("*****@*****.**") },
                                { "sk", new AttributeValue("metadata") },
                            },
                            //You could add conditional expresions if you need it
                        }
                    },

                    //Update
                    new TransactWriteItem()
                    {
                        Update = new Update()
                        {
                            TableName = "CustomerStatus",
                            Key       = new Dictionary <string, AttributeValue>
                            {
                                { "pk", new AttributeValue("*****@*****.**") },
                            },
                            //We update the #s (status attribute) if the condition is meeted
                            UpdateExpression         = "set #s = :arch",
                            ConditionExpression      = "#s = :a",
                            ExpressionAttributeNames = new Dictionary <string, string>
                            {
                                { "#s", "status" },
                            },
                            ExpressionAttributeValues = new Dictionary <string, AttributeValue>
                            {
                                { ":a", new AttributeValue("active") },
                                { ":arch", new AttributeValue("archived") },
                            },
                        }
                    }
                },
                ReturnItemCollectionMetrics = "SIZE",     //Statistics disabled by default with NONE, you could use SIZE to know statistics of the modifed items.
                ReturnConsumedCapacity      = "TOTAL"
            };

            try
            {
                var response = await client.TransactWriteItemsAsync(request);

                Console.WriteLine($" Action finished with code: {response.HttpStatusCode}, info: {response.ItemCollectionMetrics.ToString()} ");
            }
            catch (TransactionCanceledException cancelation)
            {
                //We catch the error raised when the transaction is cancelled.
                Console.WriteLine($"Transaction Cancelled: {string.Join(string.Empty, cancelation.CancellationReasons.Where(c=> c != null).Select(c=> c.Message))}"); //We show a message that list the conditions not met
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
Esempio n. 13
0
 public TransactWriteItemsHttpContent(TransactWriteItemsRequest request, string?tablePrefix) : base("DynamoDB_20120810.TransactWriteItems")
 {
     _request     = request;
     _tablePrefix = tablePrefix;
 }
Esempio n. 14
0
 public Task <TransactWriteItemsResponse> TransactWriteItemsAsync(TransactWriteItemsRequest request, CancellationToken cancellationToken = default)
 {
     throw new NotImplementedException();
 }
Esempio n. 15
0
 //--- Constructors ---
 public DynamoTableTransactWriteItems(DynamoTable table, TransactWriteItemsRequest request)
 {
     _table   = table ?? throw new ArgumentNullException(nameof(table));
     _request = request ?? throw new ArgumentNullException(nameof(request));
 }
Esempio n. 16
0
        public async Task Success()
        {
            // 前準備

            // 実行
            var logic = GetLogic();
            await logic.DeleteMainAsync(_ownerId, _scoreId);

            // 検証

            var req = new TransactWriteItemsRequest()
            {
                ReturnConsumedCapacity = ReturnConsumedCapacity.TOTAL,
                TransactItems          = new List <TransactWriteItem>()
                {
                    new TransactWriteItem()
                    {
                        Delete = new Delete()
                        {
                            Key = new Dictionary <string, AttributeValue>()
                            {
                                ["o"] = new AttributeValue("sc:01234567890123456789aa"),
                                ["s"] = new AttributeValue("01234567890123456789bb")
                            },
                            ExpressionAttributeNames = new Dictionary <string, string>()
                            {
                                ["#score"] = "s"
                            },
                            ConditionExpression = "attribute_exists(#score)",
                            TableName           = _tableName
                        }
                    },
                    new TransactWriteItem()
                    {
                        Update = new Update()
                        {
                            Key = new Dictionary <string, AttributeValue>()
                            {
                                ["o"] = new AttributeValue("sc:01234567890123456789aa"),
                                ["s"] = new AttributeValue("summary")
                            },
                            ExpressionAttributeNames = new Dictionary <string, string>()
                            {
                                ["#sc"]   = "sc",
                                ["#lock"] = "l"
                            },
                            ExpressionAttributeValues = new Dictionary <string, AttributeValue>()
                            {
                                [":increment"] = new AttributeValue()
                                {
                                    N = "-1"
                                },
                                [":newL"] = new AttributeValue("01234567890123456789cc"),
                            },
                            TableName = _tableName
                        }
                    }
                }
            };
            var compare = new LambdaEqualityCompare <TransactWriteItemsRequest>((x, y) =>
            {
                if (x.ReturnConsumedCapacity != y.ReturnConsumedCapacity)
                {
                    return(false);
                }
                throw new NotImplementedException();
                return(true);
            });

            AmazonDynamoDb.Verify(x => x.TransactWriteItemsAsync(It.Is(req, compare), default), Times.Once);
        }