Example #1
0
        public async Task GivenValidRequest_WhenTheArticleDoesNotExist_ThrowsApiException()
        {
            // Arrange
            var commentDto = new AddCommentDto
            {
                Body = "This article sucks!"
            };
            var addCommentCommand = new AddCommentCommand
            {
                Slug    = "how-to-not-train-your-dragon",
                Comment = commentDto
            };

            // Act
            var handler  = new AddCommentCommandHandler(CurrentUserContext, Context, Mapper, MachineDateTime);
            var response = await Should.ThrowAsync <ConduitApiException>(async() =>
            {
                await handler.Handle(addCommentCommand, CancellationToken.None);
            });

            // Assert
            response.StatusCode.ShouldBe(HttpStatusCode.NotFound);
            response.ShouldNotBeNull();
            response.ShouldBeOfType <ConduitApiException>();
        }
Example #2
0
        public async Task <ServiceResponse <Task> > CreateComment(int postId, AddCommentDto newComment)
        {
            ServiceResponse <Task> response = new ServiceResponse <Task>();

            try
            {
                var post = await FindPostByIdAsync(postId);

                var author = await _authorService.FindAuthorById(newComment.AuthorId);

                if (post == null)
                {
                    response.Message = "Post not found";
                }
                var comment = new Comment
                {
                    Body    = newComment.Body,
                    PubDate = newComment.PubDate,
                    Post    = post
                };
                _context.Comments.Add(comment);
                comment.Author = author;
                await _context.SaveChangesAsync();
            }
            catch (Exception ex)
            {
                response.Success = false;
                response.Message = ex.Message;
            }
            return(response);
        }
Example #3
0
        public async Task GivenValidRequest_WhenTheArticleExists_AddsCommentToArticle()
        {
            // Arrange
            var commentDto = new AddCommentDto
            {
                Body = "This article sucks!"
            };
            var addCommentCommand = new AddCommentCommand
            {
                Slug    = "how-to-train-your-dragon",
                Comment = commentDto
            };
            var articleComments = Context.Articles
                                  .Include(a => a.Comments)
                                  .FirstOrDefault(a => a.Slug == "how-to-train-your-dragon")?
                                  .Comments;

            articleComments?.Count.ShouldBe(2);
            articleComments?.ShouldNotContain(c => c.Body == "This article sucks!");

            // Act
            var handler  = new AddCommentCommandHandler(CurrentUserContext, Context, Mapper, MachineDateTime);
            var response = await handler.Handle(addCommentCommand, CancellationToken.None);

            // Assert
            response.ShouldNotBeNull();
            response.ShouldBeOfType <CommentViewModel>();
            response.Comment.ShouldNotBeNull();
            response.Comment.ShouldBeOfType <CommentDto>();
            articleComments?.Count.ShouldBe(3);
            articleComments?.ShouldContain(c => c.Body == "This article sucks!");
        }
Example #4
0
        public async Task <Picture> AddComment(int userId, int pictureId, AddCommentDto commentDto)
        {
            try
            {
                var pointOfView = _galleryDbContext.PointsOfView.AsQueryable()
                                  .Where(pOv => pOv.UserId == userId && pOv.PictureId == pictureId).FirstOrDefault();
                var added = pointOfView == null;

                pointOfView = pointOfView ?? new PointOfView()
                {
                    Points        = commentDto.Points,
                    Comment       = commentDto.Comment,
                    PictureId     = pictureId,
                    UserId        = userId,
                    AddedDateTime = DateTime.Now
                };
                pointOfView.Points        = commentDto.Points;
                pointOfView.Comment       = commentDto.Comment;
                pointOfView.AddedDateTime = DateTime.Now;

                if (added)
                {
                    await _galleryDbContext.PointsOfView.AddAsync(pointOfView);
                }

                await _galleryDbContext.SaveChangesAsync();

                return(await GetPicture(pictureId));
            }
            catch (Exception e)
            {
                return(null);
            }
        }
Example #5
0
        public async Task <ServiceResult> AddAsync(AddCommentDto add)
        {
            var entity = Mapper.Map <CommentEntity>(add);
            await _commentRepo.InsertAsync(entity);

            return(await Task.FromResult(ServiceResult.Successed("新增文章评论成功")));
        }
        public async Task <ActionResult <Comment> > PostComment(AddCommentDto comment)
        {
            var userId = HttpContext.User.FindFirstValue(ClaimTypes.NameIdentifier);

            var newComment = new Comment()
            {
                CommentId = Guid.NewGuid().ToString(),
                Text      = comment.Text,
                ParentId  = comment.ParentId,
                PostId    = comment.PostId,
                UserId    = userId,
                CreatedAt = DateTime.Now,
                UpdatedAt = DateTime.Now
            };

            _context.Comments.Add(newComment);
            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateException)
            {
                if (CommentExists(newComment.CommentId))
                {
                    return(Conflict());
                }
                else
                {
                    throw;
                }
            }

            return(CreatedAtAction("GetComment", new { id = newComment.CommentId }, newComment));
        }
Example #7
0
        public void AddComment_WithDummy_ShouldAddComment()
        {
            var context = DotaAppContextInitializer.InitializeContext();

            this.SeedItems(context);

            this.commentService = new CommentService(context);

            var addCommentDto = new AddCommentDto
            {
                ItemId   = 2,
                Comment  = "New comment from test",
                Username = "******"
            };

            int expectedId = 4;
            int actualId   = this.commentService.AddComment(addCommentDto);

            Assert.Equal(expectedId, actualId);

            int expectedCommentsCount = 4;
            var actualComments        = context.Comments
                                        .Where(c => c.ItemId == 2)
                                        .ToList();

            Assert.Equal(expectedCommentsCount, actualComments.Count);
        }
Example #8
0
        public async Task AddCommentAsync(AddCommentDto addComment)
        {
            var comment = _unitOfWork.Comments.Add(_mapper.Map <AddCommentDto, Comment>(addComment));

            comment.DateTime = DateTime.Now;

            await _unitOfWork.CommitAsync();
        }
Example #9
0
        public async Task <IActionResult> AddComment([FromBody] AddCommentDto commentDto)
        {
            var post = await _postsRepository.QueryAsync(commentDto.PostId);

            var comment = new Comment(post, commentDto.Comment);
            await _postsRepository.AddCommentAsync(post, comment);

            return(Ok(post));
        }
Example #10
0
        public async Task <IActionResult> Add([FromBody] AddCommentDto commentDto)
        {
            var result = await _commentService.AddComment(commentDto);

            return(StatusCode(result, new
            {
                Message = "A New comment has been added"
            }));
        }
        public static Comments AddCommentDTOtoComment(AddCommentDto comment, Comments addComment)
        {
            addComment.UserId      = comment.UserId;
            addComment.PostId      = comment.PostId;
            addComment.Comment     = comment.Comment;
            addComment.DateCreated = DateTime.Now;

            return(addComment);
        }
Example #12
0
        public async Task <ServiceResult> AddAsync([FromBody] AddCommentDto add)
        {
            var validation = add.Validation();

            if (validation.Fail)
            {
                return(ServiceResult.Failed(validation.Msg));
            }
            return(await Task.FromResult(await _commentSvc.AddAsync(add)));
        }
Example #13
0
        public async Task <IActionResult> AddComment([FromBody] AddCommentDto data)
        {
            await _mediator.Publish(new AddCommentCommand
            {
                UserUuid = User.Identity.Name,
                PostUuid = data.PostUuid,
                Text     = data.Text
            });

            return(Ok());
        }
Example #14
0
        public async Task <IActionResult> AddComment([FromBody] AddCommentDto dto)
        {
            if (!HttpContext.User.Identity.IsAuthenticated)
            {
                return(Forbid());
            }

            Result result = await _commentService.AddCommentAsync(dto, UserId, UserName, UserPhotoUrl);

            return(FromResult(result));
        }
Example #15
0
 public static async Task <IActionResult> Run(
     [HttpTrigger(AuthorizationLevel.Function, "post", Route = "interventions/{interventionId}/comments")]
     AddCommentDto commentDto,
     [Table(Config.InterventionsTableName, Connection = Config.StorageConnectionName)] CloudTable interventionsTable,
     string interventionId, ILogger log)
 {
     return(await AddComment(
                InterventionFilterBuilder.GetByIdFilter(interventionId),
                commentDto,
                interventionsTable
                ));
 }
Example #16
0
        public static async Task <IActionResult> RunGeoHash(
            [HttpTrigger(AuthorizationLevel.Function, "post", Route = "interventions/{latitude}/{longitude}/{interventionId}/comments")]
            AddCommentDto commentDto,
            [Table(Config.InterventionsTableName, Connection = Config.StorageConnectionName)] CloudTable interventionsTable,
            string latitude, string longitude, string interventionId, ILogger log)
        {
            var geoHash = GeoHasher.GetGeoHash(latitude, longitude);

            return(await AddComment(
                       InterventionFilterBuilder.GetInterventionGeoHashFilter(geoHash, interventionId),
                       commentDto,
                       interventionsTable
                       ));
        }
Example #17
0
        private static async Task <IActionResult> AddComment(
            string filter, AddCommentDto addCommentDto, CloudTable interventionsTable
            )
        {
            InterventionEntity intervention = await GetIntervention(filter, interventionsTable);

            if (intervention == null)
            {
                return(new StatusCodeResult(StatusCodes.Status404NotFound));
            }

            CommentDto comment = await AddCommentToIntervention(addCommentDto, interventionsTable, intervention);

            return(new JsonResult(comment));
        }
Example #18
0
        public async Task <ActionResult> AddComment(AddCommentDto addCommentDto)
        {
            Comment comment = new Comment
            {
                PostId    = addCommentDto.PostId,
                UserId    = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value),
                Content   = addCommentDto.Content,
                CreatedAt = DateTime.Now
            };

            _repo.Add(comment);
            await _repo.SaveAll();

            return(StatusCode(201));
        }
        public IActionResult Post([FromBody] AddCommentDto dto
                                  , [FromServices] IAddCommentCommand command
                                  , [FromServices] AddCommentValidator validator)
        {
            var result = validator.Validate(dto);

            if (result.IsValid)
            {
                Comment comment = _mapper.Map <Comment>(dto);
                _useCaseExecutor.ExecuteCommand(command, comment);
                return(Ok("Comment created successfully"));
            }

            return(UnprocessableEntity(UnprocessableEntityResponse.Message(result.Errors)));
        }
Example #20
0
        private async Task AddComment(AddComment notification)
        {
            var dto = new AddCommentDto
            {
                Text          = notification.Text,
                PostOwnerUuid = notification.PostOwnerUuid,
                PostUuid      = notification.PostUuid
            };

            var content = new StringContent(
                JsonConvert.SerializeObject(dto),
                Encoding.UTF8,
                "application/json");

            await _http.Post("posts", "/AddComment", content);
        }
Example #21
0
        private static async Task <CommentDto> AddCommentToIntervention(
            AddCommentDto addCommentDto, CloudTable interventionsTable, InterventionEntity intervention
            )
        {
            CommentDto comment = new CommentDto()
            {
                CreatedDate = DateTime.UtcNow,
                Comment     = addCommentDto.Comment,
                Id          = Guid.NewGuid().ToString()
            };

            intervention.AddComment(comment);
            await interventionsTable.ExecuteAsync(TableOperation.Merge(intervention));

            return(comment);
        }
Example #22
0
        public ActionResult <Comments> AddComment(AddCommentDto comment)
        {
            try
            {
                _commentsService.AddComment(comment);
            }
            catch (FlowException ex)
            {
                return(BadRequest(ex.Message));
            }
            catch (Exception)
            {
                return(StatusCode(500, "An error has occured!Try again later!"));
            }

            return(CreatedAtAction("AddComment", comment));
        }
Example #23
0
        public IActionResult Add([FromBody] AddCommentDto addComment)
        {
            if (!this.ModelState.IsValid)
            {
                return(BadRequest(this.ModelState));
            }

            try
            {
                var commentId = this.commentService.AddComment(addComment);

                return(Ok(commentId));
            }
            catch (DotaException ex)
            {
                return(BadRequest(new { message = ex.Message }));
            }
        }
Example #24
0
 public JsonResult AddComment(AddCommentDto dto)
 {
     if (dto.NewsId <= 0)
     {
         return(Json(new ResponseModel()
         {
             Code = 0, Result = "新闻不存在!"
         }));
     }
     if (string.IsNullOrWhiteSpace(dto.Contents))
     {
         return(Json(new ResponseModel()
         {
             Code = 0, Result = "评论内容不能为空!"
         }));
     }
     return(Json(_newsCommentService.AddNewsComment(dto)));
 }
Example #25
0
        public async Task <Result> AddCommentAsync(AddCommentDto dto, string userId, string userName, string userPhotoUrl)
        {
            if (string.IsNullOrEmpty(dto.Text))
            {
                return(Result.Fail("Comment is empty."));
            }

            return(await _addCommentHandler.HandleAsync(new AddCommentCommand()
            {
                Created = DateTime.UtcNow,
                UserName = userName,
                PostId = dto.PostId,
                UserId = userId,
                Text = dto.Text,
                ParentCommentId = dto.ParentCommentId,
                UserPhotoUrl = userPhotoUrl
            }));
        }
Example #26
0
        public void AddComment_WithDummy_ShouldThrowExceptionWhenItemNotFound()
        {
            var context = DotaAppContextInitializer.InitializeContext();

            this.SeedComments(context);

            this.commentService = new CommentService(context);

            var addCommentDto = new AddCommentDto
            {
                ItemId   = 777,
                Comment  = "New comment from test",
                Username = "******"
            };

            DotaException exception = Assert.Throws <DotaException>(() => this.commentService.AddComment(addCommentDto));

            Assert.Equal(Constants.InvalidOperation, exception.Message);
        }
Example #27
0
        public AddCommentDto AddComment(AddCommentDto comment)
        {
            var addComment = new Comments();

            if (comment.Comment.Length == 0)
            {
                throw new FlowException("Please insert comment!");
            }
            else if (comment.Comment.Length > 100)
            {
                throw new FlowException("Length must be lower than 100chars!");
            }

            addComment = DTOtoModel.AddCommentDTOtoComment(comment, addComment);
            _commentsRepository.Add(addComment);
            _commentsRepository.SaveEntities();

            return(comment);
        }
Example #28
0
        public async Task <IActionResult> AddComment(int userId, int pictureId, [FromBody] AddCommentDto addCommentDto)
        {
            var invokingUserId = int.Parse(User.FindFirst(claim => claim.Type == ClaimTypes.NameIdentifier).Value);

            if (userId != invokingUserId)
            {
                return(Unauthorized());
            }

            var user = await _repository.GetUser(userId);

            if (user == null)
            {
                return(BadRequest("User doen't exist"));
            }

            var picture = await _repository.GetPicture(pictureId);

            if (picture == null)
            {
                return(BadRequest("Picture doesn't exist!"));
            }

            var pictureModified = await _repository.AddComment(userId, pictureId, addCommentDto);

            if (pictureModified == null)
            {
                return(BadRequest("Something went wrong when adding the comment!"));
            }

            var pictureDto = _mapper.Map <Picture, PicturesDto>(pictureModified,
                                                                opt => opt.AfterMap(async(source, target) =>
            {
                target.YouLikeIt = await _repository.YouLikeIt(invokingUserId, target.Id);
                target.YourComment
                    = _mapper.Map <PointOfViewDto>(await _repository.YourComment(invokingUserId, target.Id));
            }));

            return(Ok(pictureDto));
        }
Example #29
0
        public int AddComment(AddCommentDto addComment)
        {
            var item = this.context.Items
                       .FirstOrDefault(i => i.Id == addComment.ItemId);

            if (item == null)
            {
                throw new DotaException(Constants.InvalidOperation);
            }

            var comment = new Comment
            {
                CommentMessage = HtmlEncoder.Default.Encode(addComment.Comment),
                Username       = addComment.Username,
                Item           = item,
                ItemId         = item.Id
            };

            this.context.Comments.Add(comment);
            this.context.SaveChanges();

            return(comment.Id);
        }
        public async Task <CommentDto> AddCaffItemCommentAsync(long caffItemId, AddCommentDto addComment)
        {
            var caffItemEntity = await _context
                                 .CaffItems
                                 .Include(ci => ci.Comments)
                                 .Where(ci => ci.Id == caffItemId)
                                 .SingleOrDefaultAsync();

            ThrowNotFoundIfNull(caffItemEntity);

            var commentEntity = _mapper.Map <Comment>(addComment);

            caffItemEntity.Comments.Add(new CaffItemComment
            {
                Comment = commentEntity
            });

            await _context.SaveChangesAsync();

            await _context.Entry(commentEntity).Reference(c => c.CreatedBy).LoadAsync();

            return(_mapper.Map <CommentDto>(commentEntity));
        }