Exemplo n.º 1
0
        public CommentCreatedDTO CreateComment(NewCommentDTO commentDto)
        {
            var post = _postsDbSet
                       .Include(x => x.Wall)
                       .FirstOrDefault(p =>
                                       p.Id == commentDto.PostId && p.Wall.OrganizationId == commentDto.OrganizationId);

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

            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;
            _uow.SaveChanges(commentDto.UserId);

            return(new CommentCreatedDTO {
                WallId = post.WallId, CommentId = comment.Id, WallType = post.Wall.Type, CommentCreator = comment.AuthorId, PostCreator = post.AuthorId, PostId = post.Id
            });
        }
Exemplo n.º 2
0
        public async Task <GetCommentDTO> CreateComment(NewCommentDTO newComment, string userName)
        {
            try
            {
                User user = await _userManager.FindByNameAsync(userName);

                Comment comment = Mapper.Map <Comment>(newComment);

                comment.CreatedUserId = user.Id;
                comment.CreatedDate   = DateTime.UtcNow;
                comment.UpdatedUserId = user.Id;
                comment.UpdatedDate   = DateTime.UtcNow;
                if (newComment.ActionFor == ActionFor.Post)
                {
                    comment.PostId = newComment.ActionForId;
                }

                _repository.Insert(comment);
                await _unitOfWork.SaveChangesAsync();

                var resultComment = Mapper.Map <GetCommentDTO>(comment);
                resultComment.CreatedUserAvatar = user.Avatar;
                resultComment.CreatedUserName   = user.UserName;

                return(resultComment);
            }
            catch (Exception ex)
            {
                throw new Exception(ResponseCodeString.CommentCreate_Error, ex.InnerException);
            }
        }
Exemplo n.º 3
0
        public async Task <GetCommentDTO> CreateComment(NewCommentDTO newComment)
        {
            ClaimsPrincipal principal = Request.GetRequestContext().Principal as ClaimsPrincipal;
            var             userName  = ClaimsPrincipal.Current.Identity.Name;

            newComment.ActionFor = ActionFor.Post;
            return(await commentService.CreateComment(newComment, userName));
        }
Exemplo n.º 4
0
        public async Task <CommentDTO> CreateComment(NewCommentDTO newComment)
        {
            var commentEntity = _mapper.Map <Comment>(newComment);

            _context.Comments.Add(commentEntity);
            await _context.SaveChangesAsync();

            var createdComment = await _context.Comments
                                 .Include(comment => comment.Author)
                                 .ThenInclude(user => user.Avatar)
                                 .FirstAsync(comment => comment.Id == commentEntity.Id);

            return(_mapper.Map <CommentDTO>(createdComment));
        }
Exemplo n.º 5
0
        public void Should_Create_New_Comment()
        {
            // Setup
            var posts = new List <Post>
            {
                new Post {
                    Id = 1, Wall = new Wall {
                        OrganizationId = 2
                    }
                }
            };

            _postsDbSet.SetDbSetData(posts.AsQueryable());

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

            _usersDbSet.SetDbSetData(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
            _commentService.CreateComment(newCommentDto);

            // Assert
            _commentsDbSet.Received(1)
            .Add(Arg.Is <Comment>(c =>
                                  c.AuthorId == _userId &&
                                  c.MessageBody == "test" &&
                                  c.PostId == 1));
            Assert.AreEqual(_postsDbSet.First().LastActivity, expectedDateTime);
        }
Exemplo n.º 6
0
        public async Task <IActionResult> PostComment([FromRoute] int shoutId, [FromBody] NewCommentDTO newCommentDTO)
        {
            ApiResponse <CreateCommentResult> apiResponse = new ApiResponse <CreateCommentResult>();

            try
            {
                apiResponse.EndpointResult = await this._shoutService.CreateCommentAsync(
                    newCommentDTO.ToComment().AddIds(shoutId, Convert.ToInt32(this._JWTService.GetClaimId(HttpContext.User)))
                    );

                if (apiResponse.EndpointResult.State != CreateShoutState.Success)
                {
                    apiResponse.Error   = true;
                    apiResponse.Message = apiResponse.EndpointResult.State.Switch(new Dictionary <CreateShoutState, Func <string> >()
                    {
                        { CreateShoutState.ContentTooLong, () => Resource_ResponseMessages_en.ContentTooLong },
                        { CreateShoutState.ContentTooSmall, () => Resource_ResponseMessages_en.ContentTooSmall }
                    },
                                                                                  () => Resource_ResponseMessages_en.Unknown
                                                                                  );

                    return(BadRequest(apiResponse));
                }

                apiResponse.Message = Resource_ResponseMessages_en.CreateCommentSuccess;

                return(Ok(apiResponse));
            }
            catch (DbException e)
            {
                apiResponse.Error   = true;
                apiResponse.Message = Resource_ResponseMessages_en.Unknown;
                // TODO: Error handling.
                return(Problem(statusCode: 500, detail: Newtonsoft.Json.JsonConvert.SerializeObject(e, Newtonsoft.Json.Formatting.Indented)));
            }
            catch (Exception e)
            {
                apiResponse.Error   = true;
                apiResponse.Message = Resource_ResponseMessages_en.Unknown;
                return(Problem(statusCode: 500, detail: Newtonsoft.Json.JsonConvert.SerializeObject(e, Newtonsoft.Json.Formatting.Indented)));
            }
        }
Exemplo n.º 7
0
        public HttpResponseMessage AddNewComment([FromBody] NewCommentDTO model)
        {
            // START TOKEN VALIDATION
            string token = Request.Headers.GetValues("auth_token").FirstOrDefault().ToString();

            if (String.IsNullOrEmpty(token))
            {
                return(Request.CreateErrorResponse(HttpStatusCode.Unauthorized, "Auth token is not valid!"));
            }
            if (_db.AuthenticationTokens.Where(x => x.Token == token).FirstOrDefault().IsDeleted == true)
            {
                return(Request.CreateErrorResponse(HttpStatusCode.Unauthorized, "Auth token is not valid!"));
            }
            TimeSpan difference = DateTime.Now - _db.AuthenticationTokens.Where(x => x.Token == token).FirstOrDefault().TokenDate;

            if (difference.TotalHours > 3)
            {
                return(Request.CreateErrorResponse(HttpStatusCode.Unauthorized, "Auth token is not valid!"));
            }
            // END TOKEN VALIDATION

            Comments newComment = new Comments
            {
                IsDeleted = false,
                UserID    = model.UserID,
                Comment   = model.Comment
            };

            _db.Comments.Add(newComment);
            PostComments newPostComment = new PostComments
            {
                CommentDate = DateTime.Now,
                CommentID   = newComment.CommentID,
                PostID      = model.PostID
            };

            _db.PostComments.Add(newPostComment);
            _db.SaveChanges();
            return(Request.CreateResponse(HttpStatusCode.OK, model));
        }
Exemplo n.º 8
0
 public async Task <ActionResult <CommentDTO> > CreatePost([FromBody] NewCommentDTO comment)
 {
     comment.AuthorId = this.GetUserIdFromToken();
     return(Ok(await _commentService.CreateComment(comment)));
 }