コード例 #1
0
        public IActionResult UpdateComment(int cardId, int commentId, [FromBody] CommentForUpdateDto comment)
        {
            if (comment == null)
            {
                return(BadRequest());
            }

            if (!ModelState.IsValid)
            {
                return(BadRequest());
            }

            if (!_cardRepository.CardExists(cardId))
            {
                return(NotFound());
            }

            var commentEntity = _cardRepository.GetComment(cardId, commentId);

            if (commentEntity == null)
            {
                return(NotFound());
            }

            Mapper.Map(comment, commentEntity);

            if (!_cardRepository.Save())
            {
                return(StatusCode(500, "A problem happened while handling your request"));
            }

            return(NoContent());
        }
コード例 #2
0
        public async Task <ActionResult <Comment> > EditComment(long commentId, CommentForUpdateDto commentForUpdateDto)
        {
            UserComment userComment = await _context.UserComments.FirstOrDefaultAsync(uc => uc.CommentId == commentId);

            if (userComment == null)
            {
                return(BadRequest("No comment with the given Id was found"));
            }

            if (userComment.UserId != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value))
            {
                return(Unauthorized());
            }

            if (commentId != commentForUpdateDto.Id)
            {
                return(BadRequest("A mismatch between the Id of the comment to update and the Id of the updated comment was found"));
            }

            if (!CommentExists(commentId))
            {
                return(NotFound());
            }

            var comment = await _context.Comments.FirstOrDefaultAsync(c => c.Id == commentId);

            comment.CommentText = commentForUpdateDto.CommentText;

            await _context.SaveChangesAsync();

            return(Ok());
        }
コード例 #3
0
        public async Task <IActionResult> UpdateCommentForPost(Guid postId, Guid id, [FromBody] CommentForUpdateDto comment)
        {
            if (comment == null)
            {
                _logger.LogError("CommentForUpdateDto object sent from client is null.");
                return(BadRequest("CommentForUpdateDto object is null"));
            }

            var post = await _context.Posts.GetPostAsync(postId, trackChanges : false);

            if (post == null)
            {
                _logger.LogInfo($"Post with id: {postId} doesn't exist in the database.");
                return(NotFound());
            }

            var commentEntity = await _context.Comments.GetCommentAsync(postId, id, trackChanges : true);

            if (commentEntity == null)
            {
                _logger.LogInfo($"Comment with id: {id} doesn't exist in the database.");
                return(NotFound());
            }

            _mapper.Map(comment, commentEntity);
            await _context.SaveAsync();

            return(NoContent());
        }
コード例 #4
0
        public async Task <IActionResult> UpdateComment(int userId, int commentId, CommentForUpdateDto commentForUpdateDto)
        {
            if (userId != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value))
            {
                return(Unauthorized());
            }

            var commentFromRepo = await _recipeRepo.GetComment(commentId);

            if (commentFromRepo == null)
            {
                return(NotFound($"Comment {commentId} not found"));
            }
            if (commentFromRepo.CommenterId != userId)
            {
                return(Unauthorized());
            }

            var postFromRepo = await _recipeRepo.GetPost(commentFromRepo.PostId);

            var commentToUpdate = _mapper.Map(commentForUpdateDto, commentFromRepo);
            var commentToReturn = _mapper.Map <Comment>(commentToUpdate);

            // var commentToReturn = _mapper.Map<CommentsForReturnedDto>(commentToUpdate);

            if (await _recipeRepo.SaveAll())
            {
                var postToReturn = _mapper.Map <PostsForDetailedDto>(postFromRepo);

                return(CreatedAtRoute("GetPost", new { userId = userId, id = postFromRepo.PostId }, postToReturn));
            }

            throw new Exception("Updating the comment failed on save");
        }
コード例 #5
0
ファイル: CommentsController.cs プロジェクト: shakami/Weblog
        public IActionResult UpdateComment(int userId, int blogId, int postId, int commentId,
                                           [FromBody] CommentForUpdateDto comment)
        {
            if (!_weblogDataRepository.UserExists(userId) ||
                !_weblogDataRepository.BlogExists(blogId) ||
                !_weblogDataRepository.PostExists(postId))
            {
                return(NotFound());
            }

            var commentFromRepo = _weblogDataRepository.GetComment(commentId);

            if (commentFromRepo is null)
            {
                return(NotFound());
            }

            var emailAddress = comment.Credentials.EmailAddress;
            var password     = comment.Credentials.Password;

            if (!_weblogDataRepository.Authorized(commentFromRepo.UserId, emailAddress, password))
            {
                return(Unauthorized());
            }

            _mapper.Map(comment, commentFromRepo);

            _weblogDataRepository.UpdateComment(commentFromRepo);
            _weblogDataRepository.Save();

            return(NoContent());
        }
コード例 #6
0
        public async Task <int> UpdateComment(Comment comment, CommentForUpdateDto dto)
        {
            comment.Description = dto.Description ??
                                  comment.Description;
            _dbLogService.LogOnUpdateOfAnEntity(comment);

            return(await _context.SaveChangesAsync());
        }
コード例 #7
0
        public void Update_Comment()
        {
            var controller       = new CommentsController(new CommentRepositoryMock());
            var commentForUpdate = new CommentForUpdateDto()
            {
                Content = "There is an issue with this item!"
            };

            var result   = controller.Put(CommentRepositoryMock.TestComment.Id, commentForUpdate);
            var okResult = result.Should().BeOfType <NoContentResult>().Subject;
        }
コード例 #8
0
        public IActionResult PartiallyUpdateComment(int commentId, int id,
                                                    [FromBody] JsonPatchDocument <CommentForUpdateDto> patchDoc)
        {
            if (patchDoc == null)
            {
                return(BadRequest());
            }

            var comment = CommentsDataStore.Current.Comments.FirstOrDefault(c => c.Id == commentId);

            if (comment == null)
            {
                return(NotFound());
            }

            var commentFromStore = comment.Replies.FirstOrDefault(c => c.Id == id);

            if (commentFromStore == null)
            {
                return(NotFound());
            }

            var commentToPatch =
                new CommentForUpdateDto()
            {
                Name        = commentFromStore.Name,
                Description = commentFromStore.Description
            };

            patchDoc.ApplyTo(commentToPatch, ModelState);

            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (commentToPatch.Description == commentToPatch.Name)
            {
                ModelState.AddModelError("Description", "The provided description should be different from the name.");
            }

            TryValidateModel(commentToPatch);

            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            commentFromStore.Name        = commentToPatch.Name;
            commentFromStore.Description = commentToPatch.Description;

            return(NoContent());
        }
コード例 #9
0
        public IActionResult Put(int id, [FromBody] CommentForUpdateDto commentForUpdate)
        {
            var comment = _commentRepository.Get(id);

            if (comment == null)
            {
                return(NotFound("Comment not found"));
            }

            comment.Content = commentForUpdate.Content != null ? commentForUpdate.Content : comment.Content;

            _commentRepository.Update(comment);
            if (!_commentRepository.Save())
            {
                return(BadRequest("Could not update comment"));
            }

            return(NoContent());
        }
コード例 #10
0
        public async void UpdateComment_FailsOnSave_ReturnsException()
        {
            // Arrange
            int commentId        = 2;
            int userId           = 2;
            var commentForUpdate = new CommentForUpdateDto
            {
                Text = "My newly updated comment"
            };
            var commentFromRepo = GetFakeCommentsList().SingleOrDefault(x => x.CommentId == commentId);

            _repoMock.Setup(x => x.GetComment(commentId)).ReturnsAsync(commentFromRepo);
            _repoMock.Setup(x => x.SaveAll()).ReturnsAsync(false);

            // Act
            Exception ex = await Assert.ThrowsAsync <Exception>(() => _postsController.UpdateComment(userId, commentId, commentForUpdate));

            // Assert
            Assert.Equal("Updating the comment failed on save", ex.Message);
        }
コード例 #11
0
        public void UpdateComment_CommenterIdUserIdMismatch_ReturnsUnauthorized()
        {
            int commentId        = 1;
            int userId           = 2;
            var commentForUpdate = new CommentForUpdateDto
            {
                Text = "My newly updated comment"
            };
            var commentFromRepo = GetFakeCommentsList().SingleOrDefault(x => x.CommentId == commentId);


            _repoMock.Setup(x => x.GetComment(commentId)).ReturnsAsync(commentFromRepo);
            _repoMock.Setup(x => x.SaveAll()).ReturnsAsync(true);

            // Act
            var result = _postsController.UpdateComment(userId, commentId, commentForUpdate).Result;

            // Assert
            var okResult = Assert.IsType <UnauthorizedResult>(result);
        }
コード例 #12
0
        public async Task <IActionResult> UpdateUser(int userId, int id, int postId, CommentForUpdateDto commentForUpdateDto)
        {
            if (userId != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value))
            {
                return(Unauthorized());
            }
            var commentrepo = await _repo.getcommentForuser(id, postId, userId);

            if (commentrepo == null)
            {
                return(Unauthorized());
            }
            var CommentFromRepo = await _repo.getComment(id, postId);

            _mapper.Map(commentForUpdateDto, CommentFromRepo);
            if (await _repo.SaveAll())
            {
                return(NoContent());
            }
            throw new Exception($"field to update post {id}");
        }
コード例 #13
0
        public async void LogOnUpdateOfEntity_UpdateComment_ShouldReturnUpdatedCommentLog()
        {
            var options = new DbContextOptionsBuilder <AppDbContext>()
                          .UseInMemoryDatabase($"TechTaskTestDatabase {Guid.NewGuid()}")
                          .Options;

            using (var context = new AppDbContext(options))
            {
                var commentToAdd = new Comment
                {
                    Id          = 3,
                    Description = "Description",
                    TasksId     = 3,
                    UserId      = Guid.NewGuid()
                };

                context.Comments.Add(commentToAdd);

                await context.SaveChangesAsync();

                var dbLog = new DbLogService(context);
                await dbLog.LogOnCreationOfEntityAsync(commentToAdd);

                var dto = new CommentForUpdateDto
                {
                    Description = "New description"
                };

                dbLog.LogOnUpdateOfAnEntity(commentToAdd);
                await context.SaveChangesAsync();
            }

            using (var context = new AppDbContext(options))
            {
                var logFromDb = await context.UpdateLogs
                                .SingleAsync(u => u.Name == "Updated Comment");

                logFromDb.Value.Should().Be(("3").ToLowerInvariant());
            }
        }
コード例 #14
0
        public void UpdateComment_Authorized_SuccessfullyUpdatedComment()
        {
            int commentId        = 2;
            int userId           = 2;
            var commentForUpdate = new CommentForUpdateDto
            {
                Text = "My newly updated comment"
            };
            var commentFromRepo = GetFakeCommentsList().SingleOrDefault(x => x.CommentId == commentId);
            var postFromRepo    = GetFakePostList().SingleOrDefault(x => x.PostId == commentFromRepo.PostId);

            _repoMock.Setup(x => x.GetComment(commentId)).ReturnsAsync(commentFromRepo);
            _repoMock.Setup(x => x.SaveAll()).ReturnsAsync(true);
            _repoMock.Setup(x => x.GetPost(commentFromRepo.PostId)).ReturnsAsync(postFromRepo);

            // Act
            var result = _postsController.UpdateComment(userId, commentId, commentForUpdate).Result as CreatedAtRouteResult;

            // Assert
            var okResult       = Assert.IsType <CreatedAtRouteResult>(result);
            var updatedComment = Assert.IsType <PostsForDetailedDto>(result.Value);
        }
コード例 #15
0
        public void UpdateComment_CommentNotFound_ReturnsNotFound()
        {
            int commentId        = 12;
            int userId           = 2;
            var commentForUpdate = new CommentForUpdateDto
            {
                Text = "My newly updated comment"
            };
            var commentFromRepo = GetFakeCommentsList().SingleOrDefault(x => x.CommentId == commentId);

            // var postFromRepo = GetFakePostList().SingleOrDefault(x => x.PostId == commentFromRepo.PostId);

            _repoMock.Setup(x => x.GetComment(commentId)).ReturnsAsync(commentFromRepo);
            _repoMock.Setup(x => x.SaveAll()).ReturnsAsync(true);

            // Act
            var result = _postsController.UpdateComment(userId, commentId, commentForUpdate).Result;

            // Assert
            var okResult = Assert.IsType <NotFoundObjectResult>(result);

            Assert.Equal("Comment 12 not found", okResult.Value);
        }
コード例 #16
0
        public async Task <IActionResult> UpdateComment(int postId, int commentId, [FromBody] CommentForUpdateDto commentForUpdateDto)
        {
            var commentToUpdate = await _repository.Comment.GetCommentAsync(commentId);

            if (commentToUpdate == null)
            {
                return(BadRequest());
            }

            //TODO: fix this
            //The instance of entity type cannot be tracked because another instance with the same key value for { 'Id'} is already being tracked

            //var userFromDb = await _userManager.GetUserAsync(this.User);
            //if (commentToUpdate.CommentedById != userFromDb.Id)
            //    return Unauthorized();

            commentToUpdate.Content = commentForUpdateDto.Content;

            _repository.Comment.UpdateComment(commentToUpdate);
            await _repository.SaveAsync();

            return(NoContent());
        }
コード例 #17
0
        public IActionResult Put(int commentId, CommentForUpdateDto commentForUpdateDto)
        {
            var comment = _commentService.GetById(commentId);

            if (comment.IsSuccessful)
            {
                comment.Data.Description = commentForUpdateDto.Description;
                IResult result = _commentService.Update(comment.Data);
                if (result.IsSuccessful)
                {
                    var channelId = HttpContext.RequestServices.GetService <IPhotoService>().GetById(comment.Data.PhotoId).Data.ChannelId;
                    this.RemoveCacheByContains(comment.Data.UserId + "/user-photos");
                    this.RemoveCacheByContains(comment.Data.UserId + "/user-comment-photos");
                    this.RemoveCacheByContains(comment.Data.UserId + "/like-photos");
                    this.RemoveCacheByContains(channelId + "/channel-photos");
                    this.RemoveCache();
                    return(Ok(result.Message));
                }
                return(this.ServerError(result.Message));
            }

            return(NotFound());
        }
コード例 #18
0
        public async Task <CommentDetailsDto> UpdateComment([FromRoute] int teamId,
                                                            [FromRoute] int taskId, [FromRoute] int commentId, [FromBody] CommentForUpdateDto dto)
        {
            dto.CommentId = commentId;
            dto.TaskId    = taskId;

            return(await _mediator.Send(new UpdateCommentCommand { CommentForUpdateDto = dto }));
        }