Esempio n. 1
0
        public ActionResult Create(int id, CommentViewModel comment)
        {
            if (this.CurrentUserCommentedInLastMinutes())
            {
                return this.JsonError(string.Format("You can comment every {0} minute", MinutesBetweenComments));
            }

            if (ModelState.IsValid)
            {
                var newComment = new PostComment
                {
                    Content = comment.Content,
                    BlogPostId = id,
                    User = this.currentUser.Get()
                };

                this.commentsData.Add(newComment);
                this.commentsData.SaveChanges();

                comment.User = this.currentUser.Get().UserName;
                comment.CommentedOn = DateTime.Now;

                return this.PartialView("_CommentDetail", comment);
            }
            else
            {
                return this.JsonError("Content is required");
            }
        }
Esempio n. 2
0
 public void PostComment(CommentViewModel commentViewModel)
 {
     _domainEvents.Raise<CommentWasPosted>(msg =>
         {
             msg.Comment = commentViewModel;
         });
 }
Esempio n. 3
0
 public static Comment Map(CommentViewModel viewModel)
 {
     var model = mapper.Map(viewModel);
     model.ArticleId = viewModel.ArticleId;
     model.UserId = viewModel.AuthorId;
     return model;
 }
Esempio n. 4
0
 //**********************************************************************************
 // GET: Thread/Delete/5
 public ActionResult DeleteThread(int id)
 {
     var OP = new CommentViewModel();
     OP.Thread = this.postService.GetThreadById(id);
     OP.Comments = this.postService.GetComments(id);
     return View(OP);
 }
 void AppendReplies(CommentViewModel comment, List<CommentViewModel> allComments)
 {
     foreach(var reply in allComments.Where(a=>a.ParentId==comment.Id))
     {                
         comment.AddReply(reply);
         AppendReplies(reply, allComments);
     }
 }
        public void EditComment(CommentViewModel model)
        {
            Guid lessonId = database.IdMaps.GetAggregateId<Lesson>(model.LessonId);
            Guid commentId = database.IdMaps.GetAggregateId<LessonComment>(model.Id.Value);
            DateTime date = model.Date == null ? DateTime.Now : model.Date.Value;

            bus.Send<EditCommentCommand>(new EditCommentCommand(lessonId, commentId, model.Content, date, model.Vers));
        }
 //*************
 // GET: Comment
 public ActionResult Comments(int id)
 {
     var OP = new CommentViewModel();
     OP.Thread = this.postService.GetThreadById(id);
     OP.Comments = this.postService.GetComments(id);
       //  return View("_OP", details);
     return View(OP);
 }
        public ActionResult Comments_Update([DataSourceRequest]DataSourceRequest request, CommentViewModel model)
        {
            if (ModelState.IsValid)
            {
                this.comments.Edit(model.Id, model.Content);
            }

            return Json(new[] { model }.ToDataSourceResult(request, ModelState));
        }
        public ActionResult Delete([DataSourceRequest] DataSourceRequest request, CommentViewModel comment)
        {
            if (comment != null)
            {
                var commentFromDb = this.comments.Find(comment.Id);
                this.comments.Remove(commentFromDb);
            }

            return this.Json(new[] { comment }.ToDataSourceResult(request), JsonRequestBehavior.AllowGet);
        }
        public ActionResult Create([DataSourceRequest] DataSourceRequest request, CommentViewModel product)
        {
            if (product != null && this.ModelState.IsValid)
            {
                this.comments.Create(new Comment() { AuthorEmail = product.AuthorEmail, Content = product.Content });
                this.comments.SaveChanges();
            }

            return this.Json(new[] { product }.ToDataSourceResult(request, this.ModelState));
        }
        public void AddNewComment(CommentViewModel model)
        {
            Guid lessonId = database.IdMaps.GetAggregateId<Lesson>(model.LessonId);
            Guid authorId = database.IdMaps.GetAggregateId<User>(model.Author.UserId);
            Guid parentId = model.ParentId == null ? Guid.Empty : database.IdMaps.GetAggregateId<LessonComment>(model.ParentId.Value);
            DateTime date = model.Date == null ? DateTime.Now : model.Date.Value;

            var command = new AddNewCommentCommand(lessonId, authorId, model.Content, date, parentId, model.Level, model.Vers);
            bus.Send<AddNewCommentCommand>(command);
            model.Id = database.IdMaps.GetModelId<LessonComment>(command.CommentId);
        }
        public ActionResult CreateComment(CommentViewModel model, string url)
        {
            if (!ModelState.IsValid)
            {
                return View(model);
            }

            var userId = this.HttpContext.User.Identity.GetUserId();
            this.ProductsService.AddComment(model.ProductId, userId, model.Content);

            return Redirect(url);
        }
        public ActionResult Delete([DataSourceRequest] DataSourceRequest request, CommentViewModel product)
        {
            var comment = this.comments.GetById(product.Id);

            if (product != null)
            {
                this.comments.Delete(comment);
                this.comments.SaveChanges();
            }

            return this.Json(new[] { product }.ToDataSourceResult(request, this.ModelState));
        }
Esempio n. 14
0
        public async Task<HttpResponseMessage> Post([FromUri]string postId, CommentViewModel model)
        {
            if (!ModelState.IsValid)
                return Request.CreateErrorResponse(HttpStatusCode.NotFound, "数据非法。");

            var post = await _postService.Get(postId);
            if (post == null)
                return Request.CreateErrorResponse(HttpStatusCode.NotFound, "找不到对应的文章。");

            var record = PostCommentRecord.Create(model.NickName, model.Content, post);
            _commentService.Add(record);

            return Request.CreateResponse(HttpStatusCode.OK, record.Id);
        }
Esempio n. 15
0
        public ActionResult AddComment(int id, CommentViewModel model)
        {
            if (this.ModelState.IsValid)
            {
                // FacilityComment mappedComment = AutoMapperConfig.Configuration.CreateMapper().Map<FacilityComment>(model);
                Facility commentedFacility = this.facilities.GetFacilityDetails(id);
                AppUser user = this.users.GetUserDetails(this.User.Identity.GetUserId());
                string username = user.UserName;
                var comment = this.comments.Add(id, model.Content, this.User.Identity.GetUserId(), username, commentedFacility, user.Avatar);
                return this.RedirectToAction("FacilityDetails", "FacilitiesPublic", new { id = id, area = "Facilities" });
            }

            return this.RedirectToAction("FacilityDetails", "FacilitiesPublic", new { id = id, area = "Facilities" });
        }
        public ActionResult Create([DataSourceRequest] DataSourceRequest request, CommentViewModel comment)
        {
            if (comment != null && this.ModelState.IsValid)
            {
                if (string.IsNullOrWhiteSpace(comment.Content))
                {
                    this.ModelState.AddModelError("Content", "Съдържанието на коментарa е задължително.");
                }

                var newComment = new Comment() { Content = comment.Content };
                this.comments.Add(newComment);
            }

            return this.Json(new[] { comment }.ToDataSourceResult(request), JsonRequestBehavior.AllowGet);
        }
Esempio n. 17
0
 public IHttpActionResult PostLessonComment(CommentViewModel comment)
 {
     if (!ModelState.IsValid)
     {
         return BadRequest(ModelState);
     }
     try
     {
         CommandWorker.AddNewComment(comment);
         return RedirectToRoute("GetCommentById", new { id = comment.Id.Value });
     }
     catch (Exception e)
     {
         return BadRequest(e.Message);
     }
 }
Esempio n. 18
0
        public static CommentViewModel GetComment(string commentKey)
        {
            Comment retrievedComment = PublishingRepository.GetComment(new Guid(commentKey));
            CommentViewModel newComment = new CommentViewModel();

            newComment.Key = retrievedComment.Key.ToString();
            newComment.ILikedIt = false;
            newComment.Likes = retrievedComment.CommentLikes.Count;
            newComment.Text = retrievedComment.Text;
            newComment.PublishDateTime = retrievedComment.PublishDateTime;

            var commentAuthorProfile = SecurityRepository.GetCompleteProfile(retrievedComment.Author);
            newComment.Author = new CompleteProfileViewModel { BasicProfile = new BasicProfileViewModel { ReferenceKey = commentAuthorProfile.BasicProfile.ReferenceKey.ToString(), AccountType = commentAuthorProfile.BasicProfile.ReferenceType }, FullName = commentAuthorProfile.FullName, Description1 = commentAuthorProfile.Description1, Description2 = commentAuthorProfile.Description2 };

            return newComment;
        }
        public ActionResult Update([DataSourceRequest] DataSourceRequest request, CommentViewModel comment)
        {
            if (comment != null && this.ModelState.IsValid)
            {
                this.comments.Update(new Comment()
                {
                    AuthorEmail = comment.AuthorEmail,
                    Id = comment.Id,
                    Content = comment.Content
                });

                this.comments.SaveChanges();
            }

            return this.Json(new[] { comment }.ToDataSourceResult(request, this.ModelState));
        }
Esempio n. 20
0
        public JsonResult Comment(CommentViewModel comment)
        {
            if (ModelState.IsValid)
            {
                var mapper = AutoMapperConfig.Configuration.CreateMapper();
                var commentAsAModel = mapper.Map<CommentViewModel, Comment>(comment);
                if (commentAsAModel.AuthorId != null)
                {
                    commentAsAModel.Author = this.usersService.GetUserById(commentAsAModel.AuthorId);
                }
                commentAsAModel.Question = this.questionsService.GetById(commentAsAModel.QuestionId);
                commentAsAModel.CreatedOn = DateTime.Now;

                this.commentsService.Add(commentAsAModel);
                return Json(new { isSuccessfullyAdded = true });
            }
            return Json(new { isSuccessfullyAdded = false });
        }
        public ActionResult Create(CommentViewModel commentViewModel)
        {
            var comment = new Comment()
            {
                AuthorId = this.User.Identity.GetUserId(),
                Content = commentViewModel.Content,
                CreatedAt = DateTime.Now,
                PictureId = commentViewModel.PictureId
            };

            this.Data.Comments.Add(comment);

            if (this.Data.SaveChanges() > 0)
            {
                this.SendCommentWithSignalR(comment.Id);
            }
            return Content("Create");
        }
        public async Task<ActionResult> Index()
        {
            if (this.HttpContext.Cache["comments"] != null)
            {
                Comments = this.HttpContext.Cache["comments"] as List<Comment>;
            }
            else
            {
                this.Comments = await ReadFile();
                this.HttpContext.Cache.Insert("comments", Comments, null, Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration);
            }

            var count = Math.Ceiling(Convert.ToDouble(this.Comments.Count) / 10.0);
            CommentViewModel result = new CommentViewModel();
            result.Comments = this.Comments.Take(10).ToList();
            result.Pages = countPages(1, Convert.ToInt32(count));
            ViewBag.CurrentPage = 1;
            return View(result);
        }
Esempio n. 23
0
 // 分享的评论格式不一样,所以要再单独写个转换类
 public static CommentViewModel ConvertShareCommentToCommon(RenrenShareGetCommentsResult.Comment comment)
 {
     try
     {
         CommentViewModel model = new CommentViewModel();
         if (model == null)
             return null;
         model.Title = comment.name;
         model.IconURL = comment.headurl;
         model.Content = MiscTool.RemoveHtmlTag(comment.content);
         model.ID = comment.id;
         model.TimeObject = ExtHelpers.GetRenrenTimeFullObject(comment.time);
         model.Type = EntryType.Renren;
         return model;
     }
     catch (System.Exception ex)
     {
         return null;
     }
 }
Esempio n. 24
0
        public ActionResult Comment(CommentViewModel comment)
        {
            if (comment != null && this.ModelState.IsValid)
            {
                comment.Content = this.htmlSecuritySanitizer.Clean(comment.Content);
                comment.Author = this.htmlSecuritySanitizer.Clean(comment.Author);
                comment.ArticleAlias = this.htmlSecuritySanitizer.Clean(comment.ArticleAlias);

                var alias = comment.ArticleAlias.Split('/').Last().ToLower();
                var userId = this.User.Identity.GetUserId();

                var article = this.articleService.GetAll()
                    .FirstOrDefault(x => x.Alias.Equals(alias));

                if (article == null)
                {
                    return this.RedirectToAction("Index");
                }

                if (article.Comments.LastOrDefault(x => x.AuthorId == userId) != null)
                {
                    // Last comment is again by me
                    this.TempData.Add("DoubleComment", "Моля, изчакайте да ви отоговорят преди да коментирате отново!");
                    return this.Redirect("/" + comment.ArticleAlias + "#comments");
                }

                var newComment = new Comment()
                {
                    Content = comment.Content,
                    AuthorId = userId,
                    ArticleId = article.Id
                };

                this.commentService.Add(newComment);

                return this.Redirect("/" + comment.ArticleAlias + "#comments");
            }

            return this.RedirectToAction("Index");
        }
Esempio n. 25
0
        public ActionResult PostComment(SubmitCommentModel commentModel)
        {
            if (ModelState.IsValid)
            {
                var username = this.User.Identity.GetUserName();
                var userId = this.User.Identity.GetUserId();

                this.Data.Comments.Add(new Comment()
                {
                    AuthorId = userId,
                    Content = commentModel.Comment,
                    LaptopId = commentModel.LaptopId,
                });

                this.Data.SaveChanges();

                var viewModel = new CommentViewModel { AuthorUsername = username, Content = commentModel.Comment };
                return PartialView("_CommentPartial", viewModel);
            }

            return new HttpStatusCodeResult(System.Net.HttpStatusCode.BadRequest, ModelState.Values.First().ToString());
        }
Esempio n. 26
0
 public static CommentViewModel ConvertCommentToCommon(RenrenNews.Comments.Comment comment)
 {
     try
     {
         if (comment == null)
             return null;
         CommentViewModel commentViewModel = new CommentViewModel();
         commentViewModel.Title = comment.name;
         // 人人的评论头像有可能来自headurl,也可能来自tinyurl,都要试一下
         commentViewModel.IconURL = string.IsNullOrEmpty(comment.headurl) ? comment.tinyurl : comment.headurl;
         commentViewModel.Content = MiscTool.RemoveHtmlTag(comment.text);
         commentViewModel.ID = comment.comment_id;
         commentViewModel.UID = comment.uid;
         commentViewModel.Type = EntryType.Renren;
         commentViewModel.TimeObject = ExtHelpers.GetRenrenTimeFullObject(comment.time);
         return commentViewModel;
     }
     catch (System.Exception ex)
     {
         return null;
     }
 }
Esempio n. 27
0
 public static CommentViewModel ConvertCommentToCommon(DoubanSDK.Comment comment)
 {
     try
     {
         if (comment == null)
             return null;
         CommentViewModel commentViewModel = new CommentViewModel();
         commentViewModel.Title = comment.user.screen_name;
         commentViewModel.IconURL = MiscTool.MakeFriendlyImageURL(comment.user.small_avatar);
         commentViewModel.Content = comment.text;
         commentViewModel.ID = comment.id;
         commentViewModel.UID = comment.user.id;
         commentViewModel.DoubanUID = comment.user.uid;
         commentViewModel.TimeObject = ExtHelpers.GetRenrenTimeFullObject(comment.created_at);
         commentViewModel.Type = EntryType.Douban;
         return commentViewModel;
     }
     catch (System.Exception ex)
     {
         return null;
     }
 }
Esempio n. 28
0
        public ActionResult Update(int?id, int?currentId, int?returnPageId)
        {
            var categories = categoryService.Get();

            ViewBag.Categories = categories;

            ViewBag.ReturnPageId = returnPageId;

            if (id != null)
            {
                var comment = commentService.FindById((int)id);
                var model   = new CommentViewModel
                {
                    Id      = comment.Id,
                    Message = comment.Message,
                    TopicId = comment.Topic.Id
                };
                return(View(model));
            }
            return(View(new CommentViewModel
            {
                TopicId = (int)currentId
            }));
        }
        public ActionResult PostComment(SubmitCommentModel commentModel)
        {
            if (ModelState.IsValid)
            {
                var username = this.User.Identity.GetUserName();
                var userId   = this.User.Identity.GetUserId();

                this.Data.Comments.Add(new Comment()
                {
                    AuthorId = userId,
                    Content  = commentModel.Comment,
                    LaptopId = commentModel.LaptopId,
                });

                this.Data.SaveChanges();

                var viewModel = new CommentViewModel {
                    AuthorUsername = username, Content = commentModel.Comment
                };
                return(PartialView("_CommentPartial", viewModel));
            }

            return(new HttpStatusCodeResult(System.Net.HttpStatusCode.BadRequest, ModelState.Values.First().ToString()));
        }
        public async Task <IActionResult> Comment(int id, [FromBody] Comment comment)
        {
            if (!_ctx.ModerationItems.Any(x => x.Id == id))
            {
                return(NoContent());
            }

            var regex = new Regex(@"\B(?<tag>@[a-zA-Z0-9-_]+)");

            comment.HtmlContent = regex.Matches(comment.Content)
                                  .Aggregate(comment.Content,
                                             (content, match) =>
            {
                var tag = match.Groups["tag"].Value;
                return(content
                       .Replace(tag, $"<a href=\"{tag}-user-link\">{tag}</a>"));
            });

            comment.ModerationItemId = id;
            _ctx.Add(comment);
            await _ctx.SaveChangesAsync();

            return(Ok(CommentViewModel.Create(comment)));
        }
        public async Task <IActionResult> Comment(CommentViewModel vm)
        {
            if (!ModelState.IsValid)
            {
                return(RedirectToAction("Post", new { id = vm.PostId }));
            }

            var post = _repo.GetPost(vm.PostId);

            if (vm.MainCommentId == 0)
            {
                post.MainComments = post.MainComments ?? new List <MainComment>();

                post.MainComments.Add(new MainComment
                {
                    Message = vm.Message,
                    Created = DateTime.Now,
                });

                _repo.UpdatePost(post);
            }

            else
            {
                var comment = new SubComment
                {
                    MainCommentId = vm.MainCommentId,
                    Message       = vm.Message,
                    Created       = DateTime.Now,
                };
                _repo.AddSubComment(comment);
            }
            await _repo.SaveChangesAsync();

            return(RedirectToAction("Post", new { id = vm.PostId }));
        }
Esempio n. 32
0
        public IActionResult OnPostPublishComment([FromRoute] string id, [FromForm] CommentViewModel NewComment)
        {
            Post = _dataStore.GetPost(id);

            if (Post == null)
            {
                return(RedirectToPage("/Index"));
            }
            else if (ModelState.IsValid)
            {
                Comment comment = new Comment
                {
                    AuthorName = NewComment.AuthorName,
                    Body       = NewComment.Body,
                };
                comment.IsPublic = true;
                comment.UniqueId = Guid.NewGuid();
                Post.Comments.Add(comment);
                _dataStore.SavePost(Post);
                return(Redirect("/post/" + id));
            }

            return(Page());
        }
Esempio n. 33
0
        public async Task <bool> AddJobComment(CommentViewModel jobComment)
        {
            try
            {
                var job = await _dbContext.Jobs.Include(c => c.JobComments).Where(j => j.Id == jobComment.JobId).FirstAsync();

                if (!string.IsNullOrEmpty(jobComment.Comment))
                {
                    JobComment comment = new JobComment();
                    comment.Comment         = jobComment.Comment;
                    comment.CommentedUserId = jobComment.UserId;
                    comment.JobId           = jobComment.JobId;
                    comment.CreatedDateTime = DateTime.UtcNow;

                    job.JobComments.Add(comment);
                    await _dbContext.SaveChangesAsync();
                }
                return(true);
            }
            catch (Exception)
            {
                return(false);
            }
        }
        public IActionResult Comment(CommentViewModel model)
        {
            if (model == null)
            {
                throw new ArgumentNullException(nameof(model));
            }

            if (!IsUserLoggedIn())
            {
                ModelState.AddModelError(String.Empty, Languages.LanguageStrings.PleaseLoginToComment);
            }

            BlogItem blogItem = _blogProvider.GetBlog(model.BlogId);

            if (blogItem == null)
            {
                ModelState.AddModelError(String.Empty, Languages.LanguageStrings.InvalidBlog);
            }


            if (ModelState.IsValid)
            {
                UserSession user    = GetUserSession();
                string      comment = WebUtility.HtmlEncode(model.Comment).Replace("\r\n", "<br />");
                _blogProvider.AddComment(blogItem, null, user.UserID, user.UserName, comment);
                return(Redirect(GetBlogItemUrl(blogItem)));
            }

            BlogPostViewModel blogModel = GetBlogPostViewModel(blogItem);

            blogModel.Breadcrumbs.Add(new BreadcrumbItem(Languages.LanguageStrings.Blog, $"/{Name}/{nameof(Index)}", false));
            blogModel.Breadcrumbs.Add(new BreadcrumbItem(blogItem.Title, blogModel.Url, false));
            model.Comment = String.Empty;

            return(View("ViewBlog", blogModel));
        }
Esempio n. 35
0
 public ActionResult Create(CommentViewModel comment)
 {
     if (ModelState.IsValid)
     {
         var user = userService.GetAll().FirstOrDefault(u => u.Login == User.Identity.Name);
         commentService.Create(new CommentEntity()
         {
             CreationDate = DateTime.Now,
             CreationTime = DateTime.Now.TimeOfDay,
             Name         = comment.Name,
             NewId        = comment.NewsId,
             UserId       = user.Id
         });
         if (Request.IsAjaxRequest())
         {
             var comments = commentService.GetAll()
                            .Where(com => com.NewId == comment.NewsId)
                            .OrderByDescending(com => com.CreationDate)
                            .ThenByDescending(com => com.CreationTime).ToList();
             return(PartialView("_Comments", comments));
         }
     }
     return(RedirectToAction("About", "Home", comment.NewsId));
 }
Esempio n. 36
0
 public MemberViewModel(DocumentIdViewModel id,
                        DocumentUriViewModel uri,
                        TitlesViewModel titles,
                        SyntaxViewModel syntax,
                        LocationViewModel location,
                        DocumentReferenceViewModel declaredIn,
                        ParametersViewModel parameters,
                        ReturnsViewModel returns,
                        UxMemberPropertiesViewModel uxProperties,
                        ValuesViewModel values,
                        MemberFlagsViewModel flags,
                        CommentViewModel comment,
                        AttributesViewModel attributes,
                        IEntity underlyingEntity)
     : base(id, uri, titles, syntax, comment, declaredIn, underlyingEntity)
 {
     Location     = location;
     Parameters   = parameters;
     Returns      = returns;
     UxProperties = uxProperties;
     Flags        = flags;
     Values       = values;
     Attributes   = attributes;
 }
Esempio n. 37
0
        public ActionResult Comments(CommentViewModel collection)
        {
            var request = new FilteredModel <Comment>
            {
                PageIndex = collection.ThisPageIndex,
                Order     = collection.PageOrder,
                OrderBy   = collection.PageOrderBy
            };
            var offset = (request.PageIndex - 1) * request.PageSize;
            var result = _mapper.Map <IList <CommentViewModel> >(_commentService.GetPaging(_mapper.Map <Comment>(collection), out long totalCount, request.OrderBy, request.Order, offset, request.PageSize));

            if (!result.Any() && totalCount > 0 && request.PageIndex > 1)
            {
                request.PageIndex = (int)(totalCount / request.PageSize);
                if (totalCount % request.PageSize > 0)
                {
                    request.PageIndex++;
                }
                result = _mapper.Map <IList <CommentViewModel> >(_commentService.GetPaging(_mapper.Map <Comment>(collection), out totalCount, request.OrderBy, request.Order, offset, request.PageSize));
            }
            ViewBag.OnePageOfEntries = new StaticPagedList <CommentViewModel>(result, request.PageIndex, request.PageSize, (int)totalCount);
            ViewBag.SearchModel      = collection;
            return(View());
        }
Esempio n. 38
0
        //
        // GET: /Comment/Details/By ID

        public ActionResult Details(int id)
        {
            try
            {
                var comment = _db.Comments.Find(id);
                if (comment != null)
                {
                    var commentViewModel = new CommentViewModel {
                        Id = comment.Id, Name = comment.Name, Email = comment.Email, Description = comment.Description, CreateDate = comment.CreateDate, PostId = comment.PostId
                    };

                    return(PartialView("_Details", commentViewModel));
                }
                else
                {
                    return(RedirectToAction("Index", "Comment"));
                }
            }
            catch (Exception ex)
            {
                ExceptionHelper.ExceptionMessageFormat(ex, true);
                return(RedirectToAction("Index", "Comment"));
            }
        }
        public async Task SendMessage(string postId, string text)
        {
            if (string.IsNullOrEmpty(text) || string.IsNullOrWhiteSpace(text))
            {
                return;
            }
            Claim   userIdClaim = Context.User.Claims.FirstOrDefault(a => a.Type == ClaimTypes.NameIdentifier);
            Comment commresult  = await this.postService.AddComment(postId, text, userIdClaim.Value);

            if (commresult == null)
            {
                return;
            }
            var commentViewModel = new CommentViewModel()
            {
                Comment         = commresult,
                IsDeleteAllowed = await this.postService.IsDeleteAllowed(commresult.User, userIdClaim.Value),
                IsReportAllowed = await this.postService.IsReportAllowed(commresult.UserId, userIdClaim.Value, commentId : commresult.Id),
                ShowReportColor = false
            };
            string res = await this.renderService.RenderToStringAsync(R4MvcExtensions._CommentBlock, commentViewModel);

            await Clients.All.SendAsync(R4MvcExtensions.SendCommentHub, res, postId, commentViewModel.Comment.Id.ToString());
        }
Esempio n. 40
0
        public ActionResult Add(CommentViewModel viewModel)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    var comment = new Comment {
                        Id = viewModel.Id, Name = viewModel.Name, Email = viewModel.Email, Description = viewModel.Description, CreateDate = DateTime.Now, PostId = viewModel.PostId
                    };

                    _db.Comments.Add(comment);
                    _db.SaveChanges();

                    return(Content(Boolean.TrueString));
                }

                return(Content(ExceptionHelper.ModelStateErrorFormat(ModelState)));
            }
            catch (Exception ex)
            {
                ExceptionHelper.ExceptionMessageFormat(ex, true);
                return(Content("Sorry! Unable to add this comment."));
            }
        }
        public ActionResult LoadComments(int pageNumber)
        {
            this.Comments = this.HttpContext.Cache["comments"] as List<Comment>;
            int numberCommentsOnThePage = int.Parse(WebConfigurationManager.AppSettings["numberCommentsOnThePage"]);
            if (pageNumber <= 0)
            {
                pageNumber = 1;
            }

            CommentViewModel result = new CommentViewModel();
            double count = Convert.ToDouble(Comments.Count) / 10.0;
            var comments = Comments.Skip((pageNumber - 1) * 10).Take(10);
            result.Comments = comments.ToList();
            result.Pages = countPages(pageNumber, Convert.ToInt32(count));

            if (Request.IsAjaxRequest())
            {
                return Json(result, JsonRequestBehavior.AllowGet);
            }
            else
            {
                return View("Index", result);
            }
        }
Esempio n. 42
0
        public async Task <IActionResult> Create([FromBody] CommentViewModel model, [FromRoute] int coachId, CancellationToken ct)
        {
            var comment = model.Adapt <Comment>();
            var coach   = await _coachService.GetAsync(coachId, ct);

            if (coach == null)
            {
                return(BadRequest());
            }

            var user = await GetCurrentUserAsync();

            if (user.Coach?.Id == coachId)
            {
                return(BadRequest());
            }

            comment.Coach = coach;
            comment.User  = user;

            await _commentService.CreateAsync(comment, ct);

            return(Ok(comment.Id));
        }
Esempio n. 43
0
 public async Task <ActionResult> CreateComment(CommentViewModel model)
 {
     try
     {
         model.CommentBy = CurrentUser.DisplayName;
         _repo.AddComments(_mapper.Map <Comment>(model), CurrentUser.Id);
         if (await _repo.SaveAllAsync())
         {
             TempData["Success"] = string.Format("Comment has been successfully Sent");
             return(RedirectToAction("Index"));
         }
         else
         {
             TempData["Error"] = "Unable to create Comment due to some internal issues.";
             return(RedirectToAction("Index"));
         }
     }
     catch (Exception e)
     {
         _telemetryClient.TrackException(e);
         ModelState.AddModelError("error", e.Message);
         return(ServerError());
     }
 }
Esempio n. 44
0
        public ActionResult Show(int id, string slug, CommentViewModel cvm)
        {
            var post = db.Posts.Find(id);

            if (post == null)
            {
                return(HttpNotFound());
            }
            if (post.Slug != slug)
            {
                return(RedirectToAction("Show", new { id = id, slug = post.Slug }));
            }
            if (ModelState.IsValid)
            {
                var comment = new Comment
                {
                    AuthorId         = User.Identity.GetUserId(),
                    Content          = cvm.Content,
                    CreationTime     = DateTime.Now,
                    ModificationTime = DateTime.Now,
                    State            = Enums.CommentState.Approved,
                    PostId           = id,
                    ParentId         = cvm.ParentId
                };
                db.Comments.Add(comment);
                db.SaveChanges();
                return(Redirect(Url.RouteUrl(new{ controller = "Post", action = "Show", id = id, slug = slug, commmetSuccess = true }) + "#leave-a-comment"));
            }
            var vm = new ShowPostViewModel
            {
                Post             = post,
                commentViewModel = cvm
            };

            return(View(vm));
        }
Esempio n. 45
0
        public ActionResult Edit(CommentViewModel viewModel)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    var comment = new Comment {
                        Id = viewModel.Id, Name = viewModel.Name, Email = viewModel.Email, Description = viewModel.Description
                    };

                    _db.Entry(comment).State = EntityState.Modified;
                    _db.SaveChanges();

                    return(Content(Boolean.TrueString));
                }

                return(Content(ExceptionHelper.ModelStateErrorFormat(ModelState)));
            }
            catch (Exception ex)
            {
                ExceptionHelper.ExceptionMessageFormat(ex, true);
                return(Content("Sorry! Unable to edit this comment."));
            }
        }
        public ActionResult PostComment(CommentViewModel comment)
        {
            var post = DbContext.Posts.Where(p => p.Id == comment.PostID).Include(p => p.PostedForum).FirstOrDefault();

            if (post == null)
            {
                //Gör något, posten finns inte
            }

            var c = new Comment
            {
                User     = UserManager.FindById(User.Identity.GetUserId()),
                Content  = comment.Content,
                TimeSent = DateTime.Now,
                Post     = post
            };



            DbContext.Comments.Add(c);
            DbContext.SaveChanges();

            return(RedirectToAction("Index", "Forum", new { id = post.PostedForum.Id }));
        }
Esempio n. 47
0
 public ActionResult Komentarze()
 {
     if (TempData["Message"] != null)
     {
         ModelState.AddModelError("", TempData["Message"].ToString());
     }
     using (sklepEntities db = new sklepEntities())
     {
         var comments = db.Comments;
         List <CommentViewModel> listComments = new List <CommentViewModel>();
         foreach (Comments item in comments)
         {
             CommentViewModel comment = new CommentViewModel();
             comment.CommentID   = item.CommentID;
             comment.ProductID   = item.ProductID;
             comment.Date        = item.Date;
             comment.Description = item.Description;
             string userLogin = db.Users.Where(x => x.UserID == item.UserID).Select(x => x.UserName).Single();
             comment.User = userLogin;
             listComments.Add(comment);
         }
         return(View(listComments));
     }
 }
 public void AddComment(CommentViewModel model)
 {
     _commentsRepo.AddComment(_autoMapper.Map <Comment>(model));
 }
Esempio n. 49
0
 public CommentView()
 {
     InitializeComponent();
     DataContext = new CommentViewModel();
 }
 public ActionResult Create(int id)
 {
     var model = new CommentViewModel();
     model.SnippetId = id;
     return this.PartialView("_CommentForm", model);
 }
Esempio n. 51
0
            private void Comment_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
            {
                if (e.Action == NotifyCollectionChangedAction.Add)
                {
                    if (sender == _originalCollection)
                    {
                        foreach (ViewModelBase vm in e.NewItems)
                        {
                            VisitAddChildren(vm, this.Count);
                        }
                    }
                    else
                    {
                        int index = 0;
                        ObservableCollection <ViewModelBase> collection = sender as ObservableCollection <ViewModelBase>;

                        // Find the previous element of the triggering collection
                        CommentViewModel previousItem = null;

                        if (collection.Count > 1)
                        {
                            previousItem = collection[collection.Count - 2] as CommentViewModel;
                        }

                        if (previousItem != null)
                        {
                            // If we have the previous item, find its last child
                            var lastChild = GetLastChild(previousItem);
                            index = this.IndexOf(lastChild);
                        }
                        else
                        {
                            // Otherwise, use our parent's index
                            for (int i = this.Count - 1; i > 0; i--)
                            {
                                if (this[i] is CommentViewModel)
                                {
                                    var comment = this[i] as CommentViewModel;
                                    if (comment.Replies == sender)
                                    {
                                        index = i;
                                        break;
                                    }
                                }
                            }
                        }

                        if (index > 0)
                        {
                            foreach (ViewModelBase vm in e.NewItems)
                            {
                                VisitAddChildren(vm, index + 1);
                            }
                        }
                    }
                }
                else if (e.Action == NotifyCollectionChangedAction.Remove)
                {
                    foreach (ViewModelBase oldItem in e.OldItems)
                    {
                        this.Remove(oldItem);
                    }
                }
            }
Esempio n. 52
0
        public virtual async Task <IActionResult> AjaxPostComment(CommentViewModel model)
        {
            // disable status code page for ajax requests
            var statusCodePagesFeature = HttpContext.Features.Get <IStatusCodePagesFeature>();

            if (statusCodePagesFeature != null)
            {
                statusCodePagesFeature.Enabled = false;
            }

            // this should validate the [EmailAddress] on the model
            // failure here should indicate invalid email since it is the only attribute in use
            if (!ModelState.IsValid)
            {
                Response.StatusCode = 403;
                //await Response.WriteAsync("Please enter a valid e-mail address");
                return(Content(StringLocalizer["Please enter a valid e-mail address"]));
            }

            var project = await ProjectService.GetCurrentProjectSettings();

            if (project == null)
            {
                Log.LogDebug("returning 500 blog not found");
                return(StatusCode(500));
            }

            if (string.IsNullOrEmpty(model.PostId))
            {
                Log.LogDebug("returning 500 because no postid was posted");
                return(StatusCode(500));
            }

            if (string.IsNullOrEmpty(model.Name))
            {
                Log.LogDebug("returning 403 because no name was posted");
                Response.StatusCode = 403;
                //await Response.WriteAsync("Please enter a valid name");
                return(Content("Please enter a valid name"));
            }

            if (string.IsNullOrEmpty(model.Content))
            {
                Log.LogDebug("returning 403 because no content was posted");
                Response.StatusCode = 403;
                //await Response.WriteAsync("Please enter a valid content");
                return(Content("Please enter a valid content"));
            }

            var blogPost = await BlogService.GetPost(model.PostId);

            if (blogPost == null)
            {
                Log.LogDebug("returning 500 blog post not found");
                return(StatusCode(500));
            }

            if (!HttpContext.User.Identity.IsAuthenticated)
            {
                if (!string.IsNullOrEmpty(project.RecaptchaPublicKey))
                {
                    var captchaResponse = await RecaptchaServerSideValidator.ValidateRecaptcha(Request, project.RecaptchaPrivateKey);

                    if (!captchaResponse.Success)
                    {
                        Log.LogDebug("returning 403 captcha validation failed");
                        Response.StatusCode = 403;
                        //await Response.WriteAsync("captcha validation failed");
                        return(Content("captcha validation failed"));
                    }
                }
            }

            var userAgent = HttpContext.Request.Headers["User-Agent"].ToString();

            var canEdit = await User.CanEditBlog(project.Id, AuthorizationService);

            var isApproved = canEdit;

            if (!isApproved)
            {
                isApproved = !project.ModerateComments;
            }

            var comment = new Comment()
            {
                Id        = Guid.NewGuid().ToString(),
                Author    = model.Name,
                Email     = model.Email,
                Website   = GetUrl(model.WebSite),
                Ip        = HttpContext.Connection.RemoteIpAddress.MapToIPv4().ToString(),
                UserAgent = userAgent,
                IsAdmin   = User.CanEditProject(project.Id),
                Content   = System.Text.Encodings.Web.HtmlEncoder.Default.Encode(
                    model.Content.Trim()).Replace("\n", "<br />"),

                IsApproved = isApproved,
                PubDate    = DateTime.UtcNow
            };

            blogPost.Comments.Add(comment);
            await BlogService.Update(blogPost);

            // TODO: clear cache

            //no need to send notification when project owner posts a comment, ie in response
            var shouldSendEmail = !canEdit;

            if (shouldSendEmail)
            {
                var postUrl = await BlogService.ResolvePostUrl(blogPost);

                var baseUrl = string.Concat(HttpContext.Request.Scheme,
                                            "://",
                                            HttpContext.Request.Host.ToUriComponent());

                postUrl = baseUrl + postUrl;

                EmailService.SendCommentNotificationEmailAsync(
                    project,
                    blogPost,
                    comment,
                    postUrl,
                    postUrl,
                    postUrl
                    ).Forget(); //async but don't want to wait
            }

            var viewModel = new BlogViewModel(ContentProcessor)
            {
                ProjectSettings = project,
                BlogRoutes      = BlogRoutes,
                CurrentPost     = blogPost,
                TmpComment      = comment,
                TimeZoneHelper  = TimeZoneHelper,
                TimeZoneId      = project.TimeZoneId,
                CanEdit         = canEdit
            };


            return(PartialView("CommentPartial", viewModel));
        }
Esempio n. 53
0
        public IActionResult Question(int questionId, string title)
        {
            int lintUserId = HttpContext.Session.GetInt32("UserId") ?? 0;
            QuestionViewModel questionViewModel = new QuestionViewModel();

            using (var unitOfWork = new UnitOfWork(new CuriousDriveContext()))
            {
                Question question = unitOfWork.Questions.GetQuestionDetails(questionId);

                questionViewModel.questionId    = question.QuestionId;
                questionViewModel.questionTitle = question.QuestionTitle;
                questionViewModel.questionHtml  = question.QuestionHtml;
                questionViewModel.createdDate   = question.CreatedDate;

                questionViewModel.userDetailsViewModel = new UserDetailsViewModel();

                questionViewModel.userDetailsViewModel.userId      = question.User.UserId;
                questionViewModel.userDetailsViewModel.displayName = question.User.DisplayName;
                questionViewModel.userDetailsViewModel.urlTitle    = Utility.GetURLTitle(question.User.DisplayName);

                questionViewModel.userDetailsViewModel.profilePictureViewModel = new ProfilePictureViewModel();

                questionViewModel.userTagListViewModel = new List <UserTagViewModel>();

                foreach (Tag tag in question.Tag)
                {
                    foreach (TagDetail tagDetail in tag.TagDetail)
                    {
                        UserTagViewModel userTagViewModel = new UserTagViewModel();

                        userTagViewModel.userId  = tagDetail.TaggedUser.UserId;
                        userTagViewModel.userTag = tagDetail.TaggedUser.DisplayName;

                        questionViewModel.userTagListViewModel.Add(userTagViewModel);
                    }
                }

                questionViewModel.commentsViewModel = new List <CommentViewModel>();

                foreach (Comment comment in question.Comment)
                {
                    CommentViewModel commentViewModel = new CommentViewModel();

                    commentViewModel.commentId   = comment.CommentId;
                    commentViewModel.commentHtml = comment.CommentHtml;
                    commentViewModel.userId      = comment.User.UserId;
                    commentViewModel.displayName = comment.User.DisplayName;
                    commentViewModel.urlTitle    = Utility.GetURLTitle(comment.User.DisplayName);

                    questionViewModel.commentsViewModel.Add(commentViewModel);
                }

                questionViewModel.questionAnswersViewModel = new List <QuestionAnswerViewModel>();

                foreach (QuestionAnswer questionAnswer in question.QuestionAnswer)
                {
                    QuestionAnswerViewModel questionAnswerViewModel = new QuestionAnswerViewModel();

                    questionAnswerViewModel.questionId       = question.QuestionId;
                    questionAnswerViewModel.questionAnswerId = questionAnswer.QuestionAnswerId;
                    questionAnswerViewModel.answerHtml       = questionAnswer.AnswerHtml;
                    questionAnswerViewModel.createdDate      = questionAnswer.CreatedDate;

                    questionAnswerViewModel.commentsViewModel = new List <CommentViewModel>();

                    foreach (Comment comment in questionAnswer.Comment)
                    {
                        CommentViewModel commentViewModel = new CommentViewModel();

                        commentViewModel.commentId   = comment.CommentId;
                        commentViewModel.commentHtml = comment.CommentHtml;
                        commentViewModel.userId      = comment.User.UserId;
                        commentViewModel.displayName = comment.User.DisplayName;
                        commentViewModel.urlTitle    = Utility.GetURLTitle(comment.User.DisplayName);

                        questionAnswerViewModel.commentsViewModel.Add(commentViewModel);
                    }

                    questionAnswerViewModel.userDetailsViewModel = new UserDetailsViewModel();

                    questionAnswerViewModel.userDetailsViewModel.userId      = questionAnswer.UserId;
                    questionAnswerViewModel.userDetailsViewModel.displayName = questionAnswer.User.DisplayName;
                    questionAnswerViewModel.userDetailsViewModel.urlTitle    = Utility.GetURLTitle(questionAnswer.User.DisplayName);

                    questionAnswerViewModel.userDetailsViewModel.profilePictureViewModel = new ProfilePictureViewModel();

                    questionViewModel.questionAnswersViewModel.Add(questionAnswerViewModel);
                }

                questionViewModel.questionClassesViewModel = new List <QuestionClassViewModel>();

                foreach (QuestionClass questionClass in question.QuestionClass)
                {
                    QuestionClassViewModel questionClassViewModel = new QuestionClassViewModel();

                    questionClassViewModel.classId   = questionClass.ClassId;
                    questionClassViewModel.className = questionClass.Class.ClassName;

                    questionViewModel.questionClassesViewModel.Add(questionClassViewModel);
                }
            }

            return(View(questionViewModel));
        }
Esempio n. 54
0
        #pragma warning disable 1998
        public async override global::System.Threading.Tasks.Task ExecuteAsync()
        {
            BeginContext(13, 2, true);
            WriteLiteral("\r\n");
            EndContext();
#line 3 "C:\Users\NickTsai\Documents\GitHub\Blog\Blog\Views\Home\Post.cshtml"

            ViewBag.Title       = Model.Title;
            ViewBag.Description = Model.Description;
            ViewBag.Keywords    = $"{Model.Tags?.Replace(",", " ")} {Model.Category}";

#line default
#line hidden
            BeginContext(179, 61, true);
            WriteLiteral("\r\n<div class=\"container\">\r\n    <div class=\"post no-shadow\">\r\n");
            EndContext();
#line 11 "C:\Users\NickTsai\Documents\GitHub\Blog\Blog\Views\Home\Post.cshtml"
            if (!String.IsNullOrEmpty(Model.Image))
            {
                var image_path = $"/Image/{Model.Image}";

#line default
#line hidden
                BeginContext(356, 16, true);
                WriteLiteral("            <img");
                EndContext();
                BeginWriteAttribute("src", " src=\"", 372, "\"", 389, 1);
#line 14 "C:\Users\NickTsai\Documents\GitHub\Blog\Blog\Views\Home\Post.cshtml"
                WriteAttributeValue("", 378, image_path, 378, 11, false);

#line default
#line hidden
                EndWriteAttribute();
                BeginContext(390, 37, true);
                WriteLiteral(" />\r\n            <span class=\"title\">");
                EndContext();
                BeginContext(428, 11, false);
#line 15 "C:\Users\NickTsai\Documents\GitHub\Blog\Blog\Views\Home\Post.cshtml"
                Write(Model.Title);

#line default
#line hidden
                EndContext();
                BeginContext(439, 9, true);
                WriteLiteral("</span>\r\n");
                EndContext();
#line 16 "C:\Users\NickTsai\Documents\GitHub\Blog\Blog\Views\Home\Post.cshtml"
            }

#line default
#line hidden
            BeginContext(459, 51, true);
            WriteLiteral("    </div>\r\n\r\n    <div class=\"post-body\">\r\n        ");
            EndContext();
            BeginContext(511, 20, false);
#line 20 "C:\Users\NickTsai\Documents\GitHub\Blog\Blog\Views\Home\Post.cshtml"
            Write(Html.Raw(Model.Body));

#line default
#line hidden
            EndContext();
            BeginContext(531, 51, true);
            WriteLiteral("\r\n    </div>\r\n\r\n    <div class=\"comment-section\">\r\n");
            EndContext();
#line 24 "C:\Users\NickTsai\Documents\GitHub\Blog\Blog\Views\Home\Post.cshtml"

            CommentViewModel viewWindow = new CommentViewModel {
                PostId = Model.Id, MainCommentId = 0
            };


#line default
#line hidden
            BeginContext(711, 2, true);
            WriteLiteral("\r\n");
            EndContext();
#line 28 "C:\Users\NickTsai\Documents\GitHub\Blog\Blog\Views\Home\Post.cshtml"

            await Html.RenderPartialAsync("_MainComment", viewWindow);


#line default
#line hidden
            BeginContext(808, 2, true);
            WriteLiteral("\r\n");
            EndContext();
            BeginContext(1017, 31, true);
            WriteLiteral("\r\n    </div>\r\n\r\n\r\n\r\n    <div>\r\n");
            EndContext();
#line 42 "C:\Users\NickTsai\Documents\GitHub\Blog\Blog\Views\Home\Post.cshtml"
            foreach (var comment in Model.MainComments)
            {
#line default
#line hidden
                BeginContext(1113, 33, true);
                WriteLiteral("            <p>\r\n                ");
                EndContext();
                BeginContext(1147, 16, false);
#line 45 "C:\Users\NickTsai\Documents\GitHub\Blog\Blog\Views\Home\Post.cshtml"
                Write(comment.UserName);

#line default
#line hidden
                EndContext();
                BeginContext(1163, 6, true);
                WriteLiteral(" ==>  ");
                EndContext();
                BeginContext(1170, 15, false);
#line 45 "C:\Users\NickTsai\Documents\GitHub\Blog\Blog\Views\Home\Post.cshtml"
                Write(comment.Message);

#line default
#line hidden
                EndContext();
                BeginContext(1185, 5, true);
                WriteLiteral(" --- ");
                EndContext();
                BeginContext(1191, 15, false);
#line 45 "C:\Users\NickTsai\Documents\GitHub\Blog\Blog\Views\Home\Post.cshtml"
                Write(comment.Created);

#line default
#line hidden
                EndContext();
                BeginContext(1206, 41, true);
                WriteLiteral("\r\n                 - \r\n                <a");
                EndContext();
                BeginWriteAttribute("onclick", " onclick=\"", 1247, "\"", 1288, 3);
                WriteAttributeValue("", 1257, "javascript:showDiv(", 1257, 19, true);
#line 47 "C:\Users\NickTsai\Documents\GitHub\Blog\Blog\Views\Home\Post.cshtml"
                WriteAttributeValue("", 1276, comment.Id, 1276, 11, false);

#line default
#line hidden
                WriteAttributeValue("", 1287, ")", 1287, 1, true);
                EndWriteAttribute();
                BeginContext(1289, 89, true);
                WriteLiteral(">\r\n                    Reply\r\n                </a>\r\n                -\r\n                <a");
                EndContext();
                BeginWriteAttribute("onclick", " onclick=\"", 1378, "\"", 1419, 3);
                WriteAttributeValue("", 1388, "javascript:hideDiv(", 1388, 19, true);
#line 51 "C:\Users\NickTsai\Documents\GitHub\Blog\Blog\Views\Home\Post.cshtml"
                WriteAttributeValue("", 1407, comment.Id, 1407, 11, false);

#line default
#line hidden
                WriteAttributeValue("", 1418, ")", 1418, 1, true);
                EndWriteAttribute();
                BeginContext(1420, 71, true);
                WriteLiteral(">\r\n                    Cancle\r\n                </a>\r\n            </p>\r\n");
                EndContext();
                BeginContext(1493, 45, true);
                WriteLiteral("            <div style=\"margin-left:20px;\">\r\n");
                EndContext();
#line 57 "C:\Users\NickTsai\Documents\GitHub\Blog\Blog\Views\Home\Post.cshtml"
                foreach (var subComment in comment.SubComments)
                {
#line default
#line hidden
                    BeginContext(1623, 41, true);
                    WriteLiteral("                <p>\r\n                    ");
                    EndContext();
                    BeginContext(1665, 19, false);
#line 60 "C:\Users\NickTsai\Documents\GitHub\Blog\Blog\Views\Home\Post.cshtml"
                    Write(subComment.UserName);

#line default
#line hidden
                    EndContext();
                    BeginContext(1684, 6, true);
                    WriteLiteral(" ==>  ");
                    EndContext();
                    BeginContext(1691, 18, false);
#line 60 "C:\Users\NickTsai\Documents\GitHub\Blog\Blog\Views\Home\Post.cshtml"
                    Write(subComment.Message);

#line default
#line hidden
                    EndContext();
                    BeginContext(1709, 5, true);
                    WriteLiteral(" --- ");
                    EndContext();
                    BeginContext(1715, 18, false);
#line 60 "C:\Users\NickTsai\Documents\GitHub\Blog\Blog\Views\Home\Post.cshtml"
                    Write(subComment.Created);

#line default
#line hidden
                    EndContext();
                    BeginContext(1733, 24, true);
                    WriteLiteral("\r\n                </p>\r\n");
                    EndContext();
#line 62 "C:\Users\NickTsai\Documents\GitHub\Blog\Blog\Views\Home\Post.cshtml"
                }

#line default
#line hidden
                BeginContext(1776, 20, true);
                WriteLiteral("            </div>\r\n");
                EndContext();
                BeginContext(1798, 21, true);
                WriteLiteral("            <div id= ");
                EndContext();
                BeginContext(1820, 10, false);
#line 65 "C:\Users\NickTsai\Documents\GitHub\Blog\Blog\Views\Home\Post.cshtml"
                Write(comment.Id);

#line default
#line hidden
                EndContext();
                BeginContext(1830, 24, true);
                WriteLiteral(" style=\"display:none\">\r\n");
                EndContext();
#line 66 "C:\Users\NickTsai\Documents\GitHub\Blog\Blog\Views\Home\Post.cshtml"

                await Html.RenderPartialAsync("_MainComment", new CommentViewModel { PostId = Model.Id, MainCommentId = comment.Id });


#line default
#line hidden
                BeginContext(2033, 20, true);
                WriteLiteral("            </div>\r\n");
                EndContext();
#line 70 "C:\Users\NickTsai\Documents\GitHub\Blog\Blog\Views\Home\Post.cshtml"
            }

#line default
#line hidden
            BeginContext(2066, 399, true);
            WriteLiteral(@"    </div>
</div>

<script language=""javascript"" type='text/javascript'>
    function showDiv(id) {
        if (document.getElementById(id)) {
            document.getElementById(id).style.display = 'block';
        }
    }
    function hideDiv(id) {
        if (document.getElementById(id)) {
            document.getElementById(id).style.display = 'none';
        }
    }
</script>
");
            EndContext();
        }
Esempio n. 55
0
        public IActionResult Index(string blogId, int pageIndex = 1, int pageRows = 5)
        {
            List <CommentViewModel> comments = new List <CommentViewModel>();

            //int count = 0;
            //int total = 0;

            using (SqlConnection conn = new SqlConnection(DataAccessBase.CONNECTION_STRING))
            {
                conn.Open();

                using (SqlCommand command = new SqlCommand("select blogid, commentid, comment, createdtime, updatedtime from comment where blogId=@blogId", conn))
                {
                    command.CommandType = CommandType.Text;
                    command.Parameters.Add("@blogId", SqlDbType.UniqueIdentifier).Value = new Guid(blogId);
                    //command.Parameters.Add("@pageIndex", System.Data.SqlDbType.Int).Value = pageIndex;

                    //command.Parameters.Add("@pageRows", System.Data.SqlDbType.Int).Value = pageRows;

                    //command.Parameters.Add("@pageCount", System.Data.SqlDbType.Int);
                    //command.Parameters["@pageCount"].Direction = System.Data.ParameterDirection.Output;

                    //command.Parameters.Add("@total", System.Data.SqlDbType.Int);
                    //command.Parameters["@total"].Direction = System.Data.ParameterDirection.Output;

                    SqlDataReader reader = command.ExecuteReader();

                    while (reader.Read())
                    {
                        CommentViewModel comment = new CommentViewModel();

                        comment.BlogId      = reader.GetGuid(0);
                        comment.CommentId   = reader.GetGuid(1);
                        comment.Comment     = reader.GetString(2);
                        comment.CreatedTime = reader.GetDateTime(3);
                        comment.UpdatedTime = reader.GetDateTime(4);

                        comments.Add(comment);
                    }

                    if (!reader.IsClosed)
                    {
                        reader.Dispose();
                    }

                    //if (command.Parameters["@pageCount"].Value != null)
                    //    count = int.Parse(command.Parameters["@pageCount"].Value.ToString());

                    //if (command.Parameters["@total"].Value != null)
                    //    total = int.Parse(command.Parameters["@total"].Value.ToString());
                }
            }

            //int previous = 1;

            //previous = pageIndex - 1;

            //if (previous <= 0)
            //{
            //    previous = 1;
            //}
            //else
            //{
            //    if (previous > count && count > 0)
            //    {
            //        previous = count;
            //    }
            //}

            //int next = 1;

            //next = pageIndex + 1;

            //if (next <= 0)
            //{
            //    next = 1;
            //}
            //else
            //{
            //    if (next > count && count > 0)
            //    {
            //        next = count;
            //    }
            //}

            //int currentPageIndex = 1;

            //if (currentPageIndex <= 0)
            //{
            //    currentPageIndex = 1;
            //}
            //else if (currentPageIndex > count)
            //{
            //    if (count > 0)
            //        currentPageIndex = count;
            //    else
            //        currentPageIndex = 1;
            //}
            //else
            //{
            //    currentPageIndex = pageIndex;
            //}

            //int firstPage = 1;
            //int lastPage = count == 0 ? 1 : count;

            //ViewBag.PageCounts = count;

            //ViewBag.Previous = previous;
            //ViewBag.Next = next;
            //ViewBag.CurrentIndex = currentPageIndex;
            //ViewBag.Total = total;
            //ViewBag.FirstPage = firstPage;
            //ViewBag.LastPage = lastPage;
            ViewBag.Comments = comments;
            ViewBag.BlogId   = blogId;

            return(View());
        }
 public CommentViewModel(CommentViewModel mapTo)
 {
     
 }
Esempio n. 57
0
        public CommentViewModel Get(int id)
        {
            CommentViewModel comment = _commentService.Get(id);

            return(comment);
        }
Esempio n. 58
0
        public async Task <IActionResult> AddComment([FromForm] int postId, [FromForm] string content)
        {
            var post = await _postService.GetPostWithUserAsync(postId);

            if (post == null)
            {
                return(NotFound());
            }

            var currentUserId = await _userService.GetCurrentUserIdAsync();

            var comment = new Comment
            {
                Content     = content,
                CommentById = currentUserId,
                PostId      = post.Id,
            };

            await _postService.AddCommentToPostAsync(comment);

            await _unitOfWork.CompleteAsync();

            var userSetting = await _userService.GetUserSettingUserIdAsync(post.CreatedBy.Id);

            //Notify the user who created the post
            if (!post.IsForCurrentUser(currentUserId))
            {
                if (userSetting.NotifyWhenUserCommentOnPost)
                {
                    var attributes = new List <NotificationAttribute>
                    {
                        new NotificationAttribute
                        {
                            Name  = "CommentId",
                            Value = comment.Id.ToString()
                        },
                        new NotificationAttribute
                        {
                            Name  = "PostId",
                            Value = post.Id.ToString()
                        }
                    };
                    var notification =
                        new Notification(post.CreatedBy, currentUserId, NotificationType.Comment, attributes);

                    post.CreatedBy.CreateNotification(notification);

                    await _unitOfWork.CompleteAsync();

                    await _notificationService.PushNotification(post.CreatedBy.Id, notification.Id);
                }
            }

            await _unitOfWork.CompleteAsync();


            var model = new CommentViewModel
            {
                Comments = new List <Comment>
                {
                    comment
                },
            };

            var commentTemplate = await _renderService.RenderViewToStringAsync("Templates/_Comment", model);

            return(Json(new
            {
                postId = comment.PostId,
                totalComments = await _postService.GetTotalCommentsForPostAsnyc(comment.PostId),
                comment = commentTemplate
            }));
        }
        public UpdatedCommentsViewModel CreateNewComment(NewCommentData data)
        {
            try
            {
                using (ApplicationDbContext context = new ApplicationDbContext())
                {
                    UpdatedCommentsViewModel viewModel = new UpdatedCommentsViewModel();
                    var task = context.Tasks.FirstOrDefault(t => t.TaskID == data.TaskID);
                    if (task != null)
                    {
                        viewModel.IsValid = true;

                        viewModel.IsValid = true;
                        if (IsAuthorized(task, context))
                        {
                            viewModel.IsAuthorized = true;
                            ApplicationUser logedUser = GetUser(context);

                            DateTime currentDateTime = DateTime.Now;

                            Comment newComment = new Comment()
                            {
                                Content = data.Content, Created = currentDateTime.AddMilliseconds(-1), ParentUser = logedUser, ParentTask = task
                            };

                            context.Comments.Add(newComment);

                            var notificationToAdd = context.TaskUpdates.Where(tu => tu.TaskID == task.TaskID && tu.UserID != logedUser.Id);
                            foreach (var taskUpdate in notificationToAdd)
                            {
                                taskUpdate.Count++;
                            }

                            context.SaveChanges();
                            //DateTime lastTimeOfLoad = new DateTime(data.TimeOfLoad);

                            //CommentViewModel[] commentsToBeUpdated = GetCommentsAfterDate(task, lastTimeOfLoad, context);

                            //viewModel.Comments = commentsToBeUpdated;
                            //viewModel.NewTimeOfLoad = currentDateTime.Ticks;

                            var groupName = "TaskComments:" + task.TaskID;
                            CommentViewModel commentViewModel = new CommentViewModel()
                            {
                                Content = newComment.Content, UserName = logedUser.UserName, Date = String.Format("{0:H:mm, d.M.}", newComment.Created.Value)
                            };
                            CommentSignalRViewModel signalRComment = new CommentSignalRViewModel()
                            {
                                GroupID = groupName, Comment = commentViewModel
                            };

                            var hubContext = GlobalHost.ConnectionManager.GetHubContext <TasksHub>();
                            hubContext.Clients.Group(groupName).newComment(signalRComment);

                            return(viewModel);
                        }
                        else
                        {
                            viewModel.IsAuthorized = false;
                        }
                    }
                    else
                    {
                        viewModel.IsValid = false;
                    }
                    return(viewModel);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                throw;
            }
        }
        public ActionResult PhysicalIndex(int ID = 0)
        {
            if (DB.GetPost(ID, false, false, true).PostType.Equals("Post"))
            {
                return(RedirectToAction("Index", new { ID = ID }));
            }
            else
            {
                PhysicalPost ppost = (PhysicalPost)DB.GetPost(ID, true, true, true);
                ViewBag.Title          = ppost.Title;
                ViewBag.Description    = ppost.Description;
                ViewBag.DateCreated    = ppost.DateCreated.ToShortDateString();
                ViewBag.Username       = DB.GetUser(ppost.UserId, "").Username;
                ViewBag.UserId         = ppost.UserId;
                ViewBag.AltDescription = ppost.AltDescription;
                ViewBag.Address        = ppost.Address;
                ViewBag.Zipcode        = ppost.Zipcode;
                ViewBag.IsLocked       = ppost.IsLocked;

                string tags = "";

                foreach (string item in ppost.Tags)
                {
                    tags = tags + " " + item;
                }

                ViewBag.Tags = tags;

                //sorteret omvendt efter tid
                IEnumerable <Comment> commentList = DB.GetCommentList(ppost.Id, true).OrderByDescending(x => x.DateCreated).ToList();
                ViewBag.CommentList = commentList;

                User user = null;
                ViewBag.UserIsAccepted = false;
                try
                {
                    if (Session["Username"] != null)
                    {
                        user = DB.GetUser(0, (string)Session["Username"]);
                        foreach (SolvrComment item in commentList)
                        {
                            if (item.CommentType.Equals("Solvr") && item.IsAccepted && item.UserId == user.Id)
                            {
                                ViewBag.UserIsAccepted = true;
                                break;
                            }
                        }
                    }
                }
                catch
                {
                    ViewBag.UserIsAccepted = false;
                }

                ViewBag.UserIsOwner = false;

                if (user != null && user.Id == ppost.UserId)
                {
                    ViewBag.UserIsOwner = true;
                }



                var model = new CommentViewModel();
                model.PostId = ppost.Id;

                return(View(model));
            }
        }