コード例 #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);
        }
コード例 #2
0
        public async Task Post_comments()
        {
            var svc = new CommentService(DbContext, Mapper, null);
            var dto = new PostCommentDto
            {
                Content   = Guid.NewGuid().ToString(),
                Name      = Guid.NewGuid().ToString(),
                ArticleId = 1,
                Code      = "1234",
                Email     = "*****@*****.**",
                IPv4      = "localhost:123"
            };
            await svc.CreateAsync(dto);

            var result = await DbContext.Comments.FirstOrDefaultAsync();

            Assert.AreEqual(dto.Content, result.Content);
            Assert.AreEqual(dto.ArticleId, result.ArticleId);
            Assert.AreEqual(dto.Name, result.Name);
            Assert.AreEqual(DateTimeOffset.Now.ToString("yyyy-MM-dd"), result.CreateTime.ToString("yyyy-MM-dd"));
            Assert.AreEqual(dto.Email, result.Email);
            Assert.AreEqual(1, result.Id);
            Assert.AreEqual("localhost:123", result.IPv4);
            Assert.AreEqual(BaseStatus.Enabled, result.Status);
        }
コード例 #3
0
        public async Task PostAsync(PostCommentDto dto)
        {
            var builder  = new StringBuilder();
            var pipeline = new MarkdownPipelineBuilder()
                           .UsePipeTables()
                           .Build();

            builder.Append(Markdown.ToHtml(dto.Content, pipeline));
            string link = _configuration["Comment:EmailNotification:LinkPrefix"] + dto.ArticleId;

            builder.AppendLine($"<br /> <a href=\"{link}\">{link}</a>");
            var message = new MimeMessage();

            message.From.Add(new MailboxAddress(_configuration["Email:NetEase126:Account"]));
            message.To.Add(new MailboxAddress(_configuration["Comment:EmailNotification:ToAddress"]));
            message.Subject = "doghappy.wang 有新评论了";
            message.Body    = new TextPart(TextFormat.Html)
            {
                Text = builder.ToString()
            };
            using var client = new SmtpClient
                  {
                      ServerCertificateValidationCallback = (s, c, h, e) => true
                  };
            await client.ConnectAsync(_configuration["Email:NetEase126:Host"]);

            await client.AuthenticateAsync(_configuration["Email:NetEase126:Account"], _configuration["Email:NetEase126:Password"]);

            await client.SendAsync(message);

            await client.DisconnectAsync(true);
        }
コード例 #4
0
        public Message CommentOnPost(string id, string comment)
        {
            SvcContext ctx = InflateContext(); if (ctx.Invalid)

            {
                return(ctx.ContextMessage);
            }

            try
            {
                var postID = Guid.ParseExact(id, "N");
                var post   = postSvc.GetPostByID(postID);
                var com    = postSvc.CreateComment(post, comment);

                var profile = CfPerfCache.GetClimber(CfIdentity.UserID);

                var dto = new PostCommentDto(com, profile);

                return(ReturnAsJson(dto));
            }
            catch (Exception ex)
            {
                return(Failed("Comment failed : " + ex.Message));
            }
        }
コード例 #5
0
        public async Task <ActionResult <PostCommentDto> > AddComment(string userId, string postId, [FromBody] PostCommentToAddDto postComment)
        {
            if (Guid.TryParse(postId, out Guid gPostId) && Guid.TryParse(userId, out Guid gUserId))
            {
                try
                {
                    if (_postService.CheckIfPostExists(gPostId) && await _userService.CheckIfUserExists(gUserId))
                    {
                        PostCommentDto addedComment = await _postCommentService.AddCommentAsync(gPostId, postComment);

                        return(CreatedAtRoute("GetComment",
                                              new
                        {
                            userId,
                            postId = addedComment.PostId,
                            commentId = addedComment.Id
                        },
                                              addedComment));
                    }
                    else
                    {
                        return(NotFound($"User: {userId} or post {postId} not found."));
                    }
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "Error occured during adding the comment. Post id: {postId}", postId);
                    return(StatusCode(StatusCodes.Status500InternalServerError));
                }
            }
            else
            {
                return(BadRequest($"{userId} or {postId} is not valid guid."));
            }
        }
コード例 #6
0
        public async Task <PostCommentDto> AddPostComment(int postId, int authorId, string comment,
                                                          int?parentId = null, int?approvedByAuthorId = null)
        {
            Author commentAuthor = Context.Author.Find(authorId);

            if (commentAuthor == null)
            {
                throw new ArgumentException("Invalid authorId");
            }

            PostComment newPostComment = new PostComment()
            {
                PostId             = postId,
                AuthorId           = authorId,
                Comment            = comment,
                ApprovedByAuthorId = approvedByAuthorId,
                ParentId           = parentId,
            };

            Context.PostComment.Add(newPostComment);
            await Context.SaveChangesAsync();

            PostCommentDto dto = newPostComment.Adapt <PostCommentDto>();

            dto.AuthorAlias = commentAuthor.Alias;

            return(dto);
        }
コード例 #7
0
        public async Task CorrectCodePostTest()
        {
            var mockCommentNotificationPostman = new Mock <ICommentNotificationPostman>();
            var svc = new CommentService(DbContext, Mapper, mockCommentNotificationPostman.Object);
            var mockISessionBasedCaptcha = new Mock <ISessionBasedCaptcha>();

            mockISessionBasedCaptcha
            .Setup(m => m.ValidateCaptchaCode(It.IsAny <string>(), It.IsAny <ISession>(), It.IsAny <bool>(), It.IsAny <bool>()))
            .Returns(true);
            var mockSession = new Mock <ISession>();
            var mockRequest = new Mock <HttpRequest>();

            mockRequest
            .SetupGet(m => m.Host)
            .Returns(new HostString("192.168.1.11"));
            var mockHttpContext = new Mock <HttpContext>();

            mockHttpContext
            .SetupGet(m => m.Session)
            .Returns(mockSession.Object);
            mockHttpContext
            .SetupGet(m => m.Request)
            .Returns(mockRequest.Object);

            using var controller = new CommentController(svc, mockISessionBasedCaptcha.Object)
                  {
                      ControllerContext = new ControllerContext
                      {
                          HttpContext = mockHttpContext.Object,
                      }
                  };

            var dto = new PostCommentDto
            {
                Content   = "Content",
                Email     = "Email",
                ArticleId = 466
            };

            var actionResult = await controller.Post(dto);

            var redirectResult = actionResult as RedirectToActionResult;
            var entity         = DbContext.Comments.First();

            Assert.IsNotNull(redirectResult);
            Assert.AreEqual("Detail", redirectResult.ActionName);
            Assert.AreEqual("Article", redirectResult.ControllerName);
            Assert.AreEqual("466", redirectResult.RouteValues["id"].ToString());

            Assert.AreEqual(466, entity.ArticleId);
            Assert.AreEqual("Content", entity.Content);
            Assert.AreEqual("Email", entity.Email);

            mockISessionBasedCaptcha.Verify(m => m.ValidateCaptchaCode(It.IsAny <string>(), It.IsAny <ISession>(), It.IsAny <bool>(), It.IsAny <bool>()), Times.Once());
            await Task.Delay(200);

            mockCommentNotificationPostman.Verify(m => m.PostAsync(It.IsAny <PostCommentDto>()), Times.Once());
        }
コード例 #8
0
        public async Task <IEnumerable <PostCommentDto> > GetAllMainByPostIdAsync(int postId,
                                                                                  int userId)
        {
            var posts = await _repository
                        .MainComment
                        .GetAllByPostIdAsync(postId, PostCommentDto.Selector(userId));

            return(posts);
        }
コード例 #9
0
        public async Task <ActionResult <PostCommentDto> > PostComment(PostCommentDto record)
        {
            if (record == null)
            {
                return(BadRequest());
            }

            var userId = GetUserId();

            var userRecord = await context.Set <User>().FindAsync(userId);

            var postRecord = await context.Set <Post>().FindAsync(record.PostId);

            if (userRecord == null || postRecord == null)
            {
                return(BadRequest());
            }

            var entity = new PostComment
            {
                Post      = postRecord,
                Author    = userRecord,
                DateAdded = DateTime.UtcNow,
                Content   = record.Content
            };

            context.Set <PostComment>().Add(entity);

            try
            {
                await context.SaveChangesAsync();

                return(Ok(new PostCommentDto
                {
                    Id = entity.Id,
                    AuthorName = entity.Author.Name,
                    Content = entity.Content,
                    DateAdded = entity.DateAdded,
                    IsAuthor = true
                }));
            }
            catch (DbUpdateException ex)
            {
                Logger.Log($"{nameof(PostsController)} {nameof(DeleteComment)}", ex.Message, NLog.LogLevel.Warn, ex);

                return(BadRequest());
            }
            catch (Exception ex)
            {
                Logger.Log($"{nameof(PostsController)} {nameof(DeleteComment)}", ex.Message, NLog.LogLevel.Warn, ex);

                return(BadRequest());
            }
        }
コード例 #10
0
ファイル: CommentService.cs プロジェクト: doghappy/HappyDog
        public async Task <CommentDto> CreateAsync(PostCommentDto dto)
        {
            var comment = _mapper.Map <Comment>(dto);

            comment.CreateTime = DateTimeOffset.Now;
            comment.Status     = BaseStatus.Enabled;
            await _db.Comments.AddAsync(comment);

            await _db.SaveChangesAsync();

            await Task.Factory.StartNew(async() => await _commentNotificationPostman.PostAsync(dto));

            return(_mapper.Map <CommentDto>(comment));
        }
コード例 #11
0
        public async Task ErrorCodePostTest()
        {
            var mockCommentNotificationPostman = new Mock <ICommentNotificationPostman>();
            var svc = new CommentService(DbContext, Mapper, mockCommentNotificationPostman.Object);
            var mockISessionBasedCaptcha = new Mock <ISessionBasedCaptcha>();

            mockISessionBasedCaptcha
            .Setup(m => m.ValidateCaptchaCode(It.IsAny <string>(), It.IsAny <ISession>(), It.IsAny <bool>(), It.IsAny <bool>()))
            .Returns(false);
            var mockSession     = new Mock <ISession>();
            var mockHttpContext = new Mock <HttpContext>();

            mockHttpContext
            .SetupGet(m => m.Session)
            .Returns(mockSession.Object);
            var mockTempData = new Mock <ITempDataDictionary>();

            using var controller = new CommentController(svc, mockISessionBasedCaptcha.Object)
                  {
                      ControllerContext = new ControllerContext
                      {
                          HttpContext = mockHttpContext.Object
                      },
                      TempData = mockTempData.Object
                  };

            var dto = new PostCommentDto
            {
                Content   = Guid.NewGuid().ToString(),
                Email     = Guid.NewGuid().ToString(),
                ArticleId = 466
            };

            var actionResult = await controller.Post(dto);

            var redirectResult = actionResult as RedirectToActionResult;

            Assert.IsNotNull(redirectResult);
            Assert.AreEqual("Detail", redirectResult.ActionName);
            Assert.AreEqual("Article", redirectResult.ControllerName);
            Assert.AreEqual("466", redirectResult.RouteValues["id"].ToString());

            mockISessionBasedCaptcha.Verify(m => m.ValidateCaptchaCode(It.IsAny <string>(), It.IsAny <ISession>(), It.IsAny <bool>(), It.IsAny <bool>()), Times.Once());
        }
コード例 #12
0
        public async Task <IActionResult> Post(PostCommentDto dto)
        {
            if (ModelState.IsValid)
            {
                if (_captcha.ValidateCaptchaCode(dto.Code, HttpContext.Session))
                {
                    dto.IPv4 = Request.Host.ToString();
                    await _commentService.CreateAsync(dto);

                    return(RedirectToAction("Detail", "Article", new { id = dto.ArticleId }));
                }
                else
                {
                    TempData["ErrorCaptcha"] = true;
                }
            }
            TempData.Put("ErrorModel", dto);
            return(RedirectToAction("Detail", "Article", new { id = dto.ArticleId }));
        }
コード例 #13
0
        public void BlogPostCRUD()
        {
            Task.Run(async() =>
            {
                int primaryAuthorId = 1;
                string blogName01   = "testBlog01";

                var blogThatShouldNotBe = _blogRqs.GetBlog(blogName01);
                if (blogThatShouldNotBe != null)
                {
                    await _blogCmds.DeleteBlogAsync(blogThatShouldNotBe.Id);
                }

                List <string> tags = new List <string>()
                {
                    "Programming", "Art"
                };
                BlogDto blogDto = new BlogDto()
                {
                    Name            = blogName01,
                    DisplayName     = "My Test Blog",
                    BlogStatusId    = (int)BlogStatuses.Draft,
                    PrimaryAuthorId = 1
                };
                blogDto.Tags.AddRange(tags);
                await _blogCmds.AddBlogAsync(blogDto);

                List <string> postTags = new List <string>()
                {
                    "PostTag01", "PostTag02", "PostTag03", "PostTag04", "PostTag05"
                };
                BlogPostDto blogPost = new BlogPostDto()
                {
                    BlogId          = blogDto.Id,
                    CommentStatusId = (int)CommentStatuses.MemberOnly,
                    PrimaryAuthorId = primaryAuthorId,
                    PostStatusId    = (int)PostStatuses.Draft,
                    Title           = "My Test Blog01 Post Title",
                    PostContent     = "Here's my first blog post content.",
                    Excerpt         = "Test excerpt content.",
                };
                blogPost.Tags.AddRange(postTags);
                BlogPostDto testPost01 = await _blogCmds.AddBlogPostAsync(blogPost);
                Assert.IsTrue(testPost01.Id > 0);

                testPost01.PostContent  = "Here's my first blog post with updated content.";
                testPost01.PostStatusId = (int)PostStatuses.Draft;
                testPost01.Excerpt      = "Updated test excerpt";

                PostCommentDto firstComment   = await _blogCmds.AddPostComment(testPost01.Id, primaryAuthorId, "A wanted to add a few test comments.");
                PostCommentDto secondsComment = await _blogCmds.AddPostComment(testPost01.Id, primaryAuthorId, "This is a second test comment.");
                PostCommentDto subComment     = await _blogCmds.AddPostComment(testPost01.Id, primaryAuthorId, "This is a sub comment for the second test comment.", secondsComment.Id);

                BlogPostDto testPost02 = await _blogCmds.AddBlogPostAsync(new BlogPostDto()
                {
                    BlogId          = blogDto.Id,
                    PrimaryAuthorId = primaryAuthorId,
                    PostStatusId    = (int)PostStatuses.Draft,
                    Title           = "My Test Blog01 Second Post Title",
                    PostContent     = "Here's my second blog post content.",
                    Excerpt         = "Second test excerpt content.",
                });
                testPost02.Tags.AddRange(postTags);
                Assert.IsTrue(testPost01.Id > 0);

                //await _blogMng.ApprovePostComment()

                var blogPostListItem = await _blogRqs.GetAllBlogPostsAsync(blogDto.Id);
                Assert.IsTrue(blogPostListItem.Count() > 1);
                int numberOfPosts          = 0;
                BlogPostsFilter blogFilter = new BlogPostsFilter()
                {
                    BlogId = blogDto.Id, Skip = 0, Take = 1
                };
                blogFilter.SortMembers.Add(new Data.Helpers.SortDescriptor("UpdatedAt", System.ComponentModel.ListSortDirection.Ascending));
                var blogPosts = _blogRqs.GetBlogPostsAsync(out numberOfPosts, blogFilter);
                Assert.IsTrue(blogPosts.Count() == 1);

                var myTestPost = await _blogRqs.GetPostAsync(testPost01.Id);

                await _blogCmds.DeletePostAsync(testPost01.Id);
                await _blogCmds.DeletePostAsync(testPost02.Id);

                await _blogCmds.DeleteBlogAsync(blogDto.Id);
                BlogDto blog = _blogRqs.GetBlog(blogDto.Id);
                Assert.IsNull(blog);
            }).GetAwaiter().GetResult();
        }
コード例 #14
0
 public async Task AddCommentAsync(PostCommentDto comment)
 {
     var result = mapper.Map <PostComment>(comment);
     await _ctx.PostComment.AddAsync(result);
 }