public void UpdatePost_PostNotChanged_ReturnsCurrentPost() { // Arrange int userId = 2; int postId = 2; var postFromRepo = GetFakePostList().SingleOrDefault(x => x.PostId == postId); var postForUpdate = new PostForUpdateDto() { NameOfDish = postFromRepo.NameOfDish, Description = postFromRepo.Description, Ingredients = postFromRepo.Ingredients, Method = postFromRepo.Method, PrepTime = postFromRepo.PrepTime, CookingTime = postFromRepo.CookingTime, Feeds = postFromRepo.Feeds, Cuisine = postFromRepo.Cuisine }; _repoMock.Setup(x => x.GetPost(postId)).ReturnsAsync(postFromRepo); _repoMock.Setup(x => x.SaveAll()).ReturnsAsync(false); // Act var result = _postsController.UpdatePost(userId, postId, postForUpdate).Result; // Assert var okResult = Assert.IsType <OkObjectResult>(result); }
public void UpdatePost_UserIdOfPostMismatch_ReturnsUnauthorized() { // Arrange int userId = 2; int postId = 3; var userFromRepo = GetFakeUserList().SingleOrDefault(x => x.Id == userId); var postFromRepo = GetFakePostList().SingleOrDefault(x => x.PostId == postId); var postForUpdate = new PostForUpdateDto() { NameOfDish = "Katsu curry", Description = "chicken and rice", Ingredients = "chicken, rice", Method = "fry chicken, boil rice", PrepTime = "20 min", CookingTime = "20 min", Feeds = "3", Cuisine = "Japanese" }; _repoMock.Setup(x => x.GetPost(postId)).ReturnsAsync(postFromRepo); // Act var result = _postsController.UpdatePost(userId, postId, postForUpdate).Result; // Assert Assert.IsType <UnauthorizedResult>(result); }
public async Task <IActionResult> UpdatePost(int userId, int postId, PostForUpdateDto postForUpdateDto) { // Validate id of logged in user == userId if (userId != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value)) { return(Unauthorized()); } // Get post from repo var postFromRepo = await _recipeRepo.GetPost(postId); // Check post was made by the user if (postFromRepo.UserId != userId) { return(Unauthorized()); } // Map updated post into the repo var postToUpdate = _mapper.Map(postForUpdateDto, postFromRepo); var postToReturn = _mapper.Map <PostsForDetailedDto>(postToUpdate); var postToReturnIfNoChanges = _mapper.Map <PostsForDetailedDto>(postFromRepo); if (await _recipeRepo.SaveAll()) { return(CreatedAtRoute("GetPost", new { userId = userId, id = postFromRepo.PostId }, postToReturn)); } else { return(Ok(postToReturnIfNoChanges)); } }
public void UpdatePost_Success_ReturnsUpdatedPost() { // Arrange int userId = 2; int postId = 2; var postFromRepo = GetFakePostList().SingleOrDefault(x => x.PostId == postId); var postForUpdate = new PostForUpdateDto() { NameOfDish = "Katsu curry", Description = "chicken and rice", Ingredients = "chicken, rice", Method = "fry chicken, boil rice", PrepTime = "20 min", CookingTime = "20 min", Feeds = "3", Cuisine = "Japanese" }; _repoMock.Setup(x => x.GetPost(postId)).ReturnsAsync(postFromRepo); _repoMock.Setup(x => x.SaveAll()).ReturnsAsync(true); // Act var result = _postsController.UpdatePost(userId, postId, postForUpdate).Result as CreatedAtRouteResult; // Assert var okResult = Assert.IsType <CreatedAtRouteResult>(result); var updatedPost = Assert.IsType <PostsForDetailedDto>(result.Value); Assert.Equal(postFromRepo.NameOfDish, updatedPost.NameOfDish); Assert.Equal(postFromRepo.Cuisine, updatedPost.Cuisine); Assert.Equal(postFromRepo.Description, updatedPost.Description); }
private ActionResult <PostDto> UpdatePostInRepository(ref PostForUpdateDto post, ref Post postFromAuthorFromRepo) { _mapper.Map(post, postFromAuthorFromRepo); postFromAuthorFromRepo.LastEdited = DateTime.UtcNow; postFromAuthorFromRepo.NumberOfEdits++; _discussionWebRepository.UpdatePost(postFromAuthorFromRepo); _discussionWebRepository.Save(); return(NoContent()); }
public async Task <IActionResult> UpdatePost(int id, PostForUpdateDto postForUpdateDto) { var postFromRepo = await _repo.GetPost(id); _mapper.Map(postForUpdateDto, postFromRepo); postFromRepo.IsVisible = true; if (await _repo.SaveAll()) { return(NoContent()); } throw new Exception($"Updating post {id} failed on save"); }
public async Task <ActionResult> UpdatePost(int id, PostForUpdateDto postForUpdateDto) { var postFromRepo = await _blogRepository.GetPostAsync(id); if (postFromRepo != null) { _mapper.Map(postForUpdateDto, postFromRepo); } if (await _blogRepository.SaveAll()) { return(NoContent()); } throw new Exception($"Failed to save on updating post {id}"); }
public async Task <IActionResult> UpdatePost(int id, int postid, PostForUpdateDto postForUpdateDto) { /*if(id != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value)) * return Unauthorized();*/ postForUpdateDto.Video_link = postForUpdateDto.Video_link.Replace("watch?v=", "embed/"); var postFromRepo = await _repo.GetPost(postid); _mapper.Map(postForUpdateDto, postFromRepo); if (await _repo.SaveAll()) { return(Ok(postFromRepo)); } throw new Exception($"Updating user {id} failed on save"); }
public async Task <IActionResult> UpdatePost(Guid id, [FromBody] PostForUpdateDto post) { if (post == null) { _logger.LogError("PostForUpdateDto object sent from client is null."); return(BadRequest("PostForUpdateDto object is null")); } var postEntity = await _context.Posts.GetPostAsync(id, trackChanges : true); if (postEntity == null) { _logger.LogInfo($"Post with id: {id} doesn't exist in the database."); return(NotFound()); } _mapper.Map(post, postEntity); await _context.SaveAsync(); return(NoContent()); }
public async Task <IActionResult> UpdateUser(int userId, int id, PostForUpdateDto postForUpdateDto) { if (userId != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value)) { return(Unauthorized()); } var postrepo = await _repo.getpostformuser(id, userId); if (postrepo == null) { return(Unauthorized()); } var postFromRepo = await _repo.getpost(id); _mapper.Map(postForUpdateDto, postFromRepo); if (await _repo.SaveAll()) { return(NoContent()); } throw new Exception($"field to update post {id}"); }
public async Task <IActionResult> UpdatePost([FromBody] PostForUpdateDto Post, [FromRoute] string Id) { var existingPost = await _dbContext.Posts.FirstOrDefaultAsync(p => p.Id == Id); if (existingPost == null) { return(BadRequest($"Post does not exist for the Id {Post.Id}")); } existingPost.UpdatedOn = Post.UpdatedOn; existingPost.Pic = Post.Pic; existingPost.Summary = Post.Summary; existingPost.Title = Post.Title; existingPost.Likes = Post.Likes; // remove it after adding the Comments controller existingPost.Comments = Post.Comments; _dbContext.Posts.Update(existingPost); await _dbContext.SaveChangesAsync(); return(Ok(existingPost)); }
public async Task <IActionResult> UpdatePost(int postId, [FromBody] PostForUpdateDto post) { var userFromDb = await _userManager.GetUserAsync(this.User); var postToUpdate = await _repository.Post.GetPostAsync(postId, false); if (postToUpdate == null) { return(BadRequest()); } if (userFromDb.Id != postToUpdate.CreatedById) { return(Unauthorized()); } postToUpdate.Body = post.Body; _repository.Post.UpdatePost(postToUpdate); await _repository.SaveAsync(); return(NoContent()); }
public async Task <IActionResult> UpdatePost(int id, PostForUpdateDto postForUpdateDto) { var postFromDb = await _repo.GetPost(id); if (postFromDb == null) { return(NotFound()); } postForUpdateDto.LastUpdated = DateTime.Now; _mapper.Map(postForUpdateDto, postFromDb); var result = await _repo.SaveAll(); if (result) { return(Ok(postFromDb)); } return(BadRequest($"Failed to update post {id}!")); }
public ActionResult <PostDto> PartiallyUpdatePostForAuthor(Guid authorId, Guid postId, JsonPatchDocument <PostForUpdateDto> patchDocument) { if (!_discussionWebRepository.AuthorExists(authorId)) { return(NotFound()); } var postForAuthorFromRepo = _discussionWebRepository.GetPost(authorId, postId); if (postForAuthorFromRepo == null) { var postDto = new PostForUpdateDto(); patchDocument.ApplyTo(postDto, ModelState); if (!TryValidateModel(postDto)) { return(ValidationProblem(ModelState)); } var postToAdd = _mapper.Map <Data.Models.Post>(postDto); postToAdd.Id = postId; return(AddPostToRepository(ref authorId, ref postToAdd)); } var postToPatch = _mapper.Map <PostForUpdateDto>(postForAuthorFromRepo); // add validation patchDocument.ApplyTo(postToPatch, ModelState); if (!TryValidateModel(postToPatch)) { return(ValidationProblem(ModelState)); } return(UpdatePostInRepository(ref postToPatch, ref postForAuthorFromRepo)); }
public IActionResult Put(Guid id, [FromBody] PostForUpdateDto editedPost) { return(NoContent()); }
public async Task <IActionResult> UpdatePost(int id, [FromForm] PostForUpdateDto postForUpdateDto) { var userId = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value); var user = await _repo.GetUser(userId); if (!user.Posts.Any(p => p.Id == id)) { return(Unauthorized()); } var postFromRepo = await _repo.GetPost(id); // var postToCreate = new Post(); postFromRepo.Title = postForUpdateDto.Title; postFromRepo.Description = postForUpdateDto.Description; postFromRepo.Category = postForUpdateDto.Category; // postFromRepo.Tags = postForUpdateDto.Tags; postFromRepo.Links = postForUpdateDto.Links; postFromRepo.Updated = postForUpdateDto.Updated; var newTags = postForUpdateDto.Tags.Split(",").ToList(); foreach (var oldTag in postFromRepo.Tags) { var index = newTags.IndexOf(oldTag.Tag.Value); if (index == -1) { _repo.Delete(oldTag); } else { newTags.RemoveAt(index); } } foreach (var newTag in newTags) { var tag = await _repo.GetTag(newTag); if (tag == null) { tag = new Tag { Value = newTag }; _repo.Add(tag); await _repo.SaveAll(); } var postTag = new PostTag { PostId = postFromRepo.Id, TagId = tag.Id }; postFromRepo.Tags.Add(postTag); } var postOldMainImage = await _repo.GetPostMainImage(id); if (postOldMainImage != null && postOldMainImage.Id != -postForUpdateDto.MainImage) { postOldMainImage.IsMain = false; if (postForUpdateDto.MainImage < 0) { var postImageFromRepo = await _repo.GetPostImage(-postForUpdateDto.MainImage); postImageFromRepo.IsMain = true; } } if (postForUpdateDto.DeletedImages != null) { var deletedImageIds = postForUpdateDto.DeletedImages.Split(","); for (int i = 0; i < deletedImageIds.Length; i++) { int postImageId = Int32.Parse(deletedImageIds[i]); if (!postFromRepo.PostImages.Any(p => p.Id == postImageId)) { return(BadRequest("Failed to update post.")); } var postImageFromRepo = await _repo.GetPostImage(postImageId); if (postImageFromRepo.PublicId != null) { var deleteParams = new DeletionParams(postImageFromRepo.PublicId); var result = _cloudinary.Destroy(deleteParams); if (result.Result == "ok") { _repo.Delete(postImageFromRepo); } } else { _repo.Delete(postImageFromRepo); } } } var files = new IFormFile[] { postForUpdateDto.AddedImage1, postForUpdateDto.AddedImage2, postForUpdateDto.AddedImage3, postForUpdateDto.AddedImage4 }; for (int i = 0; i < files.Length; i++) { var file = files[i]; if (file == null || file.Length <= 0) { continue; } var uploadResult = new ImageUploadResult(); using (var stream = file.OpenReadStream()) { var uploadParams = new ImageUploadParams() { File = new FileDescription(file.Name, stream), Transformation = new Transformation().Width(500).Height(500).Crop("fill").Gravity("face") }; uploadResult = _cloudinary.Upload(uploadParams); } var postImage = new PostImage(); postImage.DateAdded = DateTime.Now; postImage.Url = uploadResult.Uri.ToString(); postImage.PublicId = uploadResult.PublicId; // _repo.Add<PostImage>(postImageToCreate); if (i == postForUpdateDto.MainImage) { postImage.IsMain = true; } postFromRepo.PostImages.Add(postImage); } // await _repo.SaveAll(); // if(userId != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value)) // return Unauthorized(); // var userFromRepo = await _repo.GetUser(userId); // var file = postForCreationDto.Image1; // var uploadResult = new ImageUploadResult(); // if(file.Length > 0){ // using (var stream = file.OpenReadStream()) // { // var uploadParams = new ImageUploadParams() // { // File = new FileDescription(file.Name, stream), // Transformation = new Transformation().Width(500).Height(500).Crop("fill").Gravity("face") // }; // uploadResult = _cloudinary.Upload(uploadParams); // } // } // postForCreationDto.Url = uploadResult.Uri.ToString(); // postForCreationDto.PublicId = uploadResult.PublicId; // var postImage = _mapper.Map<PostImage>(postImageForCreationDto); // if (!userFromRepo.Photos.Any(u=>u.IsMain)) // photo.IsMain = true; // postImage.PostId = 0; // userFromRepo.Photos.Add(photo); // _repo.Add<PostImage>(postImage); if (await _repo.SaveAll()) { var postToReturn = _mapper.Map <PostForDetailsDto>(postFromRepo); return(CreatedAtRoute("GetPost", new { controller = "Posts", id = postFromRepo.Id }, postToReturn)); } return(BadRequest("Failed to create post.")); }
public ActionResult <PostDto> UpdatePostForAuthor(Guid authorId, Guid postId, PostForUpdateDto post) { if (!_discussionWebRepository.AuthorExists(authorId)) { return(NotFound()); } var postFromAuthorFromRepo = _discussionWebRepository.GetPost(authorId, postId); if (postFromAuthorFromRepo == null) { var postToAdd = _mapper.Map <Data.Models.Post>(post); postToAdd.Id = postId; return(AddPostToRepository(ref authorId, ref postToAdd)); } // map the entity to a PostForUpdateDto // apply the updated field values to that dto // map the PostForUpdateDto back to an entity return(UpdatePostInRepository(ref post, ref postFromAuthorFromRepo)); }