public JsonResult Create(CommentModel model) { int status = -1; if (!ModelState.IsValid) return Json(status); IContent parent = Services.ContentService.GetById(model.Id); if (parent == null) return Json(status); int comment_number; if (parent.Children().Where(x => x.ContentType.Alias == "Comment").Any()) { IContent last_comment = parent.Children().Where(x => x.ContentType.Alias == "Comment").First(); comment_number = (int)last_comment.GetValue("number") + 1; } else comment_number = 1; string comment_name = String.Format("comment#{0}", comment_number); IContent comment = UserContentHelper.CreateUserContent(comment_name, parent.Id, "Comment"); HtmlSanitizer sanitizer = new HtmlSanitizer(); string safe_text = sanitizer.Sanitize(model.Text); comment.SetValue("text", safe_text); comment.SetValue("number", comment_number); var pub_status = Services.ContentService.SaveAndPublishWithStatus(comment); if(pub_status.Success) { status = 0; return Json(status); } else return Json(status); }
public ActionResult AddComment(CommentModel model) { if (!String.IsNullOrWhiteSpace(model.Text)) { Model.StatusService.AddCommentToStatus(CurrentUser, Model.StatusService.FindStatusById(model.StatusID), model.Text); } return Redirect(model.PrevUrl); }
public void Agregar(CommentModel comentario) { var documento = new BsonDocument { { "Author", comentario.Author }, {"Text", comentario.Text}, {"Fecha", comentario.FechaHora} }; var coleccion = _database.GetCollection<BsonDocument>("Comentarios"); coleccion.InsertOne(documento); }
protected void btnRegister_Click(object sender, ImageClickEventArgs e) { if (txtUserName.Text == string.Empty ) { Utility.JS_Alert(sender, CommentConst.MESSAGE_COMMENT_EMPTY_NAME); return; } if (txtPassword.Text == string.Empty) { Utility.JS_Alert(sender, CommentConst.MESSAGE_COMMENT_EMPTY_PASSWORD); return; } if (txtContent.Text == string.Empty) { Utility.JS_Alert(sender, CommentConst.MESSAGE_COMMENT_EMPTY_CONTENT); return; } if (txtConfirmBitmapHandler.Text == string.Empty) { Utility.JS_Alert(sender, CommentConst.MESSAGE_COMMENT_EMPTY_CONFIRM_VALIDATE_STRING); return; } if (txtConfirmBitmapHandler.Text != (string)Session[Parameters.SESSION_CONFIRM_VALIDATE_STRING]) { Utility.JS_Alert(sender, CommentConst.MESSAGE_COMMENT_NOT_EQUAL_CONFIRM_VALIDATE_STRING); return; } CommentModel model = new CommentModel(articleNo); model.CommentGroup = group; model.CommentStep = step; model.CommentOrder = order; model.UserEmail = CurrentUserInfo.EMail; model.Password = FormsAuthentication.HashPasswordForStoringInConfigFile( txtPassword.Text, AuthenticateConst.AUTHENTICATE_HASH_FORMAT); //model.BoardName = boardName; model.UserName = txtUserName.Text; model.UserBlogUrl = txtUserBlogUrl.Text; model.Content = txtContent.Text; model.UserIP = Request.UserHostAddress; model.CommentType = CommentAttribute.Reply; CommentManager.GetInstance().InsertComment(model); Utility.JsCall(sender, "opener.commentUpdate"+ articleNo + "(); self.close();"); }
public IList<CommentModel> TraerTodo() { var lista = new List<CommentModel>(); var coleccion = _database.GetCollection<BsonDocument>("Comentarios"); var filter = new BsonDocument(); var count = 0; var resultado = coleccion.Find(filter).ToList(); foreach (var documento in resultado) { var comentario = new CommentModel() { Author = documento["Author"].AsString, Text = documento["Text"].AsString, FechaHora = documento.Contains("Fecha") ? documento["Fecha"].AsString : null }; lista.Add(comentario); } return lista; }
public CommentModel PostComment([FromBody] CommentModel comment) { return(_claimService.Comment(comment)); }
public ActionResult AddComment(CommentModel comment) { comment.Id = _comments.Count + 1; _comments.Add(comment); return(Content("Success :)")); }
public ActionResult AddComment(CommentModel comment) { comment.Id = _comments.Count + 1; // Create a fake ID for this comment _comments.Add(comment); return(Content("Success")); }
public async Task <IActionResult> AddComment([FromBody] CommentModel comment) { await _commentService.AddCommentAsync(comment.UserID, comment.Content, comment.ProductID); return(Ok()); }
protected void PrepareBlogPostModel(BlogPostModel model, BlogPost blogPost, bool prepareComments) { Guard.NotNull(blogPost, nameof(blogPost)); Guard.NotNull(model, nameof(model)); MiniMapper.Map(blogPost, model); model.SeName = blogPost.GetSeName(blogPost.LanguageId, ensureTwoPublishedLanguages: false); model.CreatedOn = _dateTimeHelper.ConvertToUserTime(blogPost.CreatedOnUtc, DateTimeKind.Utc); model.AddNewComment.DisplayCaptcha = _captchaSettings.CanDisplayCaptcha && _captchaSettings.ShowOnBlogCommentPage; model.Comments.AllowComments = blogPost.AllowComments; model.Comments.NumberOfComments = blogPost.ApprovedCommentCount; model.Comments.AllowCustomersToUploadAvatars = _customerSettings.AllowCustomersToUploadAvatars; model.DisplayAdminLink = _services.Permissions.Authorize(Permissions.System.AccessBackend, _services.WorkContext.CurrentCustomer); model.HasBgImage = blogPost.PreviewDisplayType == PreviewDisplayType.DefaultSectionBg || blogPost.PreviewDisplayType == PreviewDisplayType.PreviewSectionBg; model.PictureModel = PrepareBlogPostPictureModel(blogPost, blogPost.MediaFileId); if (blogPost.PreviewDisplayType == PreviewDisplayType.Default || blogPost.PreviewDisplayType == PreviewDisplayType.DefaultSectionBg) { model.PreviewPictureModel = PrepareBlogPostPictureModel(blogPost, blogPost.MediaFileId); } else if (blogPost.PreviewDisplayType == PreviewDisplayType.Preview || blogPost.PreviewDisplayType == PreviewDisplayType.PreviewSectionBg) { model.PreviewPictureModel = PrepareBlogPostPictureModel(blogPost, blogPost.PreviewMediaFileId); } if (blogPost.PreviewDisplayType == PreviewDisplayType.Preview || blogPost.PreviewDisplayType == PreviewDisplayType.Default || blogPost.PreviewDisplayType == PreviewDisplayType.Bare) { model.SectionBg = string.Empty; } // tags model.Tags = blogPost.ParseTags().Select(x => new BlogPostTagModel { Name = x, SeName = SeoHelper.GetSeName(x, _seoSettings.ConvertNonWesternChars, _seoSettings.AllowUnicodeCharsInUrls, true, _seoSettings.SeoNameCharConversion) }).ToList(); if (prepareComments) { var blogComments = blogPost.BlogComments.Where(pr => pr.IsApproved).OrderBy(pr => pr.CreatedOnUtc); foreach (var bc in blogComments) { var isGuest = bc.Customer.IsGuest(); var commentModel = new CommentModel(model.Comments) { Id = bc.Id, CustomerId = bc.CustomerId, CustomerName = bc.Customer.FormatUserName(_customerSettings, T, false), CommentText = bc.CommentText, CreatedOn = _dateTimeHelper.ConvertToUserTime(bc.CreatedOnUtc, DateTimeKind.Utc), CreatedOnPretty = bc.CreatedOnUtc.RelativeFormat(true, "f"), AllowViewingProfiles = _customerSettings.AllowViewingProfiles && !isGuest }; commentModel.Avatar = bc.Customer.ToAvatarModel(_genericAttributeService, _mediaService, _customerSettings, _mediaSettings, Url, commentModel.CustomerName); model.Comments.Comments.Add(commentModel); } } Services.DisplayControl.Announce(blogPost); }
/// <summary> /// notifies clients that comment is added /// </summary> /// <param name="comment">new comment as CommentModel</param> public void AddNewComment(CommentModel comment) { Clients.All.addNewComment(comment); }
public ActionResult Create(CommentModel comment) { _commentsRepository.Create(comment); return(Ok()); }
public void GetGetAllCommentsOfContributionById() { InMemoryDbContextFactory Db = new InMemoryDbContextFactory(); var dbContext = Db.CreateDbContext(); ContributionRepository contributionRepository = new ContributionRepository(dbContext); CommentRepository commentRepository = new CommentRepository(dbContext); ContributionModel contributionModel1 = new ContributionModel() { Id = Guid.NewGuid(), }; ContributionModel contributionModel2 = new ContributionModel() { Id = Guid.NewGuid(), }; ContributionModel contributionModel3 = new ContributionModel() { Id = Guid.NewGuid(), }; contributionRepository.Insert(contributionModel1); contributionRepository.Insert(contributionModel2); contributionRepository.Insert(contributionModel3); var contributionRepositoryResponse1 = contributionRepository.GetById(contributionModel1.Id); var contributionRepositoryResponse2 = contributionRepository.GetById(contributionModel2.Id); var contributionRepositoryResponse3 = contributionRepository.GetById(contributionModel3.Id); Assert.NotNull(contributionRepositoryResponse1); Assert.NotNull(contributionRepositoryResponse2); Assert.NotNull(contributionRepositoryResponse3); dbContext.DetachAllEntities(); CommentModel commentModel1 = new CommentModel { Id = Guid.NewGuid(), Message = "Ahoj", Contribution = contributionModel1 }; CommentModel commentModel2 = new CommentModel { Id = Guid.NewGuid(), Message = "světe", Contribution = contributionModel1 }; CommentModel commentModel3 = new CommentModel { Id = Guid.NewGuid(), Message = "Lorem", Contribution = contributionModel2 }; commentRepository.Insert(commentModel1); commentRepository.Insert(commentModel2); commentRepository.Insert(commentModel3); var commentRepositoryResponse1 = commentRepository.GetById(commentModel1.Id); var commentRepositoryResponse2 = commentRepository.GetById(commentModel2.Id); var commentRepositoryResponse3 = commentRepository.GetById(commentModel3.Id); Assert.NotNull(commentRepositoryResponse1); Assert.NotNull(commentRepositoryResponse2); Assert.NotNull(commentRepositoryResponse3); var contr1Id = contributionModel1.Id; var contr2Id = contributionModel2.Id; List <CommentModel> commentList1 = new List <CommentModel>(); commentList1.Add(commentModel1); commentList1.Add(commentModel2); contributionModel1.Comments = commentList1; List <CommentModel> commentList2 = new List <CommentModel>(); commentList2.Add(commentModel3); contributionModel2.Comments = commentList2; var commentRepositoryResponseCon1 = commentRepository.GetAllCommentsOfContributionById(contr1Id); Assert.NotNull(commentRepositoryResponseCon1); Assert.Equal(commentRepositoryResponseCon1.ElementAt(0).Id, commentModel1.Id); Assert.Equal(commentRepositoryResponseCon1.ElementAt(1).Id, commentModel2.Id); var commentRepositoryResponseCon2 = commentRepository.GetAllCommentsOfContributionById(contr2Id); Assert.NotNull(commentRepositoryResponseCon2); Assert.Equal(commentRepositoryResponseCon2.ElementAt(0).Id, commentModel3.Id); }
public ActionResult AddComment(CommentModel comment) { _comments.Add(comment); return(Content("Success :)")); }
public async Task <IActionResult> PostAdd(CommentModel model) //doing comment or reply { if (model.NeedId == null && model.RelatedCommentId == null || model.NeedId == Guid.Empty && model.RelatedCommentId == Guid.Empty) { return(Error("Yorum yapmak istediğiniz kampanyayı veya cevaplamak istedğiniz yorumu kontrol edin")); } if (!ModelState.IsValid) { return(Error(ModelState.Values.SelectMany(v => v.Errors).FirstOrDefault().ErrorMessage)); } if (model.NeedId != Guid.Empty && model.NeedId != null) // add new comment { var commentedNeed = await Context.Need.FirstOrDefaultAsync(x => x.Id == model.NeedId && !x.IsRemoved); if (commentedNeed != null) { if (commentedNeed.Stage != 3) { return(Error("Burada tartışma başlatılamaz")); } var NewComment = new NeedComment { Comment = model.Comment.RemoveLessGreaterSigns(), NeedId = (Guid)model.NeedId, UserId = Guid.Parse(User.Identity.GetUserId()) }; await Context.AddAsync(NewComment); await Context.SaveChangesAsync(); return(Succes(null, NewComment.Id, 201)); } return(Error("Tartışmanın başlatılacağı kampanya yok", null, null, 404)); } else //[reply] add relational comment { var repliedComment = await Context.NeedComment.Include(comment => comment.Need).FirstOrDefaultAsync(x => x.Id == model.RelatedCommentId && !x.IsRemoved && !x.Need.IsRemoved); if (repliedComment != null) { if (repliedComment.Need.Stage != 3) { return(Error("Burada cevap yazılamaz")); } var NewReply = new NeedComment { Comment = model.Comment.RemoveLessGreaterSigns(), UserId = Guid.Parse(User.Identity.GetUserId()), NeedId = repliedComment.NeedId, RelatedCommentId = repliedComment.Id }; await Context.AddAsync(NewReply); await Context.SaveChangesAsync(); return(Succes(null, NewReply.Id, 201)); } return(Error("Cevaplanacak yorum yok", null, null, 404)); } }
/// <summary> /// Default constructor. /// </summary> public EditModel() { Cache = new CacheModel(); Comments = new CommentModel(); Site = new SiteModel(); Params = new List<object>(); }
public async Task <PostModel> Handle(PostDetailQuery request, CancellationToken cancellationToken) { PostModel post = null; _logger.Debug("Reading details for post {PostID} with parameters {@Request}", request.PostID, request); using (var tx = _session.BeginTransaction()) { // Total likes for this post var postLikesCountQuery = _session.QueryOver <Like>() .Where(l => l.Post.ID == request.PostID) .ToRowCountQuery() .FutureValue <int>(); // Comments for this post User commentAuthor = null; CommentModel comment = null; var postCommentsQuery = _session.QueryOver <Comment>() .Where(c => c.Post.ID == request.PostID) .OrderBy(c => c.CommentDate).Asc .Inner.JoinQueryOver(c => c.Author, () => commentAuthor) .SelectList(list => list .Select(c => c.Text).WithAlias(() => comment.Text) .Select(c => c.CommentDate).WithAlias(() => comment.CommentDate) .Select(() => commentAuthor.Nickname).WithAlias(() => comment.AuthorNickName) ) .TransformUsing(Transformers.AliasToBean <CommentModel>()) .Future <CommentModel>(); // Is this post liked by the current user? var isLikedByCurrentUserQuery = _session.QueryOver <Like>() .Where(l => l.Post.ID == request.PostID) .And(l => l.User.ID == request.CurrentUserID) .ToRowCountQuery() .FutureValue <int>(); // Post to show User postAuthor = null; var postQuery = _session.QueryOver <Post>() .Where(p => p.ID == request.PostID) .Inner.JoinQueryOver(p => p.Author, () => postAuthor) .SelectList(list => list .Select(p => p.ID).WithAlias(() => post.PostID) .Select(p => p.Text).WithAlias(() => post.Text) .Select(p => p.Picture.RawBytes).WithAlias(() => post.Picture) .Select(p => p.PostDate).WithAlias(() => post.PostDate) .Select(() => postAuthor.Nickname).WithAlias(() => post.AuthorNickName) .Select(() => postAuthor.ProfilePicture.RawBytes).WithAlias(() => post.AuthorProfilePicture) ) .TransformUsing(Transformers.AliasToBean <PostModel>()) .FutureValue <PostModel>(); // Add related data post = await postQuery.GetValueAsync(); post.LikesCount = await postLikesCountQuery.GetValueAsync(); post.Comments = postCommentsQuery.ToArray(); post.IsLikedByCurrentUser = (await isLikedByCurrentUserQuery.GetValueAsync()) > 0; } return(post); }
public void Add(CommentModel comment) { _commentRepo.Add(_mapper.Map <Comment>(comment), true); }
static void testRepo() { CommunicationDbContext ctx = new CommunicationDbContext(); ReactionRepository reactionRepository = new ReactionRepository(ctx); UserRepository userRepository = new UserRepository(ctx); CommentRepository commentRepository = new CommentRepository(ctx); ContributionRepository contributionRepository = new ContributionRepository(ctx); UserModel userModel = new UserModel { Id = Guid.NewGuid(), Name = "Pavel", Surname = "Dvorak", Email = "*****@*****.**", Password = "******", TelephoneNumber = "+420420420420" }; UserModel userModel2 = new UserModel { Id = Guid.NewGuid(), Name = "Petr", Surname = "Novak", Email = "*****@*****.**", Password = "******", TelephoneNumber = "+420420420420" }; ContributionModel contribution1 = new ContributionModel { Id = Guid.NewGuid(), Message = "AhojQy,dneska v druzine byl na obed krtkův dort <3, to byl náhul", User = userModel, Time = DateTime.Now }; CommentModel commentModel1 = new CommentModel { Id = Guid.NewGuid(), Message = "No a co", Time = DateTime.Now, User = userModel, Contribution = contribution1 }; CommentModel commentModel2 = new CommentModel { Id = Guid.NewGuid(), Message = "Mnam dopi..", Time = DateTime.Now, User = userModel, Contribution = contribution1 }; userRepository.Insert(userModel); //userRepository.Insert(userModel2); contributionRepository.Insert(contribution1); commentRepository.Insert(commentModel1); commentRepository.Insert(commentModel2); var userResponse = userRepository.GetById(userModel.Id); var contributionReponse = contributionRepository.GetById(contribution1.Id); var commentResponse = commentRepository.GetCommentByUserId(userModel.Id); Console.Write("ID: " + userResponse.Id); Console.Write("\nNAME: " + userResponse.Name); Console.Write("\nEmail: " + userResponse.Email); Console.Write("\n\tStatus: " + contributionReponse.Message); Console.Write("\n\t\tComments: "); foreach (var comment in commentResponse) { Console.Write("\n\t\tMessage: " + comment.Message); } LoginService loginService = new LoginService(); loginService.register("Jmeno", "Prijmeni", "*****@*****.**", "heslo123", "123456789", null); var userByEmail = loginService.LoadUserByEmail("*****@*****.**", "heslo123"); Console.Write("\nLoadUserByUsername: "******"*****@*****.**"); try { userByEmail = loginService.LoadUserByEmail("*****@*****.**", "heslo123"); Console.Write("\nChyba "); } catch (LoginException ex) { Console.Write("\nLoadUserByUsername: " + ex.Message); } userRepository.Delete(userByEmail); userRepository.Delete(userModel); Console.ReadKey(); }
public void SaveCommentForReference(CommentModel comment, int referenceId) { Comment commentEntity = this.dataMapper.MapCommentM2E(comment); this.associateRepo.SaveCommentForReference(commentEntity, referenceId); comment.CommentId = commentEntity.CommentId; }
public void CreateComment(CommentModel newComment) { _commentRepository.CreateComment(newComment); }
public void UpdateComment(int Id, CommentModel Comment) { _commentRepository.UpdateComment(Id, Comment); }
public ActionResult CommentListing(int BlogID, GridSortOptions gridSortOptions, int?pagetype, int?page, int?pagesize, FormCollection fm, string objresult) { var _objContext = new Contexts.CommentContexts(); ViewBag.Title = " Comment Listing"; var _CommentModel = new CommentModel(); #region Ajax Call if (objresult != null) { AjaxRequest objAjaxRequest = JsonConvert.DeserializeObject <AjaxRequest>(objresult);//Convert json String to object Model if (objAjaxRequest.ajaxcall != null && !string.IsNullOrEmpty(objAjaxRequest.ajaxcall) && objresult != null && !string.IsNullOrEmpty(objresult)) { if (objAjaxRequest.ajaxcall == "paging") //Ajax Call type = paging i.e. Next|Previous|Back|Last { Session["pageNo"] = page; // stores the page no for status } else if (objAjaxRequest.ajaxcall == "sorting") //Ajax Call type = sorting i.e. column sorting Asc or Desc { page = (Session["pageNo"] != null ? Convert.ToInt32(Session["pageNo"].ToString()) : page); Session["GridSortOption"] = gridSortOptions; pagesize = (Session["PageSize"] != null ? Convert.ToInt32(Session["PageSize"].ToString()) : pagesize); } else if (objAjaxRequest.ajaxcall == "ddlPaging")//Ajax Call type = drop down paging i.e. drop down value 10, 25, 50, 100, ALL { Session["PageSize"] = (Request.QueryString["pagesize"] != null ? Convert.ToInt32(Request.QueryString["pagesize"].ToString()) : pagesize); Session["GridSortOption"] = gridSortOptions; Session["pageNo"] = page; } else if (objAjaxRequest.ajaxcall == "status")//Ajax Call type = status i.e. Active/Inactive { page = (Session["pageNo"] != null ? Convert.ToInt32(Session["pageNo"].ToString()) : page); gridSortOptions = (Session["GridSortOption"] != null ? Session["GridSortOption"] as GridSortOptions : gridSortOptions); } else if (objAjaxRequest.ajaxcall == "displayorder")//Ajax Call type = Display Order i.e. drop down values { page = (Session["pageNo"] != null ? Convert.ToInt32(Session["pageNo"].ToString()) : page); gridSortOptions = (Session["GridSortOption"] != null ? Session["GridSortOption"] as GridSortOptions : gridSortOptions); } objAjaxRequest.ajaxcall = null;; //remove parameter value } if (objAjaxRequest.hfid != null && objAjaxRequest.hfvalue != null && !string.IsNullOrEmpty(objAjaxRequest.hfid) && !string.IsNullOrEmpty(objAjaxRequest.hfvalue) && objresult != null && !string.IsNullOrEmpty(objresult) && objAjaxRequest.hfvalue.ToString().Trim().ToLower() != "displayOrder".Trim().ToLower()) { var id1 = Convert.ToInt64(objAjaxRequest.hfid); var comment = _objContext.GetComments().Where(x => x.CommentID == id1).FirstOrDefault(); if (comment != null) { //CategoryID = Convert.ToInt32(Request.QueryString["CategoryID"]); comment.IsActiveInd = objAjaxRequest.hfvalue == "1"; try { _objContext.EditComment(comment); TempData["AlertMessage"] = "Comment " + (comment.IsActiveInd == true ? "Approved" : "Disapproved") + " successfully."; } catch { TempData["AlertMessage"] = "Some error occured, Please try after some time."; } objAjaxRequest.hfid = null; //remove parameter value objAjaxRequest.hfvalue = null; //remove parameter value pagesize = (Request.QueryString["pagesize"] != null ? Convert.ToInt32(Request.QueryString["pagesize"].ToString()) : pagesize); page = (Session["pageNo"] != null ? Convert.ToInt32(Session["pageNo"].ToString()) : page); gridSortOptions = (Session["GridSortOption"] != null ? Session["GridSortOption"] as GridSortOptions : gridSortOptions); } } else { TempData["Message"] = string.Empty; } objresult = string.Empty; } #endregion Ajax Call //This section is used to retain the values of page , pagesize and gridsortoption on complete page post back(Edit, Dlete) if (!Request.IsAjaxRequest() && Session["Edit/Delete"] != null && !string.IsNullOrEmpty(Session["Edit/Delete"].ToString())) { pagesize = (Session["PageSize"] != null ? Convert.ToInt32(Session["PageSize"]) : Models.Common._pageSize); page = (Session["pageNo"] != null ? Convert.ToInt32(Session["pageNo"]) : Models.Common._currentPage); gridSortOptions = (Session["GridSortOption"] != null ? Session["GridSortOption"] as GridSortOptions : gridSortOptions); Session["Edit/Delete"] = null; } else if (!Request.IsAjaxRequest() && Session["Edit/Delete"] == null) { //gridSortOptions.Column = "CreateDate"; Session["PageSize"] = null; Session["pageNo"] = null; Session["GridSortOption"] = null; } var pageSize = pagesize.HasValue ? pagesize.Value : Models.Common._pageSize; var Page = page.HasValue ? page.Value : Models.Common._currentPage; TempData["pager"] = pagesize; if (gridSortOptions.Column != null && gridSortOptions.Column == "FullNameTxt" || gridSortOptions.Column == "EmailTxt" || gridSortOptions.Column == "PostedDate") { } else { gridSortOptions.Column = "FullNameTxt"; } var pagedViewModel = new PagedViewModel <CommentModel> { ViewData = ViewData, Query = _objContext.GetComments().Where(x => x.BlogID == BlogID).AsQueryable(), GridSortOptions = gridSortOptions, DefaultSortColumn = "FullNameTxt", Page = Page, PageSize = pageSize, }.Setup(); if (Request.IsAjaxRequest()) // check if request comes from ajax, then return Partial view { return(View("CommentListingPartial", pagedViewModel)); // ("partial view name ") } else { return(View(pagedViewModel)); } }
private CommentModel AddCommentToPost(CommentModel comment, PostModel oldPost) { comment.Post = oldPost; return(databaseContext.Comments.Add(comment)); }
public async Task <List <CommentModel> > Transform(params Comment[] entityList) { if (entityList.IsEmptyCollection()) { return(new List <CommentModel>()); } var redis = this.RedisProvider.GetDatabase(); var idList = entityList.Select(t => t.ID).ToArray(); var userIDList = entityList.Select(t => t.CreateUser).ToList(); var fields = userIDList.Select(t => (RedisValue)t).ToArray(); List <User> userList = redis.JsonHashGet <User>(RedisKeys.User, fields); List <CommentVotes> commentVotesList; List <CommentVote> commentVoteList = new List <CommentVote>(); using (var uw = this.CreateUnitOfWork()) { commentVotesList = await uw.CreateRepository <ICommentVoteRepository>().QueryCommentVotes(idList); if (SecurityManager.IsLogin) { commentVoteList = await uw.QueryAsync <CommentVote>(t => idList.Contains(t.CommentID) && t.UserID == SecurityManager.CurrentUser.ID); } } var result = entityList.Select(entity => { var model = new CommentModel { Content = entity.Content, CreateDate = entity.CreateDate, ID = entity.ID }; var user = userList.SingleOrDefault(u => u.ID == entity.CreateUser); model.CreateUser = Mapper.Map <UserBasicModel>(user); var commentVotes = commentVotesList.SingleOrDefault(t => t.CommentID == entity.ID); if (commentVotes != null) { model.Votes = commentVotes.Votes; } model.Voted = commentVoteList.Any(t => t.CommentID == entity.ID); return(model); }); foreach (var entity in entityList) { if (entity.ReplyID.HasValue) { var model = result.SingleOrDefault(t => t.ID == entity.ID); var replyToModel = result.SingleOrDefault(t => t.ID == entity.ReplyID.Value); if (replyToModel != null) { model.ReplyTo = replyToModel; } else { model.ReplyToIsDelete = true; } } } return(result.ToList()); }
public abstract Task <OperationResult <VoidResponse> > CreateOrEdit(CommentModel model, CancellationToken ct);
public IHttpActionResult AddComment(CommentModel commentModel) { commentModel.Id = _comments.Count + 1; _comments.Add(commentModel); return(Json(new { result = "success" })); }
public async Task <bool> Create(CommentModel comment) { await _context.Comments.AddAsync(comment); return(await _context.SaveChangesAsync() > 0); }
protected void PrepareBlogPostModel(BlogPostModel model, BlogPost blogPost, bool prepareComments) { if (blogPost == null) { throw new ArgumentNullException("blogPost"); } if (model == null) { throw new ArgumentNullException("model"); } model.Id = blogPost.Id; model.MetaTitle = blogPost.MetaTitle; model.MetaDescription = blogPost.MetaDescription; model.MetaKeywords = blogPost.MetaKeywords; model.SeName = blogPost.GetSeName(blogPost.LanguageId, ensureTwoPublishedLanguages: false); model.Title = blogPost.Title; model.Body = blogPost.Body; model.CreatedOn = _dateTimeHelper.ConvertToUserTime(blogPost.CreatedOnUtc, DateTimeKind.Utc); model.Tags = blogPost.ParseTags().Select(x => new BlogPostTagModel { Name = x, SeName = SeoHelper.GetSeName(x, _seoSettings.ConvertNonWesternChars, _seoSettings.AllowUnicodeCharsInUrls, _seoSettings.SeoNameCharConversion) }).ToList(); model.AddNewComment.DisplayCaptcha = _captchaSettings.Enabled && _captchaSettings.ShowOnBlogCommentPage; model.Comments.AllowComments = blogPost.AllowComments; model.Comments.AvatarPictureSize = _mediaSettings.AvatarPictureSize; model.Comments.NumberOfComments = blogPost.ApprovedCommentCount; model.Comments.AllowCustomersToUploadAvatars = _customerSettings.AllowCustomersToUploadAvatars; if (prepareComments) { var blogComments = blogPost.BlogComments.Where(pr => pr.IsApproved).OrderBy(pr => pr.CreatedOnUtc); foreach (var bc in blogComments) { var commentModel = new CommentModel(model.Comments) { Id = bc.Id, CustomerId = bc.CustomerId, CustomerName = bc.Customer.FormatUserName(), CommentText = bc.CommentText, CreatedOn = _dateTimeHelper.ConvertToUserTime(bc.CreatedOnUtc, DateTimeKind.Utc), CreatedOnPretty = bc.CreatedOnUtc.RelativeFormat(true, "f"), AllowViewingProfiles = _customerSettings.AllowViewingProfiles && bc.Customer != null && !bc.Customer.IsGuest() }; if (_customerSettings.AllowCustomersToUploadAvatars) { var customer = bc.Customer; string avatarUrl = _pictureService.GetUrl(customer.GetAttribute <int>(SystemCustomerAttributeNames.AvatarPictureId), _mediaSettings.AvatarPictureSize, FallbackPictureType.NoFallback); if (String.IsNullOrEmpty(avatarUrl) && _customerSettings.DefaultAvatarEnabled) { avatarUrl = _pictureService.GetFallbackUrl(_mediaSettings.AvatarPictureSize, FallbackPictureType.Avatar); } commentModel.CustomerAvatarUrl = avatarUrl; } model.Comments.Comments.Add(commentModel); } } Services.DisplayControl.Announce(blogPost); }
public async Task <bool> Update(CommentModel comment) { _context.Comments.Update(comment); return(await _context.SaveChangesAsync() > 0); }
private void StartTask(Object workItemState) { var param = _context.Request.Params; int projectID = Convert.ToInt32(param["projectID"]); int taskID, userID; var user = (UserModel)_context.Session["user"]; try { if (myAccess.IsProjectMember(projectID, user.User_ID, user.Role)) { bool error = false; switch (action) { /***********************************************/ // Submit a new comment of a task case "insertTaskComment": CommentModel comment = JsonConvert.DeserializeObject <CommentModel>(param["comment"]); userID = comment.User_ID; projectID = comment.Project_ID; taskID = comment.Task_ID; if ((userID == user.User_ID) && (myAccess.IsInProject(projectID, taskID, "Task"))) { result = myAccess.insertTaskComment(comment); } else { error = true; } break; // View all comments of a task case "viewTaskComment": taskID = Convert.ToInt32(param["taskID"]); if (myAccess.IsInProject(projectID, taskID, "Task")) { result = myAccess.viewTaskComment(param["taskID"], user.User_ID); } else { error = true; } break; // Delete a comment of a task case "deleteTaskComment": if (user.User_ID == Convert.ToInt32(param["userID"])) { result = myAccess.deleteTaskComment(param["commentID"], user.User_ID); } else { error = true; } break; // Edit a comment of a task case "updateTaskComment": if (user.User_ID == Convert.ToInt32(param["userID"])) { result = myAccess.updateTaskComment(param["commentID"], param["content"], user.User_ID); } else { error = true; } break; } if (error) { Code = 500; } } else { Code = 401; } } catch { Code = 403; } finally { myAccess.Dipose(); FinishWork(); } }
public override void ViewDidLoad() { base.ViewDidLoad(); HeaderView.SetImage(null, Images.Avatar); var compose = new UIBarButtonItem(UIBarButtonSystemItem.Compose); var more = new UIBarButtonItem(UIBarButtonSystemItem.Action); NavigationItem.RightBarButtonItems = new[] { more, compose }; var split = new SplitButtonElement(); var commentCount = split.AddButton("Comments", "-"); var watchers = split.AddButton("Watchers", "-"); ICollection <Section> root = new LinkedList <Section>(); root.Add(new Section { split }); var secDetails = new Section(); root.Add(secDetails); this.WhenAnyValue(x => x.ViewModel.ShowDescription) .DistinctUntilChanged() .Subscribe(x => { if (x) { secDetails.Insert(0, UITableViewRowAnimation.None, _descriptionElement); } else { secDetails.Remove(_descriptionElement); } }); this.WhenAnyValue(x => x.ViewModel.Description) .Where(x => !string.IsNullOrWhiteSpace(x)) .Select(x => new DescriptionModel(x, (int)UIFont.PreferredSubheadline.PointSize, true)) .Select(x => new MarkdownView { Model = x }.GenerateString()) .Subscribe(_descriptionElement.SetValue); var split1 = new SplitViewElement(AtlassianIcon.Configure.ToImage(), AtlassianIcon.Error.ToImage()); var split2 = new SplitViewElement(AtlassianIcon.Flag.ToImage(), AtlassianIcon.Spacedefault.ToImage()); var split3 = new SplitViewElement(AtlassianIcon.Copyclipboard.ToImage(), AtlassianIcon.Calendar.ToImage()); secDetails.Add(split1); secDetails.Add(split2); secDetails.Add(split3); var assigneeElement = new ButtonElement("Assigned", string.Empty, UITableViewCellStyle.Value1) { Image = AtlassianIcon.User.ToImage(), }; secDetails.Add(assigneeElement); var commentsSection = new Section("Comments"); root.Add(commentsSection); var addComment = new ButtonElement("Add Comment") { Image = AtlassianIcon.Addcomment.ToImage() }; commentsSection.Reset(new[] { addComment }); ViewModel .Comments .ChangedObservable() .Subscribe(x => { if (x.Count > 0) { var comments = x.Select(y => new Comment(y.Avatar.ToUrl(), y.Name, y.Content, y.CreatedOn)).ToList(); var commentModel = new CommentModel(comments, (int)UIFont.PreferredSubheadline.PointSize); var content = new CommentsView { Model = commentModel }.GenerateString(); _commentsElement.SetValue(content); commentsSection.Insert(0, UITableViewRowAnimation.None, _commentsElement); } else { commentsSection.Remove(_commentsElement); } }); Root.Reset(root); OnActivation(d => { this.WhenAnyValue(x => x.ViewModel.Issue) .Where(x => x != null) .Subscribe(x => { var avatarUrl = x.ReportedBy?.Avatar; HeaderView.Text = x.Title; HeaderView.SubText = "Updated " + ViewModel.Issue.UtcLastUpdated.Humanize(); HeaderView.SetImage(new Avatar(avatarUrl).ToUrl(128), Images.Avatar); TableView.TableHeaderView = HeaderView; }) .AddTo(d); this.WhenAnyObservable(x => x.ViewModel.DismissCommand) .Subscribe(_ => NavigationController.PopViewController(true)) .AddTo(d); this.WhenAnyValue(x => x.ViewModel.Issue) .Subscribe(x => { split1.Button1.Text = x?.Status; split1.Button2.Text = x?.Priority; split2.Button1.Text = x?.Metadata?.Kind; split2.Button2.Text = x?.Metadata?.Component ?? "No Component"; split3.Button1.Text = x?.Metadata?.Version ?? "No Version"; split3.Button2.Text = x?.Metadata?.Milestone ?? "No Milestone"; }) .AddTo(d); HeaderView .Clicked .BindCommand(this, x => x.ViewModel.GoToReporterCommand) .AddTo(d); compose .GetClickedObservable() .SelectUnit() .BindCommand(ViewModel.GoToEditCommand) .AddTo(d); addComment .Clicked .Subscribe(_ => NewCommentViewController.Present(this, ViewModel.AddComment)) .AddTo(d); assigneeElement .BindValue(this.WhenAnyValue(x => x.ViewModel.Assigned)) .AddTo(d); assigneeElement .BindDisclosure( this.WhenAnyValue(x => x.ViewModel.Assigned) .Select(x => !string.Equals(x, "Unassigned", StringComparison.OrdinalIgnoreCase))) .AddTo(d); assigneeElement .Clicked .SelectUnit() .BindCommand(ViewModel.GoToAssigneeCommand) .AddTo(d); more.Bind(ViewModel.ShowMenuCommand) .AddTo(d); this.WhenAnyValue(x => x.ViewModel.Issue) .Select(x => x != null) .Subscribe(x => compose.Enabled = x) .AddTo(d); this.WhenAnyObservable(x => x.ViewModel.Comments.CountChanged) .StartWith(ViewModel.Comments.Count) .Subscribe(x => commentCount.Text = x.ToString()) .AddTo(d); this.WhenAnyValue(x => x.ViewModel.Issue.FollowerCount) .Subscribe(x => watchers.Text = x.ToString()) .AddTo(d); }); }
public static async Task <bool> UploadComment(string userToken, CommentModel comment, string postId) { var result = await socialServiceAccess.PostData($"Comment/Comment?token={userToken}&postid={postId}", comment); return(result.IsSuccessStatusCode); }
public static void NotifyCommentObserver(CommentModel comment) { AlbumModel album = comment.Album; UrlHelper url = new UrlHelper(HttpContext.Current.Request.RequestContext); Uri requestUrl = url.RequestContext.HttpContext.Request.Url; //Don't send notification if comment belongs to album's owner or if notification is turned off if (album.User.NotifyComment && album.User.Id!= comment.User.Id) { string link = string.Format("{0}://{1}{2}", requestUrl.Scheme, requestUrl.Authority, url.Action("Show", "Album", new { id = album.Id })) +"#comment"+comment.Id; string body = string.Format("{0} has added comment to your album {1}:</br><i>{2}</i></br></br> To see your album visit this <a href='{3}'>link.</a>", comment.User.Login, album.Name, comment.Body,link); MailSendJob mail = new MailSendJob(); mail.to = album.User.Email; mail.subject = string.Format("{0} has added comment to your album" , comment.User.Login); mail.body = body; ThreadStart job = new ThreadStart(mail.send); Thread thread = new Thread(job); thread.Start(); } }
public void SaveComment(CommentModel comment, int associateId) { Comment commentEntity = this.dataMapper.MapCommentM2E(comment); this.associateRepo.SaveComment(commentEntity, associateId); comment.CommentId = commentEntity.CommentId; }
public ActionResult Comment(int id, String comment) { AlbumRepository albums = new AlbumRepository(); AlbumModel album = albums.GetById(id, withUser: true); UserRepository users = new UserRepository(); UserModel user = users.GetByUsername(HttpContext.User.Identity.Name); NewCommentModel newComment = new NewCommentModel(); //Wylaczone komentowanie if (!album.CommentsAllow) { newComment.Message = "You can't comment this album"; return Json(newComment); } CommentModel model = new CommentModel(); model.Album = album; model.Body = comment; model.Date = DateTime.Now; model.User = user; //Komentarze wlasciciela albumu sa automatycznie akceptowane, komentarze innego uzytkownika sa akceptowane //jesli wylaczono opcje autoryzacji newComment.Accepted = (album.User.Id == user.Id) || !album.CommentsAuth; newComment.Body = comment; newComment.Date = model.Date.ToString("dd/MM/yyyy HH:mm:ss"); newComment.UserName = user.Login; newComment.Link = @Url.Action("ViewProfile", "User", new { userName = model.User.Login }); model.Accepted = newComment.Accepted; if (user != null) { if (albums.AddComment(model)) { newComment.Id = model.Id ?? 1; newComment.Message = "Your comment has been saved."; //funkcja automatycznie sprawdza czy wyslac powiadomienie Helpers.NotifyCommentObserver(model); } else { newComment.Message = "Can't add comment."; newComment.Body = null; } } else { newComment.Body = null; newComment.Message = "You need to be logged in to comment"; } return Json(newComment); }
private void initParam() { articleNo = GetParamInt("articleNo", -1); commentNo = GetParamInt("commentNo", -1); model = CommentManager.GetInstance().GetComment(commentNo); if (commentNo == -1 || model == null || model.UserEmail != CurrentUserInfo.EMail) { script = string.Format("alert('{0}'); self.close();", UmcConfiguration.Message[CommentConst.MESSAGE_ERROR_VALIEDATE_PARAM]); Utility.JsCall(this, script); } }
public JsonResult List(CommentModel filter, PageInfo pageInfo) { var result = commentService.GetListByFilter(filter, pageInfo); return(Json(result, JsonRequestBehavior.AllowGet)); }
protected BaseIssueView() { CommentsElement = new HtmlElement("comments"); this.WhenAnyValue(x => x.ViewModel.GoToUrlCommand) .Subscribe(x => CommentsElement.UrlRequested = x.ExecuteIfCan); DescriptionElement = new HtmlElement("description"); this.WhenAnyValue(x => x.ViewModel.GoToUrlCommand) .Subscribe(x => DescriptionElement.UrlRequested = x.ExecuteIfCan); this.WhenAnyValue(x => x.ViewModel.ShowMenuCommand) .Select(x => x.ToBarButtonItem(UIBarButtonSystemItem.Action)) .Subscribe(x => NavigationItem.RightBarButtonItem = x); this.WhenAnyValue(x => x.ViewModel.GoToAssigneesCommand) .Switch() .Subscribe(_ => ShowAssigneeSelector()); this.WhenAnyValue(x => x.ViewModel.GoToMilestonesCommand) .Switch() .Subscribe(_ => ShowMilestonesSelector()); this.WhenAnyValue(x => x.ViewModel.GoToLabelsCommand) .Switch() .Subscribe(_ => ShowLabelsSelector()); this.WhenAnyValue(x => x.ViewModel.GoToOwnerCommand) .Subscribe(x => HeaderView.ImageButtonAction = x != null ? new Action(() => ViewModel.GoToOwnerCommand.ExecuteIfCan()) : null); Appeared.Take(1) .Select(_ => Observable.Timer(TimeSpan.FromSeconds(0.2f))) .Switch() .ObserveOn(RxApp.MainThreadScheduler) .Select(_ => this.WhenAnyValue(x => x.ViewModel.IsClosed)) .Switch() .Subscribe(x => { HeaderView.SubImageView.TintColor = x ? UIColor.FromRGB(0xbd, 0x2c, 0) : UIColor.FromRGB(0x6c, 0xc6, 0x44); HeaderView.SetSubImage((x ? Octicon.IssueClosed :Octicon.IssueOpened).ToImage()); }); MilestoneElement = new StringElement("Milestone", string.Empty, UITableViewCellStyle.Value1) { Image = Octicon.Milestone.ToImage() }; MilestoneElement.Tapped = () => ViewModel.GoToMilestonesCommand.ExecuteIfCan(); this.WhenAnyValue(x => x.ViewModel.AssignedMilestone) .Select(x => x == null ? "No Milestone" : x.Title) .Subscribe(x => MilestoneElement.Value = x); AssigneeElement = new StringElement("Assigned", string.Empty, UITableViewCellStyle.Value1) { Image = Octicon.Person.ToImage() }; AssigneeElement.Tapped = () => ViewModel.GoToAssigneesCommand.ExecuteIfCan(); this.WhenAnyValue(x => x.ViewModel.AssignedUser) .Select(x => x == null ? "Unassigned" : x.Login) .Subscribe(x => AssigneeElement.Value = x); LabelsElement = new StringElement("Labels", string.Empty, UITableViewCellStyle.Value1) { Image = Octicon.Tag.ToImage() }; LabelsElement.Tapped = () => ViewModel.GoToLabelsCommand.ExecuteIfCan(); this.WhenAnyValue(x => x.ViewModel.AssignedLabels) .Select(x => (x == null || x.Count == 0) ? "None" : string.Join(",", x.Select(y => y.Name))) .Subscribe(x => LabelsElement.Value = x); this.WhenAnyValue(x => x.ViewModel.CanModify) .Select(x => x ? UITableViewCellAccessory.DisclosureIndicator : UITableViewCellAccessory.None) .Subscribe(x => MilestoneElement.Accessory = AssigneeElement.Accessory = LabelsElement.Accessory = x); DetailsSection.Add(MilestoneElement); DetailsSection.Add(AssigneeElement); DetailsSection.Add(LabelsElement); this.WhenAnyValue(x => x.ViewModel.Issue) .IsNotNull() .Subscribe(x => { HeaderView.Text = x.Title; HeaderView.ImageUri = x.User.AvatarUrl; if (x.UpdatedAt.HasValue) { HeaderView.SubText = "Updated " + x.UpdatedAt.Value.UtcDateTime.Humanize(); } else { HeaderView.SubText = "Created " + x.CreatedAt.UtcDateTime.Humanize(); } RefreshHeaderView(); }); this.WhenAnyValue(x => x.ViewModel.MarkdownDescription) .Subscribe(x => { if (string.IsNullOrEmpty(x)) { DetailsSection.Remove(DescriptionElement); } else { var model = new DescriptionModel(x, (int)UIFont.PreferredSubheadline.PointSize); var markdown = new DescriptionView { Model = model }; var html = markdown.GenerateString(); DescriptionElement.Value = html; if (!DetailsSection.Contains(DescriptionElement)) { DetailsSection.Insert(0, UITableViewRowAnimation.Fade, DescriptionElement); } } }); CommentsSection.FooterView = new TableFooterButton("Add Comment", () => ViewModel.AddCommentCommand.ExecuteIfCan()); this.WhenAnyValue(x => x.ViewModel.Events) .Select(x => x.Changed) .Switch() .Select(x => ViewModel.Events) .Subscribe(events => { var comments = events.Select(x => { var body = string.Empty; var comment = x as IssueCommentItemViewModel; var @event = x as IssueEventItemViewModel; if (comment != null) { body = comment.Comment; } else if (@event != null) { body = CreateEventBody(@event.EventInfo, @event.Commit); } return(new Comment(x.AvatarUrl.ToUri(), x.Actor, body, x.CreatedAt.LocalDateTime.Humanize())); }) .Where(x => !string.IsNullOrEmpty(x.Body)) .ToList(); if (comments.Count > 0) { var commentModel = new CommentModel(comments, (int)UIFont.PreferredSubheadline.PointSize); var razorView = new CommentsView { Model = commentModel }; var html = razorView.GenerateString(); CommentsElement.Value = html; if (!CommentsSection.Contains(CommentsElement)) { CommentsSection.Insert(0, UITableViewRowAnimation.Fade, CommentsElement); } } else { CommentsSection.Remove(CommentsElement); } }); var commentsButton = SplitButton.AddButton("Comments", "-"); var participantsButton = SplitButton.AddButton("Participants", "-"); this.WhenAnyValue(x => x.ViewModel.Issue.Comments) .Subscribe(x => commentsButton.Text = x.ToString()); this.WhenAnyValue(x => x.ViewModel.Participants) .Subscribe(x => participantsButton.Text = x.ToString()); }
public async Task <IActionResult> AddAnswerToComment(Guid id, Guid commentId, [FromBody] CommentModel model) => (await _commentService.AddAnswerToCommentAsync(id, commentId, model)) .OnSuccess(x => (IActionResult)Ok(x)) .OnFailure(_ => BadRequest(), error => error is ArgumentNullError) .OnFailure(error => error.ToObjectResult(), error => error != null) .OnFailure(_ => ModelState.ToObjectResult());
public void RenderComments() { var comments = ViewModel.Comments .Select(x => new Comment(x.User.AvatarUrl, x.User.Login, ViewModel.ConvertToMarkdown(x.Body), x.CreatedAt)) .Concat(ViewModel.Events.Select(x => new Comment(x.Actor.AvatarUrl, x.Actor.Login, CreateEventBody(x.Event, x.CommitId), x.CreatedAt))) .Where(x => !string.IsNullOrEmpty(x.Body)) .OrderBy(x => x.Date) .ToList(); var commentModel = new CommentModel(comments, (int)UIFont.PreferredSubheadline.PointSize); var razorView = new CommentsView { Model = commentModel }; var html = razorView.GenerateString(); InvokeOnMainThread(() => { _commentsElement.SetValue(!comments.Any() ? null : html); Render(); }); }
public ActionResult AddComment(CommentModel model) { _commentService.AddComment(model, UserManager.FindById(User.Identity.GetUserId())); return(new EmptyResult()); }