public async Task GivenValidContentForExistingNews_WhenCreatingComment_ThenReturnsSuccessfulResponse() { // Arrange var draft = CreateDraftEntity(); var payload = new CreateCommentDto { DraftId = draft.Id, Content = "some content" }; Factory.DraftRepositoryMock.Setup(m => m.Get(payload.DraftId)).Returns(Task.FromResult(draft)); // Act var response = await AuthenticatedPost(Endpoint, payload); // Assert response.ShouldBeSuccessful(); var envelope = await response.ShouldBeOfType <CommentDto>(); envelope.ShouldBeSuccessful(); envelope.Payload.Id.Should().NotBeEmpty(); envelope.Payload.Content.Should().Be(payload.Content); envelope.Payload.DraftId.Should().Be(draft.Id); envelope.Payload.ReplyingTo.Should().BeNull(); envelope.Payload.CreatedAt.Should().BeBefore(DateTime.UtcNow); envelope.Payload.CreatedBy.Should().Be(Factory.Identity.Username); envelope.Payload.Likes.Should().Be(0); envelope.Payload.Replies.Should().Be(0); }
public async Task <IActionResult> CreateComment(int id, [FromBody] CreateCommentDto createCommentDto) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var currentUserId = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value); var commentToCreate = new Comment { CommentText = createCommentDto.CommentText, DateCommented = DateTime.Now, CommenterId = currentUserId, PostId = id }; _repo.Add(commentToCreate); if (await _repo.SaveAll()) { return(StatusCode(201)); } throw new Exception("Failed on save."); }
public async Task <IActionResult> Create([FromBody] CreateCommentDto commentDto) { if (!ModelState.IsValid) { return(BadRequest()); } return(await Execute(async() => { var user = new User { Username = _identityHelper.Username, Id = _identityHelper.Id }; var comment = Comment.Create( commentDto.DraftId, commentDto.Content, user); comment.ReplyingTo = commentDto.ReplyingTo; await _commentService.Save(comment); return _mapper.Map <CommentDto>(comment); })); }
public async Task CreateCommentAsync(CreateCommentDto input) { var issue = await _issueRepository.GetAsync(input.IssueId); issue.AddComment(CurrentUser.GetId(), input.Text); await _issueRepository.UpdateAsync(issue); }
public async Task AddComment([FromBody] CreateCommentDto request) { request.UserId = User.GetUserId(); request.UserName = User.GetUserName(); await _advertCommentService.AddAsync(request); }
public virtual async Task <CommentWithDetailsDto> CreateAsync(CreateCommentDto input) { return(await RequestAsync <CommentWithDetailsDto>(nameof(CreateAsync), new ClientProxyRequestTypeValue { { typeof(CreateCommentDto), input } })); }
public async Task <Comment> Create(string postId, CreateCommentDto dto) { User user = await _sessionService.GetUser(); Validate("create", dto.Content, user); Post post = await _postRepository.GetById(postId); if (post == null) { _logger.LogWarning($"There is no post {postId}"); throw HttpError.NotFound($"There is no post {postId}"); } var comment = new Comment { Content = dto.Content, CreationTime = DateTime.Now, LastUpdateTime = DateTime.Now, AuthorId = user.Id, Likes = 0, Dislikes = 0, PostId = postId, Id = Guid.NewGuid().ToString() }; await _commentRepository.Create(comment); _logger.LogInformation($"Comment {comment.Id} has been created"); return(comment); }
public ActionResult Create(CreateCommentDto dto) { if (!ModelState.IsValid) { TempData["greska"] = "Doslo je do greske pri unosu"; RedirectToAction("create"); } try { _addComment.Execute(dto); _emailSender.Subject = "Uspesno ste postavili komentar"; _emailSender.ToEmail = dto.Email; _emailSender.Body = "Hvala na komentaru"; _emailSender.Send(); return(RedirectToAction(nameof(Index))); } catch (Exception e) { TempData["error"] = e.Message; ViewBag.News = _context.News.Select(n => new NewsCommentDto { Heading = n.Heading, NewsId = n.Id }); return(View()); } }
public void Execute(CreateCommentDto request) { if (!_context.Users.Any(r => r.Id == request.UserId)) { throw new EntityNotFoundException("User "); } if (!_context.Posts.Any(r => r.Id == request.PostId)) { throw new EntityNotFoundException("Post "); } _context.Commnets.Add(new Comment { PostId = request.PostId, UserId = request.UserId, Text = request.Text, ModifiedOn = null, IsDeleted = false }); _context.SaveChanges(); var email = _context.Commnets.Where(p => p.UserId == request.UserId).Select(u => u.User.Email).First().ToString(); _emailSender.Subject = "Comment posted!"; _emailSender.Body = "Your Comment was created! Yey!"; _emailSender.ToEmail = email; _emailSender.Send(); }
public void Execute(CreateCommentDto request) { if (request == null) { throw new NullReferenceException(); } else { try { var comment = new Comments { Name = request.Username, Comment = request.Text, NewsId = request.NewsId, Email = request.Email, CreatedAt = DateTime.Now }; Context.Comments.Add(comment); Context.SaveChanges(); } catch (Exception e) { throw new NullReferenceException(); } } }
public async Task <Result <CommentDto> > Create(CreateCommentDto createCommentDto, Guid userId) { var user = await Context.Users.FirstOrDefaultAsync(u => u.Id == userId); if (user == null) { return(Result <CommentDto> .Failed(new NotFoundObjectResult(new ApiMessage { Message = ResponseMessage.UserNotFound }))); } var eEvent = await Context.Events.FirstOrDefaultAsync(u => u.Id == createCommentDto.EventId); if (eEvent == null) { return(Result <CommentDto> .Failed(new NotFoundObjectResult(new ApiMessage { Message = ResponseMessage.UserNotFound }))); } var comment = _mapper.Map <Comment>(createCommentDto); comment.User = user; comment.Event = eEvent; await AddAsync(comment); await Context.SaveChangesAsync(); return(Result <CommentDto> .SuccessFull(_mapper.Map <CommentDto>(comment))); }
public long CreateComment(long postId, CreateCommentDto createCommentDto) { if (!this.queryService.Query <Post>().Any(x => x.Id == postId)) { throw new ApiException(this.apiResultService.BadRequestResult( (ErrorCode.Parse(ErrorCodeType.InvalidReferenceId, AtanetEntityName.Comment, PropertyName.Comment.PostId, AtanetEntityName.Post), new ErrorDefinition(postId, "The given post does not exist", PropertyName.Comment.PostId)))); } var currentUserId = this.userService.GetCurrentUserId(); if (!this.scoreService.Can(AtanetAction.CreateComment, currentUserId)) { var minScore = this.scoreService.GetMinScore(AtanetAction.CreateComment); throw new ApiException(this.apiResultService.BadRequestResult($"User must have a score greater than {minScore} in order to create comments")); } using (var unitOfWork = this.unitOfWorkFactory.CreateUnitOfWork()) { var comment = this.mapper.Map <Comment>(createCommentDto); comment.PostId = postId; comment.UserId = currentUserId; var commentRepository = unitOfWork.CreateEntityRepository <Comment>(); commentRepository.Create(comment); unitOfWork.Save(); return(comment.Id); } }
public async Task <IActionResult> Create([FromBody] CreateCommentDto createComment) { try { var user = HttpContext.User.Claims.FirstOrDefault(c => c.Type.Equals(ClaimsIdentity.DefaultNameClaimType)); var userEmail = user?.Value; var userId = (await _userService.GetUserByLogin(userEmail)).Id; var comment = new Comment { Id = Guid.NewGuid(), NewsId = createComment.NewsId, Text = createComment.CommentText, CreateDate = DateTime.Now, UserId = userId, }; _unitOfWork.Comment.Add(comment); await _unitOfWork.SaveAsync(); return(Ok()); } catch (Exception ex) { Log.Error(ex.Message); return(BadRequest(ex.Message)); throw; } }
public void Create_AddsCommentToDb() { // Arrange var context = this.ServiceProvider.GetRequiredService <WmipDbContext>(); var commentsService = new CommentsService(context); var creationInfo = new CreateCommentDto { Body = "bod", Title = "title", PostId = 1, UserId = "1" }; // Act var result = commentsService.Create(creationInfo, out Comment comment); //Assert Assert.True(result); Assert.Single(context.Comments); Assert.NotNull(comment); Assert.Equal(creationInfo.Title, comment.Title); Assert.Equal(creationInfo.Body, comment.Body); Assert.Equal(creationInfo.PostId, comment.CommentedOnId); Assert.Equal(creationInfo.UserId, comment.UserId); }
public async Task <string> CreateCommentAsync(string userId, CreateCommentDto createCommentDto) { User user = await _userManager.FindByIdAsync(userId); Guard.Against.NullItem(user, nameof(user)); Post post = await _postRepository.GetByConditionAsync(x => x.Id == createCommentDto.PostId); Guard.Against.NullItem(post, nameof(post)); if (!string.IsNullOrEmpty(createCommentDto.ParentId)) { Comment parentComment = await _commentRepository.GetByConditionAsync(x => x.Id == createCommentDto.ParentId); Guard.Against.NotEqual(parentComment.Post.Id, post.Id); } var comment = _mapper.Map <Comment>(createCommentDto); comment.Author = user; comment.Post = post; await _commentRepository.CreateAsync(comment); return(comment.Id); }
public async Task <IActionResult> AddComment([FromForm] CreateCommentDto comment) { //логика добавления комментария await _commentService.AddAsync(comment); return(RedirectToAction("Get", "Advert", new { id = comment.AdvertId })); }
public async Task <long> CreateAsync(CreateCommentDto model) { var comment = await _factory.MakeAsync(model); await _repository.AddAndSaveAsync(comment); return(await Task.FromResult(comment.Id)); }
public static Comment mapFromCreateDto(CreateCommentDto createCommentDto) { Comment result = new Comment(); result.Important = createCommentDto.Important; result.Text = createCommentDto.Text; return(result); }
public async Task <CommentWithDetailsDto> CreateAsync(CreateCommentDto input) { var comment = new Comment(_guidGenerator.Create(), input.PostId, input.RepliedCommentId, input.Text); comment = await _commentRepository.InsertAsync(comment); return(ObjectMapper.Map <Comment, CommentWithDetailsDto>(comment)); }
public async Task <IActionResult> Create([FromBody] CreateCommentDto createCommentDto) { string userId = _httpContext.User.FindFirstValue("sub"); string commentId = await _mediator.Send(new CreateCommentCommand(userId, createCommentDto)); return(Created($"{HttpContext.Request.GetDisplayUrl()}/{commentId}", null)); }
public async Task <IActionResult> AddComment([FromBody] CreateCommentDto request) { var result = await Mediator.Send(new AddCommentRequest { PostId = request.PostId, Body = request.Body, ReplyTo = request.ReplyTo, AuthorId = CurrentUserId !.Value });
public async Task <IActionResult> CreateComment(string postId, [FromBody] CreateCommentDto createCommentDto) { var result = await Mediator.Send(new CreateCommentCommand { CreateCommentDto = new CreateCommentDto(createCommentDto, AuthorizedUserId), PostId = postId }); return(Ok(result)); }
public CreateNewCommentCommandHandlerTests() { _articleReadingService = Mock.Of <IArticleReadingService>(); _mapper = Mock.Of <IMapper>(); _createNewCommentCommandHandler = new CreateNewCommentCommandHandler(_articleReadingService, _mapper); _createNewCommentCommand = new CreateNewCommentCommand(); _createCommentDto = new CreateCommentDto(); Mock.Get(_mapper).Setup(m => m.Map <CreateCommentDto>(_createNewCommentCommand)).Returns(_createCommentDto); }
private Comment CreateComment(CreateCommentDto commentDto, string guid, string url) { return(new Comment() { CommentId = guid, Content = commentDto.Content, CreatedOn = DateTime.UtcNow, ImgUrl = url }); }
private void NotifyPostingUser(CreateCommentDto commentDto, User user, string guid) { var PostingId = _usersRepository.GetPosting(commentDto.PostId).UserId; if (user.UserId != PostingId) { object commentNotification = new { commentId = guid, user, postId = commentDto.PostId, ReciverId = PostingId }; _serverComunication.NotifyUser("/CommentOnPost", commentNotification); } }
public ActionResult Post([FromBody] CreateCommentDto dto) { try { _createComment.Execute(dto); return(StatusCode(201)); } catch (EntityNotFoundException e) { return(NotFound(e.Message)); } catch (Exception e) { return(StatusCode(500, e.Message)); } }
public async Task <CommentWithDetailsDto> CreateAsync(CreateCommentDto input) { var comment = new Comment(GuidGenerator.Create(), input.PostId, input.RepliedCommentId, input.Text); comment = await CommentRepository.InsertAsync(comment); await CurrentUnitOfWork.SaveChangesAsync(); return(ObjectMapper.Map <Comment, CommentWithDetailsDto>(comment)); }
public async Task <IActionResult> Create([FromBody] CreateCommentDto createCommentDto) { var result = await _unitOfWork.CommentService.Create(createCommentDto, UserId); if (!result.Success) { return(result.ApiResult); } return(Created(Url.Link("GetCounty", new { result.Data.Id }), _mapper.Map <CommentDto>(result.Data))); }
public async void Comments_POST_Returns_404() { CreateCommentDto commentDto = new CreateCommentDto() { Text = "Text" }; var response = await this.HttpClient.PostAsync($"/api/v1/posts/{Guid.NewGuid()}/comments", new StringContent(JsonConvert.SerializeObject(commentDto), Encoding.UTF8, "application/json")); Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); }
public async Task <IActionResult> InsertCommentAsync([FromBody] CreateCommentDto model) { if (!await recaptchaManager.ValidateReCaptchaResponseAsync(model.CaptchaResponse)) { return(Ok()); } await commentService.InsertCommentAsync(model); return(Ok()); }