public void Should_Update_Comment() { var sampleUser = GetRandomUserName(); var sampleUserWall = GetRandomUserWallOwner(true); var sampleCommentUser = GetRandomUserName(); var request = GetSampleWallCreateRequest(sampleUser, sampleUserWall); var samplePostId = wallPostProvider.AddPost(request); var commentCreateRequest = new CommentCreateRequest { Body = "TestComment", CreatedBy = sampleCommentUser, WallPostId = samplePostId }; var commentId = commentProvider.AddComment(commentCreateRequest); var commentUpdateRequest = new CommentUpdateRequest { CommentId = commentId, PostId = samplePostId, Body = "UpdatedComment" }; commentProvider.UpdateComment(commentUpdateRequest); var postComments = commentProvider.GetComments(samplePostId, 0, 100); var spesificComment = commentProvider.GetComment(samplePostId, commentId); var shouldBeEqual = string.Equals(spesificComment.Body, commentUpdateRequest.Body, StringComparison.OrdinalIgnoreCase); var shouldExist = postComments.Any(c => c.Id == commentId && c.ModifiedDate.HasValue && c.Body == commentUpdateRequest.Body); Assert.IsTrue(shouldExist); }
private void SaveButton_Click(object sender, EventArgs e) { var commentProvider = new CommentProvider(); var request = new CommentCreateRequest(); request.Body = CommentBodyTextBox.Text; request.CreatedBy = FormHelper.Username; request.WallPostId = FormId; commentProvider.AddComment(request); var feedProvider = new NewsfeedProvider(); var newsFeedEntry = new NewsfeedItem { By = FormHelper.Username, ReferencePostId = FormId, FeedType = NewsfeedActionType.comment, WallOwner = new Core.Models.Wall.NewsfeedWallModel { IsPublic = true, OwnerId = FormHelper.Username, WallOwnerType = Core.Models.Wall.WallType.user } }; feedProvider.AddNewsfeedItem(newsFeedEntry); this.Close(); }
public void Should_Remove_Comment_From_WallPost() { var sampleUser = GetRandomUserName(); var sampleUserWall = GetRandomUserWallOwner(true); var sampleCommentUser = GetRandomUserName(); var request = GetSampleWallCreateRequest(sampleUser, sampleUserWall); var samplePostId = wallPostProvider.AddPost(request); var commentCreateRequest = new CommentCreateRequest { Body = "TestComment", CreatedBy = sampleCommentUser, WallPostId = samplePostId }; var commentId = commentProvider.AddComment(commentCreateRequest); var postComments = commentProvider.GetComments(samplePostId, 0, 100); var shouldExist = postComments.Any(c => c.Id == commentId && c.CreatedBy == sampleCommentUser); Assert.IsTrue(shouldExist); commentProvider.DeleteComment(samplePostId, commentId); postComments = commentProvider.GetComments(samplePostId, 0, 100); var shouldNotExist = postComments.Any(c => c.Id == commentId && c.CreatedBy == sampleCommentUser); Assert.IsFalse(shouldNotExist); }
public ReviewViewModel Post(ReviewCreateRequest request) { var commentCreateRequest = new CommentCreateRequest() { Captcha = request.Captcha, CustomData = request.CustomData, Email = request.Email, Message = request.Message, Name = request.Name, Rating = request.Rating, Thread = request.Thread, ThreadKey = request.ThreadKey }; var commentResponse = this.PostInternal(commentCreateRequest); var result = new ReviewViewModel() { AuthorIpAddress = commentResponse.AuthorIpAddress, CustomData = commentResponse.CustomData, DateCreated = commentResponse.DateCreated, Email = commentResponse.Email, Key = commentResponse.Key, Message = commentResponse.Message, Name = commentResponse.Name, ProfilePictureThumbnailUrl = commentResponse.ProfilePictureThumbnailUrl, ProfilePictureUrl = commentResponse.ProfilePictureUrl, Rating = commentResponse.Rating, Status = commentResponse.Status, ThreadKey = commentResponse.ThreadKey }; return result; }
public async Task <IActionResult> PostComment(int knowledgeBaseId, [FromBody] CommentCreateRequest request) { var comment = new Comment() { Content = request.Content, KnowledgeBaseId = request.KnowledgeBaseId, OwnwerUserId = string.Empty /*TODO: GET USER FROM CLAIM*/, }; _context.Comments.Add(comment); var knowledgeBase = await _context.KnowledgeBases.FindAsync(knowledgeBaseId); if (knowledgeBase != null) { return(BadRequest(new ApiBadRequestResponse($"Cannot found knowledge base with id: {knowledgeBaseId}"))); } knowledgeBase.NumberOfComments = knowledgeBase.NumberOfVotes.GetValueOrDefault(0) + 1; _context.KnowledgeBases.Update(knowledgeBase); var result = await _context.SaveChangesAsync(); if (result > 0) { return(CreatedAtAction(nameof(GetCommentDetail), new { id = knowledgeBaseId, commentId = comment.Id }, request)); } else { return(BadRequest(new ApiBadRequestResponse("Create comment failed"))); } }
/// <summary> /// Gets the author. /// </summary> /// <param name="commentData">The comment data.</param> /// <returns></returns> public static IAuthor GetAuthor(CommentCreateRequest commentData) { var authorObject = CommentsUtilitiesReflector.Reflect("GetAuthor", commentData); var author = authorObject as IAuthor; return(author); }
public ReviewViewModel Post(ReviewCreateRequest request) { var commentCreateRequest = new CommentCreateRequest() { Captcha = request.Captcha, CustomData = request.CustomData, Email = request.Email, Message = request.Message, Name = request.Name, Rating = request.Rating, Thread = request.Thread, ThreadKey = request.ThreadKey }; var commentResponse = this.PostInternal(commentCreateRequest); var result = new ReviewViewModel() { AuthorIpAddress = commentResponse.AuthorIpAddress, CustomData = commentResponse.CustomData, DateCreated = commentResponse.DateCreated, Email = commentResponse.Email, Key = commentResponse.Key, Message = commentResponse.Message, Name = commentResponse.Name, ProfilePictureThumbnailUrl = commentResponse.ProfilePictureThumbnailUrl, ProfilePictureUrl = commentResponse.ProfilePictureUrl, Rating = commentResponse.Rating, Status = commentResponse.Status, ThreadKey = commentResponse.ThreadKey }; return(result); }
public async Task <CommentViewModel> Save([FromBody] CommentCreateRequest request) { var claimsPrincipal = HttpContext.User; var user = await _userManager.GetUserAsync(claimsPrincipal); return(await _blogService.SaveComment(request, user != null)); }
public async Task <CommentViewModel> SaveComment(CommentCreateRequest request, bool isAdmin) { var blog = _dataProvider.GetBlog(); var validation = await _reCaptchaValidator.Validate(new ReCaptchaValidationRequest { Resonse = request.ReCaptchaToken, Secret = blog.CaptchaSecret }); if (!validation.success) { return(null); } var gravatarHash = _gravatarService.GetGravatarHash(request.AuthorEmail); request.Text = request.Text.Replace("\n", "<br />"); var comment = _dataProvider.CreateComment(request.PostId, request.AuthorName, request.AuthorEmail, request.Text, gravatarHash, isAdmin); if (blog.SendCommentEmail) { await _emailService.SendCommentEmail(request); } return(_mapper.Map <CommentViewModel>(comment)); }
public async Task <IActionResult> PutComment(int commentId, [FromBody] CommentCreateRequest request) { //// GET COMMENT WITH ID (KEY) var comment = await _context.Comments.FindAsync(commentId); //// IF KEY IS NOT EXIST (COMMENT IS NULL), RETURN STATUS 404 if (comment == null) { return(BadRequest(new ApiBadRequestResponse($"Cannot found comment with id: {commentId}"))); } //// IF OWNWER USER DIFFERENT CURRENT USER, RETURN STATUS 403 if (comment.OwnerUserId != User.GetUserId()) { return(Forbid()); } //// UPDATE INFORMATION AND SAVE CHANGE comment.Content = request.Content; _context.Comments.Update(comment); var result = await _context.SaveChangesAsync(); //// IF RESULT AFTER UPDATE IS GREATER THAN 0 (TRUE), RETURN STATUS 204, ELSE RETURN STATUS 400 if (result > 0) { return(NoContent()); } return(BadRequest(new ApiBadRequestResponse($"Update comment failed"))); }
public void Should_Like_And_Dislike_Comment() { var sampleUser = GetRandomUserName(); var sampleUserWall = GetRandomUserWallOwner(true); var sampleLikeUser = GetRandomUserName(); var request = GetSampleWallCreateRequest(sampleUser, sampleUserWall); var samplePostId = wallPostProvider.AddPost(request); var commentCreateRequest = new CommentCreateRequest { Body = "TestComment", CreatedBy = sampleUser, WallPostId = samplePostId }; var commentId = commentProvider.AddComment(commentCreateRequest); entryLikeProvider.LikeComment(commentId, sampleLikeUser); entryLikeProvider.LikeComment(commentId, sampleLikeUser); var likes = entryLikeProvider.GetCommentLikes(commentId); var shouldExist = likes.Contains(sampleLikeUser); var shouldExistOnce = likes.Count(l => l == sampleLikeUser) == 1; Assert.IsTrue(shouldExist && shouldExistOnce); entryLikeProvider.UnlikeComment(commentId, sampleLikeUser); likes = entryLikeProvider.GetCommentLikes(commentId); var shouldNotExist = likes.Contains(sampleLikeUser); Assert.IsFalse(shouldNotExist); }
public async Task <IActionResult> PutReport(int reportId, [FromBody] CommentCreateRequest request) { var report = await _context.Reports.FindAsync(reportId); if (report == null) { return(BadRequest(new ApiNotFoundResponse($"Cannot found report with id {reportId}"))); } if (report.ReportUserId != User.Identity.Name) { return(Forbid()); } report.Content = request.Content; _context.Reports.Update(report); var result = await _context.SaveChangesAsync(); if (result > 0) { return(NoContent()); } return(BadRequest(new ApiBadRequestResponse($"Update report failed"))); }
public long AddComment(CommentCreateRequest request) { var result = commentRepo.SaveComment(request); if (result != null && result.Id > 0) { var cacheModel = new CommentCacheModel { Body = request.Body, CommentId = result.Id, CreatedBy = request.CreatedBy, CreatedDate = result.CreatedDate, PostId = request.WallPostId }; try { commentCounterCacheRepo.Increment(cacheModel.PostId); } catch (Exception ex) { logger.Error(string.Format( "[AddComment] Error incrementing comment count for postId : {0}", cacheModel.PostId), ex); } return(result.Id); } return(0); }
public async Task <IActionResult> PostComment(int knowledgeBaseId, [FromBody] CommentCreateRequest request) { var comment = new Comment() { Content = request.Content, KnowledgeBaseId = knowledgeBaseId, OwnerUserId = User.GetUserId(), ReplyId = request.ReplyId }; _context.Comments.Add(comment); var knowledgeBase = await _context.KnowledgeBases.FindAsync(knowledgeBaseId); if (knowledgeBase == null) { return(BadRequest(new ApiBadRequestResponse($"Cannot found knowledge base with id: {knowledgeBaseId}"))); } knowledgeBase.NumberOfComments = knowledgeBase.NumberOfComments.GetValueOrDefault(0) + 1; _context.KnowledgeBases.Update(knowledgeBase); var result = await _context.SaveChangesAsync(); if (result > 0) { await _cacheService.RemoveAsync(CacheConstants.RecentComments); //Send mail if (comment.ReplyId.HasValue) { var repliedComment = await _context.Comments.FindAsync(comment.ReplyId.Value); var repledUser = await _context.Users.FindAsync(repliedComment.OwnerUserId); var emailModel = new RepliedCommentVm() { CommentContent = request.Content, KnowledeBaseId = knowledgeBaseId, KnowledgeBaseSeoAlias = knowledgeBase.SeoAlias, KnowledgeBaseTitle = knowledgeBase.Title, RepliedName = repledUser.FirstName + " " + repledUser.LastName }; //https://github.com/leemunroe/responsive-html-email-template var htmlContent = await _viewRenderService.RenderToStringAsync("_RepliedCommentEmail", emailModel); await _emailSender.SendEmailAsync(repledUser.Email, "Có người đang trả lời bạn", htmlContent); } return(CreatedAtAction(nameof(GetCommentDetail), new { id = knowledgeBaseId, commentId = comment.Id }, new CommentVm() { Id = comment.Id })); } else { return(BadRequest(new ApiBadRequestResponse("Create comment failed"))); } }
public async Task <ActionResult> CreateComment([FromBody] CommentCreateRequest body) { var result = await commentCreator.Handle(new CommentCreateParams(body.PostId, User !, body.Body, body.ParentId)); return(result.Match <ActionResult>( comment => Ok(comment), fail => BadRequest(fail) )); }
public async Task <CommentVm> PostComment(CommentCreateRequest commentCreateRequest) { HttpContent httpContent = new StringContent(JsonConvert.SerializeObject(commentCreateRequest), Encoding.UTF8, "application/json"); var response = await _httpClient.PostAsync("api/Comments", httpContent); response.EnsureSuccessStatusCode(); return(await response.Content.ReadAsAsync <CommentVm>()); }
public async Task <IActionResult> AddNewComment([FromForm] CommentCreateRequest request) { var result = await _knowledgeBaseApiClient.PostComment(request); if (result != null) { return(Ok(result)); } return(BadRequest()); }
public async Task <IActionResult> EditComment(int commentId, [FromForm] CommentCreateRequest request) { var result = await _knowledgeBaseApiClient.PutComment(commentId, request); if (result) { return(Ok(result)); } return(BadRequest()); }
public ActionResult Create(CommentCreateRequest request, int?authuid, UserModel authUser) { request.Content = UrlDecode(request.Content); request.AuthUid = authuid.Value; request.AuthUser = authUser; request.Files = Request.Files; return(new RestfulResult { Data = this._commentDataService.Create(request) }); }
public CommentCreateRequestValidatorTest() { request = new CommentCreateRequest() { CaptchaCode = "abc", Content = "test", KnowledgeBaseId = 1, ReplyId = null }; validator = new CommentCreateRequestValidator(); }
public ExecuteResult <CommentInfoResponse> Create(CommentCreateRequest request) { CommentEntity entity; if ((request.Files == null || request.Files.Count == 0) && string.IsNullOrEmpty(request.Content)) { return(new ExecuteResult <CommentInfoResponse>(null) { StatusCode = StatusCode.ClientError, Message = "没有评论内容!" }); } using (var ts = new TransactionScope()) { entity = _commentRepository.Insert(new CommentEntity { Content = request.Content, CreatedDate = DateTime.Now, CreatedUser = request.AuthUid, ReplyUser = request.ReplyUser, SourceId = request.SourceId, SourceType = (int)request.SType, Status = 1, UpdatedDate = DateTime.Now, UpdatedUser = request.AuthUid, User_Id = request.AuthUid }); //插入一个提醒 _remindService.Insert(new RemindEntity { CreatedDate = DateTime.Now, CreatedUser = request.AuthUid, IsRemind = false, RemindUser = request.AuthUid, SourceId = entity.Id, Stauts = (int)DataStatus.Default, Type = (int)SourceType.Comment, UpdatedDate = DateTime.Now, UpdatedUser = request.AuthUid, User_Id = entity.ReplyUser }); //处理文件上传 if (request.Files != null && request.Files.Count > 0) { ServiceLocator.Current.Resolve <IResourceService>().Save(request.Files, request.AuthUid, 0, entity.Id, SourceType.CommentAudio); } ts.Complete(); } return(new ExecuteResult <CommentInfoResponse>(MappingManager.CommentInfoResponseMapping(entity, request.Version))); }
private CommentResponse SubmitCommentInternal(CommentCreateRequest commentData, IThread thread, IAuthor author) { var cs = SystemManager.GetCommentsService(); var currentConfig = CommentsUtilitiesReflector.GetThreadConfigByType(thread.Type, thread.Key); if (currentConfig.RequiresAuthentication) { if (author.Key.IsNullOrWhitespace() || author.Key == Guid.Empty.ToString()) { throw new InvalidOperationException("Comment cannot be submitted at the moment. Please refresh the page and try again."); } } if (currentConfig.EnableRatings) { if (commentData.Rating == null) { throw new InvalidOperationException("A message displayed when ratings are allowed and a comment is submitted without rating."); } if (CommentsUtilitiesReflector.GetCommentsByThreadForCurrentAuthorWithRating(thread.Key).Any()) { throw new InvalidOperationException("Only one comment with rating is allowed per user."); } } var authorIp = CommentsUtilitiesReflector.GetIpAddressFromCurrentRequest(); var commentProxy = new CommentProxy(commentData.Message, thread.Key, author, authorIp, commentData.Rating); commentProxy.CustomData = commentData.CustomData; if (currentConfig.RequiresApproval) { commentProxy.Status = StatusConstants.WaitingForApproval; } else { commentProxy.Status = StatusConstants.Published; } IComment newComment = cs.CreateComment(commentProxy); var result = CommentsUtilitiesReflector.GetCommentResponse(newComment, ClaimsManager.GetCurrentIdentity().IsBackendUser); if (commentData.Captcha != null) { CommentsUtilitiesReflector.RemoveCaptchaFromTempStorage(commentData.Captcha.Key); } ServiceUtility.DisableCache(); return(result); }
public async Task <int> CreateCommentAsync(CommentCreateRequest request) { Comment comment = _mapper.Map <Comment>(request); comment.CreateDate = DateTime.Now; comment.ModifiedDate = DateTime.Now; await _repository.CommmentRepo.CreateAsync(comment); await _repository.SaveChangesAsync(); return(comment.Id); }
public async Task <ApiResult <bool> > Create(CommentCreateRequest request) { var comment = new Comment() { Created_At = DateTime.Now, Content = request.Content, UserId = request.UserId, BlogId = request.BlogId }; _context.Comments.Add(comment); return(await SaveChangeService.SaveChangeAsyncNotImage(_context)); }
public ActionResult Create(FormCollection formCollection, CommentCreateRequest request, [FetchUser(KeyName = "userid")] UserModel userModel) { request.AuthUid = userModel.Id; request.Files = Request.Files; request.AuthUser = userModel; request.Content = UrlDecode(request.Content); this._commentDataService.Create(request); return(new ContentResult() { Content = "OK" }); }
public async Task <IActionResult> Create(CommentCreateRequest request) { if (ModelState.IsValid == false) { return(BadRequest(ModelState)); } var result = await _commentService.Create(request); if (result.IsSuccessed == false) { return(BadRequest(result)); } return(Ok(result)); }
public async Task <IActionResult> CreateComment(int id, string content) { var claimIdentity = User.Identity as ClaimsIdentity; string userid = claimIdentity.FindFirst(ClaimTypes.NameIdentifier).Value; var commentCreateRequest = new CommentCreateRequest { UserID = userid, ProductID = id, Content = content }; await _commentClient.PostComment(commentCreateRequest); return(RedirectToAction("Detail", "ProductClient", new { id = id })); }
public async Task <IActionResult> Create([FromForm] CommentCreateRequest request) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var result = await _commentService.Create(request); if (!result.IsSuccess) { return(BadRequest(result)); } return(Ok(result)); }
public async Task <IActionResult> CommentAsync(CommentCreateRequest request) { if (ModelState.IsValid) { request.UserId = new Guid(ViewBag.UserId); var result = await _commentService.Create(request); if (result.IsSuccessed == true) { return(RedirectToAction("detail", new { blogId = request.BlogId })); } ModelState.AddModelError(string.Empty, result.Message); return(View(request)); } return(View(request)); }
public async Task <bool> SendCommentEmail(CommentCreateRequest request) { var post = _dataProvider.GetPostById(request.PostId); var user = _dataProvider.GetUserById(post.UserId); var blog = _dataProvider.GetBlog(); if (!string.IsNullOrWhiteSpace(blog.SmtpPassword)) { blog.SmtpPassword = _protector.Unprotect(blog.SmtpPassword); } var response = true; try { using (var client = new SmtpClient { Credentials = new NetworkCredential(blog.SmtpUsername, blog.SmtpPassword), EnableSsl = blog.SmtpUseSsl, Host = blog.SmtpHost, Port = int.Parse(blog.SmtpPort), Timeout = 10000 }) { var sendMailTask = client.SendMailAsync(user.Email, user.Email, $"{blog.EmailPrefix} Comment on post '{post.Title}'", $"Comment by: {request.AuthorName} - {request.AuthorEmail}\n" + $"Comment: {request.Text}"); if (await Task.WhenAny(sendMailTask, Task.Delay(5000)) == sendMailTask) { response = true; } else { // sendMailTask task timed out client.SendAsyncCancel(); response = false; } } } catch { response = false; } return(response); }
public async Task <ApiResult <string> > Create(CommentCreateRequest request) { var sections = _httpContextAccessor.HttpContext.Session.GetString("Token"); _client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", sections); var json = JsonConvert.SerializeObject(request); var httpContent = new StringContent(json, Encoding.UTF8, "application/json"); var response = await _client.PostAsync($"/api/comments", httpContent); var result = await response.Content.ReadAsStringAsync(); if (response.IsSuccessStatusCode) { return(JsonConvert.DeserializeObject <ApiResultSuccess <string> >(result)); } return(JsonConvert.DeserializeObject <ApiResultErrors <string> >(result)); }
private CommentResponse SubmitCommentInternal(CommentCreateRequest commentData, IThread thread, IAuthor author) { var cs = SystemManager.GetCommentsService(); var currentConfig = CommentsUtilitiesReflector.GetThreadConfigByType(thread.Type, thread.Key); if (currentConfig.RequiresAuthentication) { if (author.Key.IsNullOrWhitespace() || author.Key == Guid.Empty.ToString()) { throw new InvalidOperationException("Comment cannot be submitted at the moment. Please refresh the page and try again."); } } if (currentConfig.EnableRatings) { if (commentData.Rating == null) { throw new InvalidOperationException("A message displayed when ratings are allowed and a comment is submitted without rating."); } if (CommentsUtilitiesReflector.GetCommentsByThreadForCurrentAuthorWithRating(thread.Key).Any()) { throw new InvalidOperationException("Only one comment with rating is allowed per user."); } } var authorIp = CommentsUtilitiesReflector.GetIpAddressFromCurrentRequest(); var commentProxy = new CommentProxy(commentData.Message, thread.Key, author, authorIp, commentData.Rating); commentProxy.CustomData = commentData.CustomData; if (currentConfig.RequiresApproval) commentProxy.Status = StatusConstants.WaitingForApproval; else commentProxy.Status = StatusConstants.Published; IComment newComment = cs.CreateComment(commentProxy); var result = CommentsUtilitiesReflector.GetCommentResponse(newComment, ClaimsManager.GetCurrentIdentity().IsBackendUser); ServiceUtility.DisableCache(); return result; }
/// <summary> /// Gets the author. /// </summary> /// <param name="commentData">The comment data.</param> /// <returns></returns> public static IAuthor GetAuthor(CommentCreateRequest commentData) { var authorObject = CommentsUtilitiesReflector.Reflect("GetAuthor", commentData); var author = authorObject as IAuthor; return author; }
private CommentResponse PostInternal(CommentCreateRequest request) { CommentsWebServiceReflector.Validate(request); CommentResponse result; try { var author = CommentsUtilitiesReflector.GetAuthor(request); var cs = SystemManager.GetCommentsService(); var thread = cs.GetThread(request.ThreadKey); if (thread == null) { request.Thread.Key = request.ThreadKey; CommentsWebServiceReflector.Validate(request.Thread); CommentsWebServiceReflector.ValidatePostRequest(request.Thread.Type, request.Captcha, false); var group = cs.GetGroup(request.Thread.GroupKey); if (group == null) { CommentsWebServiceReflector.Validate(request.Thread.Group); request.Thread.Group.Key = request.Thread.GroupKey; var groupProxy = new GroupProxy(request.Thread.Group.Name, request.Thread.Group.Description, author) { Key = request.Thread.Group.Key }; group = cs.CreateGroup(groupProxy); } var threadProxy = new ThreadProxy(request.Thread.Title, request.Thread.Type, group.Key, author) { Key = request.Thread.Key, Language = request.Thread.Language, DataSource = request.Thread.DataSource, Behavior = request.Thread.Behavior }; thread = cs.CreateThread(threadProxy); } else { if (thread.IsClosed) throw new InvalidOperationException("Thread is closed."); CommentsWebServiceReflector.ValidatePostRequest(thread.Type, request.Captcha, false); } result = this.SubmitCommentInternal(request, thread, author); } catch (InvalidOperationException ex) { throw new InvalidOperationException("Comment cannot be submitted at the moment. Please refresh the page and try again.", ex); } ServiceUtility.DisableCache(); return result; }