public void ExecuteAsync_NoHandlerDefined_ThrowsException() { var commandDispatcher = new CommandDispatcher(t => { throw new Exception(); }); var expectedMessage = string.Format("Can not resolve handler for ICommandHandler<{0}>", typeof(ICommand).Name); Assert.That(async () => await commandDispatcher.DispatchAsync(_command), Throws.InstanceOf<ResolverException>().And.Message.EqualTo(expectedMessage)); }
public async Task <IActionResult> Put([FromBody] UpdateBook command) { if (command == null) { return(BadRequest()); } await CommandDispatcher.DispatchAsync(command); return(NoContent()); }
public async Task <IActionResult> Create([FromBody] CreateUser command) { if (command == null) { return(BadRequest()); } await CommandDispatcher.DispatchAsync(command); return(Created($"users/{command.Email}", new object())); }
public async Task <IActionResult> AddToFoodLog([FromBody] AddToFoodLogCommand command) { var email = User.FindFirst(ClaimTypes.NameIdentifier)?.Value; var userId = await _userService.GetUserIdAsync(email); command.UserId = userId; await CommandDispatcher.DispatchAsync <AddToFoodLogCommand>(command); return(NoContent()); }
static void Main(string[] args) { using (var bs = new BusSubscription()) using (var d = new CommandDispatcher(bs)) { var superHeroId = Guid.NewGuid(); var superVillainId = Guid.NewGuid(); Thread.Sleep(1000); Console.WriteLine("Adding Joker"); d.DispatchAsync(new AddSuperVillain() { Name = "Joker", Id = superVillainId }).Wait(); Console.WriteLine("Adding Spiderman"); d.DispatchAsync(new AddSuperhero { Name = "Spiderman", Id = superHeroId, Address = "New York", Dob = new DateTime(1984, 11, 15) }).Wait(); Thread.Sleep(5000); Console.WriteLine("Joker tries to demolish New York"); d.DispatchAsync(new TryDestroyACity { Id = Guid.NewGuid(), SuperVillainId = superVillainId, CityName = "New York", CountryCode = "US" }).Wait(); Thread.Sleep(5000); Console.WriteLine("Joker tries to poison Volga"); d.DispatchAsync(new TryPoisonWater() { Id = Guid.NewGuid(), SuperVillainId = superVillainId, RiverName = "Volga", CountryCode = "RU" }).Wait(); Thread.Sleep(5000); Console.WriteLine("Spiderman is too tired and retired!"); d.DispatchAsync(new RetireSuperhero { Id = superHeroId }); Console.ReadLine(); } }
public async Task <IActionResult> SendMessage(SendMessage command) { if (ModelState.IsValid) { await CommandDispatcher.DispatchAsync(command); } else { throw new Exception("No input parameter"); } return(RedirectToAction("Index")); }
public async Task <IActionResult> Post([FromBody] Create command) { var id = Guid.NewGuid(); command.Id = id; command.UserId = UserId; await CommandDispatcher.DispatchAsync(command); var task = _cache.GetTask(command.Id); return(Created("task/", task)); }
public async Task <ActionResult> Create(CreateTournament command) { if (ModelState.IsValid) { await CommandDispatcher.DispatchAsync(command); this.HttpContext.Response.StatusCode = 201; return(RedirectToAction("Index", new { message = "JUPI udalo sie utworzyc nowy turniej", status = "success" })); } ViewBag.Message = "NIe udalo sie stworzyc turnieju"; return(View()); }
public async Task <IActionResult> Post([FromForm(Name = "File")] IFormFile image) { var command = new AddImage { ImageOriginal = image }; await CommandDispatcher.DispatchAsync(command); var resultImage = await _imageService.GetImage(command.Id); return(Ok(resultImage)); }
public async Task Should_Invoke_Registered_Attributed_Command_Handler() { var commandHandler = new TestAttributedCommandHandler(_outputHelper); var registration = new CommandHandlerAttributeRegistration(); registration.Register(() => commandHandler); var dispatcher = new CommandDispatcher(registration); await dispatcher.DispatchAsync(new DoSomethingCommand()); Assert.Equal(1, commandHandler.HandledCommands.Count); Assert.Contains(commandHandler.HandledCommands, c => c is DoSomethingCommand); }
public async Task <IActionResult> UpdateProduct(Guid id, [FromBody] JsonPatchDocument <ProductDto> productPatch) { UpdateProductCommand command = new UpdateProductCommand(); command.Id = id; command.ProductPatch = productPatch; await CommandDispatcher.DispatchAsync <UpdateProductCommand>(command); var p = await _productService.GetProductAsync(id); return(Ok(p)); }
public async Task <IActionResult> Post([FromBody] Create command) { var id = Guid.NewGuid(); command.Id = id; command.UserId = UserId; await CommandDispatcher.DispatchAsync(command); var project = _cache.GetProject(command.Id); return(Created("/project", project)); }
public async Task <IActionResult> Post([FromBody] CreateRoom command) { await CommandDispatcher.DispatchAsync(command); /* * await _roomservice.RegisterAsync(command.Name, command.RoomNumber, command.Lectern, command.VotingSystem, * command.SoundSystem, command.MagneticWall, command.Computer, command.InterpretationService, * command.BrainstormingWall, command.LEDWall, command.Microphone, command.Multiphone, command.LCDScreen, * command.Flipchart, command.WhiteScreen, command.Videoconference, command.Projector); */ return(Created($"room/{command.RoomNumber}", new object())); }
public async Task <IActionResult> Post([FromBody] Create command) { var labelId = Guid.NewGuid(); command.Id = labelId; command.UserId = UserId; await CommandDispatcher.DispatchAsync(command); var label = _cache.GetLabel(labelId); return(Created($"label/{labelId}", label)); }
public async Task <IActionResult> AddProduct([FromBody] AddProductCommand command) { command.Id = Guid.NewGuid(); await CommandDispatcher.DispatchAsync <AddProductCommand>(command); var product = await _productService.GetProductAsync(command.Id); if (product != null) { return(CreatedAtRoute("GetProduct", new { id = command.Id }, product)); } return(StatusCode(500)); }
public void TestDispatch_CommandHandlerNotFound() { var services = new ServiceCollection(); var serviceProvider = services.BuildServiceProvider(); var dispatcher = new CommandDispatcher(serviceProvider); var command = new TestCommand { Value = "value", }; Assert.ThrowsAsync <CommandHandlerNotFoundException>(() => dispatcher.DispatchAsync(command)); }
public async Task Should_Invoke_Registered_Command_Handler_With_CancellationToken() { var commandHandler = new TestCommandHandler(_outputHelper); var registration = new CommandHandlerRegistration(); registration.Register(() => (ICommandAsyncHandler <DoSomethingCommand>)commandHandler); var dispatcher = new CommandDispatcher(registration); var cts = new CancellationTokenSource(); await dispatcher.DispatchAsync(new DoSomethingCommand(), cts.Token); Assert.Equal(1, commandHandler.HandledCommands.Count); Assert.Contains(commandHandler.HandledCommands, c => c is DoSomethingCommand); }
public async Task Should_Invoke_Registered_Command_Handler_In_Container() { var commandHandler = new TestCommandHandler(_outputHelper); var container = new Container(); container.Register <ICommandHandler <DoSomethingCommand> >(() => commandHandler, Lifestyle.Singleton); var containerAdapter = new SimpleInjectorContainerAdapter(container); var dispatcher = new CommandDispatcher(new ContainerCommandHandlerResolver(containerAdapter)); // Sync handler resolver await dispatcher.DispatchAsync(new DoSomethingCommand()); Assert.Equal(1, commandHandler.HandledCommands.Count); Assert.Contains(commandHandler.HandledCommands, c => c is DoSomethingCommand); }
public async Task <IActionResult> PostFileAsync() { if (HttpContext.Request.Form.Files.Any()) { var file = HttpContext.Request.Form.Files[0]; var memoryStream = new MemoryStream(); await file.CopyToAsync(memoryStream); await CommandDispatcher.DispatchAsync(new UploadFileCommand { Filename = file.FileName, MemoryStream = memoryStream, UserId = UserId }); return(StatusCode(201)); } else { return(StatusCode(400)); } }
public async Task <IActionResult> Post([FromHeader] object header, [FromBody] AddNewTrip command) { Microsoft.Extensions.Primitives.StringValues value = ""; var coll = Request.Headers.TryGetValue("Authorization", out value); var coll1 = Request.Body; var values = value.ToString().Split().ToList(); var stream = values[1]; var handler = new JwtSecurityTokenHandler(); var jsonToken = handler.ReadToken(stream); var tokenS = handler.ReadToken(stream) as JwtSecurityToken; command.UserID = tokenS.Claims.First().Value; await CommandDispatcher.DispatchAsync(command); return(StatusCode(201)); }
public async Task InvokeHandler() { // Arrange var updateEmailHandler = new Mock <ICommandHandlerAsync <ChangeEmailCommand> >(); var handlers = new Dictionary <Type, IEnumerable <object> > { { typeof(ICommandHandlerAsync <ChangeEmailCommand>), new object[] { updateEmailHandler.Object } } }; var sut = new CommandDispatcher(handlers); var updateEmailCommand = new ChangeEmailCommand("somemail", "newmail"); // Act await sut.DispatchAsync(updateEmailCommand); // Assert updateEmailHandler.Verify(handler => handler.HandleAsync(updateEmailCommand), Times.Once); }
public Task Should_Throw_When_No_Registered_Command_Handler_Is_Found() { return(Assert.ThrowsAsync <NoCommandHandlerResolvedException>(async() => { var registration = new CommandHandlerRegistration(); var dispatcher = new CommandDispatcher(registration); try { await dispatcher.DispatchAsync(new DoSomethingCommand()); } catch (Exception ex) { _outputHelper.WriteLine(ex.ToString()); throw; } })); }
public async Task NotInvokeHandlerWhenOfInvalidType() { // Arrange var updateEmailHandler = new Mock <ICommandHandlerAsync <ChangeEmailCommand> >(); var handlers = new Dictionary <Type, IEnumerable <object> > { { typeof(ICommandHandlerAsync <ChangeEmailCommand>), new[] { new { Invalid = "Handler" } } } }; var updateEmailCommand = new ChangeEmailCommand("somemail", "newmail"); var sut = new CommandDispatcher(handlers); // Act await sut.DispatchAsync(updateEmailCommand); // Assert updateEmailHandler.Verify(handler => handler.HandleAsync(updateEmailCommand), Times.Never); }
public async Task TestDispatch_CommandHandlerFound() { var services = new ServiceCollection(); services.AddScoped <ICommandHandler <TestCommand>, TestCommandHandler>(); var serviceProvider = services.BuildServiceProvider(); var dispatcher = new CommandDispatcher(serviceProvider); var command = new TestCommand { Value = "value", }; var exception = await Record.ExceptionAsync(() => dispatcher.DispatchAsync(command)); Assert.Null(exception); }
public async Task AuditsBeforeExecute() { // Arrange int executionOrder = 0; int auditExecutionIndex = -1; int executeExecutionIndex = -1; Mock <ICommandRegistry> registry = new Mock <ICommandRegistry>(); Mock <ICommandExecuter> executer = new Mock <ICommandExecuter>(); Mock <ICommandScopeManager> commandContextManager = new Mock <ICommandScopeManager>(); Mock <ICommandAuditPipeline> auditorPipeline = new Mock <ICommandAuditPipeline>(); Mock <IOptionsProvider> optionsProvider = new Mock <IOptionsProvider>(); optionsProvider.Setup(x => x.Options).Returns(new Options()); CommandDispatcher dispatcher = new CommandDispatcher( registry.Object, executer.Object, commandContextManager.Object, auditorPipeline.Object, optionsProvider.Object); CommandDispatchContext commandDispatchContext = new CommandDispatchContext("someid", new Dictionary <string, object>()); commandContextManager.Setup(x => x.Enter()).Returns(commandDispatchContext); SimpleCommand command = new SimpleCommand(); auditorPipeline.Setup(x => x.AuditPreDispatch(command, commandDispatchContext, It.IsAny <CancellationToken>())).Callback(() => { auditExecutionIndex = executionOrder; executionOrder++; }).Returns(Task.FromResult(0)); executer.Setup(x => x.ExecuteAsync(command, It.IsAny <CancellationToken>())).Callback(() => { executeExecutionIndex = executionOrder; executionOrder++; }).Returns(Task.FromResult <SimpleResult>(null)); // Act await dispatcher.DispatchAsync(command, default(CancellationToken)); // Assert auditorPipeline.Verify(x => x.AuditPreDispatch(command, commandDispatchContext, It.IsAny <CancellationToken>()), Times.Once); Assert.Equal(0, auditExecutionIndex); Assert.Equal(1, executeExecutionIndex); }
public Task Should_Throw_When_No_Registered_Command_Handler_In_Container_Is_Found() { return(Assert.ThrowsAsync <NoCommandHandlerResolvedException>(async() => { var container = new Container(); var containerAdapter = new SimpleInjectorContainerAdapter(container); var dispatcher = new CommandDispatcher(new ContainerCommandHandlerResolver(containerAdapter)); // Sync handler resolver try { await dispatcher.DispatchAsync(new DoSomethingCommand()); } catch (Exception ex) { _outputHelper.WriteLine(ex.ToString()); throw; } })); }
public Task Should_Propagate_Exception_From_Command_Handler() { return(Assert.ThrowsAnyAsync <Exception>(async() => { var commandHandler = new TestCommandHandler(_outputHelper); var registration = new CommandHandlerRegistration(); registration.Register(() => (ICommandAsyncHandler <ThrowExceptionCommand>)commandHandler); var dispatcher = new CommandDispatcher(registration); try { await dispatcher.DispatchAsync(new ThrowExceptionCommand()); } catch (Exception ex) { _outputHelper.WriteLine(ex.ToString()); throw; } })); }
public async Task ExecutesWithoutDispatcher() { // Arrange Mock <ICommandRegistry> registry = new Mock <ICommandRegistry>(); Mock <ICommandExecuter> executer = new Mock <ICommandExecuter>(); Mock <ICommandScopeManager> commandContextManager = new Mock <ICommandScopeManager>(); Mock <ICommandAuditPipeline> auditorPipeline = new Mock <ICommandAuditPipeline>(); Mock <IOptionsProvider> optionsProvider = new Mock <IOptionsProvider>(); optionsProvider.Setup(x => x.Options).Returns(new Options()); CommandDispatcher dispatcher = new CommandDispatcher(registry.Object, executer.Object, commandContextManager.Object, auditorPipeline.Object, optionsProvider.Object); SimpleCommand command = new SimpleCommand(); // Act await dispatcher.DispatchAsync(command, default(CancellationToken)); // Assert executer.Verify(x => x.ExecuteAsync(command, It.IsAny <CancellationToken>())); }
public async Task <ActionResult> CreateCarReservation(CreateCarReservation command) { CommandResult result; if (ModelState.IsValid) { result = await CommandDispatcher.DispatchAsync(command); if (!result.Success) { ViewBag.CarTypeList = await QueryDispatcher.DispatchAll <CarTypeViewModel>(); ModelState.AddModelError("", $"{result.Message}"); return(View()); } return(View("ReservationSuccess")); } else { ViewBag.CarTypeList = await QueryDispatcher.DispatchAll <CarTypeViewModel>(); return(View(command)); } }
public async Task <IActionResult> Put([FromBody] ChangeUserPassword command) { await CommandDispatcher.DispatchAsync(command); return(NoContent()); }
public async Task <IActionResult> Post([FromBody] CreateArticle command) { await CommandDispatcher.DispatchAsync(command); return(Created($"articles/11111", new object())); }