Exemplo n.º 1
0
        public async Task <PostCommentDto> CreateAndReturnMainCommentAsync(NewCommentDto
                                                                           commentDto, int authorId, IFormFile file)
        {
            string imagePath;

            if (file != null)
            {
                imagePath = await _imageSaver
                            .SaveAndReturnImagePath(file, "Comment",
                                                    commentDto.PostId);
            }
            var newComment = new MainComment
            {
                Comment = new Models.Comment()
                {
                    PostId  = commentDto.PostId,
                    Content = commentDto.Content,
                    Date    = DateTime.Now,
                    UserId  = authorId
                }
            };

            _repository.MainComment.CreateMainComment(newComment);
            await _repository.SaveAsync();

            var createdComment = _repository.MainComment.FindById(newComment.Id,
                                                                  PostCommentDto.Selector(authorId));

            return(createdComment);
        }
        public async Task <IActionResult> AddComment(int userId, int postId, NewCommentDto newCommentDto)
        {
            if (userId != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value))
            {
                return(Unauthorized());
            }

            if (await blogService.GetPost(postId) == null)
            {
                return(NotFound());
            }

            newCommentDto.PostId      = postId;
            newCommentDto.CommenterId = userId;

            var comment = mapper.Map <Comment>(newCommentDto);

            usersService.Add <Comment>(comment);

            if (await usersService.SaveAll())
            {
                return(Ok());
            }

            return(BadRequest("Failed to add comment"));
        }
Exemplo n.º 3
0
 public Task <ApiResponse <CommentDto> > AddCommentAsync(NewCommentDto comment)
 {
     if (comment == null)
     {
         throw new ArgumentNullException(nameof(comment));
     }
     return(PostAsync <NewCommentDto, ApiResponse <CommentDto> >(_advertOptions.AddCommentUrl, comment));
 }
Exemplo n.º 4
0
        public async Task NewComment_TaskExistsAndNewCommentDataInvalid_ShouldReturnBadRequest()
        {
            taskComment = new NewCommentDto
            {
                TaskId = newTask.TaskId
            };

            var response = await DoPostRequest("api/comment/newcomment", taskComment);

            Assert.AreEqual(HttpStatusCode.BadRequest, response.StatusCode);
        }
Exemplo n.º 5
0
 public async Task <ActionResult> Create([FromBody] NewCommentDto newCommentDto)
 {
     return(await HandleExceptions(async() =>
     {
         if (ModelState.IsValid)
         {
             await _commentManager.AddCommentAsync(newCommentDto);
             return Ok();
         }
         return BadRequest("Model state is not valid");
     }));
 }
Exemplo n.º 6
0
        public async Task <ActionResult <PostCommentDto> > CreateAsync(
            [FromHeader(Name = "userId")] int userId,
            [FromBody] NewCommentDto newCommentDto,
            [FromForm] IFormFile file)
        {
            var entity = await _postCommentService.CreateAndReturnMainCommentAsync(
                newCommentDto,
                userId,
                file);

            return(CreatedAtAction("CreateAsync", entity));
        }
Exemplo n.º 7
0
        public async Task NewComment(NewCommentDto dto)
        {
            var memberInfo = await _memberRepository.FirstOrDefaultAsync(t => t.Id == dto.MemberId);

            if (memberInfo == null)
            {
                throw new UserFriendlyException("请先登录账户!");
            }
            var postInfo = await _forumPostRepository.FirstOrDefaultAsync(t => t.Id == dto.PostId);

            if (postInfo == null)
            {
                throw new UserFriendlyException("回复的帖子不存在!");
            }
            if (dto.Content.Length < 5)
            {
                throw new UserFriendlyException("回复内容不能少于5个字");
            }

            if (dto.Content.Length > 100)
            {
                throw new UserFriendlyException("回复内容不能超过100个字");
            }

            ForumComment forumComment = new ForumComment();

            forumComment.MemberId    = dto.MemberId;
            forumComment.ForumPostId = postInfo.Id;
            forumComment.Content     = dto.Content;
            forumComment.Floor       = postInfo.CommentCount + 1;

            postInfo.LastCommentTime = DateTime.Now;
            postInfo.CommentCount++;

            var commentId = await _forumCommentRepository.InsertAndGetIdAsync(forumComment);

            if (dto.Images != null && dto.Images.Count > 0)
            {
                foreach (var image in dto.Images)
                {
                    ForumImage forumImage = new ForumImage();
                    forumImage.Type    = ForumImageType.Comment;
                    forumImage.Image   = image;
                    forumImage.OwnerId = commentId;
                    await _forumImageRepository.InsertAsync(forumImage);
                }
            }

            await _forumPostRepository.UpdateAsync(postInfo);
        }
Exemplo n.º 8
0
        public async Task <CommentCreatedDto> CreateCommentAsync(NewCommentDto commentDto)
        {
            var post = await _postsDbSet
                       .Include(x => x.Wall)
                       .FirstOrDefaultAsync(p => p.Id == commentDto.PostId && p.Wall.OrganizationId == commentDto.OrganizationId);

            if (post == null)
            {
                throw new ValidationException(ErrorCodes.ContentDoesNotExist, "Post does not exist");
            }

            var watchEntity = await _postWatchers.FindAsync(commentDto.PostId, commentDto.UserId);

            var comment = new Comment
            {
                AuthorId    = commentDto.UserId,
                MessageBody = commentDto.MessageBody,
                PictureId   = commentDto.PictureId,
                PostId      = commentDto.PostId,
                Likes       = new LikesCollection(),
                LastEdit    = DateTime.UtcNow
            };

            _commentsDbSet.Add(comment);

            post.LastActivity = _systemClock.UtcNow;

            if (watchEntity == null)
            {
                _postWatchers.Add(new PostWatcher
                {
                    PostId = post.Id,
                    UserId = commentDto.UserId
                });
            }

            await _uow.SaveChangesAsync(commentDto.UserId);

            return(new CommentCreatedDto
            {
                WallId = post.WallId,
                CommentId = comment.Id,
                WallType = post.Wall.Type,
                CommentCreator = comment.AuthorId,
                PostCreator = post.AuthorId,
                PostId = post.Id,
                MentionedUsersIds = commentDto.MentionedUserIds?.Distinct()
            });
        }
Exemplo n.º 9
0
        public async Task <NewCommentDto> NewComment(NewCommentDto comment)
        {
            var entity = mapper.Map <Core.Entities.Comment>(comment);

            await commentRepository.Create(entity);

            if (await commentRepository.SaveChanges())
            {
                return(comment);
            }
            else
            {
                return(null);
            }
        }
Exemplo n.º 10
0
        public async Task <CommentDto> Create(NewCommentDto newItem)
        {
            if (newItem == null)
            {
                throw new ArgumentNullException();
            }

            var comment = _mapper.Map <Comment>(newItem);

            comment.DateCreated = DateTime.Now;
            await _repository.Add(comment);

            var commentDto = _mapper.Map <CommentDto>(comment);

            return(commentDto);
        }
Exemplo n.º 11
0
        public async Task Should_Create_New_Comment()
        {
            // Setup
            var posts = new List <Post>
            {
                new Post {
                    Id = 1, Wall = new Wall {
                        OrganizationId = 2
                    }
                }
            };

            _postsDbSet.SetDbSetDataForAsync(posts.AsQueryable());

            var users = new List <ApplicationUser>
            {
                new ApplicationUser
                {
                    Id = _userId
                }
            };

            _usersDbSet.SetDbSetDataForAsync(users.AsQueryable());

            var expectedDateTime = DateTime.UtcNow;

            _systemClock.UtcNow.Returns(expectedDateTime);

            var newCommentDto = new NewCommentDto
            {
                MessageBody    = "test",
                OrganizationId = 2,
                PictureId      = "pic",
                PostId         = 1,
                UserId         = _userId
            };

            // Act
            await _commentService.CreateCommentAsync(newCommentDto);

            // Assert
            _commentsDbSet.Received(1)
            .Add(Arg.Is <Comment>(c => c.AuthorId == _userId && c.MessageBody == "test" && c.PostId == 1));

            Assert.AreEqual((await _postsDbSet.FirstAsync()).LastActivity, expectedDateTime);
        }
Exemplo n.º 12
0
        public async Task NewComment_TaskExistsAndNewCommentDataIsValid_ShouldSaveNewComment()
        {
            taskComment = new NewCommentDto
            {
                TaskId   = newTask.TaskId,
                Content  = "blabla",
                PersonId = ADMIN_PERSON_ID
            };

            var response = await DoPostRequest("api/comment/newcomment", taskComment);

            response.EnsureSuccessStatusCode();

            var result = GetSingleResult <NewCommentDto>(await response.Content.ReadAsStringAsync());

            Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
            Assert.NotNull(result);
            Assert.AreEqual(result.CommentId, taskComment.CommentId);
        }
Exemplo n.º 13
0
        public async Task <IActionResult> AdvertById(NewCommentDto comment)
        {
            if (comment.Text == null)
            {
                return(View("Error", new ErrorViewModel {
                    RequestId = "Enter text"
                }));
            }
            var cats = await _categoryApiClient.GetCategoriesAsync();

            ViewBag.Categories = cats.Data;
            comment.UserId     = User.Claims.FirstOrDefault(c => c.Type.Contains("nameidentifier")).Value;



            ApiResponse <CommentDto> response = null;

            try
            {
                response = await _advertApiClient.AddCommentAsync(comment);
            }
            catch (ApplicationException ex)
            {
                if (ex.Message.Equals("401"))
                {
                    return(Redirect($"~/Home/Logout"));
                }
                else
                {
                    return(View("Error", new ErrorViewModel {
                        RequestId = ex.Message
                    }));
                }
            }



            return(Redirect($"{comment.AdvertId}"));
        }
Exemplo n.º 14
0
        public async Task NewComment_GivenAValidCommentDataAndShouldFailToSave_ShouldReturnNull()
        {
            var newComment = new NewCommentDto
            {
                Content  = "New comment",
                PersonId = Guid.NewGuid(),
                TaskId   = Guid.NewGuid()
            };

            mockCommentRepository.Setup(x => x.Create(mapper.Map <Core.Entities.Comment>(newComment)))
            .Returns(Task.CompletedTask);
            mockCommentRepository.Setup(x => x.SaveChanges())
            .ReturnsAsync(false);

            var commentService = new CommentService(mockCommentRepository.Object, mapper);

            var result = await commentService.NewComment(newComment);

            mockCommentRepository.Verify(v => v.SaveChanges(), Times.Once);

            Assert.IsNull(result);
        }
Exemplo n.º 15
0
        public async Task <IActionResult> NewComment(NewCommentDto comment)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return(CustomResponse(ModelState));
                }

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

                var result = await commentService.NewComment(comment);

                return(Ok(result));
            }
            catch (Exception ex)
            {
                return(HandleException(ex.Message));
            }
        }
Exemplo n.º 16
0
        public async Task <CommentDto> AddCommentAsync(NewCommentDto dto)
        {
            if (dto == null)
            {
                throw new ArgumentNullException(nameof(dto));
            }
            if (string.IsNullOrEmpty(dto.Text))
            {
                throw new Exception($"{nameof(dto)} Заполните все данные");
            }

            var advert = await _advertRepository.GetAsync(dto.AdvertId);

            if (advert == null)
            {
                throw new Exception($"{nameof(advert)} Такого объявления не существует");
            }
            var entity = _mapper.Map <Comment>(dto);

            advert.Comments.Add(entity);
            await _advertRepository.SaveChangesAsync();

            return(_mapper.Map <CommentDto>(entity));
        }
Exemplo n.º 17
0
        public async Task <IActionResult> AddComment([FromBody] NewCommentDto newCommentDto)
        {
            var createComment = await _commentService.Create(newCommentDto);

            return(Ok(createComment));
        }
Exemplo n.º 18
0
        public async Task AddCommentAsync(NewCommentDto comment)
        {
            var newComment = _mapper.Map <Comment>(comment);
            await _appContext.Comments.AddAsync(newComment);

            await _appContext.SaveChangesAsync(default);
Exemplo n.º 19
0
 public async Task <IActionResult> AddCommentAsync(NewCommentDto comment)
 {
     return(ApiResult(await _advertManager.AddCommentAsync(comment)));
 }