public async Task HandleAsync(CompleteOrderCommand command, ICorrelationContext context) { var order = await _ordersRepository.GetAsync(command.Id); if (order == null || order.CustomerId != command.CustomerId) { throw new ASampleException("order_not_found", $"Order with id: '{command.Id}' was not found for customer with id: '{command.CustomerId}'."); } order.Complete(); await _ordersRepository.UpdateAsync(order); await _busPublisher.PublishAsync(new OrderCompletedEvent(command.Id, command.CustomerId), context); }
protected override async Task Handle(DeletePersonLocationCommand command, CancellationToken cancellationToken) { var personLocation = await _dbContext.Locations.FindAsync(command.LocationId); if (personLocation != null) { _dbContext.Locations.Remove(personLocation); await _dbContext.SaveChangesAsync(); } _logger.LogInformation($"[Local Transaction] : Person location deleted."); await _busPublisher.PublishAsync(new PersonLocationDeleted(personLocation.Id, personLocation.LocationName), null); }
protected override async Task Handle(DeletePersonPhoneNumberCommand command, CancellationToken cancellationToken) { var personPhoneNumber = await _dbContext.Phones.FindAsync(command.PhoneNumberId); if (personPhoneNumber != null) { _dbContext.Phones.Remove(personPhoneNumber); await _dbContext.SaveChangesAsync(); } _logger.LogInformation($"[Local Transaction] : Person phone number deleted."); await _busPublisher.PublishAsync(new PersonPhoneNumberDeleted(personPhoneNumber.Id, personPhoneNumber.PhoneNumber), null); }
public Task HandleAsync(CreateCustomer command, ICorrelationContext context) { Customer user = new Customer(command.Id, command.FullName, command.Email, command.Phone, command.Address); mongoRepository.AddAsync(user); return(busPublisher.PublishAsync( new CustomerCreated( command.Id, command.FullName, command.Email, command.Phone, command.Address ), context)); }
public async Task HandleAsync(SignedUp @event, ICorrelationContext context) { Customer customer = new Customer(@event.UserId); customer.Create(@event.FirstName, @event.AccountType, @event.LastName); customer.SetEmail(@event.Email); customer.Use(); await _customerRepo.AddAsync(customer); //Publish event that new customer has signed up CustomerCreated customerCreated = new CustomerCreated(@event.UserId, @event.FirstName, @event.LastName, @event.Email, ""); await _busPublisher.PublishAsync(customerCreated, null); }
public async Task HandleAsync(CreateAirplane command, ICorrelationContext context) { if (await _airplanesRepository.GetAsync(command.AirplaneRegistrationNumber) != null) { throw new BeComfyException("airplane_already_exists", $"Airplane with registration number: '{command.AirplaneRegistrationNumber}' already exists."); } var airplane = new Airplane(command.AirplaneId, command.AirplaneRegistrationNumber, command.AirplaneModel, command.AvailableSeats, command.RequiredCrew); await _airplanesRepository.AddAsync(airplane); await _busPublisher.PublishAsync(new AirplaneCreated(command.AirplaneId, command.AirplaneRegistrationNumber, command.AirplaneModel), context); }
public async Task HandleAsync(CreateProduct command, ICorrelationContext context) => await _handler .Handle(async() => { if (await _productsRepository.ExistsAsync(command.Name)) { throw new DShopException("product_already_exists", $"Product: '{command.Name}' already exists."); } var product = new Product(command.Id, command.Name, command.Description, command.Vendor, command.Price); await _productsRepository.AddAsync(product); }) .OnSuccess(async() => await _busPublisher.PublishAsync( new ProductCreated(command.Id, command.Name, command.Description, command.Vendor, command.Price), context) ) .OnCustomError(async ex => await _busPublisher.PublishAsync( new CreateProductRejected(command.Id, ex.Message, ex.Code), context) ) .OnError(async ex => await _busPublisher.PublishAsync( new CreateProductRejected(command.Id, ex.Message, "create_product_failed"), context) ) .ExecuteAsync();
public async Task HandleAsync(RevokeOrder command, ICorrelationContext context) { var order = await _ordersRepository.GetAsync(command.Id); if (order == null || order.CustomerId != command.CustomerId) { throw new DShopException("order_not_found", $"Order with id: '{command.Id}' " + $"was not found for customer with id: '{command.CustomerId}'."); } order.Revoke(); await _ordersRepository.UpdateAsync(order); await _busPublisher.PublishAsync(new OrderRevoked(command.Id, command.CustomerId), context); }
public async Task HandleAsync(ApproveOrder command, ICorrelationContext context) { var order = await _ordersRepository.GetAsync(command.Id); if (order == null) { throw new DShopException("order_not_found", $"Order with id: '{command.Id}' was not found."); } order.Approve(); await _ordersRepository.UpdateAsync(order); await _busPublisher.PublishAsync(new OrderApproved(command.Id, order.CustomerId), context); }
public async Task HandleAsync(UpdateTodo command, ICorrelationContext context) { var todoItem = await _repository.GetAsync(command.Id); if (todoItem == null) { await _busPublisher.PublishAsync( new UpdateTodoItemRejected(command.Id, "todo_item_does_not_exist", $"TodoItem with id: '{command.Id}' was not found."), context); return; //throw new MinotaurException("todo_item_not_found", // $"TodoItem with id: '{command.Id}' was not found."); } todoItem.SetTitle(command.Title); todoItem.SetDescription(command.Description); todoItem.SetUserId(command.Id); todoItem.SetIsDone(command.IsDone); await _repository.UpdateAsync(todoItem); await _busPublisher.PublishAsync( new TodoItemUpdated(command.Id, command.Title, command.Description, command.IsDone, command.UserId), context); }
public async Task HandleAsync(AddPlayer command, ICorrelationContext context) { var player = Domain.Entities.Player.Create( command.FirstName, command.LastName, externalId: command.ExternalId); var repo = _uow.GetRepositoryAsync <Domain.Entities.Player>(); await repo.AddAsync(player); _uow.SaveChanges(); await _busPublisher.PublishAsync(new PlayerAdded(player.Id), context); }
public async Task HandleAsync(UpdatePerson command, ICorrelationContext context) { var person = await _personRepository.GetAsync(command.Id); if (person.Completed) { throw new CoursesManagementException("person_data_completed", $"Customer account was already created for user with id: '{command.Id}'."); } person.Complete(command.FirstName, command.LastName, command.Address, command.Country); await _personRepository.UpdateAsync(person); await _busPublisher.PublishAsync(new PersonUpdated(command.Id, command.Email, command.FirstName, command.LastName, command.Address, command.Country), context); }
public async Task HandleAsync(CancelOrder command, ICorrelationContext context) { var order = await _ordersRepository.GetAsync(command.Id); if (order == null || order.CustomerId != command.CustomerId) { throw new DShopException("order_not_found", $"Order with id: '{command.Id}' " + $"was not found for customer with id: '{command.CustomerId}'."); } order.Cancel(); await _ordersRepository.UpdateAsync(order); await _busPublisher.PublishAsync(new OrderCanceled(command.Id, command.CustomerId, order.Items.ToDictionary(i => i.Id, i => i.Quantity)), context); }
public async Task HandleAsync(AddGameEventSource command) { if (await _gameSourceRepository.ExistsAsync(command.Id)) { throw new GameEventSourceAlreadyExistsException(command.Id); } var gameSource = new GameEventSource(command.Id, command.IsWin, command.Score); await _gameSourceRepository.AddAsync(gameSource); var messageId = Guid.NewGuid().ToString("N");//this is unique per message type, each message has its own messageId in rabbitmq var correlationId = _messagePropertiesAccessor.MessageProperties.CorrelationId; var correlationContext = _correlationContextAccessor.CorrelationContext; var @event = new GameEventSourceAdded(command.Id, command.Score, command.IsWin, command.UserId); await _busPublisher.PublishAsync(@event, messageId : messageId, correlationId : correlationId, messageContext : correlationContext); }
public async Task HandleAsync(CreateLeague command, ICorrelationContext context) { var league = League.Create( command.Name, command.Description, Enumeration.FromDisplayName <LeagueType>(command.LeagueType.Name)); var repo = _uow.GetRepositoryAsync <League>(); var entity = (await repo.AddAsync(league)).Entity; _uow.SaveChanges(); await _busPublisher.PublishAsync(new LeagueCreated(entity.Id), context); }
public async Task HandleAsync(CreateTaskCommand command, ICorrelationContext context) { var task = new Domain.Task(command.Id, command.Title, command.Description, command.AssignedTo, command.PlannedStartDate, command.PlannedEndDate, command.ActualStartDate, command.ActualEndDate, command.Status, command.Priority, command.AttachmentPath, command.Owner, command.EntryDate); var taskCreated = new TaskCreatedEvent(command.Id, command.Title, command.Description, command.AssignedTo, command.PlannedStartDate, command.PlannedEndDate, command.ActualStartDate, command.ActualEndDate, command.Status, command.Priority, command.AttachmentPath, command.Owner, command.EntryDate); await _taskRepository.AddAsync(task); await _publisher.PublishAsync(taskCreated, context); // publish the event to bus // do some logging }
public async Task PublishAsync(params IEvent[] events) { if (events is null) { return; } foreach (var @event in events) { if (@event is null) { continue; } await _busPublisher.PublishAsync(@event, _contextAccessor.CorrelationContext); } }
public async Task HandleAsync(CancelCourse command, ICorrelationContext context) { _logger.LogInformation($"Cancelling a course: '{command.Id}'"); if (!await _courseRepository.ExistsAsync(command.Id)) { throw new CoursesManagementException("course_not_found", $"Course with id: '{command.Id}' was not found."); } var course = await _courseRepository.GetAsync(command.Id); course.SetState(State.Cancelled); await _courseRepository.UpdateAsync(course); _logger.LogInformation($"Cancelled a course: '{command.Id}'"); await _busPublisher.PublishAsync(new CourseCancelled(command.Id), context); }
public async Task HandleAsync(TourBack command, ICorrelationContext context) { var tourRepo = _uow.GetRepositoryAsync <Tour>(); Tour tour = await tourRepo.SingleAsync(t => t.Id == command.TourId); tour.MoveTourStatusBack(); tourRepo.UpdateAsync(tour); _uow.SaveChanges(); if (tour.IsRegistrationOpened()) { // todo:: or reopened? await _busPublisher.PublishAsync(new TourRegistrationOpened(tour.Id), context); } }
protected override async Task Handle(CreatePersonCommand command, CancellationToken cancellationToken) { _dbContext.Persons.Add(new Data.Entity.Person { Id = command.Id, Name = command.Name, Surname = command.Surname, CompanyName = command.CompanyName, }); await _dbContext.SaveChangesAsync(); _logger.LogInformation($"[Local Transaction] : Person created."); await _busPublisher.PublishAsync(new PersonCreated(command.Id, command.Name, command.Surname, command.CompanyName), null); }
public async Task HandleAsync(AddGameEventSource command, ICorrelationContext context) { var gameEventSource = await _gameSourceRepository.GetAsync(command.Id); if (gameEventSource != null) { gameEventSource.UpdateScoreAndIsWin(command.Score, command.IsWin); await _gameSourceRepository.UpdateAsync(gameEventSource); } else { var gameSource = new GameEventSource(command.Id, command.IsWin, command.Score, command.UserId); await _gameSourceRepository.AddAsync(gameSource); } await _busPublisher.PublishAsync(new GameEventSourceAdded(command.Id, command.Score, command.IsWin, command.UserId), context); }
private async Task CheckVehiclesConnectivityAsync() { var vehicles = await _trackedVehicleRepository.GetAsync(_ => true) .AnyContext(); var tasks = vehicles.Select(v => _pingSender.SendAsync(v.IPAddress, _options.Value.PingTimeout)); var results = await Task.WhenAll(tasks) .AnyContext(); foreach (var r in results) { var vehicle = vehicles.FirstOrDefault(v => v.IPAddress == r.IPAddress); if (vehicle == null) // vehicle is no longer tracked { _logger.LogInformation($"Vehicle with IP address '{r.IPAddress}' was not found"); continue; } var status = r.IPStatus == IPStatus.Success ? TrackedVehicleStatus.Connected : TrackedVehicleStatus.Disconnected; if (status == vehicle.Status) { continue; } var @event = new VehicleStatusChangedEvent(vehicle.Id, status); await _busPublisher.PublishAsync(@event) .AnyContext(); vehicle.SetConnectionStatus(status); // Enhancement: use bulk update await _trackedVehicleRepository.UpdateAsync(vehicle) .AnyContext(); var history = new TrackingHistory(Guid.NewGuid().ToString(), vehicle.Id, status); await _trackingHistoryRepository.AddAsync(history) .AnyContext(); } }
public async Task HandleAsync(CreateDiscount command, ICorrelationContext context) { var customer = await _customersRepository.GetAsync(command.CustomerId); if (customer is null) { throw new VirtualMarketException("customer_not_found", $"Customer with id: '{command.CustomerId}' was not found."); } var discount = new Discount(command.Id, command.CustomerId, command.Code, command.Percentage); await _discountsRepository.AddAsync(discount); await _busPublisher.PublishAsync(new DiscountCreated(command.Id, command.CustomerId, command.Code, command.Percentage), context); }
public async Task HandleAsync(DeleteVehicleCommand command) { var vehicle = await _vehicleRepository.GetAsync(command.VehicleId) .AnyContext(); if (vehicle == null) { throw new AccException("vehicle_not_found", $"Vehicle: '{command.VehicleId}' was not found"); } vehicle.SetDeleteFlag(); await _vehicleRepository.UpdateAsync(vehicle) .AnyContext(); await _busPublisher.PublishAsync(new VehicleDeletedEvent(vehicle.Id)) .AnyContext(); }
public async Task <bool> Handle(ProductChangeCommand request, CancellationToken cancellationToken) { var product = _mapper.Map <ProductDto>(request); if (product != null) { await _productRepository.UpdateProductAsync(product); await _busPublisher.PublishAsync(new ProductChangedEvent(request.ProductId, request.Name, request.Price, request.Quantity), request.CorrelationContext); return(Task.CompletedTask.IsCompletedSuccessfully); } return(Task.CompletedTask.IsFaulted); }
public async Task PublishAsync(IEnumerable <IEvent> events) { if (events is null) { return; } foreach (var @event in events) { if (@event is null) { continue; } var messageId = Guid.NewGuid().ToString(); await _busPublisher.PublishAsync(@event, messageId); } }
public async Task HandleAsync(CreateOrder command, ICorrelationContext context) { if (await _ordersRepository.HasPendingOrder(command.CustomerId)) { throw new DShopException("customer_has_pending_order", $"Customer with id: '{command.CustomerId}' has already a pending order."); } var cart = await _customersService.GetCartAsync(command.CustomerId); var items = cart.Items.Select(i => new OrderItem(i.ProductId, i.ProductName, i.Quantity, i.UnitPrice)).ToList(); var order = new Order(command.Id, command.CustomerId, items, "USD"); await _ordersRepository.AddAsync(order); await _busPublisher.PublishAsync(new OrderCreated(command.Id, command.CustomerId, items.ToDictionary(i => i.Id, i => i.Quantity)), context); }
protected async Task SendAsync <T>(T message) where T : class { var spanContext = _tracer.ActiveSpan is null ? string.Empty : _tracer.ActiveSpan.Context.ToString(); var messageId = Guid.NewGuid().ToString("N"); //this is unique per message type, each message has its own messageId in rabbitmq var correlationId = Guid.NewGuid().ToString("N"); //unique for whole message flow , here gateway initiate our correlationId along side our newly publish message to keep track of our request var resourceId = Guid.NewGuid().ToString("N"); if (HttpContext.Request.Method == "POST" && message is JObject jObject) { jObject.SetResourceId(resourceId); } var correlationContext = _correlationContextBuilder.Build(HttpContext, correlationId, spanContext, message.GetType().Name.ToSnakeCase(), resourceId); await _busPublisher.PublishAsync <T>(message, messageId : messageId, correlationId : correlationId, spanContext : spanContext, messageContext : correlationContext); HttpContext.Response.StatusCode = 202; //we send 202 status code and a correlationId immediately to end user after we published message to the message broker HttpContext.Response.SetOperationHeader(correlationId); }
public async Task HandleAsync(ReserveProductCommand command, ICorrelationContext context) { foreach ((Guid productId, int quantity) in command.Products) { var product = await _productRepository.GetAsync(productId); if (product == null) { _logger.LogInformation($"Product was not found: '{productId}' (can't reserve)."); continue; } product.SetQuantity(product.Quantity - quantity); await _productRepository.UpdateAsync(product); } await _busPublisher.PublishAsync(new ProductReservedEvent(command.OrderId, command.Products), context); }
public async Task HandleAsync(CreateCustomer command, ICorrelationContext context) { var customer = await _customersRepository.GetAsync(command.Id); if (customer.Completed) { throw new DShopException(Codes.CustomerAlreadyCompleted, $"Customer account was already created for user with id: '{command.Id}'."); } customer.Complete(command.FirstName, command.LastName, command.Address, command.Country); await _customersRepository.UpdateAsync(customer); var cart = new Cart(command.Id); await _cartsRepository.AddAsync(cart); await _busPublisher.PublishAsync(new CustomerCreated(command.Id, customer.Email, command.FirstName, command.LastName, command.Address, command.Country), context); }