public IActionResult CreateAuthor([FromBody] AuthorCreateDto author) { if (author == null) { return(BadRequest()); } var authorEntity = AutoMapper.Mapper.Map <Author>(author); _libraryRepository.AddAuthor(authorEntity); if (!_libraryRepository.Save()) { throw new Exception("Creating an author failed on save."); } var authorToReturn = AutoMapper.Mapper.Map <AuthorDto>(authorEntity); var links = CreateLinksForAuthor(authorToReturn.Id, null); var linkedResourceToReturn = authorToReturn.ShapeData(null) as IDictionary <string, object>; linkedResourceToReturn.Add("links", links); return(CreatedAtRoute("GetAuthor", new { id = linkedResourceToReturn["Id"] }, linkedResourceToReturn)); }
public bool CreateAuthor(AuthorCreateDto authorToCreateDto) { var authorToCreate = MapConfig.Mapper.Map <Author>(authorToCreateDto); _authorContext.Add(authorToCreate); return(Save()); }
public async Task <IActionResult> Create([FromBody] AuthorCreateDto authorDTO) { try { _logger.logInfo($"Author submission attempted"); if (authorDTO == null) { _logger.logWarn($"Empty request was submitted"); return(BadRequest(ModelState)); } if (!ModelState.IsValid) { _logger.logWarn($"Author data was incomplete"); return(BadRequest(ModelState)); } var author = _mapper.Map <Author>(authorDTO); bool isSuccess = await _authorRepository.Create(author); if (!isSuccess) { return(InternalError($"Author creation failed")); } _logger.logInfo($"Author Created"); return(Created("Create", new { author })); } catch (Exception e) { return(InternalError($"{e.Message} - {e.InnerException}")); } }
public IActionResult Post([FromBody] AuthorCreateDto authorCreate) { if (authorCreate == null) { return(BadRequest()); } var author = Mapper.Map <Author>(authorCreate); Repository.CreateAuthor(author); if (!Repository.Save()) { throw new Exception("Author creation unsuccessful."); } var authorDto = Mapper.Map <AuthorDto>(author); var links = CreateAuthorLinks(authorDto.Id, null); var authorResourceLinks = authorDto.ShapeData(null) as IDictionary <string, object>; authorResourceLinks.Add("links", links); return(CreatedAtRoute("GetAuthor", new { id = authorResourceLinks["Id"] }, authorResourceLinks)); }
public async Task <IActionResult> Create([FromBody] AuthorCreateDto authorDto) { var location = GetControllerActionNames(); try { _logger.LogWarn($"{location}: Empty Request was submited."); if (authorDto == null) { _logger.LogWarn($"{location}: Empty Request was submited."); return(BadRequest(ModelState)); } if (!ModelState.IsValid) { _logger.LogWarn($"{location}: Data was Incomplete."); return(BadRequest(ModelState)); } var author = _mapper.Map <Author>(authorDto); var isSuccess = await _authorRepository.Create(author); if (!isSuccess) { return(InternalError($"{location}: Creation failed.")); } _logger.LogInfo("Created successfully"); _logger.LogInfo($"{location}: {author} "); return(Created("Create", new { author })); } catch (Exception e) { return(InternalError($"{location}: {e.Message} - {e.InnerException}")); } }
public async Task <ActionResult <AuthorDto> > CreateAuthor([FromBody] AuthorCreateDto author) { // .Net now automatically sends BadRequest 400 for null parameter. No need to check. try { var authorEntity = _mapper.Map <Author>(author); await _authorLibraryRepository.AddAuthorAsync(authorEntity); //Implement HATEOAS var links = CreateLinksForAuthor(authorEntity.Id); // Cast as expando object - IDictionary<string, object> var linkedResourceToReturn = _mapper.Map <AuthorDto>(authorEntity) .ShapeData(null) as IDictionary <string, object>; // add links property linkedResourceToReturn.Add("links", links); //HTTP SC 201 response return(CreatedAtRoute("GetAuthor", new { authorId = linkedResourceToReturn["Id"] }, linkedResourceToReturn)); } catch (Exception) { return(BadRequest()); } }
public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next) { AuthorCreateDto authorDto = (AuthorCreateDto)context.ActionArguments["authorCreateDto"]; IBookRepository bookRepository = (IBookRepository)context.HttpContext.RequestServices.GetService(typeof(IBookRepository)); if (ErrorOnBooks(authorDto) && ErrorOnBooksIds(authorDto)) { context.ModelState.AddModelError("BooksIds", "You need to pass the ids of the books that this author wrote or create the books that this author wrote"); context.ModelState.AddModelError("Books", "You need to create the books that this author wrote or pass the ids of the books that this author wrote"); context.Result = new BadRequestObjectResult(context.ModelState); } else if (!ErrorOnBooksIds(authorDto)) { if (await NotFoundedBooksIdsAsync(authorDto, bookRepository)) { context.ModelState.AddModelError("BooksIds", "The passed ids does not match with any book. You n"); context.Result = new BadRequestObjectResult(context.ModelState); } else { await next(); } } else { await next(); } }
public async Task Create_Authors_And_Get() { var authorToCreate = new AuthorCreateDto() { Name = "Joe" }; HttpResponseMessage response = await this._client.PostAsJsonAsync("/Api/AuthorsV3", authorToCreate); // Fail the test if non-success result response.EnsureSuccessStatusCode(); // Get the response as a string var authorCreated = await response.Content.ReadAsAsync <Author>(); // Assert on correct content Assert.NotNull(authorCreated); HttpResponseMessage responseGet = await this._client.GetAsync($"/Api/AuthorsV3/{authorCreated.Id}"); // Fail the test if non-success result responseGet.EnsureSuccessStatusCode(); // Get the response as a string var author = await responseGet.Content.ReadAsAsync <Author>(); // Assert on correct content Assert.NotNull(author); Assert.Equal(authorToCreate.Name, author.Name); }
public async Task <ActionResult <AuthorDto> > Post([FromBody] AuthorCreateDto authorCreateDto) { AuthorDto newAuthor = _mapper.Map <AuthorDto>( await _authorService.AddAsync(_mapper.Map <Author>(authorCreateDto)) ); return(CreatedAtAction("Get", new { id = newAuthor.Id }, newAuthor)); }
public async Task <ActionResult <AuthorDto> > PostAuthor(AuthorCreateDto authorDto) { var author = _mapper.Map <Author>(authorDto); _context.Authors.Add(author); await _context.SaveChangesAsync(); return(CreatedAtAction("GetAuthor", new { id = author.Id }, _mapper.Map <AuthorDto>(author))); }
public async Task <Author> FilledAuthorOnCreateAsync(AuthorCreateDto authorDto) { Author author = _mapper.Map <Author>(authorDto); author.RegisterDate = DateTime.Now; List <Book> books = await GetBooksOnCreateAsync(authorDto); author = FilledAuthorBooksOnCreateProperty(author, authorDto, books); return(author); }
public async Task <ActionResult> Create([FromBody] AuthorCreateDto authorCreateDto) { Author author = await _controllerServices.FilledAuthorOnCreateAsync(authorCreateDto); await _authorRepository.CreateAsync(author); AuthorReadDto authorReadDto = _controllerServices.GetAuthorReadDto(author); return(CreatedAtRoute("GetAuthorById", new { author.Id }, authorReadDto)); }
public ActionResult <AuthorDTO> CreateAuthor(AuthorCreateDto author) { var authorEntity = _mapper.Map <CourseLibrary.API.Entities.Author>(author); _courseLibraryRepository.AddAuthor(authorEntity); _courseLibraryRepository.Save(); var authorToReturn = _mapper.Map <AuthorDTO>(authorEntity); return(CreatedAtRoute("GetAuthor", new { authorId = authorToReturn.Id }, authorToReturn)); }
public ActionResult Post(AuthorCreateDto authorDto) { var author = new Author { FirstName = authorDto.FirstName, LastName = authorDto.LastName }; _bookLibrary.Authors.Add(author); _bookLibrary.SaveChanges(); return(CreatedAtAction("Get", new { id = author.Id }, author)); }
public IActionResult AddAuthor(AuthorCreateDto authorCreateDto) { var author = _mapper.Map <Author>(authorCreateDto); _repository.AddAuthor(author); _repository.SaveChanges(); var authorDto = _mapper.Map <AuthorDto>(author); return(CreatedAtRoute(nameof(GetAuthorById), new { authorId = authorDto.Id }, authorDto)); }
public ActionResult <Author> Create(AuthorCreateDto AuthorCreateDto) { try { return(service.Create(AuthorCreateDto)); } catch (Exception error) { return(Conflict(error.Message)); } }
public IActionResult CreateAuthor([FromBody] AuthorCreateDto author) { if (author == null) { return(BadRequest()); } var authorEntity = _mapper.Map <Author>(author); return(CreateAuthor(authorEntity)); }
public ActionResult <AuthorGetDto> CreateAuthor(AuthorCreateDto author) { var authorEntity = _mapper.Map <Author>(author); _repo.AddAuthor(authorEntity); _repo.Save(); var authorToReturn = _mapper.Map <AuthorGetDto>(authorEntity); return(CreatedAtAction(nameof(GetAuthors), new { authorId = authorToReturn.Id }, authorToReturn)); }
public async Task <ActionResult <Author> > CreateAuthor(AuthorCreateDto author) { if (author == null) { return(BadRequest()); } var authorEntity = _mapper.Map <Author>(author); var returnedEntity = await _authorRepository.AddAsync(authorEntity); return(CreatedAtRoute("GetAuthor", new { authorId = returnedEntity.Id }, returnedEntity)); }
private async Task <List <Book> > GetBooksOnCreateAsync(AuthorCreateDto authorDto) { List <Book> books = new List <Book>(); if (AreBooksNewOnCreate(authorDto)) { books = _mapper.Map <List <Book> >(authorDto.Books); } else { books = await _bookRepository.FindAllWithFilterAsync(b => authorDto.BooksIds.Any(id => id == b.Id)); } return(books); }
public async Task Create_Author_With_Empty_Name() { var authorToCreate = new AuthorCreateDto() { Name = string.Empty }; HttpResponseMessage response = await this._client.PostAsJsonAsync("/Api/AuthorsV3", authorToCreate); // Fail the test if non-success result // Get the response as a string // Assert on correct content Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); }
public void validator_fails_when_author_code_is_too_long() { var sut = new AuthorCreateDto() { FirstName = "Mickey", LastName = "Mantle", AuthorCode = StringGenerator.GenerateRandomString(12), PhoneNumber = "360-549-5484" }; var result = _validator.TestValidate(sut); result.ShouldHaveValidationErrorFor(x => x.AuthorCode) .WithErrorMessage("Author Code must be exactly 11 characters") .WithSeverity(Severity.Error) .WithErrorCode("A-Rule-003"); }
public IActionResult Put(Guid id, [FromBody] AuthorCreateDto authorCreate) { if (authorCreate == null && string.IsNullOrWhiteSpace(authorCreate.Name)) { return(this.BadRequest(new { message = "author name cannot be empty" })); } var author = _authors.FirstOrDefault(x => x.Id == id); if (author == null) { return(this.NotFound(new { message = "author was not found" })); } author.Name = authorCreate.Name; return(this.Ok(author)); }
public IActionResult Put(Guid id, [FromBody] AuthorCreateDto authorCreate) { if (authorCreate == null && string.IsNullOrWhiteSpace(authorCreate.Name)) { throw new ArgumentException("author name cannot be empty"); } var author = _authors.FirstOrDefault(x => x.Id == id); if (author == null) { throw new ArgumentException("author name was not found"); } author.Name = authorCreate.Name; return(this.Ok(author)); }
public void validator_fails_when_author_code_is_wrong_format() { var sut = new AuthorCreateDto() { FirstName = "Mickey", LastName = "Mantle", AuthorCode = "ABC-12-3456", PhoneNumber = "360-549-5484" }; var result = _validator.TestValidate(sut); result.ShouldHaveValidationErrorFor(x => x.AuthorCode) .WithErrorMessage("Author code must be in the format of ###-##-####") .WithSeverity(Severity.Error) .WithErrorCode("A-Rule-004"); }
public void validator_fails_when_author_code_is_empty() { var sut = new AuthorCreateDto() { FirstName = "Mickey", LastName = "Mantle", AuthorCode = string.Empty, PhoneNumber = "360-549-5484" }; var result = _validator.TestValidate(sut); result.ShouldHaveValidationErrorFor(x => x.AuthorCode) .WithErrorMessage("Author Code cannot be empty") .WithSeverity(Severity.Error) .WithErrorCode("A-Rule-002"); }
public void validator_fails_when_author_code_is_null() { var sut = new AuthorCreateDto() { FirstName = "Mickey", LastName = "Mantle", AuthorCode = null, PhoneNumber = "360-549-5484" }; var result = _validator.TestValidate(sut); _ = _validator.ValidateProperties(sut); using (new AssertionScope()) { result.ShouldHaveValidationErrorFor(x => x.AuthorCode) .WithErrorMessage("Author Code cannot be null") .WithSeverity(Severity.Error) .WithErrorCode("A-Rule-001"); _validator.HasErrors.Should().BeTrue(); _validator.GetErrors().Should().NotBeNull(); _validator.GetAllErrors().Should().NotBeEmpty(); _validator.GetAllWarnings().Should().BeEmpty(); (_validator.GetErrors("AuthorCode") as List <string>).Should().NotBeEmpty(); (_validator.GetErrors() as List <string>).Should().NotBeEmpty(); (_validator.GetErrors("FirstName") as List <string>).Should().BeEmpty(); (_validator.GetWarnings("FirstName") as List <string>).Should().BeEmpty(); (_validator.GetWarnings() as List <string>).Should().BeEmpty(); ((Action)(() => _validator.GetErrors("AuthorId"))) .Should().Throw <ArgumentException>() .And.Message.Should().Contain("Property name AuthorId does not exist in"); ((Action)(() => _validator.GetWarnings("AuthorId"))) .Should().Throw <ArgumentException>() .And.Message.Should().Contain("Property name AuthorId does not exist in"); _validator.Errors.Count.Should().BeGreaterThan(0); } }
public async Task Create_Authors() { var authorToCreate = new AuthorCreateDto() { Name = "this is a random name" }; HttpResponseMessage response = await this._client.PostAsJsonAsync("/Api/AuthorsV3", authorToCreate); // Fail the test if non-success result response.EnsureSuccessStatusCode(); // Get the response as a string var author = await response.Content.ReadAsAsync <Author>(); // Assert on correct content Assert.NotNull(author); }
public async Task <IActionResult> CreateAuthor(AuthorCreateDto AuthorCreateDto) { if (ModelState.IsValid) { _logger.LogInformation("POST api/author => OK"); var author = _mapper.Map <Author>(AuthorCreateDto); await _unitOfWork.Author.Create(author); await _unitOfWork.Save(); return(Ok()); } else { _logger.LogInformation("POST api/author => NOT OK"); return(NotFound()); } }
public Author Create(AuthorCreateDto dto) { dto.FullName = FormatString.Trim_MultiSpaces_Title(dto.FullName, true); var isExist = GetDetail(dto.FullName); if (isExist != null) { throw new Exception(dto.FullName + " existed"); } var entity = new Author { FullName = dto.FullName, Image = dto.Image, Biography = dto.Biography }; return(repository.Add(entity)); }