public async Task Handle_WhenTodoDoesNotExist_ShouldThrowException() { // Arrange var userId = Guid.NewGuid(); var command = new DeleteTodoCommand { UserId = userId, Id = -1 }; var dbOptions = new DbContextOptionsBuilder <TodoDbContext>().UseInMemoryDatabase(Guid.NewGuid().ToString()).Options; using (var context = new TodoDbContext(dbOptions)) { var sut = new DeleteTodoCommandHandler(context, rpcNotificationsMock.ServiceClient, rpcPermissionsMock.ServiceClient); try { // Act var result = await sut.Handle(command, new CancellationToken(false)); Assert.True(false, "Should throw exception"); } catch (EntityNotFoundException <Todo> ex) { // Assert Assert.NotNull(ex); } } }
public async Task Task_Delete() { var connection = TestHelper.GetConnection(); var options = TestHelper.GetMockDBOptions(connection); try { using (var context = new AppcentTodoContext(options)) { var service = new DeleteTodoCommandHandler(context); var command = new DeleteTodoCommand(); command.Data = new DeleteTodoRequest { TodoId = 2, UserName = "******" }; var result = await service.Execute(command); Assert.True(result.Result.IsSuccess); } using (var context = new AppcentTodoContext(options)) { var task = context.AcTasks.FirstOrDefault(e => e.TaskId == 2); Assert.True(task.IsDeleted); } } finally { connection.Close(); } }
public async Task Handle_WhenUserHasPermission_ShouldNotThrowException() { // Arrange var userId = Guid.NewGuid(); var command = new DeleteTodoCommand { UserId = userId, Id = 1 }; var rpcResponse = new IsUserAllowedResponse { IsAllowed = true }; rpcPermissionsMock.ClientMock.Setup(x => x.IsUserAllowed(It.IsAny <IsUserAllowedRequest>(), It.IsAny <CallOptions>())).Returns(rpcResponse); var dbOptions = new DbContextOptionsBuilder <TodoDbContext>().UseInMemoryDatabase(Guid.NewGuid().ToString()).Options; using (var context = new TodoDbContext(dbOptions)) { context.Todos.Add(new Todo { Id = 1, Name = "todo 1" }); context.SaveChanges(); var sut = new DeleteTodoCommandHandler(context, rpcNotificationsMock.ServiceClient, rpcPermissionsMock.ServiceClient); // Act var result = await sut.Handle(command, new CancellationToken(false)); } }
public async Task Handle_WhenUserDoesNotHavePermission_ShouldThrowException() { // Arrange var userId = Guid.NewGuid(); var command = new DeleteTodoCommand { UserId = userId, Id = -1 }; var rpcResponse = new IsUserAllowedResponse { IsAllowed = false }; rpcPermissionsMock.ClientMock.Setup(x => x.IsUserAllowed(It.IsAny <IsUserAllowedRequest>(), It.IsAny <CallOptions>())).Returns(rpcResponse); var dbOptions = new DbContextOptionsBuilder <TodoDbContext>().UseInMemoryDatabase(Guid.NewGuid().ToString()).Options; using (var context = new TodoDbContext(dbOptions)) { // Act var sut = new DeleteTodoCommandHandler(context, rpcNotificationsMock.ServiceClient, rpcPermissionsMock.ServiceClient); try { var result = await sut.Handle(command, new CancellationToken(false)); Assert.True(false, "Should throw exception"); } catch (InvalidOperationException ex) { // Assert Assert.NotNull(ex); } } }
public async Task Handle_WhenTodoDeleted_ShouldNotifiyUser() { // Arrange var userId = Guid.NewGuid(); var command = new DeleteTodoCommand { UserId = userId, Id = 1 }; var dbOptions = new DbContextOptionsBuilder <TodoDbContext>().UseInMemoryDatabase(Guid.NewGuid().ToString()).Options; using (var context = new TodoDbContext(dbOptions)) { context.Todos.Add(new Todo { Id = 1, Name = "todo 1" }); context.SaveChanges(); var sut = new DeleteTodoCommandHandler(context, rpcNotificationsMock.ServiceClient, rpcPermissionsMock.ServiceClient); // Act await sut.Handle(command, new CancellationToken(false)); } // Assert rpcNotificationsMock.ClientMock.Verify(x => x.SendPush(It.IsAny <SendPushRequest>(), It.IsAny <CallOptions>()), Times.Once); }
public async Task Handle_WhenUserHasPermission_ShouldDeleteTodo() { // Arrange var userId = Guid.NewGuid(); var command = new DeleteTodoCommand { UserId = userId, Id = 2 }; var dbOptions = new DbContextOptionsBuilder <TodoDbContext>().UseInMemoryDatabase(Guid.NewGuid().ToString()).Options; using (var context = new TodoDbContext(dbOptions)) { context.Todos.Add(new Todo { Id = 1, Name = "todo 1" }); context.Todos.Add(new Todo { Id = 2, Name = "todo 2" }); context.SaveChanges(); var sut = new DeleteTodoCommandHandler(context, rpcNotificationsMock.ServiceClient, rpcPermissionsMock.ServiceClient); // Act await sut.Handle(command, new CancellationToken(false)); var detetedTodo = await context.Todos.FirstOrDefaultAsync(t => t.Id == command.Id); // Assert detetedTodo.ShouldBeNull(); } }
public async Task <ActionResult> DeleteTodo([FromRoute] int id) { var request = new DeleteTodoCommand(User.Identity?.Name, id); var response = await _mediator.Send(request); return(response.Match <ActionResult>( ok => NoContent(), notFound => NotFound() )); }
public TodoListPageModel(ITodoItemService todoItemService) { _todoItemService = todoItemService; Todos = new ObservableCollection <TodoItemViewModel>(); // Todo: Unsubscribe events in case the view models view would be removed from the navigation stack MessagingCenter.Instance.Subscribe <ITodoItemService, TodoItem>( this, Messages.TodoItemsAdded, (sender, todo) => { Todos.Add(new TodoItemViewModel(_todoItemService, todo)); }); MessagingCenter.Instance.Subscribe <ITodoItemService, TodoItem>( this, Messages.TodoItemsRemoved, (sender, todo) => { var vm = Todos.SingleOrDefault(t => t.TodoItem.Id == todo.Id); if (vm != null) { Todos.Remove(vm); } }); AddTodoCommand = new Command( () => { CoreMethods.PushPageModel <AddTodoItemPageModel>(); }); DeleteTodoCommand = new Command <TodoItemViewModel>( async(todo) => { if (await CoreMethods.DisplayAlert( "Delete todo", $"Do you really want to delete todo '{todo.Name}'?", "Yes", "No") == false) { return; } await _todoItemService.RemoveTodoAsync(todo.TodoItem); SelectedTodo = null; DeleteTodoCommand.ChangeCanExecute(); }, (todo) => SelectedTodo != null); }
public async Task <MutationResult> DeleteTodo(string id) { var request = new DeleteTodoCommand { TodoId = id }; try { await processor.Run(request); return(MutationResult.Success()); } catch (Exception e) { return(MutationResult.Error(e)); } }
public async Task <OneOf <Ok, NotFound> > Handle(DeleteTodoCommand request, CancellationToken cancellationToken) { var todo = await _todosRepository .GetAsync(todo => todo.Id == request.Id && todo.UserLogin == request.UserLogin); if (todo == null) { return(new NotFound()); } _todosRepository.Delete(todo); await _todosRepository.SaveChangesAsync(); return(new Ok()); }
public async Task <ActionResult> DeleteTodo([FromBody] DeleteTodoDto viewRequest) { if (!TryValidateModel(viewRequest)) { return(BadRequest(ValidationHelper.GetModelErrors(ModelState))); } var request = this._mapper.Map <DeleteTodoRequest>(viewRequest); request.UserName = HttpContext.User.Identity.Name; var command = new DeleteTodoCommand { Data = request }; return(await Go(command)); }
private static void WorkWithQueryProcessor() { System.Console.WriteLine("\n-- Using QueryProcessor --"); var queryProcessor = new QueryProcessor(); var cmdProcessor = new CommandProcessor(); // Run a query with help of the query processor var query = new FindTodosByCategoryQuery { Category = "Etc" }; var queryResult = queryProcessor.Handle(query).Result; // Run a delete command with the command processor and see how the decorator is used var delCommand = new DeleteTodoCommand() { Id = queryResult[0].Id }; cmdProcessor.Handle(delCommand); PrintResults(queryResult); }
private static void WorkWithCommandsWithoutIoc() { System.Console.WriteLine("\n-- No IoC --"); // Line up some commands to execute var itemToCreateThenChange = new Todo { Caption = "Feed cat", Category = "Etc" }; var cmd1 = new CreateTodoCommand { Data = new Todo { Caption = "I SHOULD BE DELETED", Category = "Etc" } }; // id will become 1 var cmd2 = new CreateTodoCommand { Data = itemToCreateThenChange }; // id will become 2 var cmd3 = new CreateTodoCommand { Data = new Todo { Caption = "Pay bills", Category = "Etc" } }; // id will become 3 var cmd4 = new CreateTodoCommand { Data = new Todo { Caption = "I DO NOT PASS THE FILTER", Category = "Uncategorized" } }; // id will become 3 var updateCommand = new UpdateTodoCommand { Data = new Todo { Id = itemToCreateThenChange.Id, Category = itemToCreateThenChange.Category, Caption = "Feed BOTH cats" } }; var deleteCommand = new DeleteTodoCommand { Id = 1 }; // delete milk // Prepare the handlers var createHandler = new CreateTodoCommandHandler(new CachedRepository <Todo>()); var updateHandler = new UpdateTodoCommandHandler(new CachedRepository <Todo>()); var deleteHandler = new DeleteTodoCommandHandler(new CachedRepository <Todo>()); // Example using a decorator. We're instantiating the decorator manually here but the idea is to it with IoC. // This decorator outputs some logging to to Console.Out. var decorating_deleteHandler = new LoggingCommandHandlerDecorator <DeleteTodoCommand>(deleteHandler, (ILogger) new ConsoleLogger()); // Create something then queue it for deletion createHandler.Handle(cmd1).Wait(); deleteCommand.Id = cmd1.Output; Task.WaitAll( createHandler.Handle(cmd2) , createHandler.Handle(cmd3) , createHandler.Handle(cmd4) ); updateHandler.Handle(updateCommand).Wait(); decorating_deleteHandler.Handle(deleteCommand).Wait(); // Example using a queryhandler to deliver results var qhandler = new FindTodosByCategoryQueryHandler(new CachedRepository <Todo>()); var query = new FindTodosByCategoryQuery { Category = "Etc" }; var queryResult = qhandler.Handle(query); // Only two items should show up since we deleted one, and one doesn't match the query. PrintResults(queryResult.Result); }
public TodoItemsViewModel() { TodoList = new ObservableCollection <TodoItem>(); AddTodoCommand = new RelayCommand(() => { TodoList.Add(new TodoItem($"Neues ToDo {TodoItem.LastID + 2}", "...", DateTime.Now + TimeSpan.FromDays(1))); SelectedItem = TodoList[TodoList.Count - 1]; DeleteTodoCommand.OnCanExecuteChanged(); }); DeleteTodoCommand = new RelayCommand(() => { TodoList.Remove(SelectedItem); DeleteTodoCommand.OnCanExecuteChanged(); }, () => SelectedItem != null ); NextTodoCommand = new RelayCommand(() => { if (TodoList.IndexOf(SelectedItem) < TodoList.Count - 1) { SelectedItem = TodoList[TodoList.IndexOf(SelectedItem) + 1]; } else { SelectedItem = TodoList[0]; } }); PreviewTodoCommand = new RelayCommand(() => { if (TodoList.IndexOf(SelectedItem) > 0) { SelectedItem = TodoList[TodoList.IndexOf(SelectedItem) - 1]; } else { SelectedItem = TodoList.Last(); } }); SaveTodosCommand = new RelayCommand(() => { TodoStorageService.SaveTodos(); }); ToggleFavoriteCommand = new RelayCommand <object>(HandleNotifications); Task.Factory.StartNew(async() => { try { await TodoStorageService.LoadTodos(); await Task.Delay(500); } catch (Exception exp) { await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { NoSelectionText = exp.Message; LoadingComplete?.Invoke(this, EventArgs.Empty); }); return; } await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { this.TodoList = TodoItemManager.ItemList; NoSelectionText = TodoList.Count > 0 ? "Wähle ein Todo aus oder erstelle ein Neues!" : "Erstelle dein erstes Todo!"; LoadingComplete?.Invoke(this, EventArgs.Empty); }); }); }