示例#1
0
        public async Task <ActionResult> PutComments([FromRoute] int id, [FromBody] CommentVM vm)
        {
            var user = await GetLoginUser();

            if (user == null)
            {
                return(GetErrorResult("no_login"));
            }
            if (!IsEnabledForUser(user))
            {
                return(GetErrorResult("discussion_disabled"));
            }

            if (id != vm.id)
            {
                return(GetErrorResult("bad_id"));
            }

            var comm = await _context.Comments.FindAsync(id);

            if (comm.uid != user.id || comm.tag != "diss")
            {
                return(GetErrorResult("bad_comment"));
            }

            comm.content = vm.content;

            // _context.Entry(comm).State = EntityState.Modified;
            await _context.SaveChangesAsync();

            _message.TriggerEvent("diss-changed");

            return(Ok(comm.ToVM(user)));
        }
示例#2
0
        public ActionResult EventDetails(int?id)
        {
            CommentVM ComVM = new CommentVM();

            ComVM.Event    = db.events.Find(id);
            ComVM.Comments = new List <Comment>();
            ComVM.Comments = db.Comments.Where(c => c.EventId == id).ToList();
            using (var client = new HttpClient(new HttpClientHandler {
                AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate
            }))
            {
                var states = Extensions.GetDescription(ComVM.Event.State);
                client.BaseAddress = new Uri("Https://maps.googleapis.com/maps/api/geocode/");
                HttpResponseMessage response = client.GetAsync($"json?address={ComVM.Event.Street}+{ComVM.Event.Zip},+{ComVM.Event.City},+{states}&key=AIzaSyBBA-VL6jTbTGJNW77AsuCuLRVwXB2wKGo").Result;
                response.EnsureSuccessStatusCode();
                var        result = response.Content.ReadAsStringAsync().Result;
                RootObject root   = JsonConvert.DeserializeObject <RootObject>(result);

                double Latitude  = 0.0;
                double Longitude = 0.0;
                foreach (var item in root.results)
                {
                    Latitude     = item.geometry.location.lat;
                    Longitude    = item.geometry.location.lng;
                    ViewBag.Lat  = Latitude.ToString();
                    ViewBag.Long = Longitude.ToString();
                }
            }


            return(View(ComVM));
        }
        public IHttpActionResult PostComment(CommentVM model)
        {
            StringBuilder traceLog = null;
            ServiceResponse <CommentVM> objResponse = null;

            try
            {
                traceLog = new StringBuilder();
                traceLog.AppendLine("Start: ChallengeMessageFeed PostComment():-Message-" + model.Message + ",CommentBy-" + model.CommentBy);
                objResponse              = new ServiceResponse <CommentVM>();
                objResponse.jsonData     = ChallengeMessageFeedBL.PostComment(model);
                objResponse.IsResultTrue = true;
                return(Ok(objResponse));
            }
            catch (Exception ex)
            {
                LogManager.LogManagerInstance.WriteErrorLog(ex);
                return(BadRequest(ex.Message));
            }
            finally
            {
                traceLog.AppendLine("End: ChallengeMessageFeed PostComment() Response Data:-Result Status-" + objResponse.IsResultTrue + ",CommentId-" + objResponse.jsonData != null ? objResponse.jsonData.CommentId.ToString() : "" + ",Posted DateTime-" + DateTime.Now.ToLongDateString());
                LogManager.LogManagerInstance.WriteTraceLog(traceLog);
                traceLog = null;
            }
        }
        // [Route("")]
        public ObjectResult Create([FromBody] CommentVM value)
        {
            var commentId = this.commentManager.SaveComment(value);
            var c         = this.commentManager.GetComment(commentId);

            return(new HttpOkObjectResult(new { Status = "Success", Data = c }));
        }
        public async Task <ApiResult <CommentVM> > GetById(int commentId)
        {
            //1. Find id of comments
            var comment = await _context.Comments.FindAsync(commentId);

            if (comment == null)
            {
                return(new ApiErrorResult <CommentVM>(SystemConstants.Message.CanNotFindIdMessage + "comment table with Id: " + commentId));
            }

            //Find comment id in post
            var post = await _context.Posts.Where(x => x.Id == comment.PostId).FirstOrDefaultAsync();

            var data = new CommentVM()
            {
                Id            = comment.Id,
                Title         = comment.Title,
                Summary       = comment.Summary,
                ParentId      = comment.ParentId,
                DateCreated   = comment.DateCreated,
                DateModified  = comment.DateModified,
                PostTitle     = post.Title,
                PostSummary   = post.Summary,
                PostViewCount = post.ViewCount
            };

            //Return data
            return(new ApiSuccessResult <CommentVM>(data));
        }
示例#6
0
        public async Task SendNewCommentEmail(CommentVM comment, int teamId)
        {
            var subscribers = await userRepository.GetSubscribers(teamId, NotificationTypeCode.NewComment);

            var emailTemplate = emailTemplateRepository.GetEmailTemplate("NewComment");

            if (emailTemplate != null)
            {
                string emailSubject = emailTemplate.Subject;
                string emailBody    = emailTemplate.EmailBody;
                Email  email        = new Email();


                string issueUrl  = UrlBuilderHelper.SiteBaseUrl + "issues/" + comment.IssueId;
                var    issueLink = "<a href='" + issueUrl + "'>" + "# " + comment.IssueId + " " + comment.IssueId + "</a>";
                emailBody     = emailBody.Replace("@author", comment.Author.Name);
                emailBody     = emailBody.Replace("@link", issueLink);
                emailBody     = emailBody.Replace("@comment", comment.CommentBody);
                emailBody     = emailBody.Replace("@issueId", comment.IssueId.ToString());
                email.Body    = emailBody;
                emailSubject  = emailSubject.Replace("@issueId", comment.IssueId.ToString());
                email.Subject = emailSubject;

                foreach (var subscriber in subscribers)
                {
                    email.ToAddress.Add(subscriber.EmailAddress);
                }

                email.Send();
            }
        }
示例#7
0
        public async Task <ActionResult> Detail(CommentVM comment, string nameAlias)
        {
            var response = new ClientProductDetailResponse();

            response.Product = await _clientProductService.GetProductByNameAlias(nameAlias);

            var relateList = await _clientProductService.GetProductsByCategoryId(response.Product.CategoryId);

            //Orderby Rating
            response.RelateProducts = relateList.Take(10);

            if (ModelState.IsValid)
            {
                if (await _clientCommentService.AddCommentToDB(comment) > 0)
                {
                    response.Comments = await _clientCommentService.GetProductListComment(response.Product.ProductId);

                    return(View(response));
                }
            }
            response.Comments = await _clientCommentService.GetProductListComment(response.Product.ProductId);

            ModelState.AddModelError("Review", "Bạn chưa bình luận");
            return(View(response));
        }
示例#8
0
 public RedirectToActionResult Comment(CommentVM cvm)
 {
     // if model is valid, store in database
     if (ModelState.IsValid)
     {
         // Create a new comment model with the passed in comment
         Comment comment = new Comment {
             Text = cvm.Text
         };
         // Add logged in user to the model
         comment.User = userManager.GetUserAsync(User).Result;
         // Add date and time of submission
         comment.Date = DateTime.Now;
         // Query the database for the associated Story object
         Story story = (from s in repo.Stories
                        where s.StoryID == cvm.StoryID
                        select s).First <Story>();
         // Add the comment to the story and update the database
         story.Comments.Add(comment);
         repo.UpdateStory(story);
         // Redirect user to the HappyTails view
         return(RedirectToAction("HappyTails"));
     }
     ViewBag.TempData["Error"] = "There was a problem submitting your comment. Please try again.";
     return(RedirectToAction("Comment"));
 }
示例#9
0
        public void SaveComment(CommentVM commentVM)
        {
            var comment = _mapper.Map <Comment>(commentVM);

            _commentRepository.Insert(comment);
            _commentRepository.Save();
        }
示例#10
0
        public async Task <IActionResult> UpdateComment(CommentVM vm)
        {
            if (ModelState.IsValid)
            {
                string currentUserId = await OnGetSesstion();

                var comment = _context.ArticleComment.Where(x => x.Id == vm.Id && x.UserId == currentUserId).SingleOrDefault();
                if (comment == null)
                {
                    return(NotFound());
                }
                comment.Status = "history";
                ArticleComment updatedComment = new ArticleComment
                {
                    OriginalId = comment.Id,
                    ArticleId  = comment.ArticleId,
                    Comment    = vm.Comment,
                    CreateTime = DateTime.Now,
                    Status     = "active",
                    UserId     = currentUserId
                };
                _context.ArticleComment.Add(updatedComment);
                _context.SaveChanges();
                return(Json(new { success = true }));
            }
            return(Json(new { success = false }));
        }
示例#11
0
        public object Create(CommentVM commentVM)
        {
            try
            {
                AdComment Comment      = new AdComment();
                object    ObjectReturn = CreateS.Comment(commentVM, Comment);
                if (ObjectReturn != null)
                {
                    return(ObjectReturn);
                }

                db.SaveChanges();
                db      = new TageerEntities();
                Comment = db.AdComments.Find(Comment.Id);
                return(new ResponseVM(RequestTypeEnumVM.Success, Token.Created, new CommentVM
                {
                    Id = Comment.Id,
                    AdId = Comment.FKAd_Id,
                    Comment = Comment.Comment,

                    UserImage = Comment.User.Image,
                    UserName = Comment.User.UserName
                }));
            }
            catch (Exception ex)
            {
                return(new ResponseVM(RequestTypeEnumVM.Error, Token.SomeErrorInServer, ex));
            }
        }
示例#12
0
        public ActionResult ShowProduct(int id)
        {
            Product product = context.ProductFactory.Get(id);

            ProductVM productVM = new ProductVM();

            productVM.Product  = product;
            productVM.Comments = new List <CommentVM>();
            foreach (Comment item in context.CommentFactory.GetAllBy("ProductID", id))
            {
                CommentVM cvm = new CommentVM()
                {
                    Comment = item,
                    Member  = context.MemberFactory.Get("Token", item.TokenKey)
                };
                productVM.Comments.Add(cvm);
            }

            if (activeUser != null)
            {
                if ((activeUser.ProductsViewed as List <int>).Exists(x => x == id) == false)
                {
                    activeUser.ProductsViewed.Add(id);
                    Session[activeUserKey] = activeUser;

                    product.Views += 1;
                    context.ProductFactory.Update(product);
                }
            }

            ViewBag.LikeCount = context.LikeRelationFactory.CountBy("ProductID", id);

            return(View(productVM));
        }
        public async Task <IActionResult> AddComment(string postId, CommentVM comment)
        {
            var post = await _blog.GetPostById(postId);

            if (!ModelState.IsValid)
            {
                return(View("Post", post));
            }

            if (post == null || !PostModule.AreCommentsOpen(post, _settings.Value.CommentsCloseAfterDays))
            {
                return(NotFound());
            }
            var cleanComment = CommentVMModule.toComment(comment);

            // the website form key should have been removed by javascript
            // unless the comment was posted by a spam robot
            if (!Request.Form.ContainsKey("website"))
            {
                post = PostModule.AddComment(cleanComment, post);
                await _blog.SavePost(post);
            }

            return(Redirect(PostModule.GetLink(post) + "#" + cleanComment.ID));
        }
示例#14
0
        public ActionResult AddComment(int id)
        {
            CommentVM commentView = new CommentVM();

            commentView.Event = _context.events.Where(e => e.EventId == id).Single();
            return(View(commentView));
        }
示例#15
0
        public async Task <ActionResult> PostComments([FromRoute] int trackid, [FromBody] CommentVM vm)
        {
            var user = await GetLoginUser();

            if (user == null)
            {
                return(GetErrorResult("no_login"));
            }
            if (!IsCommentsEnabled(user))
            {
                return(GetErrorResult("track_comments_disabled"));
            }

            var track = await _context.Tracks.FindAsync(trackid);

            if (track?.IsVisibleToUser(user) != true)
            {
                return(GetErrorResult("track_not_found"));
            }

            var comm = new Comment
            {
                tag     = "track/" + trackid,
                uid     = user.id,
                date    = DateTime.UtcNow,
                content = vm.content
            };

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

            return(CreatedAtAction(nameof(PostComments), comm.ToVM(user)));
        }
        public IActionResult Index()
        {
            var result = new CommentVM();

            var query = commentRepo.GetBy(x => true);

            result.Items = query.OrderByDescending(x => x.CreateDate).Take(100).Select(x => new CommentMM
            {
                Id          = x.Id,
                PNRNumber   = x.PNRNumber,
                RateAVG     = x.RateGiven,
                CreateDate  = x.CreateDate.Value,
                Explanation = x.CommentText,
                Room        = new RoomMM
                {
                    Type = x.Room.Type
                },
                User = new UserMM
                {
                    Id      = x.UserID,
                    Name    = x.User.Name,
                    Surname = x.User.Surname
                }
            }).ToList();

            return(View(result));
        }
 public int SaveComment(CommentVM comment)
 {
     comment.Author = new UserDto {
         Id = this.userSessionHelper.UserId
     };
     return(this.commentRepository.Save(comment));
 }
示例#18
0
        public ActionResult CreateComment(string text, int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }

            Post post = UnitOfWork.PostManager.GetById(id);

            if (!text.IsNullOrWhiteSpace())
            {
                var     userId  = System.Web.HttpContext.Current.User.Identity.GetUserId();
                var     user    = UnitOfWork.ApplicationUserManager.FindById(userId);
                Comment comment = new Comment()
                {
                    Text = text,
                    User = user,
                    Time = DateTime.Now,
                    Post = post
                };
                UnitOfWork.CommentManager.Add(comment);
            }
            CommentVM commentVm = new CommentVM()
            {
                PostId   = post.Id,
                Comments = post.Comments.OrderBy(c => c.Time)
            };

            return(PartialView("_comments", commentVm));
        }
示例#19
0
        public async Task <ActionResult> Comment(CommentVM comment)
        {
            int sessionUserId = Convert.ToInt32(Session["UserId"]);

            //validation
            if (sessionUserId == 0)
            {
                return(RedirectToAction("Login", "Account")); //if not login
            }

            if (ModelState.IsValid) //validation
            {
                Comment userComment = new Comment()
                {
                    UserId    = sessionUserId,
                    CreatedOn = DateTime.Now,
                    userInput = comment.userInput
                };
                _db.Comments.Add(userComment);
                await _db.SaveChangesAsync();

                return(RedirectToAction("Index"));
            }
            return(View("Index")); //optional
        }
        /// <summary>
        /// 获取活动评论
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task <IActionResult> GetComments(Guid id, string listPageParaJson)
        {
            var listPagePara = new ListPageParameter();

            if (listPageParaJson != null)
            {
                listPagePara = Newtonsoft.Json.JsonConvert.DeserializeObject <ListPageParameter>(listPageParaJson);
            }

            ViewBag.activityId = id;
            //获取一级评论
            var commentList = await _commonExtension.GetAll().OrderByDescending(x => x.CommentDataTime).Include(x => x.Activity).Include(x => x.User).Include(x => x.User.Avatar).Where(x => x.Activity.ID == id && x.ParentGrade == null).ToListAsync();

            var comments = new List <CommentVM>();

            foreach (var item in commentList)
            {
                var commentVM = new CommentVM(item);
                commentVM.CommentChildrens = await _commonExtension.GetAll().OrderBy(x => x.CommentDataTime).Include(x => x.Activity).Include(x => x.AcceptUser).Include(x => x.User).Include(x => x.User.Avatar).Where(x => x.ParentGrade == item.ID).ToListAsync();

                comments.Add(commentVM);
            }
            var commentPageList    = IQueryableExtensions.ToPaginatedList(comments.AsQueryable(), listPagePara.PageIndex, listPagePara.PageSize);
            var commentCollections = new List <CommentVM>();

            foreach (var commentTermPage in commentPageList)
            {
                commentCollections.Add(commentTermPage);
            }
            var pageGroup = PagenateGroupRepository.GetItem(commentPageList, 5, listPagePara.PageIndex);

            ViewBag.PageGroup     = pageGroup;
            ViewBag.PageParameter = listPagePara;
            return(View("~/Views/BusinessView/ActivityTermView/_GetComments.cshtml", commentCollections));
        }
示例#21
0
        public ResponseVM CreateComment(CommentVM model, string email)
        {
            bool res = false;

            if (email != null)
            {
                _commentRepository.Create(new Comment
                {
                    Title       = model.Title,
                    Content     = model.Message,
                    AccounEmail = email,
                    CommentTime = DateTime.Now,
                    AccountId   = model.AccountId
                });

                _commitProvider.Save();

                return(new ResponseVM()
                {
                    Result = true,
                    Message = "Pet Createed"
                });
            }
            else
            {
                return(new ResponseVM()
                {
                    Result = res,
                    Message = "Account not Found!"
                });
            }
        }
        public ActionResult Create(CommentVM fvm, int idP)
        {
            Comment c = new Comment()
            {
                CommentId   = fvm.CommentId,
                PostId      = idP,
                UserId      = 2,
                Content     = fvm.Content,
                CommentDate = DateTime.Today,
                NbrLikes    = 0
            };

            Service.Add(c);
            Service.Commit();
            Post post = Ser.GetById(idP);

            post.Comments.Add(c);
            //return RedirectToRoute("Post/Details/"+idP);
            return(Redirect("~/Post/Details/" + idP));

            /*return RedirectToRoute(new
             * {
             *  controller = "Post",
             *  action = "Details",
             *  id = idP
             * });*/
        }
示例#23
0
        public async Task <ActionResult> PostComments([FromBody] CommentVM vm)
        {
            var user = await GetLoginUser();

            if (user == null)
            {
                return(GetErrorResult("no_login"));
            }
            if (!IsEnabledForUser(user))
            {
                return(GetErrorResult("discussion_disabled"));
            }

            var comm = new Comment {
                tag     = "diss",
                uid     = user.id,
                date    = DateTime.UtcNow,
                content = vm.content
            };

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

            _message.TriggerEvent("diss-changed");

            return(CreatedAtAction(nameof(PostComments), comm.ToVM(user)));
        }
示例#24
0
        // GET: Comments/Edit/5
        public ActionResult CommentEdit(int?id)
        {
            Comments comments = db.Comments.Where(x => x.ID == id).SingleOrDefault();

            CommentVM model = new CommentVM()
            {
                ID           = comments.ID,
                FullName     = comments.FullName,
                Email        = comments.Email,
                Detail       = comments.Detail,
                AddedDate    = DateTime.Now /*Convert.ToDateTime(comments.AddedDate)*/,
                ModifiedDate = DateTime.Now,
                IsConfirm    = Convert.ToBoolean(comments.IsConfirm),
                CategoryID   = Convert.ToInt32(comments.CategoryID),
                //MemberID=Convert.ToInt32(comments.MemberID),
                TsarID = Convert.ToInt32(comments.TsarID)
            };

            ViewBag.CategoryID = new SelectList(db.Categories, "ID", "CategoryName", comments.CategoryID);

            ViewBag.MemberID = new SelectList(db.Members, "ID", "UserName", comments.MemberID);

            ViewBag.TsarID = new SelectList(db.Tsars, "ID", "TsarName", comments.TsarID);

            return(View(model));
        }
        public async Task <IActionResult> Edit(Guid id, CommentVM vm)
        {
            if (ModelState.IsValid)
            {
                var getOperation = await _bo.ReadAsync(id);

                if (!getOperation.Success)
                {
                    return(OperationErrorBackToIndex(getOperation.Exception));
                }

                if (getOperation.Result == null)
                {
                    return(RecordNotFound());
                }

                var result = getOperation.Result;

                if (!vm.CompareToModel(result))
                {
                    result = vm.ToComment(result);

                    var updateOperation = await _bo.UpdateAsync(result);

                    if (!updateOperation.Success)
                    {
                        TempData["Alert"] = AlertFactory.GenerateAlert(NotificationType.Danger, updateOperation.Exception);
                        return(View(vm));
                    }

                    return(OperationSuccess("The record was successfully updated."));
                }
            }
            return(RedirectToAction(nameof(Index)));
        }
        public ActionResult ShowProduct(int id = 0)
        {
            if (id > 0)
            {
                ProductVM vm = new ProductVM();
                vm.Product  = productFactory.Get(id);
                vm.Images   = imageFactory.GetBy("ProductID", id);
                vm.Category = categoryFactory.Get(vm.Product.CategoryID);

                List <CommentVM> comments = new List <CommentVM>();
                foreach (Comment comment in commentFactory.GetBy("ProductID", id))
                {
                    CommentVM cmv = new CommentVM();
                    cmv.Comment = comment;
                    cmv.User    = userFactory.Get(comment.UserID);

                    comments.Add(cmv);
                }

                comments = comments.OrderBy(x => DateTime.Parse(x.Comment.Date)).ToList();
                comments.Reverse();

                ViewBag.Comments = comments;

                return(View(vm));
            }
            else
            {
                return(RedirectToAction("Products"));
            }
        }
        public async Task <IActionResult> Edit(Guid?id)
        {
            if (id == null)
            {
                return(RecordNotFound());
            }

            var getOperation = await _bo.ReadAsync((Guid)id);

            if (!getOperation.Success)
            {
                return(OperationErrorBackToIndex(getOperation.Exception));
            }

            if (getOperation.Result == null)
            {
                return(RecordNotFound());
            }

            var vm = CommentVM.Parse(getOperation.Result);

            var listClientOperation = await _clientBO.ListUndeletedAsync();

            if (!listClientOperation.Success)
            {
                return(OperationErrorBackToIndex(listClientOperation.Exception));
            }

            var clientList = new List <SelectListItem>();

            foreach (var item in listClientOperation.Result)
            {
                var clientName = await _profileBO.ReadAsync(item.ProfileId);

                var listItem = new SelectListItem()
                {
                    Value = item.Id.ToString(), Text = (clientName.Result.FullName + " -- " + clientName.Result.Country)
                };

                if (item.Id == vm.ClientId)
                {
                    listItem.Selected = true;
                }

                clientList.Add(listItem);
            }

            ViewBag.Clients = clientList;

            var crumbs = GetCrumbs();

            crumbs.Add(new BreadCrumb()
            {
                Action = "Edit", Controller = "Comments", Icon = "fa-edit", Text = "Edit"
            });

            ViewData["Title"]       = "Edit comment";
            ViewData["BreadCrumbs"] = crumbs;
            return(View(vm));
        }
        public IHttpActionResult PostComment(CommentVM model)
        {
            StringBuilder traceLog = null;
            ServiceResponse <CommentVM> objResponse = null;

            try
            {
                traceLog = new StringBuilder();
                traceLog.AppendLine("Start: PostComment() Request Data:-PostId-" + model.PostId + ",UserName" + model.UserName + ",UserId-" + model.UserId + ",Message-" + model.Message);
                objResponse              = new ServiceResponse <CommentVM>();
                objResponse.jsonData     = ProfileBL.PostComment(model);
                objResponse.IsResultTrue = true;
                return(Ok(objResponse));
            }
            catch (Exception ex)
            {
                LogManager.LogManagerInstance.WriteErrorLog(ex);
                return(BadRequest(ex.Message));
            }
            finally
            {
                traceLog.AppendLine("End:PostComment() Response Result status-" + objResponse.IsResultTrue + ",Posted DateTime-" + DateTime.Now.ToLongDateString());
                LogManager.LogManagerInstance.WriteTraceLog(traceLog);
                traceLog = null;
            }
        }
示例#29
0
        public async Task <IActionResult> MainCommentUpdate(CommentVM vm)
        {
            if (!ModelState.IsValid)
            {
                // redirect to same post
                return(RedirectToAction("Details", new { id = vm.PostId }));
            }

            if (ModelState.IsValid)
            {
                var comment = await _uniofWork.MainComment.GetByIdAsync(vm.MainCommentId);

                if (comment == null)
                {
                    return(RedirectToAction("Details", new { id = vm.PostId }));
                }

                // access to edit have admin, moderator and post author
                bool result = AccessRights.AuthorAdminAccessRight(HttpContext, comment.ApplicationUserId, _db);
                if (!result)
                {
                    return(new RedirectResult("~/Identity/Account/AccessDenied"));
                }

                comment.Message = vm.Message;
                await _uniofWork.SaveChangesAsync();
            }
            return(RedirectToAction("Details", new { id = vm.PostId }));
        }
示例#30
0
        public async Task <IActionResult> Comment(CommentVM vm)
        {
            if (!ModelState.IsValid)
            {
                // redirect to same post
                return(RedirectToAction("Details", new { id = vm.PostId }));
            }

            // get logged user
            var claimsIdentity = (ClaimsIdentity)User.Identity;
            var claim          = claimsIdentity.FindFirst(ClaimTypes.NameIdentifier);

            if (vm.MainCommentId == 0)
            {
                await _uniofWork.MainComment.AddCommentFromCommentView(vm, claim);
            }
            else
            {
                await _uniofWork.SubComment.AddCommentFromCommentView(vm, claim);
            }

            await _uniofWork.SaveChangesAsync();

            return(RedirectToAction("Details", new { id = vm.PostId }));
        }
        public async Task<ActionResult> Add(CommentAuthPipelineModel authVM, CommentVM<ObjectId> commentVM)
        {
            AuthResult authResult = null;

            //Auth
            if (!User.Identity.IsAuthenticated)
            {
                authResult = await _authManager.AuthComment(authVM);
                if (!authResult.Result)
                {
                    return Json(new
                    {
                        message = authResult.Message
                    });
                }
                _currentUser = authResult.User;
            }

            //Add comment
            commentVM.Content = HttpUtility.HtmlDecode(commentVM.Content);
            var comment = new Comment<ObjectId>(commentVM);
            comment.AuthorID = _currentUser.Id;
            comment.AuthorName = _currentUser.UserName;
            comment.AuthorAvatar = _currentUser.Avatar;

            PipelineResult result = await _postManager.CommentManager.Insert(new CommentPipelineModel<ObjectId>()
            {
                Comment = comment,
                UserRoles = _userRoles.Select(p => p.ToString()).ToList(),
                Permission = (int)CategoryPermission.View,
                ViewPermission = (int)CategoryPermission.View
            });

            return new JsonCamelCaseResult()
            {
                Data = new
                {
                    message = result.Message,
                    comment = result.Result
                        ? new CommentRenderVM<ObjectId>(comment, _postManager.AvatarImageQueries)
                        : null,
                    user = authResult == null
                        ? null
                        : new
                        {
                            userName = authResult.User.UserName,
                            avatar = _postManager.AvatarImageQueries.PathCreator.CreateStaticUrl(authResult.User.Avatar),
                            antiForgeryToken = authResult.AntiForgeryToken
                        }
                },
                NullValueHandling = NullValueHandling.Ignore
            };
        }
        public int Save(CommentVM comment)
        {
            using (var con = new SqlConnection(ConnectionString))
            {
                con.Open();

                var p = con.Query<int>("INSERT INTO Comment(CommentText,IssueID,CreatedDate,CreatedByID) VALUES (@cmnt,@issueId,@dt,@createdById);SELECT CAST(SCOPE_IDENTITY() as int)",
                                        new { cmnt = comment.CommentText, @issueId = comment.IssueId, @dt = DateTime.Now, @createdById = comment.Author.Id });
                return p.First();

            }
        }
        public async Task<ActionResult> Update(CommentVM<ObjectId> commentVM)
        {
            //?userID match

            commentVM.Content = HttpUtility.HtmlDecode(commentVM.Content);
            var comment = new Comment<ObjectId>(commentVM);
            comment.CommentID = commentVM.CommentID ?? ObjectId.Empty;
            comment.AuthorID = _currentUser.Id;
            comment.AuthorName = User.Identity.Name;
            comment.AuthorAvatar = User.GetAvatar();

            PipelineResult result = await _postManager.CommentManager.Update(new CommentPipelineModel<ObjectId>()
            {
                Comment = comment,
                UserRoles = _userRoles.Select(p => p.ToString()).ToList(),
                Permission = (int)CategoryPermission.View,
                ViewPermission = (int)CategoryPermission.View,
            });

            return new JsonCamelCaseResult
            {
                Data = new
                {
                    error = result.Result ? null : result.Message,
                    list = result.Result
                        ? new CommentRenderVM<ObjectId>(comment, _postManager.AvatarImageQueries)
                        : null,
                    state = comment.State
                },
                NullValueHandling = NullValueHandling.Ignore
            };
        }
        public virtual JsonResult AddComment(long articleId, string textComment, long? conversationId)
        {
            ProviderCurrentMember currentMember = ProviderCurrentMember.Instance;
            AjaxReturnMsgVM viewModel = new AjaxReturnMsgVM
            {
                StatusCode = AjaxReturnMsgVM.Status.success,
                StatusMessage = String.Empty
            };

            ContentCheck result = null;
            if (!currentMember.IsSuperAdmin)
            {
                string email = string.Empty;
                string domain = string.Empty;

                if (currentMember.HasValidAltId(ProviderAlternateMemberId.AlternateType.Email))
                {
                    email = currentMember.Emails[0].Email.Address;
                }

                if (currentMember.HasValidAltId(ProviderAlternateMemberId.AlternateType.Domain))
                {
                    domain = currentMember.Domains[0].Domain.AbsoluteUri;
                }

                // The mollom client crashes if passed in special html chars (&nbsp;) so strip those before sending it over
                string cleanedTextComment = HtmlParser.StripSpecialChars(textComment);
                MollomClient client = new MollomClient(InsideWordWebSettings.MollomPrivateKey, InsideWordWebSettings.MollomPublicKey);
                result = client.CheckContent(string.Empty, cleanedTextComment,
                                                          currentMember.DisplayAdministrativeName,
                                                          email,
                                                          domain,
                                                          HttpContext.Request.UserHostAddress);
            }

            if (!currentMember.IsLoggedOn)
            {
                viewModel.StatusCode = AjaxReturnMsgVM.Status.failure;
                viewModel.StatusMessage = "You must be logged in to Comment.";
            }
            else if (!ProviderArticle.Exists(articleId))
            {
                viewModel.StatusCode = AjaxReturnMsgVM.Status.failure;
                viewModel.StatusMessage = "The article you commented on no longer exists.";
            }
            else if(string.IsNullOrEmpty(textComment) || textComment.Length < 2)
            {
                viewModel.StatusCode = AjaxReturnMsgVM.Status.failure;
                viewModel.StatusMessage = "A comment needs more than 1 character.";
            }
            else if(textComment.Length > ProviderComment.TextSize)
            {
                viewModel.StatusCode = AjaxReturnMsgVM.Status.failure;
                viewModel.StatusMessage = "A comment can't be more than "+ProviderComment.TextSize+ " characters.";
            }
            else if (result != null && result.Classification == ContentClassification.Spam)
            {
                viewModel.StatusCode = AjaxReturnMsgVM.Status.failure;
                viewModel.StatusMessage = "Your comment has been blocked as spam.";
            }
            else if (result != null && result.Quality < InsideWordWebSettings.MollomCommentQuality)
            {
                viewModel.StatusCode = AjaxReturnMsgVM.Status.failure;
                viewModel.StatusMessage = "The quality of your comment is too low. Try improving things such as spelling and grammar.";
            }
            else
            {
                ProviderArticle anArticle = new ProviderArticle(articleId);
                ProviderConversation conversation;
                if (conversationId.HasValue)
                {
                    conversation = new ProviderConversation(conversationId.Value);
                }
                else
                {
                    conversation = new ProviderConversation();
                }

                ProviderComment comment = new ProviderComment();
                CommentBL.AddComment(textComment,
                                     currentMember,
                                     anArticle,
                                     ref conversation,
                                     ref comment);

                ProviderMember author = anArticle.Author;
                long? articleAuthorId = null;
                if (author != null)
                {
                    articleAuthorId = author.Id;
                }

                bool isReply = conversation.Comments.Count > 1;
                if (isReply)
                {
                    CommentVM commentVM = new CommentVM(comment, currentMember, articleAuthorId);
                    commentVM.IsReply = isReply;
                    viewModel.Content = ControllerExtension.RenderPartialViewToString(this, MVC.Child.Views.Comment, (object)commentVM);
                }
                else
                {
                    ConversationVM conversationVM = new ConversationVM(conversation, ProviderCurrentMember.Instance, articleAuthorId);
                    viewModel.Content = ControllerExtension.RenderPartialViewToString(this, MVC.Child.Views.Conversation, (object)conversationVM);
                }

                if (author != null &&
                    author.Id != currentMember.Id &&
                    author.HasValidAltId(ProviderAlternateMemberId.AlternateType.Email))
                {
                    // do some calculations to determine if we should send the e-mail
                    int commentCount = anArticle.CountComments;
                    int n = (int)Math.Log((double)commentCount, 2);
                    if (n < 0) { n = 0; }
                    if (commentCount % (1 << n) == 0)
                    {
                        EmailManager.Instance.SendCommentNotificationEmail(author.Emails[0].Email, anArticle, currentMember);
                    }
                }
            }

            return Json(viewModel);
        }
        public async Task<ActionResult> Delete(CommentVM<ObjectId> commentVM)
        {
            //?userID match

            var comment = new Comment<ObjectId>(commentVM);
            comment.CommentID = commentVM.CommentID ?? ObjectId.Empty;
            comment.AuthorID = _currentUser.Id;
            comment.AuthorName = _currentUser.UserName;
            comment.AuthorAvatar = _currentUser.Avatar;

            PipelineResult result = await _postManager.CommentManager.Delete(new CommentPipelineModel<ObjectId>()
            {
                Comment = comment,
                UserRoles = _userRoles.Select(p => p.ToString()).ToList(),
                Permission = (int)CategoryPermission.View,
                ViewPermission = (int)CategoryPermission.View,
            });

            return new JsonCamelCaseResult
            {
                Data = new
                {
                    error = result.Result ? null : result.Message,
                    result = result.Result
                }
            };
        }