示例#1
0
        public async Task <IActionResult> CreateComment([FromBody] CreateComment newComment)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return(Json(new { IsSuccess = false, Message = "" }));
                }
                else
                {
                    var currentUser = _userRepository.GetByIdAsync(_userAppContext.CurrentUserId);

                    var author = new UserViewModel
                    {
                        Id              = currentUser.Id,
                        NickName        = currentUser.NickName,
                        ProfileImageUrl = currentUser.ProfileImageUrl,
                        WalletAddress   = currentUser.WalletAddress
                    };

                    var commentCreated = await _commentService.CreateComment(newComment.PostId, newComment.Content, author);

                    return(Json(new { IsSuccess = true, Topic = commentCreated }));
                }
            }
            catch (Exception e)
            {
                return(Json(new { IsSuccess = false, Message = e.Message }));
            }
        }
示例#2
0
        private async Task MentionUsersAsync(CreateComment createComment)
        {
            if (!string.IsNullOrWhiteSpace(createComment.Text))
            {
                var emails = MentionRegex.Matches(createComment.Text).Select(x => x.Value.Substring(1)).ToArray();

                if (emails.Length > 0)
                {
                    var mentions = new List <string>();

                    foreach (var email in emails)
                    {
                        var user = await userResolver.FindByIdOrEmailAsync(email);

                        if (user != null)
                        {
                            mentions.Add(user.Id);
                        }
                    }

                    if (mentions.Count > 0)
                    {
                        createComment.Mentions = mentions.ToArray();
                    }
                }
            }
        }
        public async Task <ActionResult> AddComment(CreateComment model)
        {
            if (!ModelState.IsValid)
            {
                return(Content("false"));
            }
            var com = new ComD {
                Content = model.Content
            };

            com.Date       = DateTime.Now;
            com.Author     = userrepo.GetElement(User.Identity.Name);
            com.Discussion = repo.GetElements().First(x => x.Id == model.PostID);
            com.Kind       = model.Side;
            dynamic response = await MyClient.ConnectWithAPI(model.Content);

            if ((bool)response.Passed)
            {
                if (repo.CreateComment(com))
                {
                    return(Json(new { error = "", success = true, response = JsonConvert.SerializeObject(response) }));
                }
                else
                {
                    return(Json(new { error = "Base", success = false, response = JsonConvert.SerializeObject(response) }));
                }
            }
            else
            {
                return(Json(new { error = "NotPassed", success = false, response = JsonConvert.SerializeObject(response) }));
            }
        }
示例#4
0
        public async Task Create_should_create_events()
        {
            var command = new CreateComment {
                Text = "text1"
            };

            var result = await sut.ExecuteAsync(CreateCommentsCommand(command));

            result.ShouldBeEquivalent(EntityCreatedResult.Create(command.CommentId, 0));

            sut.GetCommentsAsync(0).Result.Should().BeEquivalentTo(new CommentsResult {
                Version = 0
            });
            sut.GetCommentsAsync(-1).Result.Should().BeEquivalentTo(new CommentsResult
            {
                CreatedComments = new List <Comment>
                {
                    new Comment(command.CommentId, LastEvents.ElementAt(0).Headers.Timestamp(), command.Actor, "text1")
                },
                Version = 0
            });

            LastEvents
            .ShouldHaveSameEvents(
                CreateCommentsEvent(new CommentCreated {
                CommentId = command.CommentId, Text = command.Text
            })
                );
        }
示例#5
0
        public async Task <IActionResult> Comment(NewsCommentViewModel vm,
                                                  [FromServices] GetOneNews getOneNews,
                                                  [FromServices] CreateComment createComment)
        {
            if (!ModelState.IsValid)
            {
                var singleNews = getOneNews.Do(vm.NewsId);
                return(RedirectToAction("SingleNewsDisplay", new { id = singleNews.Id }));
            }

            var news = getOneNews.Do(vm.NewsId);

            if (vm.NewsMainCommentId == 0)
            {
                await createComment.CreateMainComment(new CreateComment.MainCommentRequest
                {
                    OneNewsId = news.Id,
                    Created   = DateTime.Now,
                    Creator   = "",
                    Message   = vm.Message,
                });
            }
            else
            {
                await createComment.CreateSubComment(new CreateComment.SubCommentRequest
                {
                    NewsMainCommentId = vm.NewsMainCommentId,
                    Created           = DateTime.Now,
                    Creator           = "",
                    Message           = vm.Message,
                });
            }

            return(RedirectToAction("SingleNewsDisplay", new { id = news.Id }));
        }
示例#6
0
 public int Add(CreateComment prod)
 {
     using (IDbConnection dbConnection = Connection)
     {
         return(dbConnection.Execute(CommentQueries.Add, prod));
     }
 }
示例#7
0
        public void CanCreate_should_throw_exception_if_text_not_defined()
        {
            var command = new CreateComment();

            ValidationAssert.Throws(() => GuardComments.CanCreate(command),
                                    new ValidationError("Text is required.", "Text"));
        }
        public NormalAnswer CreateComment(CreateComment input, int userId)
        {
            if (input.postId >= 0 && !GetWholePost(input.postId).success)
            {
                return(new NormalAnswer(false, "Post not found", 404));
            }

            var command = new SQLiteCommand(this.connection);

            command.CommandText = "INSERT INTO comment (userId, superPostId, superCommentId, text) " +
                                  $"VALUES ({userId}, {input.postId}, {input.commentId}, '{input.text}');";

            if (command.ExecuteNonQuery() > 0)
            {
                command.CommandText = "select last_insert_rowid()";
                int id = (int)((Int64)command.ExecuteScalar());

                var comment = GetComment(id);

                if (comment != null)
                {
                    return(new ComplexAnswer(true, "successful", 200, comment));
                }
            }
            return(new NormalAnswer(false, "internal server error [sql]", 500));
        }
示例#9
0
        public async Task Create_should_create_events()
        {
            var command = new CreateComment {
                Text = "text1", Url = new Uri("http://uri")
            };

            var result = await sut.ExecuteAsync(CreateCommentsCommand(command));

            result.ShouldBeEquivalent((object)EntityCreatedResult.Create(command.CommentId, 0));

            sut.GetCommentsAsync(0).Result.Should().BeEquivalentTo(new CommentsResult {
                Version = 0
            });
            sut.GetCommentsAsync(-1).Result.Should().BeEquivalentTo(new CommentsResult
            {
                CreatedComments = new List <Comment>
                {
                    new Comment(command.CommentId, GetTime(), command.Actor, "text1", command.Url)
                },
                Version = 0
            });

            LastEvents
            .ShouldHaveSameEvents(
                CreateCommentsEvent(new CommentCreated {
                Text = command.Text, Url = command.Url
            })
                );
        }
示例#10
0
        public void CanCreate_should_not_throw_exception_if_text_defined()
        {
            var command = new CreateComment {
                Text = "text"
            };

            GuardComments.CanCreate(command);
        }
示例#11
0
        public static CommentDto FromCommand(CreateComment command)
        {
            var time = SystemClock.Instance.GetCurrentInstant();

            return(SimpleMapper.Map(command, new CommentDto {
                Id = command.CommentId, User = command.Actor, Time = time
            }));
        }
示例#12
0
        public async Task <IActionResult> Post([FromBody] CreateComment model)
        {
            var entity = model.MapEntity(model, await _commentService.GetAuthorId(model.AuthorUsername));

            var createdResult = await _commentService.CreateCommentAsync(entity);

            return(new JsonResult(createdResult));
        }
示例#13
0
 public bool Add(CreateComment comment)
 {
     if (_commentRepository.Add(comment) != 0)
     {
         return(true);
     }
     return(false);
 }
示例#14
0
 public IActionResult CreateComment(CreateComment newComment)
 {
     if (ModelState.IsValid)
     {
         string sql = $@"INSERT INTO comments(comment, user_id, created_at, updated_at, message_id) VALUES ('{newComment.comment}', '{HttpContext.Session.GetInt32("user_id")}', NOW(), NOW(), '{newComment.message_id}')";
         DbConnector.Execute(sql);
     }
     return(RedirectToAction("dashboard"));
 }
示例#15
0
 public IActionResult Post([FromBody] CreateComment value)
 {
     if (ModelState.IsValid)
     {
         if (_commentService.Add(value))
         {
             return(Ok());
         }
     }
     return(BadRequest());
 }
示例#16
0
        public static void CanCreate(CreateComment command)
        {
            Guard.NotNull(command, nameof(command));

            Validate.It(() => "Cannot create comment.", e =>
            {
                if (string.IsNullOrWhiteSpace(command.Text))
                {
                    e(Not.Defined("Text"), nameof(command.Text));
                }
            });
        }
示例#17
0
        public static void CanCreate(CreateComment command)
        {
            Guard.NotNull(command);

            Validate.It(e =>
            {
                if (string.IsNullOrWhiteSpace(command.Text))
                {
                    e(Not.Defined(nameof(command.Text)), nameof(command.Text));
                }
            });
        }
示例#18
0
        public virtual async Task <IActionResult> Comment(CreateComment model)
        {
            string userId = User.GetUserId();
            await service.CreateCommmentAsync(model.ImageId, model.Description, userId);

            //Get last page to show new comment
            var serviceResult = await service.GetImageCommentsAsync(model.ImageId, 20000000, settings.CommentsPageSize);

            var viewModel = mapper.Map <CommentViewModel>(serviceResult);

            viewModel.ImageId = model.ImageId;
            return(View(viewModel));
        }
        public async Task Should_not_enrich_with_mentioned_user_ids_for_notification()
        {
            var command = new CreateComment
            {
                Text = "Hi @[email protected]", IsMention = true
            };

            var context = CreateContextForCommand(command);

            await sut.HandleAsync(context);

            A.CallTo(() => userResolver.FindByIdOrEmailAsync(A <string> .Ignored))
            .MustNotHaveHappened();
        }
        public async Task <IActionResult> CreateCommentAsync(Guid postId, [FromBody] CreateComment request)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }
            var comment = new Comment
            {
                Body   = request.Body,
                PostId = postId
            };
            await _repo.CreateCommentAsync(postId, comment);

            return(Created(nameof(Route.CommentsCreate), comment));
        }
示例#21
0
        //get post comments

        //post comment
        public bool CreateComment(CreateComment model)
        {
            var entity =
                new Comment()
            {
                CommentId = _commentId,
                Text      = model.Text
            };

            using (var ctx = new ApplicationDbContext())
            {
                ctx.Comment.Add(entity);
                return(ctx.SaveChanges() == 1);
            }
        }
        public IHttpActionResult Post(CreateComment comment)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var service = CreateCommentService();

            if (!service.CreateComment(comment))
            {
                return(InternalServerError());
            }

            return(Ok());
        }
示例#23
0
        public async Task Delete_should_create_events_and_update_state()
        {
            var createCommand = new CreateComment {
                Text = "text1"
            };
            var updateCommand = new UpdateComment {
                Text = "text2", CommentId = createCommand.CommentId
            };
            var deleteCommand = new DeleteComment {
                CommentId = createCommand.CommentId
            };

            await sut.ExecuteAsync(CreateCommentsCommand(createCommand));

            await sut.ExecuteAsync(CreateCommentsCommand(updateCommand));

            var result = await sut.ExecuteAsync(CreateCommentsCommand(deleteCommand));

            result.ShouldBeEquivalent(new EntitySavedResult(2));

            sut.GetCommentsAsync(-1).Result.Should().BeEquivalentTo(new CommentsResult {
                Version = 2
            });
            sut.GetCommentsAsync(0).Result.Should().BeEquivalentTo(new CommentsResult
            {
                DeletedComments = new List <Guid>
                {
                    deleteCommand.CommentId
                },
                Version = 2
            });
            sut.GetCommentsAsync(1).Result.Should().BeEquivalentTo(new CommentsResult
            {
                DeletedComments = new List <Guid>
                {
                    deleteCommand.CommentId
                },
                Version = 2
            });

            LastEvents
            .ShouldHaveSameEvents(
                CreateCommentsEvent(new CommentDeleted {
                CommentId = createCommand.CommentId
            })
                );
        }
示例#24
0
        public static String CreateComment(IExecuteSystem es, String owner, String photo, String message,
                                           List <String> attaches = null, Boolean?fromGroup = null, String replyToComment = null,
                                           String stickerId       = null)
        {
            var method = new CreateComment
            {
                OwnerId        = owner,
                PhotoId        = photo,
                Message        = message,
                Attachments    = attaches,
                FromGroup      = fromGroup,
                ReplyToComment = replyToComment,
                StickerId      = stickerId
            };

            return(es.Execute(method));
        }
示例#25
0
        public async Task <IActionResult> AddAsync([FromBody] CreateComment newComment)
        {
            try
            {
                var commentId = await _postCommentService.AddAsync(User.GetUserId(), newComment.PostId, newComment.Content);

                return(Created($"comments/post/{newComment.PostId}/comment/{commentId}", null));
            }
            catch (Exception e)
            {
                _logger.LogError($"Returning exception: {e.Message}");
                return(Json(new ExceptionDto
                {
                    Error = e.Message
                }));
            }
        }
示例#26
0
        private async Task <OperationResult <int> > Delete(CreateComment item)
        {
            using (TransactionScope scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
            {
                var comment = await commentRepo.GetByIdAsync(item.id);

                if (comment == null)
                {
                    return new OperationResult <int>()
                           {
                               Success = false, Message = Messages.COMMENT_NOT_EXIST
                           }
                }
                ;
                if (comment.authorId != item.authorId)
                {
                    return new OperationResult <int>()
                           {
                               Success = false, Message = Messages.USER_NO_COMMENT
                           }
                }
                ;

                try
                {
                    var id = await commentRepo.DeleteAsync(comment);

                    scope.Complete();
                    return(new OperationResult <int>()
                    {
                        Success = true, Message = Messages.COMMENT_DELETED, Result = id
                    });
                }
                catch (Exception ex)
                {
                    return(new OperationResult <int>()
                    {
                        Success = false, Message = ex.Message
                    });
                }
            }
        }
    }
}
示例#27
0
        public async Task <OperationResult <comment> > PostCommentOnEvent(CreateComment item)
        {
            using (TransactionScope scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
            {
                if (!item.ParameterValid())
                {
                    return new OperationResult <comment>()
                           {
                               Success = false, Message = Messages.PARAMETERS_NOT_NULL
                           }
                }
                ;
                item.initialDate = DateTime.Now;
                var eventRes = await eventService.GetByIdAsync(item.eventId);

                if (!eventRes.Success)
                {
                    return new OperationResult <comment>()
                           {
                               Success = false, Message = eventRes.Message
                           }
                }
                ;

                try
                {
                    var newComment = await commentRepo.PostAsyncV2(item);

                    scope.Complete();
                    return(new OperationResult <comment>()
                    {
                        Success = true, Message = Messages.COMMENT_CREATED, Result = newComment
                    });
                }
                catch (Exception ex)
                {
                    return(new OperationResult <comment>()
                    {
                        Success = false, Message = ex.Message
                    });
                }
            }
        }
示例#28
0
        public ActionResult <Comment> CreateCommentInPost([FromRoute(Name = "post_id")] int postId,
                                                          CreateComment createComment)
        {
            var post    = GetPost(postId);
            var comment = new Comment
            {
                Author      = GetAuthorizedUser(),
                ParentPost  = post,
                ParentResub = post.ParentResub,
                Content     = createComment.Content,
                Created     = DateTime.UtcNow
            };

            Db.Comments.Add(comment);
            Db.SaveChanges();
            Db.Entry(comment).Collection(c => c.Votes).Load();

            return(CreatedAtRoute("GetComment", new { comment_id = comment.Id }, comment));
        }
示例#29
0
        public async Task <ActionResult <CommentModel> > AddComment(string blogId, [FromBody] CreateComment commentRequest)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            await _commentService.GetCurrentBlogAsync(blogId);

            var commentMapper = _mapper.Map <CreateComment, UpdateCommentRequest>(commentRequest);

            commentMapper.UserName = HttpContext.User.Identity.Name;

            var comment = await _commentService.CreateCommentAsync(commentMapper);

            var uri = $"/comments/{comment.CreatedOn.ToString("MM/dd/yyyy/HH:mm:ss.fff")}";

            return(Created(uri, comment));
        }
 public bool CreateComment(CreateComment model)
 {
     using (var ctx = new ApplicationDbContext())
     {
         bool isValid = int.TryParse(model.PostId, out int id);
         if (!isValid)
         {
             id = 0;
         }
         var entity = new Comment()
         {
             Author  = _userId,
             Content = model.Content,
             PostId  = id,
         };
         ctx.Comments.Add(entity);
         return(ctx.SaveChanges() == 1);
     }
 }