public async Task EditCategoryCommandHandle_UpdatesExistingCategory() { //Arrange var category = new AllMarkt.Entities.Category { Name = "TestName", Description = "TestDescription" }; AllMarktContextIM.Categories.Add(category); AllMarktContextIM.SaveChanges(); var existingCategory = AllMarktContextIM.Categories.First(); var editCategoryCommand = new EditCategoryCommand { Id = existingCategory.Id, Name = "TestName_EDIT", Description = "TestDescription_EDIT" }; //Act await _editCategoryCommandHandler.Handle(editCategoryCommand, CancellationToken.None); //Assert AllMarktContextIM.Categories.Should().Contain(x => x.Id == editCategoryCommand.Id); category.Name.Should().Be(editCategoryCommand.Name); category.Description.Should().Be(editCategoryCommand.Description); }
public async Task <IActionResult> EditCategory(CategoryViewModel model) { if (!ModelState.IsValid) { return(View(model)); } var ecc = new EditCategoryCommand { Id = model.Id, NewName = model.Name, NewDescription = model.Description }; var result = await _cp.ProcessAsync(ecc); if (result.Succeeded) { _logger.LogInformation("Successfully updated Category with id {0} to name {1} and description {2}", model.Id, model.Name, model.Description); return(RedirectToAction("ManageCategories")); } _logger.LogWarning("Unable to update Category with id {0} to name {1} and description {2}", model.Id, model.Name, model.Description); // todo: better error handling ModelState.AddModelError("Error", "Unable to update category, perhaps the name is not unique"); return(View(model)); }
public async Task <IActionResult> PutCategory([FromBody] Category category) { var command = new EditCategoryCommand(category); var result = await _mediator.Send(command); return(Ok(result)); }
public async Task <IHttpActionResult> Put(Guid uid, [FromBody] EditCategoryCommand editCategory) { editCategory.Uid = uid; return(await ProcessCommand( command : () => Mediator.Send(editCategory), paramValidators : RequestParamValidator.CategoryEditValidator(editCategory))); }
public static RequestParamValidator[] CategoryEditValidator(EditCategoryCommand editCommand) { return(new[] { new RequestParamValidator(() => editCommand == null, "Request has to be set"), CategoryUidValidator(editCommand?.Uid), new RequestParamValidator(() => string.IsNullOrEmpty(editCommand.Name), "Name has to be set for category") }); }
public async Task <CategoryDTO> Handle(EditCategoryCommand request, CancellationToken cancellationToken) { //Updates category in the database when you change the category name. var category = request.Category; _unitOfWork.GetRepository <Category>().Update(category); await _unitOfWork.SaveChangesAsync(); return(_mapper.Map <CategoryDTO>(category)); }
public Task <HttpResponseMessage> Put(int id, [FromBody] dynamic body) { var command = new EditCategoryCommand( id: id, title: (string)body.title ); var category = _service.Update(command); return(CreateResponse(HttpStatusCode.OK, category)); }
public void ShouldNotCallHandleIfTagNotExist() { dbSetCategory.Setup(x => x.FindAsync(id)).Returns(null); context.Setup(x => x.Categories).Returns(dbSetCategory.Object); EditCategoryCommandHandler editCategoryCommandHandler = new EditCategoryCommandHandler(context.Object, stringLocalizer.Object, mapper.Object); EditCategoryCommand editCategoryCommand = new EditCategoryCommand(categoryDto); Func <Task> act = async() => await editCategoryCommandHandler.Handle(editCategoryCommand, new CancellationToken()); act.Should().ThrowAsync <NotFoundException>(); }
public void ShouldRequireValidCategoryId() { var categoryToEdit = new Faker <CategoryCreateOrEditDto>("en") .RuleFor(a => a.Id, f => f.Random.Guid()) .RuleFor(a => a.Title, f => f.Lorem.Sentence()) .Generate(); var command = new EditCategoryCommand(categoryToEdit); Func <Task> act = async() => await SendAsync(command); act.Should().ThrowAsync <NotFoundException>(); }
public void ShouldNotCallHandleIfNotSavedChanges() { dbSetCategory.Setup(x => x.FindAsync(id)).Returns(new ValueTask <Category>(Task.FromResult(category))); context.Setup(x => x.Categories).Returns(dbSetCategory.Object); context.Setup(x => x.SaveChangesAsync(It.IsAny <CancellationToken>())).Returns(Task.FromResult(0)); EditCategoryCommandHandler editCategoryCommandHandler = new EditCategoryCommandHandler(context.Object, stringLocalizer.Object, mapper.Object); EditCategoryCommand editCategoryCommand = new EditCategoryCommand(categoryDto); Func <Task> act = async() => await editCategoryCommandHandler.Handle(editCategoryCommand, new CancellationToken()); act.Should().ThrowAsync <RestException>(); }
public Category Update(EditCategoryCommand command) { var category = _repository.Get(command.Id); category.UpdateTitle(command.Title); _repository.Update(category); if (Commit()) { return(category); } return(null); }
public async Task ShouldCallHandle() { dbSetCategory.Setup(x => x.FindAsync(id)).Returns(new ValueTask <Category>(Task.FromResult(category))); context.Setup(x => x.Categories).Returns(dbSetCategory.Object); context.Setup(x => x.SaveChangesAsync(It.IsAny <CancellationToken>())).Returns(Task.FromResult(1)); EditCategoryCommandHandler editCategoryCommandHandler = new EditCategoryCommandHandler(context.Object, stringLocalizer.Object, mapper.Object); EditCategoryCommand editCategoryCommand = new EditCategoryCommand(categoryDto); var result = await editCategoryCommandHandler.Handle(editCategoryCommand, new CancellationToken()); mapper.Verify(x => x.Map(editCategoryCommand, category), Times.Once); result.Should().Be(Unit.Value); }
/// <summary> /// c'tor /// </summary> /// <param name="createCategoryCommand">createCategoryCommand</param> /// <param name="associateCategoryToParentCommand">associateCategoryToParentCommand</param> /// <param name="getCategoryCommand">Get Category Command</param> /// <param name="editCategoryCommand">Edit Category Command</param> /// <param name="deleteRelationshipCommand">Delete Relationship Command</param> /// <param name="findEntitiesInListCommand">Find entities in List Command</param> /// <param name="associatedItemRetrievalService">associatedItemRetrievalService</param> public CategoryImporter( CreateCategoryCommand createCategoryCommand, AssociateCategoryToParentCommand associateCategoryToParentCommand, GetCategoryCommand getCategoryCommand, EditCategoryCommand editCategoryCommand, DeleteRelationshipCommand deleteRelationshipCommand, FindEntitiesInListCommand findEntitiesInListCommand, IAssociatedItemRetrievalService associatedItemRetrievalService) { _createCategoryCommand = createCategoryCommand; _associateCategoryToParentCommand = associateCategoryToParentCommand; _getCategoryCommand = getCategoryCommand; _editCategoryCommand = editCategoryCommand; _deleteRelationshipCommand = deleteRelationshipCommand; _findEntitiesInListCommand = findEntitiesInListCommand; _associatedItemRetrievalService = associatedItemRetrievalService; }
public async Task ShouldNotEditCategoryIfTitleIsEmpty() { var loggedUser = await RunAsUserAsync("scott101@localhost", "Pa$$w0rd!"); var categoryId = await CreateCategory(); var categoryToCreate = new Faker <CategoryCreateOrEditDto>("en") .RuleFor(a => a.Id, f => categoryId) .Generate(); categoryToCreate.Title = null; var command = new EditCategoryCommand(categoryToCreate); Func <Task> act = async() => await SendAsync(command); act.Should().ThrowAsync <Common.Exceptions.ValidationException>(); }
public async Task ShouldUpdateCategory() { var loggedUser = await RunAsUserAsync("scott101@localhost", "Pa$$w0rd!"); var categoryId = await CreateCategory(); var categoryToModify = new Faker <CategoryCreateOrEditDto>("en") .RuleFor(a => a.Id, f => categoryId) .RuleFor(a => a.Title, f => f.Lorem.Sentence()) .Generate(); var command = new EditCategoryCommand(categoryToModify); await SendAsync(command); var modifiedCategory = await FindByGuidAsync <Category>(categoryId); modifiedCategory.Id.Should().Be(categoryToModify.Id); modifiedCategory.Title.Should().Be(categoryToModify.Title); modifiedCategory.LastModifiedBy.Should().Be(loggedUser); modifiedCategory.LastModified.Should().BeCloseTo(DateTime.UtcNow, new TimeSpan(0, 0, 1)); }
public ActionResult Edit(CategoryEditViewModel vm) { var command = new EditCategoryCommand { Id = vm.Id, Icon = vm.Icon, Name = vm.Name }; if (vm.Image != null) { var result = SaveAs(vm.Image, PlatformConfiguration.UploadedCategoryPath); if (result != null) { command.FileId = result.File.Id; command.IsFileChanged = true; } } Command.Execute(command); return(RedirectToAction("Index")); }
public async Task <IActionResult> EditCategory(CategoryViewModel model) { if (ModelState.IsValid) { var ecc = new EditCategoryCommand() { Id = model.Id, NewName = model.Name, NewDescription = model.Description }; var result = await _cp.ProcessAsync(ecc); if (result.Succeeded) { return(RedirectToAction("ManageCategories")); } else { return(NotFound()); } } return(View(model)); }
/// <summary> /// Post selected CategoryViewModel to message hub /// </summary> protected override void ItemClick(CategoryViewModel category) { EditCategoryCommand.Execute(category); }
public async Task <IActionResult> UpdateCategory(int serviceId, EditCategoryCommand command) { return(Ok(await Mediator.Send(command))); }
/// <summary> /// Post selected CategoryViewModel to message hub /// </summary> protected override async Task ItemClick(CategoryViewModel category) { await EditCategoryCommand.ExecuteAsync(category); }
public async Task <IActionResult> Edit([FromHybrid] EditCategoryCommand command) { return(await Execute(command)); }
/// <summary> /// Initializes a new instance of the TaskViewModel class. /// </summary> public TaskViewModel() { if (IsInDesignMode) { TestDataService testData = new TestDataService(); TaskData = testData.Output; } else { string FileName = @".\TaskData.xml"; if (File.Exists(FileName)) { XmlSerializer reader = new XmlSerializer(typeof(ObservableCollection <Category>)); StreamReader file = new System.IO.StreamReader(FileName); TaskData = reader.Deserialize(file) as ObservableCollection <Category>; } else { TaskData = new ObservableCollection <Category>(); TaskData.Add(new Category() { CategoryName = "Inbox", Index = Guid.NewGuid().ToString(), TaskList = new ObservableCollection <Task>() }); TaskData[0].TaskList.Add(new Task() { TaskName = "Welcome", TaskNote = "", IsFinished = false, SubtaskList = new ObservableCollection <Subtask>() } ); TaskData.Add(new Category() { CategoryName = "Today", Index = Guid.NewGuid().ToString(), TaskList = new ObservableCollection <Task>() }); TaskData.Add(new Category() { CategoryName = "Someday", Index = Guid.NewGuid().ToString(), TaskList = new ObservableCollection <Task>() }); TaskData.Add(new Category() { CategoryName = "Log", Index = Guid.NewGuid().ToString(), TaskList = new ObservableCollection <Task>() }); } } Category_State = "Normal"; AddTaskCommand = new RelayCommand(() => AddTask()); FilterTaskCommand = new RelayCommand(() => FilterTask()); ClearFilterCommand = new RelayCommand(() => { FilterStr = string.Empty; }); AddTask_EnterKeyCommand = new RelayCommand <KeyEventArgs>((e) => { if (e.Key == Key.Enter) { AddTask(); } }); EditCategory_DoubleClick_Command = new RelayCommand <MouseButtonEventArgs>((e) => { if (e.ChangedButton == MouseButton.Left && e.ClickCount == 2) { EditCategoryCommand.Execute(new object()); e.Handled = true; } }); EditCategory_Key_Command = new RelayCommand <KeyEventArgs>((e) => { if (e.Key == Key.Enter) { EditCategoryCommand.Execute(new object()); } }); EditCategoryCommand = new RelayCommand(() => { if (Category_State == "Normal") { Messenger.Default.Send <MessengerToken>(MessengerToken.Category_EditMode, "RequestSending_from_TaskVM_to_TaskView_EditCategory"); Category_State = "Edit"; } else { foreach (Category c in TaskData) { if (string.IsNullOrEmpty(c.CategoryName)) { c.CategoryName = "Unnamed"; } } Messenger.Default.Send <MessengerToken>(MessengerToken.Category_NormalMode, "RequestSending_from_TaskVM_to_TaskView_EditCategory"); Category_State = "Normal"; } }); DeleteCategoryCommand = new RelayCommand <string>((index) => { for (int i = 0; i < TaskData.Count; i++) { if (TaskData[i].Index == index) { TaskData.RemoveAt(i); break; } } }); AddCategoryCommand = new RelayCommand(() => { TaskData.Insert(TaskData.Count - 1, new Category() { CategoryName = "Unnamed", Index = Guid.NewGuid().ToString(), TaskList = new ObservableCollection <Task>() }); Messenger.Default.Send <MessengerToken>(MessengerToken.Category_EditMode, "RequestSending_from_TaskVM_to_TaskView_EditCategory"); Category_State = "Edit"; }); Messenger.Default.Register <MessengerToken>(this, "RequestSending_from_MainVM_to_TaskVM_SaveTaskData", false, (msg) => { if (msg == MessengerToken.Save) { try { XmlSerializer writer = new XmlSerializer(typeof(ObservableCollection <Category>)); StreamWriter file = new StreamWriter(@".\TaskData.xml"); writer.Serialize(file, TaskData); file.Close(); } catch (Exception e) { Exception ie = e.InnerException; } } }); Messenger.Default.Register <MessengerToken>(this, "RequestSending_from_DetailsVM_to_TaskVM_SelectedTask", false, (msg) => { if (msg == MessengerToken.Delete_this_task) { RemoveTask(); } }); }