private bool MatchingCommand(PlaceOrderCommand command) { Assert.That(command.Id, Is.Not.EqualTo(Guid.Empty)); Assert.That(command.AggregateId, Is.EqualTo(_id)); AssertItemsMatch(command.Items); return(true); }
public Task <ShortOrder> PlaceOrder( string instrument, PlaceOrderCommand request, CancellationToken ct = default(CancellationToken)) { return(EpochNonce.Lock(_credentials.ApiKey, async nonce => { var cmd = new PlaceOrderRequest(_credentials, nonce) { Amount = request.Amount, OrderType = request.OrderType, Price = request.Price }; var(symbol1, symbol2) = CexIoInstrument.FromInstrument(CexIoInstrument.FromLykkeInstrument(instrument, _currencyMapping)); using (var response = await _client.PostAsJsonAsync($"place_order/{symbol1}/{symbol2}", cmd, ct)) { response.EnsureSuccessStatusCode(); var token = await response.Content.ReadAsAsync <JToken>(ct); EnsureSuccessContent(token); return token.ToObject <ShortOrder>(); } })); }
public async Task WhenPlacingOrderThenAssignOrderingNumbersToOrderLines() { var productId1 = Guid.NewGuid(); var productId2 = Guid.NewGuid(); var inputCommand = new PlaceOrderCommand { ChosenShippingMethodName = "shipping1", ChosenPaymentMethodName = "payment1", OrderLines = GetPlaceOrderCommandOrderLinesWithProductIds(productId1, productId2) }; OrderEntity orderOnRepositoryInput = null; _mediator.Setup(m => m.Send(It.IsAny <GetProductsByMultipleIdsQuery>(), default)) .ReturnsAsync(GetProductsWithIds(productId2, productId1)); _shippingMethodRepository.Setup(r => r.GetByName("shipping1")) .ReturnsAsync(new ShippingMethod { Fee = 1.0 }); _paymentMethodRepository.Setup(r => r.GetByName("payment1")) .ReturnsAsync(new PaymentMethod { Fee = 1.0 }); _orderRepository.Setup(r => r.Create(It.IsAny <OrderEntity>())) .Callback <OrderEntity>(o => orderOnRepositoryInput = o); var result = await _placeOrderCommandHandler.Handle(inputCommand, default); orderOnRepositoryInput.OrderLines.Count.Should().Be(2); orderOnRepositoryInput.OrderLines[0].OrderLineNo.Should().Be(0); orderOnRepositoryInput.OrderLines[1].OrderLineNo.Should().Be(1); }
private async Task PlaceFakeOrder() { var customer = _customerNames[_random.Next(_customerNames.Length)]; var coffee = _coffeeOrders[_random.Next(_coffeeOrders.Length)]; var command = new PlaceOrderCommand(Guid.NewGuid(), customer, coffee); await _bus.Send(command); }
public IActionResult PlaceOrder([FromBody] PlaceOrderDTO order, [FromServices] PlaceOrderCommand placeOrderCommand) { placeOrderCommand.Order = order; placeOrderCommand.Execute(); return(NoContent()); }
public IHttpActionResult Post(PlaceOrderCommand cmd) { if (Guid.Empty.Equals(cmd.Id)) { var response = new HttpResponseMessage(HttpStatusCode.Forbidden) { Content = new StringContent("order information must be supplied in the POST body"), ReasonPhrase = "Missing Order Id" }; throw new HttpResponseException(response); } var command = new StartNewOrder(cmd.Id, cmd.ProductId, cmd.Quantity); try { ServiceLocator.OrderCommands.Handle(command); var link = new Uri(string.Format("http://localhost:8182/api/orders/{0}", command.Id)); return(Created(link, command)); } catch (ArgumentException argEx) { return(BadRequest(argEx.Message)); } }
public async Task ShouldThrowEmptyShoppingVanException() { // Arrange var accountId = await RunAsDefaultUserAsync(); var createCustomerCommand = new CreateCustomerCommand { AccountId = accountId, ShopName = "Test Shop Name", ShopAddress = "Test Shop address", LocationOnMap = "Test LocationOnMap" }; await SendAsync(createCustomerCommand); // Act // Place Order Command var placeOrderCommand = new PlaceOrderCommand(); // Assert // Shipp Order Command FluentActions.Invoking(() => SendAsync(placeOrderCommand)).Should().Throw <EmptyShoppingVanException>(); }
public ActionResult Post(PlaceOrderCommand cmd) { if (Guid.Empty.Equals(cmd.Id)) { return(Problem( title: "Missing Order Id", detail: "order information must be supplied in the POST body", statusCode: StatusCodes.Status400BadRequest )); } var command = new StartNewOrder(cmd.Id, cmd.ProductId, cmd.Quantity); try { ServiceLocator.OrderCommands.Handle(command); var link = new Uri(string.Format("https://localhost:44359/api/orders/{0}", command.Id)); return(Created(link, command)); } catch (ArgumentException argEx) { return(BadRequest(argEx.Message)); } }
static async Task RunLoop(IEndpointInstance endpointInstance) { while (true) { log.Info("Press 'P' to place an order, or 'Q' to quit."); var key = Console.ReadKey(); Console.WriteLine(); switch (key.Key) { case ConsoleKey.P: var command = new PlaceOrderCommand { OrderId = Guid.NewGuid().ToString(), OrderData = "OrderData" }; log.Info($"Sending PlaceOrder command, OrderId = {command.OrderId}"); await endpointInstance.Send(command) .ConfigureAwait(false); break; case ConsoleKey.Q: return; default: log.Info("Unknown input. Please try again."); break; } } }
public async void Setup() { var dbContext = new OrderDbContext { Orders = Aef.FakeDbSet(orders) }; placedAtDate = DateTime.UtcNow; orderId = new Guid("DE81F6B5-7F29-4AE7-A72B-023F6B58DE72"); var placeOrderCommand = new PlaceOrderCommand { OrderId = orderId, OrderNumber = 100, PlacedAtDate = placedAtDate }; var context = new TestableMessageHandlerContext(); var orderStorageContextMock = new Mock <IDbContextWrapper <OrderDbContext> >(); orderStorageContextMock.SetupIgnoreArgs(x => x.Get(null)).Returns(dbContext); handler = new PlaceOrderCommandHandler(orderStorageContextMock.Object); await handler.Handle(placeOrderCommand, context); await dbContext.SaveChangesAsync(); }
static async Task RunLoop(IEndpointInstance endpointInstance) { while (true) { log.Info("Press 'P' to place an order, or 'Q' to quit."); var key = Console.ReadKey(); Console.WriteLine(); switch (key.Key) { case ConsoleKey.P: // Instantiate the command var command = new PlaceOrderCommand { OrderId = Guid.NewGuid().ToString() }; // Send the command to the local endpoint log.Info($"Sending PlaceOrderCommand, OrderId = { command.OrderId }"); // The Local part means that we are not sending to an external endpoint (in a different process) so we // intend to handle the message in the same endpoint that sent it await endpointInstance.Send(command) .ConfigureAwait(false); break; case ConsoleKey.Q: return; default: log.Info("Unknown input. PLease try again."); break; } } }
public IEnumerable Handle(PlaceOrderCommand c) { if (!_tabOpen) { throw new TabNotOpen(); } var drink = c.Items.Where(i => i.IsDrink).ToList(); if (drink.Any()) { yield return(new DrinksOrdered { Id = c.Id, Items = drink }); } var food = c.Items.Where(i => !i.IsDrink).ToList(); if (food.Any()) { yield return(new FoodOrdered { Id = c.Id, Items = food }); } }
static async Task RunLoop(IBus bus) { while (true) { Console.WriteLine("Press 'P' to place an order, or 'Q' to quit."); var key = Console.ReadKey(); Console.WriteLine(); switch (key.Key) { case ConsoleKey.P: // Instantiate the command var command = new PlaceOrderCommand { OrderId = Guid.NewGuid() }; // Send the command to the local endpoint Console.WriteLine($"Sending PlaceOrder command, OrderId = {command.OrderId}"); await bus.Send(command).ConfigureAwait(false); break; case ConsoleKey.Q: return; default: Console.WriteLine("Unknown input. Please try again."); break; } } }
public async Task <IActionResult> Index([FromBody] PlaceOrderCommand cmd) { var customer = await GetCustomer(cmd.CustomerId.Value); var order = new Order { CustomerId = cmd.CustomerId.Value, ItemNumber = cmd.ItemNumber, Quantity = cmd.Quantity }; _dbContext.Orders.Add(order); await _dbContext.SaveChangesAsync(); _tracer.ActiveSpan?.Log(new Dictionary <string, object> { { "event", "OrderPlaced" }, { "orderId", order.OrderId }, { "customer", order.CustomerId }, { "customer_name", customer.Name }, { "item_number", order.ItemNumber }, { "quantity", order.Quantity } }); return(Ok()); }
public void WhenCartItemIsNull_ShouldHaveValidationError() { var command = new PlaceOrderCommand { CartItems = null }; _rulesValidator.ShouldHaveValidationErrorFor(p => p.CartItems, command); }
public void WhenCartItemIsEmpty_ShouldHaveValidationError() { var command = new PlaceOrderCommand { CartItems = new List <CartItemModel>() }; _rulesValidator.ShouldHaveValidationErrorFor(p => p.CartItems, command); }
public async Task PlaceOrderCommand_validation_should_fail_with_empty_required_fields() { var handler = new PlaceOrderCommandHandler(_unitOfWork, _currencyConverter); var command = new PlaceOrderCommand(Guid.Empty, Guid.Empty, string.Empty); var result = await handler.Handle(command, CancellationToken.None); result.ValidationResult.IsValid.Should().BeFalse(); result.ValidationResult.Errors.Count.Should().Be(3); }
public override async Task HandleAsync(PlaceOrderIntegrationEvent @event) { var command = new PlaceOrderCommand { CustomerId = @event.CustomerId, Price = @event.Price }; await _bus.SendAsync(command); }
public async Task Handle(PlaceOrderCommand message, IMessageHandlerContext context) { var @event = mapper.Map <PlacedOrderEvent>(message); var result = await eventContext.AddAsync($"Order {message.OrderId}", @event); @event.LogPosition = result.LogPosition; @event.NextExpectedVersion = result.NextExpectedVersion; await context.Publish(@event); }
public async Task <IActionResult> PlaceOrder([FromRoute] Guid cartId, [FromBody] PlaceOrderRequest request) { if (!ModelState.IsValid) { return(BadRequest()); } var command = new PlaceOrderCommand(cartId, request.CustomerId, request.Currency); return(Response(await _mediator.Send(command))); }
public ActionResult OrderProduct(string name, string product) { var command = new PlaceOrderCommand() { OrderMadeBy = name, Product = product }; Bus.Send(command); return(View("OrderPlaced")); }
private static void UpdateStock(PlaceOrderCommand messageBody) { Console.WriteLine("Starting UpdateStock for: {0}, at {1}", messageBody.Product, DateTime.Now); var workflow = new UpdateStockWorkflow(messageBody.Id, messageBody.Product, messageBody.Quantity); workflow.Run(); Console.WriteLine("Finished UpdateStock for: {0}, at {1}", messageBody.Product, DateTime.Now); Console.WriteLine(); }
public IActionResult Place(OrderViewModel order) { var orderId = Guid.NewGuid(); var itemIds = new[] { order.ItemId1, order.ItemId2 }.Where(i => !string.IsNullOrEmpty(i)).ToArray(); _log.LogInformation("Placing order {OrderId} ({ItemCount} items) for {CustomerName}", orderId, itemIds.Length, order.CustomerName); var command = new PlaceOrderCommand(orderId, order.CustomerName, itemIds); _messageBus.Publish(command); return RedirectToAction(nameof(Thanks)); }
public async Task <PlaceOrderResponse> CreateSellLimitOrderAsync(PlaceOrderCommand order) { JToken data = await GetDataAsync($"sell/{WebUtility.UrlEncode(order.Asset)}/", _httpClientFactory.GetClient(_credentials, InternalApiKey), new Dictionary <string, string> { { "amount", order.Amount.ToString(CultureInfo.InvariantCulture) }, { "price", order.Price.ToString(CultureInfo.InvariantCulture) } }); return(data.ToObject <PlaceOrderResponse>()); }
public async Task <IActionResult> PlaceOrder(int id, [FromBody] OrderModel model) { var userID = User.Claims.First(x => x.Type == "UserID").Value; var cmd = new PlaceOrderCommand(id, userID, model); var response = await _mediator.Send(cmd); if (response) { return(Ok("Order has been successfully placed")); } return(BadRequest("Something went wrong while trying to place order")); }
public async Task <IActionResult> Index([FromBody] PlaceOrderCommand cmd) { var customer = await GetCustomer(cmd.CustomerId.Value); _tracer.ActiveSpan?.Log(new Dictionary <string, object> { { "event", "OrderPlaced" }, { "customer", cmd.CustomerId }, { "customer_name", customer.Name }, { "item_number", cmd.ItemNumber }, { "quantity", cmd.Quantity } }); return(Ok()); }
async void Loop(IMessageSession session) { Console.WriteLine("Press enter to send Place Order Command"); int tempOrderNumber = 0; string tempContentId = string.Empty; string tempContentVersion = "0"; while (true) { var key = Console.ReadKey(); if (key.Key == ConsoleKey.Enter) { for (int i = 0; i < 2000; i++) { var orderNumber = i + 1; Guid orderId = Guid.NewGuid(); string contentId = orderId.ToString(); string contentVersion = DateTime.UtcNow.Ticks.ToString(); //(i + 1).ToString(); if (i % 2 == 1) // DiscardedMessages { orderNumber = tempOrderNumber; contentId = tempContentId; contentVersion = tempContentVersion;//"-1"; } var placeOrderCommand = new PlaceOrderCommand { OrderId = orderId, OrderNumber = orderNumber, PlacedAtDate = DateTime.UtcNow }; var sendOptions = new SendOptions(); sendOptions.SetHeader("ContentId", contentId); sendOptions.SetHeader("ContentVersion", contentVersion); sendOptions.SetDestination("LoadTest"); await session.Send(placeOrderCommand, sendOptions) .ConfigureAwait(false); tempOrderNumber = orderNumber; tempContentId = contentId; tempContentVersion = (long.Parse(contentVersion) - 1000).ToString(); Console.WriteLine($"Place Order Command sent {orderNumber}"); } } } }
public async Task <IActionResult> PlaceOrder( [HttpTrigger(AuthorizationLevel.Function, "post")] HttpRequest req, ILogger log, CancellationToken cancellationToken) { var body = await new StreamReader(req.Body).ReadToEndAsync(); var cartItems = JsonConvert.DeserializeObject <List <CartItemModel> >(body); var command = new PlaceOrderCommand { CartItems = cartItems }; await _mediator.Send(command, cancellationToken); return(new OkResult()); }
private void button1_Click(object sender, EventArgs e) //place order { if (CorrectAddressFormat) { OrderId = StaticAccessor.DB.GetNewestOrderId() + 1; Order.Address = Address; var placeOrderCommand = new PlaceOrderCommand(Order); StaticAccessor.Invoker.Command = placeOrderCommand; StaticAccessor.Invoker.Invoke(); Hide(); var UPOM = new UserPlaceOrderMenu(UserId, OrderId); UPOM.ShowDialog(); } }
public async Task Handle(PlaceOrderCommand message, IMessageHandlerContext context) { Console.WriteLine("Order has been placed......"); Data.AddressFrom = message.AddressFrom; Data.AddressTo = message.AddressTo; Data.Price = message.Price; Data.Weight = message.Weight; var options = new SendOptions(); options.SetDestination("Saga.Planning"); await context.Send(new OrderPlanCommand { AddressTo = Data.AddressTo, OrderId = Data.OrderId }, options) .ConfigureAwait(false); }
public void PlaceOrder(ProductViewModel vm) { var command = new PlaceOrderCommand(vm.ProductId, vm.ProductName, vm.Quantity); using (var queue = new MessageQueue(PlaceOrderQueue)) { var message = new Message { BodyStream = command.ToJsonStream(), Label = command.GetMessageType(), Recoverable = true }; queue.Send(message); } }