public void Update(UpdateContactCommand updateCommand) { var contact = contactRepository.GetById(updateCommand.Id); contact.Update(updateCommand); contact.County = countyRepository.GetById(updateCommand.CountyId.Value); contact.Country = countryRepository.GetById(updateCommand.CountyId.Value); contactRepository.PersistAll(); }
public static async Task Run( [QueueTrigger("contacts", Connection = "AzureWebJobsStorage")] string contactJson, ILogger log, ExecutionContext context) { var logPrefix = GetLogPrefix(); log.LogInformation($"{logPrefix}: {contactJson}"); var contactFromFile = JsonConvert.DeserializeObject <FileUploadContact>(contactJson); var config = new ConfigurationBuilder() .SetBasePath(context.FunctionAppDirectory) .AddJsonFile("local.settings.json", true, true) .AddEnvironmentVariables() .Build(); var sqlConnectionString = config.GetConnectionString("Sql"); var fileUploadContext = new FileUploadContext(sqlConnectionString); var getEmployerQuery = new GetEmployerQuery(fileUploadContext); var employerInSql = await getEmployerQuery.Execute(contactFromFile.CompanyName, contactFromFile.CreatedOnCompany); if (employerInSql == null) { // TODO Employer has to exist } var getContactQuery = new GetContactQuery(fileUploadContext); var contactInSql = await getContactQuery.Execute(contactFromFile.CompanyName, contactFromFile.CreatedOnCompany); var contact = ContactMapper.Map(contactFromFile, contactInSql, employerInSql.Id); if (contactInSql == null) { log.LogInformation($"{logPrefix} Creating Contact: {contactFromFile.Contact}"); var createEmployerCommand = new CreateContactCommand(fileUploadContext); await createEmployerCommand.Execute(contact); log.LogInformation($"{logPrefix} Created Contact: {contactFromFile.Contact}"); } else { var areEqual = contactInSql.Equals(contact); if (!areEqual) { log.LogInformation($"{logPrefix} Updating Contact: {contactFromFile.Contact}"); var updateContactCommand = new UpdateContactCommand(fileUploadContext); await updateContactCommand.Execute(contact); log.LogInformation($"{logPrefix} Updated Contact: {contactFromFile.Contact}"); } } log.LogInformation($"{logPrefix} Processed Contact: {contactFromFile.Contact}"); }
public async Task <IActionResult> UpdateContact(UpdateContactCommand updateContactCommand) { updateContactCommand.OwnerId = _identityService.GetUserIdentity(); var result = await _mediator.Send(updateContactCommand); return(result ? (IActionResult)Ok() : (IActionResult)BadRequest()); }
public async Task <APIResult> Update([FromBody] UpdateContactCommand command) { var rs = await mediator.Send(command); return(new APIResult() { Result = rs }); }
public void UpdateContactWithInvalidValuesThrowsException() { var model = ContactsModelObjectMother.Random(); model.FirstName = null; var cmd = new UpdateContactCommand(model); var handler = new UpdateContactCommandHandler(uow.Object, eventBus.Object, repo.Object); Assert.Throws <EntityValidationException>(() => handler.Handle(cmd, new System.Threading.CancellationToken())); }
public async Task <ActionResult> Update(int id, UpdateContactCommand command) { if (id != command.Id) { return(BadRequest()); } await Mediator.Send(command); return(NoContent()); }
public async Task <int> Edit([FromBody] ClubContactsModel clubContactModel) { if (true /*ModelState.IsValid*/) { UpdateContactCommand updateContactCommand = new UpdateContactCommand(clubContactModel); var result = await _mediator.Send(updateContactCommand); return(result); } return(0); }
public async Task <IActionResult> Update([FromRoute] int id, [FromBody] UpdateContactCommand command) { if (command is null) { return(BadRequest()); } command.UserId = UserId; command.Id = id; return(Ok(await Mediator.Send(command))); }
public void Throws_ValidationException_DateOfBirth_Default() { // Arrange var sut = new UpdateContactValidator(); var cmd = new UpdateContactCommand { Id = int.MaxValue, Name = "A", Address = "A" }; // Act var result = sut.Validate(cmd); // Assert Assert.False(result.IsValid); Assert.Contains(result.Errors, e => e.PropertyName == nameof(cmd.DateOfBirth)); }
public void UpdateRepeatedContactThrowsException() { var original = ContactEntityObjectMother.Random(); var duplicated = ContactEntityObjectMother.Random(); duplicated.Name = original.Name; repo.Setup(x => x.ExistsContactWithName(duplicated.Name, duplicated.Id)).Returns(true); var model = ContactsModelObjectMother.FromEntity(duplicated); var cmd = new UpdateContactCommand(model); var handler = new UpdateContactCommandHandler(uow.Object, eventBus.Object, repo.Object); Assert.Throws <DomainException>(() => handler.Handle(cmd, new System.Threading.CancellationToken())); }
public void Throws_ValidationException_Address_Empty() { // Arrange var sut = new UpdateContactValidator(); var cmd = new UpdateContactCommand { Id = int.MaxValue, Name = "A", Address = string.Empty, DateOfBirth = DateTime.Now }; // Act var result = sut.Validate(cmd); // Assert Assert.False(result.IsValid); Assert.Contains(result.Errors, e => e.PropertyName == nameof(cmd.Address)); }
public void Validation_OK() { // Arrange var sut = new UpdateContactValidator(); var cmd = new UpdateContactCommand { Id = int.MaxValue, Name = "A", Address = "A", DateOfBirth = DateTime.Now.AddDays(-1) }; // Act var result = sut.Validate(cmd); // Assert Assert.True(result.IsValid); Assert.Empty(result.Errors); }
public void Throws_ValidationException_Name_Too_Long() { // Arrange var sut = new UpdateContactValidator(); var cmd = new UpdateContactCommand { Id = int.MaxValue, Name = new String('0', Constants.MaxLengths.ContactName + 1), Address = "A", DateOfBirth = DateTime.Now }; // Act var result = sut.Validate(cmd); // Assert Assert.False(result.IsValid); Assert.Contains(result.Errors, e => e.PropertyName == nameof(cmd.Name)); }
public async Task Throws_RequestException_Contact_Not_Found() { using var factory = new AppDbContextFactory(); using var context = factory.CreateContext(); // Arrange var sut = new UpdateContactHandler(_logger, context, _mediator.Object); var cmd = new UpdateContactCommand { Id = int.MaxValue, Name = "A", Address = "A", DateOfBirth = DateTime.Now.AddDays(-1) }; // Act & Assert var ex = await Assert.ThrowsAsync <RequestException>(() => sut.Handle(cmd)); _mediator.Verify(m => m.Publish(It.IsAny <ContactUpdatedNotification>(), default), Times.Never()); }
public Contact Update(UpdateContactCommand command) { var contact = _contactsContext .Contacts .Include(c => c.Address) .First(c => c.Id == command.ContactId); if (!string.IsNullOrWhiteSpace(command.Surname)) { contact.Surname = command.Surname; } if (!string.IsNullOrWhiteSpace(command.Name)) { contact.Name = command.Name; } _contactsContext.SaveChanges(); return(contact); }
public async Task <int> Update([FromBody] ClubContactsModel clubContactModel) { ////if (ModelState.IsValid) //{ // await _clubContactsViewModelService.UpdateOrCreateClubContactMember("BAZ", clubContactViewModel); // System.Diagnostics.Debug.WriteLine($"ClubContactsController::Update contact.GetFullName()"); //} if (ModelState.IsValid) { UpdateContactCommand updateContactCommand = new UpdateContactCommand(clubContactModel); var result = await _mediator.Send(updateContactCommand); return(result); } return(0); }
public IResult UpdateContact(IUpdateContactParameters parameters) { if(parameters == null) { throw new ArgumentNullException("parameters"); } var parametersResult = parameters.ToParsedParameters(); if(!parametersResult.Success) { return parametersResult; } var commandResult = new UpdateContactCommand(_companyUnitOfWork).Execute(parametersResult.ResultingObject); if(!commandResult.Success) { return commandResult; } _companyUnitOfWork.Commit(); return SyncParameters.Using(new SuccessResult(), commandResult.ResultingObject.ToCompanyKey()); }
public Task <bool> Handle(UpdateContactCommand request, CancellationToken cancellationToken) { if (!request.IsValid()) { return(Task.FromResult(false)); } var contact = new Contact(request.Id, request.CategoryId, request.Name, request.Email, request.BirthDate, request.PhoneNumber); var existingContact = _contactUnitOfWork.ContactsRepository.GetByEmail(request.UserId, request.Email); //Checking if the object is the same from db using this e-mail if (existingContact != null && existingContact.Id != contact.Id) { if (!existingContact.Equals(contact)) { _eventHandler.RaiseEvent(new DomainNotification(request.MessageType, "The contact e-mail has already been taken.")); return(Task.FromResult(false)); } } _contactUnitOfWork.ContactsRepository.UpdateContact(contact); //Storing the creation event if (_contactUnitOfWork.Commit()) { _eventHandler.RaiseEvent(new ContactUpdatedEvent(contact.Id, contact.Name, contact.Email, contact.BirthDate, contact.PhoneNumber)); } return(Task.FromResult(true)); }
public ICommandResult Handle(UpdateContactCommand command) { command.Validate(); if (command.Invalid) { return(new GenericCommandResult(false, "Ops, parece que os dados do contato estão errados!", command.Notifications)); } // Recupera var Contact = _repository.GetById(command.Id); // modificacoes Contact.UpdateName(command.Name); Contact.ChangeGender(command.Gender); Contact.ChangeDateBirth(command.Birth); // salva no banco _repository.Update(Contact); // Retorna o resultado return(new GenericCommandResult(true, "Contato salvo com sucesso!", Contact)); }
public async Task Throws_RequestException_Contact_Exists() { using var factory = new AppDbContextFactory(); using var context = factory.CreateContext(true); // Arrange var sut = new UpdateContactHandler(_logger, context, _mediator.Object); var contacts = context.Contacts.ToList(); var c1 = contacts.First(); var c2 = contacts.Last(); var cmd = new UpdateContactCommand { Id = c2.Id, Name = c1.Name.ToLower(), Address = c1.Address.ToUpper(), DateOfBirth = c1.DateOfBirth }; // Act & Assert var ex = await Assert.ThrowsAsync <RequestException>(() => sut.Handle(cmd)); _mediator.Verify(m => m.Publish(It.IsAny <ContactUpdatedNotification>(), default), Times.Never()); }
public void UpdateSameContactDoesNotThrowsException() { var contact = ContactEntityObjectMother.Random(); var model = ContactsModelObjectMother.FromEntity(contact); repo.Setup(x => x.GetById(contact.Id)).Returns(contact); repo.Setup(x => x.ExistsContactWithName(contact.Name, contact.Id)).Returns(false); repo.Setup(x => x.Update(It.IsAny <ContactEntity>())); uow.Setup(x => x.StartChanges()); uow.Setup(x => x.CommitChanges()); eventBus.Setup(x => x.Record(It.Is <ContactUpdatedDomainEvent>(p => p.FirstName == model.FirstName && p.LastName == model.LastName && p.AggregateRootId == model.Id))); eventBus.Setup(x => x.PublishAsync()).Returns(Task.Delay(500)); var cmd = new UpdateContactCommand(model); var handler = new UpdateContactCommandHandler(uow.Object, eventBus.Object, repo.Object); var result = handler.Handle(cmd, new System.Threading.CancellationToken()).Result; repo.VerifyAll(); uow.VerifyAll(); eventBus.VerifyAll(); }
public async Task GivenUpdateContactCommandWithInvalidId_ReturnsNotFoundStatusCode() { var invalidCommand = new UpdateContactCommand { Id = "8e7c209e-48b9-4aca-84d5-196b4a527098", FirstName = "Juan", LastName = "Valenzuela", Email = "*****@*****.**", ImageUrl = "juan.jpg", PhoneNumber = "+11234567890", Street1 = "1234 E Main St", Street2 = "", City = "Scottsdale", State = "Arizona", Country = "United States", ZipCode = "12345" }; var content = Utilities.GetRequestContent(invalidCommand); var response = await _client.PutAsync($"/api/contacts/update/{invalidCommand.Id}", content); Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); }
public async Task OK() { using var factory = new AppDbContextFactory(); using var context = factory.CreateContext(true); // Arrange var sut = new UpdateContactHandler(_logger, context, _mediator.Object); var contact = context.Contacts.First(); var cmd = new UpdateContactCommand { Id = contact.Id, Name = "C", Address = "C", DateOfBirth = DateTime.Now.AddDays(-1) }; // Act var result = await sut.Handle(cmd); // Assert Assert.True(contact.Name == "C"); Assert.True(contact.Address == "C"); _mediator.Verify(m => m.Publish(It.IsAny <ContactUpdatedNotification>(), default), Times.Once()); }
public async Task <ActionResult> UpdateContact(UpdateContactCommand command) { return(Ok(await Mediator.Send(command))); }
public async Task <ActionResult <UpdateContactUpdated> > Update(Guid id, [FromBody] UpdateContactCommand updateContact) { return(Ok(await Mediator.Send(updateContact))); }
public Contact Put([FromBody] UpdateContactCommand command) { QueriesOrCommands.Add(nameof(UpdateContactCommand)); return(UpdateContact(command)); }
public void UpdateContact(UpdateContactCommand updateCommand) { _contactService.UpdateContact(updateCommand.PhoneNumber, updateCommand.Contact); }
public async Task <bool> Update(UpdateContactCommand command) { return(await Mediator.Send(command)); }
public async Task <ActionResult <Customer> > Edit(int id, UpdateContactCommand command) { command.Id = id; return(await _mediator.Send(command)); }
public async Task <ContactViewModel> Update(int id, UpdateContactCommand command) { command.Id = id; return(await _mediator.Send(command)); }
public async Task <IActionResult> Update([FromBody] UpdateContactCommand command) { await Mediator.Send(command); return(Ok(command)); }
public void Update(UpdateContactCommand command) { Populate(command); }