Beispiel #1
0
        public async Task CreateAsync_WithValidData_ShouldAddCommentToDatabase()
        {
            // Arrange
            var context            = InMemoryDbContext.Initiliaze();
            var commentsRepository = new EfDeletableEntityRepository <Comment>(context);
            var postsRepository    = new EfDeletableEntityRepository <Post>(context);
            var service            = new CommentsService(commentsRepository, postsRepository);

            await this.SeedUsersAndPost(context);

            var model = new CommentCreateModel
            {
                CreatorId = "userId",
                PostId    = 52,
                Text      = "Comment Text",
            };

            // Act
            int expectedCount = context.Comments.Count() + 1;
            await service.CreateAsync(model);

            int actualCount = context.Comments.Count();

            // Assert
            Assert.Equal(expectedCount, actualCount);
        }
        public virtual PartialViewResult Add(CommentCreateModel model)
        {
            var commentsTarget = FullContext.GetCommentsTarget();
            var targetEntityId = commentsTarget.EntityId.Value;

            if (!ModelState.IsValid)
            {
                return(OverView(targetEntityId));
            }

            var createDto = MapToCreateDto(model, targetEntityId);
            var command   = new AddCommentCommand(FullContext, createDto);

            _commandPublisher.Publish(command);

            OnCommentCreated(createDto.Id);

            switch (commentsTarget.Type.ToInt())
            {
            case int type
                when ContextExtensions.HasFlagScalar(type, ContextType.Activity | ContextType.PagePromotion):
                var activityCommentsInfo = GetActivityComments(targetEntityId);

                return(OverView(activityCommentsInfo));

            default:
                return(OverView(targetEntityId));
            }
        }
Beispiel #3
0
        public IActionResult CreateComment([FromBody] CommentCreateModel commentModel)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            string userId = User.FindFirstValue(ClaimTypes.NameIdentifier);
            User   user   = _repoWrapper.User.FindByCondition(u => u.Id.ToString() == userId).FirstOrDefault();

            if (user == null)
            {
                return(BadRequest("Token is incorrect"));
            }

            Podcast podcast = _repoWrapper.Podcast.FindByCondition(p => p.Id == commentModel.PodcastId).FirstOrDefault();

            if (podcast == null)
            {
                return(NotFound("PodcastId is incorrect"));
            }

            Comment comment = new Comment()
            {
                Text            = commentModel.Text,
                PodcastId       = commentModel.PodcastId,
                UserId          = user.Id,
                PublicationDate = DateTime.Now
            };

            _repoWrapper.Comment.Create(comment);
            _repoWrapper.Save();

            return(Ok(comment));
        }
Beispiel #4
0
        public ActionResult AddComment(CommentCreateModel commentModel, int ticketId)
        {
            var user   = this.Data.Users.All().FirstOrDefault(u => u.UserName == this.User.Identity.Name);
            var ticket = this.Data.Tickets.GetById(ticketId);

            if (ModelState.IsValid)
            {
                var newComment = new Comment()
                {
                    Content = commentModel.Content,
                    Ticket  = ticket,
                    User    = user
                };

                this.Data.Comments.Add(newComment);
                this.Data.SaveChanges();

                return(PartialView("_CommentPartial", new CommentDisplayModel()
                {
                    Content = commentModel.Content, Username = this.User.Identity.Name
                }));
            }
            else
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest, "Invalid comment"));
            }
        }
Beispiel #5
0
        public async Task <IActionResult> CreateCommentAsync([FromRoute] int postId, [FromBody] CommentCreateModel model)
        {
            if (string.IsNullOrWhiteSpace(model.Content))
            {
                throw new IsRequiredException("content");
            }

            if (model.Content.Length < 20)
            {
                throw new ContentIsInvalidException();
            }

            if (!await _postRepository.AnyByIdAsync(postId))
            {
                throw new NotFound404Exception("post");
            }

            DateTime now = DateTime.Now;

            var comment = new Comment
            {
                AccountId   = CurrentAccountId,
                PostId      = postId,
                Content     = model.Content,
                CreatedDate = now,
                UpdatedDate = now
            };

            await _postRepository.CreateCommentAsync(comment);

            return(Ok(CommentDTO.GetFrom(comment)));
        }
        public IHttpActionResult Post(CommentCreateModel comment)
        {
            var userId = this.context.Users.FirstOrDefault(u => u.UserName == comment.AuthorUsername).Id;

            if (comment != null && this.ModelState.IsValid)
            {
                var databaseComment = new Comment
                {
                    Content    = comment.Content,
                    NewsItemId = comment.NewsItemId,
                    AuthorId   = userId,
                    CreatedOn  = DateTime.Now
                };

                context.Comments.Add(databaseComment);
                context.SaveChanges();

                return(Ok(new
                {
                    id = databaseComment.Id,
                    content = databaseComment.Content,
                    author = databaseComment.Author.UserName,
                    createdOn = databaseComment.CreatedOn,
                }));
            }
            else
            {
                return(this.BadRequest(this.ModelState));
            }
        }
        public virtual PartialViewResult CreateView(Guid activityId)
        {
            var model = new CommentCreateModel {
                UpdateElementId = GetOverviewElementId(activityId)
            };

            return(PartialView(CreateViewPath, model));
        }
Beispiel #8
0
        public async Task AddCommentAsync(CommentCreateModel model)
        {
            var commentDto = _mapper.Map <CommentDTO>(model);

            commentDto.AppUserId = (await _currentUser.GetCurrentUser(_httpContextAccessor.HttpContext)).Id;

            await _commentService.AddCommentAsync(commentDto);
        }
Beispiel #9
0
        public async Task <IActionResult> Create(CommentCreateModel model)
        {
            var user = await _userManager.GetUserAsync(User);

            await _service.Create(model, user.Id);

            return(NoContent());
        }
Beispiel #10
0
        public async Task Create(CommentCreateModel model, string userId)
        {
            var entity = _mapper.Map <Comment>(model);

            entity.UserId = userId;

            await _context.AddAsync(entity);
        }
 public async Task <IActionResult> Post([FromBody] CommentCreateModel model)
 {
     _logger.LogInformation($"Create new videoGame : {HttpContext.Request.Query} ");
     if (await _service.CreateAsync(_mapper.Map <CommentDTO>(model)))
     {
         return(Ok());
     }
     return(BadRequest());
 }
 public ActionResult CreateComment(CommentCreateModel model)
 {
     if (ModelState.IsValid)
     {
         var comment = model.ConvertToComment();
         comment.Id = CommentHelper.CreateComment(comment);
         return(PartialView("_Comment", new CommentViewModel(comment)));
     }
     return(Json(new { error = CommentHelper.BuildErrorMessage(ModelState) }));
 }
Beispiel #13
0
        public void CreateComment(CommentCreateModel model, int userId)
        {
            using (var unitOfWork = _unitOfWorkFactory.Create())
            {
                Comment comment = Mapper.Map <Comment>(model);
                comment.AuthorId = userId;

                unitOfWork.Comments.Create(comment);
            }
        }
Beispiel #14
0
        public async Task <IActionResult> PostComment([FromBody] CommentCreateModel rateModel, [FromRoute][Required] int id)
        {
            var command = Mapper.Map <CommandCreateComment>(rateModel);

            command.PlaceId = id;

            await Mediator.Send(command);

            return(Ok());
        }
        public async Task <IActionResult> Create(CommentCreateModel model)
        {
            User user = await _userManager.GetUserAsync(User);

            _commentService.CreateComment(model, user.Id);

            List <CommentModel> models = _commentService.GetAllComments(model.AdId);

            return(PartialView("_AllComments", models));
        }
        public IHttpActionResult CreateComment([FromBody] CommentCreateModel commentToCreate)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }
            var service = CreateCommentService();

            service.CreateComment(commentToCreate);
            return(Ok());
        }
        public void AddComment(CommentCreateModel commentToCreate)
        {
            var entity = new Comment()
            {
                UserId = _userId,
                Text   = commentToCreate.Text,
                PostId = commentToCreate.PostId
            };

            _ctx.Comments.Add(entity);
            _ctx.SaveChanges();
        }
Beispiel #18
0
        public void CreateComment(CommentCreateModel commentToCreate)
        {
            var entity = new Comment()
            {
                //UserId = commentToCreate.UserId,
                Text         = commentToCreate.Text,
                CreatedAtUtc = commentToCreate.CreatedAtUtc
            };

            _ctx.Comments.Add(entity);
            _ctx.SaveChanges();
        }
        protected virtual CommentCreateDto MapToCreateDto(CommentCreateModel createModel, Guid activityId)
        {
            var currentMemberId = _intranetMemberService.GetCurrentMember().Id;
            var dto             = new CommentCreateDto(
                Guid.NewGuid(),
                currentMemberId,
                activityId,
                createModel.Text,
                createModel.ParentId,
                createModel.LinkPreviewId);

            return(dto);
        }
Beispiel #20
0
 public IActionResult Create([FromBody] CommentCreateModel model)
 {
     if (!_accountDomainService.CheckIfUserExistsFromHeader(HttpContext.Request))
     {
         return(Unauthorized());
     }
     else
     {
         long creatorId = long.Parse(HttpContext.Request.Headers["X-Account-Id"]);
         var  comment   = new Comment(model.Content, creatorId, model.PostId);
         _commentRepository.Create(comment);
         return(Ok());
     }
 }
Beispiel #21
0
        public IActionResult Create(CommentCreateModel commentCreateModel, int id)
        {
            var userName = User.Identity.Name;
            var e        = _db.Comments.Add(new CommentModel
            {
                Author     = _db.Users.FirstOrDefault(u => u.UserName == userName),
                CreateDate = DateTime.Now,
                Text       = commentCreateModel.CommentText,
                Post       = _db.Posts.FirstOrDefault(p => p.Id == id)
            });

            _db.SaveChanges();
            return(RedirectToAction("Index", "Comment", new { id = id }));
        }
Beispiel #22
0
        public async Task <bool> CreateComment(CommentCreateModel model, string userName, string link, int?commentId)
        {
            var userProfile = await context
                              .Profiles
                              .Include(u => u.User)
                              .FirstOrDefaultAsync(p => p.User.UserName == userName);

            var news = await context
                       .News
                       .FirstOrDefaultAsync(n => n.Id == model.NewsId);

            if (news != null)
            {
                await statisticNewsService.SetState(model.NewsId, userName, "view", string.Empty);

                var now = DateTime.Now;
                await context.Comments.AddAsync(new Data.dbModels.Comment
                {
                    News        = news,
                    DateComment = now,
                    Text        = model.TextComment,
                    Owner       = userProfile,
                    UserNameTo  = model.UsernameAddresTo,
                    CommentIdTo = model.CommentIdTo
                });

                if (!string.IsNullOrEmpty(model.UsernameAddresTo))
                {
                    var profileFrom  = userProfile.Id;
                    var userFromName = userProfile.User.UserName;

                    var userToId = (await context
                                    .Users
                                    .FirstOrDefaultAsync(u => u.UserName == model.UsernameAddresTo))
                                   ?.Id;

                    var profileTo = await context.Profiles.FirstOrDefaultAsync(p => p.UserId == userToId);

                    if (profileTo != null)
                    {
                        await SetNotificationAsync(profileTo, profileFrom, link, userFromName, commentId);
                    }
                }

                await context.SaveChangesAsync();

                return(true);
            }
            return(false);
        }
Beispiel #23
0
        public async Task <IActionResult> Create([FromBody] CommentCreateModel model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState.ToDictionary(
                                      kvp => kvp.Key,
                                      kvp => kvp.Value.Errors.Select(e => e.ErrorMessage).ToArray()
                                      )));
            }

            var postCreatorId = await this.service.CreateAsync(model);

            return(Ok(postCreatorId));
        }
Beispiel #24
0
        public IActionResult Add(CommentCreateModel commentCreateModel)
        {
            var userId = int.Parse(User.FindFirst("Id").Value);

            var response = _commentsService.Add(commentCreateModel.Comment, commentCreateModel.TicketId, userId);

            if (response.IsSuccessful)
            {
                return(RedirectToAction("Details", "Ticket", new { id = commentCreateModel.TicketId }));
            }
            else
            {
                return(RedirectToAction("ActionNonSuccessful", "Info", new { Message = response.Message }));
            }
        }
Beispiel #25
0
        public static CommentDTO ConvertToCommentDTO(CommentCreateModel createModel)
        {
            if (createModel == null)
            {
                throw new ArgumentNullException();
            }

            CommentDTO commentDTO = new CommentDTO
            {
                PostId  = createModel.PostId,
                Content = createModel.Content
            };

            return(commentDTO);
        }
Beispiel #26
0
        public async Task <ActionResult> CreateComment(CommentCreateModel model)
        {
            var    username = User.GetUserName();
            string link     = model.NewsId.ToString();

            var commentIdTo = model.CommentIdTo;
            var result      = await commentService.CreateComment(model, username, link, commentIdTo);

            if (result)
            {
                return(Ok());
            }

            return(BadRequest());
        }
Beispiel #27
0
        public ActionResult Create(CommentCreateModel model)
        {
            if (ModelState.IsValid)
            {
                return(View(model));
            }
            var service = CreateCommentService();

            if (service.CreateComment(model))
            {
                TempData["SaveResult"] = "Your note was created.";
                return(RedirectToAction("Index"));
            }
            ModelState.AddModelError("", "Note could not be created.");
            return(View(model));
        }
Beispiel #28
0
        private async Task <CommentCreateDto> MapToCreateDtoAsync(
            CommentCreateModel createModel,
            Guid activityId)
        {
            var currentMemberId = await _intranetMemberService.GetCurrentMemberIdAsync();

            var dto = new CommentCreateDto(
                Guid.NewGuid(),
                currentMemberId,
                activityId,
                createModel.Text,
                createModel.ParentId,
                createModel.LinkPreviewId);

            return(dto);
        }
Beispiel #29
0
        public async Task <ActionResult> Create([FromBody] CommentCreateModel commentModel)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(new ResponseModel(400, "Invalid value was entered! Please, redisplay form.")));
            }

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

            commentDto.AuthorId = this.GetCurrentUserId();

            var result = await _commentService.CreateAsync(commentDto);

            return(result.Succeeded
                ? Ok(new ResponseModel(200, "Completed.", "Comment created."))
                : (ActionResult)BadRequest(new ResponseModel(400, "Failed.", result.Error)));
        }
Beispiel #30
0
        public async Task <IHttpActionResult> Add([FromBody] CommentCreateModel model)
        {
            if (model.EntityType.Is(IntranetEntityTypeEnum.Social, IntranetEntityTypeEnum.News, IntranetEntityTypeEnum.Events))
            {
                var member = await _intranetMemberService.GetCurrentMemberAsync();

                var activityGroupId = _groupActivityService.GetGroupId(model.EntityId);

                if (activityGroupId.HasValue)
                {
                    var group = _groupService.Get(activityGroupId.Value);
                    if (group == null || group.IsHidden)
                    {
                        return(StatusCode(HttpStatusCode.Forbidden));
                    }
                }

                if (activityGroupId.HasValue && !member.GroupIds.Contains(activityGroupId.Value))
                {
                    return(StatusCode(HttpStatusCode.Forbidden));
                }
            }

            var createDto = await MapToCreateDtoAsync(model, model.EntityId);

            var command = new AddCommentCommand(model.EntityId, model.EntityType, createDto);

            _commandPublisher.Publish(command);

            await OnCommentCreatedAsync(createDto.Id, model.EntityType);

            switch (model.EntityType)
            {
            case IntranetEntityTypeEnum type
                when type.Is(IntranetEntityTypeEnum.News, IntranetEntityTypeEnum.Social, IntranetEntityTypeEnum.Events):
                var activityCommentsInfo = GetActivityComments(model.EntityId);

                return(Ok(await _commentsHelper.OverViewAsync(activityCommentsInfo.Id, activityCommentsInfo.Comments, activityCommentsInfo.IsReadOnly)));

            default:
                return(Ok(await _commentsHelper.OverViewAsync(model.EntityId)));
            }
        }
        private void ValidateCommentCreateModel(CommentCreateModel model)
        {
            if (model == null)
            {
                throw new ServerErrorException(
                    "Comment cannot be null",
                    HttpStatusCode.BadRequest);
            }

            if (string.IsNullOrEmpty(model.Text))
            {
                throw new ServerErrorException(
                    "Comment text must be set",
                    HttpStatusCode.BadRequest);
            }
        }