public void SaveComment(CommentInfo comment) { var portalSecurity = new PortalSecurity(); if (!String.IsNullOrEmpty(comment.Comment)) { comment.Comment = HttpUtility.HtmlDecode(portalSecurity.InputFilter(comment.Comment, PortalSecurity.FilterFlag.NoScripting)); comment.Comment = portalSecurity.InputFilter(comment.Comment, Security.PortalSecurity.FilterFlag.NoMarkup); } //TODO: enable once the profanity filter is working properly. //objCommentInfo.Comment = portalSecurity.Remove(objCommentInfo.Comment, DotNetNuke.Security.PortalSecurity.ConfigType.ListController, "ProfanityFilter", DotNetNuke.Security.PortalSecurity.FilterScope.PortalList); if (comment.Comment != null && comment.Comment.Length > 2000) { comment.Comment = comment.Comment.Substring(0, 1999); } string xml = null; if (comment.CommentXML != null) { xml = comment.CommentXML.OuterXml; } comment.CommentId = _dataService.Journal_Comment_Save(comment.JournalId, comment.CommentId, comment.UserId, comment.Comment, xml); var newComment = GetComment(comment.CommentId); comment.DateCreated = newComment.DateCreated; comment.DateUpdated = newComment.DateUpdated; }
/// <summary> /// /// </summary> /// <param name="commentInfo"></param> /// <param name="commentInfos"></param> /// <param name="teamDic">Key:チームID Value:チーム名略 のDictionary</param> public JlgGameText(CommentInfo commentInfo = null, IEnumerable<CommentInfo> commentInfos = null, Dictionary<int, string> teamDic = null) { if (commentInfo == null) { this.DislayHalf = GetDisplayHalf(0, null); return; } this.CommentInfoId = commentInfo.CommentInfoId; this.CommentReportId = commentInfo.CommentReportId; this.StateID = commentInfo.StateID; this.StateName = commentInfo.StateName; this.Half = commentInfo.Half; this.Comment = commentInfo.Comment; this.DislayHalf = this.GetDisplayHalf(this.CommentInfoId, commentInfos); int? teamId = null; string teamNameS = null; string displayComment = null; this.SplitComment(this.Comment, teamDic, ref teamId, ref teamNameS, ref displayComment); this.TeamID = teamId; this.TeamNameS = teamNameS; this.DisplayComment = displayComment; }
/// <summary> /// DataModel 转 ViewModel /// </summary> /// <param name="commentInfo"></param> /// <returns></returns> public static CommentVModel CommentInfoToVModel(CommentInfo commentInfo) { if (commentInfo == null) { return(new CommentVModel()); } return(new CommentVModel { Id = commentInfo.Id, AId = commentInfo.AId, UserId = commentInfo.UserId, CreateTime = commentInfo.CreateTime, Content = commentInfo.Content, IP = commentInfo.IP, UserAgent = commentInfo.UserAgent, State = commentInfo.State, RefuseReason = commentInfo.RefuseReason, IsDelete = commentInfo.IsDelete, LastEditUserId = commentInfo.LastEditUserId, LastEditTime = commentInfo.LastEditTime, IsStick = commentInfo.IsStick, DianZanNum = commentInfo.DianZanNum }); }
/// <summary> /// Create new comment. /// </summary> /// <param name="comment"></param> /// <returns></returns> public async Task <Result <CommentInfo> > AddAsync(CommentInfo comment) { comment.Date = DateTime.Now; var commentDb = _mapper.Map <CommentInfo, CommentDb>(comment); try { await _commentRepository.AddAsync(commentDb); return(Result <CommentInfo> .Ok(_mapper.Map <CommentInfo>(commentDb))); } catch (DbUpdateConcurrencyException e) { return((Result <CommentInfo>) Result <CommentInfo> .Fail($"Cannot save comment. {e.Message}")); } catch (DbUpdateException e) { return((Result <CommentInfo>) Result <CommentInfo> .Fail($"Cannot save comment. Duplicate field. {e.Message}")); } catch (DbEntityValidationException e) { return((Result <CommentInfo>) Result <CommentInfo> .Fail($"Invalid comment. {e.Message}")); } }
/// <summary> /// 数据转换 /// </summary> /// <param name="read"></param> /// <returns></returns> private List <CommentInfo> DataReaderToCommentList(OleDbDataReader read) { List <CommentInfo> list = new List <CommentInfo>(); while (read.Read()) { CommentInfo comment = new CommentInfo(); comment.CommentId = Convert.ToInt32(read["CommentId"]); comment.ParentId = Convert.ToInt32(read["ParentId"]); comment.PostId = Convert.ToInt32(read["PostId"]); comment.UserId = Convert.ToInt32(read["UserId"]); comment.Name = Convert.ToString(read["Name"]); comment.Email = Convert.ToString(read["Email"]); comment.SiteUrl = Convert.ToString(read["SiteUrl"]); comment.Content = Convert.ToString(read["Content"]); comment.EmailNotify = Convert.ToInt32(read["EmailNotify"]); comment.IpAddress = Convert.ToString(read["IpAddress"]); comment.CreateDate = Convert.ToDateTime(read["CreateDate"]); comment.Approved = Convert.ToInt32(read["Approved"]); list.Add(comment); } read.Close(); return(list); }
public CommentInfo Comments_Selectbycmt_uid(string cmt_uid) { DbCommand dbCommandWrapper = Db_0.GetStoredProcCommand("Proc_Comments_Selectbycmt_uid"); Db_0.AddInParameter(dbCommandWrapper, "@cmt_uid", DbType.String, cmt_uid); try { CommentInfo obj = null; using (IDataReader reader = Db_0.ExecuteReader(dbCommandWrapper)) { if (reader.Read()) { obj = getCommentInfo(reader, false); } } return(obj); } catch (Exception e) { throw new Exception(e.Message); } }
private string GetHTMLComment(Comment comment, bool isPreview) { var commentInfo = new CommentInfo { CommentID = comment.ID.ToString(), UserID = comment.CreateBy, TimeStamp = comment.CreateOn, TimeStampStr = comment.CreateOn.Ago(), UserPost = Global.EngineFactory.GetParticipantEngine().GetByID(comment.CreateBy).UserInfo.Title, IsRead = true, Inactive = comment.Inactive, CommentBody = comment.Content, UserFullName = DisplayUserSettings.GetFullUserName( Global.EngineFactory.GetParticipantEngine().GetByID(comment.CreateBy).UserInfo), UserAvatar = Global.GetHTMLUserAvatar(comment.CreateBy) }; var defComment = new CommentsList(); ConfigureComments(defComment, null); if (!isPreview) { commentInfo.IsEditPermissions = ProjectSecurity.CanEditComment(Discussion.Project, comment); commentInfo.IsResponsePermissions = ProjectSecurity.CanCreateComment(); var when = Global.EngineFactory.GetParticipantEngine().WhenReaded(Page.Participant.ID, Discussion.UniqID); commentInfo.IsRead = when.HasValue && when.Value > comment.CreateOn; } return(CommentsHelper.GetOneCommentHtmlWithContainer( defComment, commentInfo, comment.Parent == Guid.Empty, false)); }
/// <summary> /// 删除 /// </summary> /// <param name="commentId"></param> /// <returns></returns> public int DeleteComment(int commentId) { CommentInfo comment = GetComment(commentId); int result = _commentRepository.Delete(new CommentInfo { CommentId = commentId }); //统计 new StatisticsService().UpdateStatisticsCommentCount(-1); if (comment != null) { //用户 new UserService().UpdateUserCommentCount(comment.UserId, -1); //文章 //TODO:postservice //new PostService().UpdatePostCommentCount(comment.PostId, -1); } _recentcomments = null; return(result); }
/// <summary> /// 生成代码文本集合 /// </summary> /// <param name="table">表名</param> /// <param name="namespacePfx">命名空间前辍</param> /// <param name="type">类型</param> /// <param name="fileNames">文件名集合</param> /// <returns>代码文本集合</returns> protected override string[] BuilderCodeTexts(TableInfo table, string namespacePfx, string type, out string[] fileNames) { string name = $"{table.Name.FristUpper()}Info"; string parentClass = "UserInfo".Equals(name) ? "BasicUserInfo" : "PersonTimeInfo"; EnumGenerator enumGenerator = new EnumGenerator(); fileNames = new string[] { $"{name}.cs" }; StringBuilder propCode = new StringBuilder(); ITypeMapperService typeMapper = SimpleFactory.Create(type); if (!table.Columns.IsNullOrCount0()) { for (int i = 0; i < table.Columns.Count; i++) { ColumnInfo c = table.Columns[i]; string propName = c.Name.FristUpper(); if (IGNORE_PROP_NAMES.Contains(propName)) { continue; } if ("UserInfo".Equals(name)) { if (USER_IGNORE_PROP_NAMES.Contains(propName)) { continue; } } string propType = typeMapper.GetPropertyType(c); CommentInfo comment = null; if (!string.IsNullOrWhiteSpace(c.Description)) { try { comment = JsonUtil.Deserialize <CommentInfo>(c.Description); if (comment != null && comment.Enum != null) { propType = enumGenerator.BuilderCodeText(comment.Enum, namespacePfx); } } catch { } } string commentDesc = null; StringBuilder attrCode = new StringBuilder(); if (!c.IsNull) { attrCode.Append(GetAttrCode("Required")); attrCode.AppendLine(); } if (c.Length != null && "string".Equals(propType)) { attrCode.Append(GetAttrCode(string.Format("MaxLength({0})", c.Length))); attrCode.AppendLine(); } if (comment != null) { if (string.IsNullOrWhiteSpace(comment.Desc)) { commentDesc = c.Description; } else { commentDesc = comment.Desc; } if (!string.IsNullOrWhiteSpace(comment.Name)) { attrCode.Append(GetAttrCode(string.Format("DisplayName(\"{0}\")", comment.Name))); attrCode.AppendLine(); } if (comment.MinLength != null && "string".Equals(propType)) { attrCode.Append(GetAttrCode(string.Format("MinLength({0})", comment.MinLength))); attrCode.AppendLine(); } if (comment.Range != null && comment.Range.Length == 2) { attrCode.Append(GetAttrCode(string.Format("Range({0}, {1})", comment.Range[0], comment.Range[1]))); attrCode.AppendLine(); } } else { commentDesc = c.Description; } if (string.IsNullOrWhiteSpace(commentDesc)) { commentDesc = propName; } propCode.Append(PropertyTemplate .Replace("|Description|", commentDesc) .Replace("|JsonName|", c.Name.FristLower()) .Replace("|Attribute|", attrCode.ToString()) .Replace("|Type|", propType) .Replace("|Name|", propName) .Replace("|Order|", (i + 1).ToString())); if (i == table.Columns.Count - 1) { continue; } propCode.AppendLine(); propCode.AppendLine(); } } var desc = string.IsNullOrWhiteSpace(table.Description) ? name : table.Description; return(new string[] { ClassTemplate .Replace("|NamespacePfx|", namespacePfx) .Replace("|Description|", desc) .Replace("|Name|", name) .Replace("|Inherit|", parentClass) .Replace("|Property|", propCode.ToString()) }); }
public void CommentCreate_AsPreMod_ReturnCorrectError() { var siteName = "h2g2"; var siteId = 1; var uid = "uid"; var text = "test text"; var siteList = mocks.DynamicMock<ISiteList>(); var readerCreator = mocks.DynamicMock<IDnaDataReaderCreator>(); var site = mocks.DynamicMock<ISite>(); var reader = mocks.DynamicMock<IDnaDataReader>(); var cacheManager = mocks.DynamicMock<ICacheManager>(); var callingUser = mocks.DynamicMock<ICallingUser>(); var commentForum = new CommentForum { Id = uid, SiteName = siteName, ModerationServiceGroup = ModerationStatus.ForumStatus.PreMod }; var commentInfo = new CommentInfo { text = text }; callingUser.Stub(x => x.IsSecureRequest).Return(true); callingUser.Stub(x => x.UserID).Return(1); callingUser.Stub(x => x.IsUserA(UserTypes.SuperUser)).Return(false).Constraints(Is.Anything()); cacheManager.Stub(x => x.GetData("")).Return(null).Constraints(Is.Anything()); site.Stub(x => x.SiteID).Return(siteId); site.Stub(x => x.IsEmergencyClosed).Return(false); site.Stub(x => x.IsSiteScheduledClosed(DateTime.Now)).Return(false); reader.Stub(x => x.HasRows).Return(true); reader.Stub(x => x.Read()).Return(true).Repeat.Once(); readerCreator.Stub(x => x.CreateDnaDataReader("commentcreate")).Return(reader); siteList.Stub(x => x.GetSite(siteName)).Return(site); mocks.ReplayAll(); var comments = new Comments(null, readerCreator, cacheManager, siteList); comments.CallingUser = callingUser; var comment = comments.CreateComment(commentForum, commentInfo); Assert.IsNotNull(comment); readerCreator.AssertWasCalled(x => x.CreateDnaDataReader("commentcreate")); }
public void CommentCreate_ForumClosed_NotableUser_ReturnResults() { var siteName = "h2g2"; var siteId = 1; var uid = "uid"; var text = "test comment"; var siteList = mocks.DynamicMock<ISiteList>(); var readerCreator = mocks.DynamicMock<IDnaDataReaderCreator>(); var site = mocks.DynamicMock<ISite>(); var reader = mocks.DynamicMock<IDnaDataReader>(); var cacheManager = mocks.DynamicMock<ICacheManager>(); var callingUser = mocks.DynamicMock<ICallingUser>(); var commentForum = new CommentForum { Id = uid, SiteName = siteName }; var commentInfo = new CommentInfo { text = text }; callingUser.Stub(x => x.IsSecureRequest).Return(true); callingUser.Stub(x => x.UserID).Return(1); callingUser.Stub(x => x.IsUserA(UserTypes.Notable)).Return(true); cacheManager.Stub(x => x.GetData("")).Return(null).Constraints(Is.Anything()); site.Stub(x => x.SiteID).Return(siteId); site.Stub(x => x.IsEmergencyClosed).Return(false); site.Stub(x => x.IsSiteScheduledClosed(DateTime.Now)).Return(false); reader.Stub(x => x.HasRows).Return(true); reader.Stub(x => x.Read()).Return(true).Repeat.Once(); readerCreator.Stub(x => x.CreateDnaDataReader("commentcreate")).Return(reader); siteList.Stub(x => x.GetSite(siteName)).Return(site); mocks.ReplayAll(); var comments = new Comments(null, readerCreator, cacheManager, siteList); comments.CallingUser = callingUser; var retVal = comments.CreateComment(commentForum, commentInfo); Assert.AreEqual(text, retVal.text); reader.AssertWasCalled(x => x.Execute()); }
public void CommentCreate_NotSecureWithoutSiteOption_ReturnCorrectComment() { var siteName = "h2g2"; var uid = "uid"; var text = "Here is my text that is not posted securely"; var siteList = mocks.DynamicMock<ISiteList>(); var readerCreator = mocks.DynamicMock<IDnaDataReaderCreator>(); var site = mocks.DynamicMock<ISite>(); var reader = mocks.DynamicMock<IDnaDataReader>(); var cacheManager = mocks.DynamicMock<ICacheManager>(); var callingUser = mocks.DynamicMock<ICallingUser>(); var commentForum = new CommentForum { Id = uid, SiteName = siteName }; var commentInfo = new CommentInfo { text = text }; callingUser.Stub(x => x.UserID).Return(1); callingUser.Stub(x => x.IsUserA(UserTypes.SuperUser)).Return(false).Constraints(Is.Anything()); cacheManager.Stub(x => x.GetData("")).Return(null).Constraints(Is.Anything()); site.Stub(x => x.IsEmergencyClosed).Return(false); site.Stub(x => x.IsSiteScheduledClosed(DateTime.Now)).Return(false); reader.Stub(x => x.HasRows).Return(true); reader.Stub(x => x.Read()).Return(true).Repeat.Once(); readerCreator.Stub(x => x.CreateDnaDataReader("commentcreate")).Return(reader); siteList.Stub(x => x.GetSite(siteName)).Return(site); siteList.Stub(x => x.GetSiteOptionValueInt(0, "CommentForum", "EnforceSecurePosting")).Return(0); mocks.ReplayAll(); var comments = new Comments(null, readerCreator, cacheManager, siteList); comments.CallingUser = callingUser; comments.CreateComment(commentForum, commentInfo); readerCreator.AssertWasCalled(x => x.CreateDnaDataReader("commentcreate")); }
/// <summary> /// 添加 /// </summary> /// <param name="comment"></param> /// <returns></returns> public int InsertComment(CommentInfo comment) { string cmdText = string.Format(@"insert into [{0}comments]( PostId, ParentId,UserId,Author,Email,AuthorUrl,Contents,EmailNotify,IpAddress,CreateTime,Approved) values ( @PostId, @ParentId,@UserId,@Author,@Email,@AuthorUrl,@Contents,@EmailNotify,@IpAddress,@CreateTime,@Approved)",ConfigHelper.Tableprefix); OleDbParameter[] prams = { OleDbHelper.MakeInParam("@PostId", OleDbType.Integer,4, comment.PostId), OleDbHelper.MakeInParam("@ParentId", OleDbType.Integer,4, comment.ParentId), OleDbHelper.MakeInParam("@UserId", OleDbType.Integer,4, comment.UserId), OleDbHelper.MakeInParam("@Author", OleDbType.VarWChar,255, comment.Author), OleDbHelper.MakeInParam("@Email", OleDbType.VarWChar,255, comment.Email), OleDbHelper.MakeInParam("@AuthorUrl", OleDbType.VarWChar,255, comment.AuthorUrl), OleDbHelper.MakeInParam("@Contents", OleDbType.VarWChar,255, comment.Contents), OleDbHelper.MakeInParam("@EmailNotify", OleDbType.Integer,4 , comment.EmailNotify), OleDbHelper.MakeInParam("@IpAddress", OleDbType.VarWChar,255, comment.IpAddress), OleDbHelper.MakeInParam("@CreateTime", OleDbType.Date,8, comment.CreateTime), OleDbHelper.MakeInParam("@Approved", OleDbType.Integer,4 , comment.Approved), }; OleDbHelper.ExecuteNonQuery(CommandType.Text, cmdText, prams); int newId = Convert.ToInt32(OleDbHelper.ExecuteScalar(string.Format("select top 1 [CommentId] from [{0}comments] order by [CommentId] desc",ConfigHelper.Tableprefix))); return newId; }
public void DeleteById(CommentInfo commentInfo) { ((CommentRepositary)(forumUOW.CommentRepositary)).DeleteById(commentInfo.CommentId); forumUOW.Save(); }
public void Create(CommentInfo comment) { var commentEntity = AutoMapper.Mapper.Map <CommentEntity>(comment); repository.Create(commentEntity); }
public virtual void GetCommentFormat(CommentInfo info){ info.supported = true; info.lineStart = "//"; info.blockStart = "/*"; info.blockEnd = "*/"; info.useLineComments = true; }
protected void btnAddComment_Click(object sender, EventArgs e) { try { if (Page.IsValid && comment.Value == ans1 && DotNetNuke.Entities.Users.UserController.GetCurrentUserInfo().UserID != -1) { CommentInfo ci = new CommentInfo(); ci.ArticleId = ArticleId; if (DotNetNuke.Entities.Users.UserController.GetCurrentUserInfo().UserID != -1) { ci.Authed = true; } else { ci.Authed = false; } ci.Comment = txtComment.Text; ci.CreatedUser = txtName.Text.Trim(); ci.Mail = null; ci.Url = null; ci.CreatedDate = DateTime.Now; ci.IsPrivate = false; ci.PortalId = DotNetNuke.Entities.Portals.PortalController.GetCurrentPortalSettings().PortalId; ci.UserId = DotNetNuke.Entities.Users.UserController.GetCurrentUserInfo().UserID; CommentController.Add(ci); BindComment(); txtComment.Text = ""; comment.Value = ""; } if (DotNetNuke.Entities.Users.UserController.GetCurrentUserInfo().UserID == -1) { Page.ClientScript.RegisterStartupScript(this.GetType(), "mKey", "alert('Your comment is sent for approval');", true); } } catch (Exception ex) { UserInfo info = UserController.GetCurrentUserInfo(); ErrorLog objLog = new ErrorLog(); objLog.ErrorDescription = ex.ToString(); objLog.ErrorDate = DateTime.Now; objLog.ErrorFunctionName = System.Reflection.MethodBase.GetCurrentMethod().Name; objLog.ErrorControlName = (GetType().ToString().Replace("ASP.", "").Replace("_ascx", ".ascx").Remove(0, GetType().ToString().Replace("ASP.", "").Replace("_ascx", ".ascx").LastIndexOf("_") + 1)); objLog.ErrorLoggedInUser = info.Username; objLog.AddErrorToLog(objLog); } }
/// <summary> /// 数据转换 /// </summary> /// <param name="read"></param> /// <returns></returns> private static List<CommentInfo> DataReaderToCommentList(OleDbDataReader read) { var list = new List<CommentInfo>(); while (read.Read()) { var comment = new CommentInfo { CommentId = Convert.ToInt32(read["CommentId"]), ParentId = Convert.ToInt32(read["ParentId"]), PostId = Convert.ToInt32(read["PostId"]), UserId = Convert.ToInt32(read["UserId"]), Author = Convert.ToString(read["Author"]), Email = Convert.ToString(read["Email"]), AuthorUrl = Convert.ToString(read["AuthorUrl"]), Contents = Convert.ToString(read["Contents"]), EmailNotify = Convert.ToInt32(read["EmailNotify"]), IpAddress = Convert.ToString(read["IpAddress"]), CreateTime = Convert.ToDateTime(read["CreateTime"]), Approved = Convert.ToInt32(read["Approved"]) }; list.Add(comment); } read.Close(); return list; }
/// <summary> /// 更新 /// </summary> /// <param name="comment"></param> /// <returns></returns> public int UpdateComment(CommentInfo comment) { string cmdText = string.Format(@"update [{0}comments] set PostId=@PostId, ParentId=@ParentId, UserId=@UserId, Author=@Author, Email=@Email, AuthorUrl=@AuthorUrl, Contents=@Contents, EmailNotify=@EmailNotify, IpAddress=@IpAddress, CreateTime=@CreateTime, Approved=@Approved where CommentId=@CommentId ",ConfigHelper.Tableprefix); OleDbParameter[] prams = { OleDbHelper.MakeInParam("@PostId", OleDbType.Integer,4, comment.PostId), OleDbHelper.MakeInParam("@ParentId", OleDbType.Integer,4, comment.ParentId), OleDbHelper.MakeInParam("@UserId", OleDbType.Integer,4, comment.UserId), OleDbHelper.MakeInParam("@Author", OleDbType.VarWChar,255, comment.Author), OleDbHelper.MakeInParam("@Email", OleDbType.VarWChar,255, comment.Email), OleDbHelper.MakeInParam("@AuthorUrl", OleDbType.VarWChar,255, comment.AuthorUrl), OleDbHelper.MakeInParam("@Contents", OleDbType.VarWChar,255, comment.Contents), OleDbHelper.MakeInParam("@EmailNotify", OleDbType.Integer,4 , comment.EmailNotify), OleDbHelper.MakeInParam("@IpAddress", OleDbType.VarWChar,255, comment.IpAddress), OleDbHelper.MakeInParam("@CreateTime", OleDbType.Date,8, comment.CreateTime), OleDbHelper.MakeInParam("@Approved", OleDbType.Integer,4 , comment.Approved), OleDbHelper.MakeInParam("@CommentId", OleDbType.Integer,4, comment.CommentId), }; return OleDbHelper.ExecuteNonQuery(CommandType.Text, cmdText, prams); }
public HelpCommentOutput(VariantGroup variantGroup) { VariantGroup = variantGroup; CommentInfo = variantGroup.CommentInfo; }
public void SendMail(int postid, string email, PostInfo post, string content, string author, string siteurl, CommentInfo c, int parentid) { #region 发邮件 try { if (BlogConfig.GetSetting().SendMailNotifyByComment == 1) //给订阅者发邮件 { //先不考虑审核的问题 List <CommentInfo> list = CommentService.GetCommentList(int.MaxValue, 1, -1, postid, 0, -1, 1, string.Empty); List <string> emailList = new List <string>(); foreach (CommentInfo cmt in list) { if (!Jqpress.Framework.Utils.Validate.IsValidEmail(cmt.Email)) { continue; } //自己不用发 if (email == cmt.Email) { continue; } //不重复发送 if (emailList.Contains(cmt.Email)) { continue; } emailList.Add(cmt.Email); string subject = string.Empty; string body = string.Empty; subject = string.Format("[评论订阅通知]{0}", post.Title); body += string.Format("您订阅的{0}有新评论了:<br/>", post.Title); body += "<hr/>"; body += content; body += "<hr/>"; body += "<br />评论作者: " + author; if (!string.IsNullOrEmpty(siteurl)) { body += string.Format(" (<a href=\"{0}\">{0}</a>)", siteurl); } body += "<br />评论时间: " + DateTime.Now; body += string.Format("<br />原文连接: <a href=\"{0}\" title=\"{1}\" >{1}</a>", post.Url, post.Title); body += "<br />注:系统自动通知邮件,不要回复。"; EmailHelper.SendAsync(cmt.Email, subject, body); } } if (BlogConfig.GetSetting().SendMailAuthorByComment == 1 && c.ParentId <= 0) //给文章作者发邮件 回复时不发邮件 { string subject = string.Empty; string body = string.Empty; subject = string.Format("[新评论通知]{0}", post.Title); body += string.Format("您发表的{0}有新评论了:<br/>", post.Title); body += "<hr/>"; body += content; body += "<hr/>"; body += "<br />评论作者: " + author; if (!string.IsNullOrEmpty(siteurl)) { body += string.Format(" (<a href=\"{0}\">{0}</a>)", siteurl); } body += "<br />评论时间: " + DateTime.Now; body += string.Format("<br />原文连接: <a href=\"{0}\" title=\"{1}\" >{1}</a>", post.Url, post.Title); body += "<br />注:系统自动通知邮件,不要回复。"; UserInfo user = UserService.GetUser(post.UserId); if (user != null && Jqpress.Framework.Utils.Validate.IsValidEmail(user.Email)) { EmailHelper.SendAsync(user.Email, subject, body); } } if (BlogConfig.GetSetting().SendMailNotifyByComment == 1)//回复时发邮件 { //获取原品论者的邮箱 string replyemail = CommentService.GetComment(parentid).Email; string subject = string.Empty; string body = string.Empty; subject = string.Format("[评论回复通知]{0}", post.Title); body += string.Format("您对 {0} 发表的评论有回复了:<br/>", post.Title); body += "<hr/>"; body += content; body += "<hr/>"; body += "<br />评论作者: " + author; if (!string.IsNullOrEmpty(siteurl)) { body += string.Format(" (<a href=\"{0}\">{0}</a>)", siteurl); } body += "<br />回复时间: " + DateTime.Now; body += string.Format("<br />原文连接: <a href=\"{0}\" title=\"{1}\" >{1}</a>", post.Url, post.Title); body += "<br />注:系统自动通知邮件,不要回复。"; if (email != "" && Jqpress.Framework.Utils.Validate.IsValidEmail(replyemail)) { EmailHelper.SendAsync(email, subject, body); } } }catch (Exception e) { } #endregion }
private void TestTextXmlSerialisation(PostStyle.Style style, string expected, string input, bool isEditor) { var target = new CommentInfo { PostStyle = style, text = CommentInfo.FormatComment(input, style, CommentStatus.Hidden.NotHidden, isEditor) }; var docExpected = new XmlDocument(); docExpected.Load(StringUtils.SerializeToXml(expected)); expected = docExpected.DocumentElement.InnerXml; var doc = new XmlDocument(); doc.Load(target.ToXml()); Assert.AreEqual(expected, doc.DocumentElement["text"].InnerXml); }
public IActionResult Page(int recipeId) { var recipeInfo = new RecipeInfo(); recipeInfo.RecipeIngredients = new List <RecipeIngredients>(); recipeInfo.Ingredients = new List <Ingredient.Ingredient>(); recipeInfo.Category = new Category(); recipeInfo.IngredientsList = new List <string>(); recipeInfo.Recipe = _db.Recipes.FirstOrDefault(r => r.Id == recipeId); recipeInfo.CurrentUser = HttpContext.Session.GetInt32("_Userid").Value; if (recipeInfo.Recipe == null) { return(View("Index")); } if (recipeInfo.Recipe.Photo != null) { recipeInfo.Image = Convert.ToBase64String(recipeInfo.Recipe.Photo); } var recipeIngredients = _db.RecipeIngredients .Where(r => r.RecipeId == recipeId) .Select(i => new { i.IngredientId, i.Amount, i.AmountType }) .ToArray(); var ingIds = new List <int>(); for (var i = 0; i < recipeIngredients.Length; i++) { recipeInfo.RecipeIngredients.Add( new RecipeIngredients { IngredientId = recipeIngredients[i].IngredientId, Amount = recipeIngredients[i].Amount, AmountType = recipeIngredients[i].AmountType }); ingIds.Add(recipeIngredients[i].IngredientId); } recipeInfo.Category = _db.Categories.SingleOrDefault(c => c.Id == recipeInfo.Recipe.CategoryId); var ingredients = _db.Ingredients .Where(i => ingIds.Contains(i.Id)); foreach (var ingredient in ingredients) { recipeInfo.Ingredients.Add( new Ingredient.Ingredient { Id = ingredient.Id, Name = ingredient.Name }); } for (var i = 0; i < recipeInfo.Ingredients.Count; i++) { var fullIngredient = ""; if (recipeInfo.RecipeIngredients[i].Amount != "N/A") { fullIngredient = recipeInfo.RecipeIngredients[i].Amount + " "; if (recipeInfo.RecipeIngredients[i].AmountType != "N/A") { fullIngredient = fullIngredient + recipeInfo.RecipeIngredients[i].AmountType + " of "; } } fullIngredient = fullIngredient + recipeInfo.Ingredients[i].Name; recipeInfo.IngredientsList.Add(fullIngredient); } var comments = _db.Comments.Where(c => c.RecipeId == recipeInfo.Recipe.Id) .OrderByDescending(u => u.CreatedAt).ToList(); var commentInfoList = new List <CommentInfo>(); foreach (var comment in comments) { var user = _db.Users.FirstOrDefault(u => u.Id == comment.UserId); if (user != null) { var commentInfo = new CommentInfo { CommentObj = comment, Commenter = user.DisplayName }; commentInfoList.Add(commentInfo); } } var rating = 0; var dbRating = _db.RecipeRatings.Where(r => r.RecipeId == recipeInfo.Recipe.Id).ToList(); recipeInfo.RatingCount = dbRating.Count; if (dbRating.Count > 0) { // averaging the rating foreach (var rate in dbRating) { rating += rate.Rating; } recipeInfo.Rating = rating / recipeInfo.RatingCount; } else { recipeInfo.Rating = rating; } ViewData["CommentInfo"] = commentInfoList; var recipeOwner = _db.Users.FirstOrDefault(u => u.Id == recipeInfo.Recipe.UploaderId); if (recipeOwner != null) { ViewData["RecipeOwner"] = recipeOwner.DisplayName; } var savedRecipe = _db.SavedRecipes.FirstOrDefault(sr => sr.RecipeId == recipeId && sr.UserId == recipeInfo.CurrentUser); if (savedRecipe != null) { ViewData["AlreadySaved"] = true; } else { ViewData["AlreadySaved"] = false; } return(View(recipeInfo)); }
public IHttpActionResult Main(int siteId, int channelId, int contentId) { try { var body = new RequestBody(); var publishmentSystemInfo = PublishmentSystemManager.GetPublishmentSystemInfo(siteId); if (!publishmentSystemInfo.Additional.IsCommentable) { return(Unauthorized()); } var account = body.GetPostString("account"); var password = body.GetPostString("password"); var replyId = body.GetPostInt("replyId"); var content = body.GetPostString("content"); if (replyId > 0) { string replyUserName; string replyContent; DataProvider.CommentDao.GetUserNameAndContent(replyId, out replyUserName, out replyContent); if (!string.IsNullOrEmpty(replyContent)) { var displayName = BaiRongDataProvider.UserDao.GetDisplayName(replyUserName); if (!string.IsNullOrEmpty(displayName)) { displayName = $"@{displayName}:"; } content += $" //{displayName}{replyContent}"; } } UserInfo userInfo; if (!string.IsNullOrEmpty(account) && !string.IsNullOrEmpty(password)) { string userName; string errorMessage; if (!BaiRongDataProvider.UserDao.ValidateAccount(account, password, out userName, out errorMessage)) { LogUtils.AddUserLog(userName, EUserActionType.LoginFailed, "用户登录失败"); BaiRongDataProvider.UserDao.UpdateLastActivityDateAndCountOfFailedLogin(userName); return(BadRequest(errorMessage)); } BaiRongDataProvider.UserDao.UpdateLastActivityDateAndCountOfLogin(userName); userInfo = BaiRongDataProvider.UserDao.GetUserInfoByUserName(userName); body.UserLogin(userName); } else { userInfo = body.UserInfo; } if (!publishmentSystemInfo.Additional.IsAnonymousComments && !body.IsUserLoggin) { return(Unauthorized()); } var commentInfo = new CommentInfo { Id = 0, PublishmentSystemId = siteId, NodeId = channelId, ContentId = contentId, GoodCount = 0, UserName = userInfo.UserName, IsChecked = !publishmentSystemInfo.Additional.IsCheckComments, AddDate = DateTime.Now, Content = content }; commentInfo.Id = DataProvider.CommentDao.Insert(commentInfo); return(Ok(new { User = new User(userInfo), Comment = new Comment(commentInfo, userInfo) })); } catch (Exception ex) { return(InternalServerError(ex)); } }
public bool AddInfo(CommentInfo commentInfo)//通过对象添加 { yiContext.CommentInfo.Add(commentInfo); return(yiContext.SaveChanges() > 0); }
public ActionResult BanComment(CommentInfo model) { new DataAccess().BanComment(model.ID); return(RedirectToAction("Index", "Lot", new { id = model.LotID })); }
private void TestTextJsonSerialisation(PostStyle.Style style, string expected, string input, bool isEditor) { var target = new CommentInfo() { PostStyle = style, text = CommentInfo.FormatComment(input, style, CommentStatus.Hidden.NotHidden, isEditor) }; MemoryStream stream = (MemoryStream)StringUtils.SerializeToJson(target); var doc = Encoding.UTF8.GetString(stream.ToArray()); var returnedObject = (CommentInfo)StringUtils.DeserializeJSONObject(doc, target.GetType()); Assert.AreEqual(expected, returnedObject.text); //var regText = new Regex("\"text\"\\:\"(.*)\","); //Assert.IsTrue(regText.IsMatch(doc)); //MatchCollection matches = regText.Matches(doc); //foreach (Match match in matches) //{ // var actual = match.Value.Substring(8, match.Value.Length - 10); // actual = actual.Replace("\\/", "/"); // actual = actual.Replace("/\\", "/"); // Assert.AreEqual(expected, actual); //} }
public void Edit(CommentInfo comment) { var commentEntity = AutoMapper.Mapper.Map <CommentEntity>(comment); repository.Edit(commentEntity); }
public static int Update(CommentInfo item, _[] ignore) => dal.Update(item, ignore?.Where(a => a > 0).Select(a => Enum.GetName(typeof(_), a)).ToArray()).ExecuteNonQuery();
/// <summary> /// 保存评论 /// </summary> public void SaveComment() { int contentMaxLength = 1000; //内容最长长度 int postid = Jqpress.Framework.Web.PressRequest.GetFormInt("postid", 0); string author = StringHelper.CutString(Jqpress.Framework.Web.PressRequest.GetFormString("commentauthor"), 0, 20); string email = StringHelper.CutString(Jqpress.Framework.Web.PressRequest.GetFormString("commentemail"), 0, 50); string siteurl = StringHelper.CutString(Jqpress.Framework.Web.PressRequest.GetFormString("commentsiteurl"), 0, 100); int parentid = Jqpress.Framework.Web.PressRequest.GetFormInt("ReplyToCommentId", 0); string content = Jqpress.Framework.Web.PressRequest.GetFormString("commentcontent"); int remeber = Jqpress.Framework.Web.PressRequest.GetFormInt("commentremember", 0); int emailnotify = Jqpress.Framework.Web.PressRequest.GetFormInt("commentemail", 0); string verifycode = Jqpress.Framework.Web.PressRequest.GetFormString("commentverifycode"); CommentInfo c = new CommentInfo(); c.ParentId = parentid; c.Contents = StringHelper.TextToHtml(StringHelper.CutString(content, 0, contentMaxLength)); c.CreateTime = DateTime.Now; c.Email = Jqpress.Framework.Web.HttpHelper.HtmlEncode(email); c.EmailNotify = emailnotify; c.IpAddress = Jqpress.Framework.Web.PressRequest.GetIP(); c.ParentId = 0; c.PostId = postid; c.UserId = 0; c.Author = author; c.AuthorUrl = siteurl; PostInfo post = PostService.GetPost(postid); switch (BlogConfig.GetSetting().CommentApproved) { case 1: c.Approved = (int)ApprovedStatus.Success; break; case 2: string[] blackwords = BlogConfig.GetSetting().CommentSpamwords.Split(','); bool hasBlackword = false; foreach (string word in blackwords) { if (c.Contents.IndexOf(word) != -1) { hasBlackword = true; break; } } c.Approved = hasBlackword ? (int)ApprovedStatus.Wait : (int)ApprovedStatus.Success; break; case 3: default: c.Approved = (int)ApprovedStatus.Wait; break; } int newID = CommentService.InsertComment(c); string response = "<li id=\"comment-comment-" + newID + "\" class=\"comment even thread-even depth-1\">"; response += "<div class=\"comment-body\" id=\"div-comment-" + newID + "\">"; response += "<div class=\"comment-author vcard\">"; response += "<img width=\"26\" height=\"26\" class=\"avatar avatar-26 photo avatar-default\" "; response += "src=\"http://www.gravatar.com/avatar/" + c.GravatarCode + "?size=26\" \">"; response += "<cite class=\"fn\">" + c.Author + "</cite> "; response += "<span class=\"says\">说:</span></div>"; response += " <p> "; response += c.Contents; response += "</p>"; response += "</li>"; HttpContext.Current.Response.Write(response); SendMail(postid, email, post, content, author, siteurl, c, parentid); HttpContext.Current.Response.End(); /* * <li id="comment-comment-${item.commentid}" class="comment even thread-even depth-1"> * <div class="comment-author vcard"> * <img width="26" height="26" class="avatar avatar-26 photo avatar-default" * src="http://www.gravatar.com/avatar/${item.gravatarcode}?size=26" alt="${item.nickname}"> * * <cite class="fn">${item.authorlink}</cite> <span class="says">说:</span></div> */ }
/// <summary> /// 获得某文章的所有评论(最新接口) /// </summary> /// <param name="sourceId">文章Id</param> /// <param name="page">评论所在的页码</param> /// <param name="limit">页最大评论数</param> /// <returns></returns> public Stream Comments_SelectPaged2(string sourceId, string page, string limit) { WebOperationContext context = WebOperationContext.Current; context.OutgoingResponse.ContentType = "application/json; charset=utf-8"; // 设置评论搜索条件 CommentsSearchInfo search = new CommentsSearchInfo(); search.cmt_sourceId = sourceId.ToSafetyStr(); search.cmt_status = 1; search.page = int.Parse(page); search.pagesize = int.Parse(limit); // 获取评论 int rowcount = 0; List <CommentInfo> comments = DataAccess_News.Comments_SelectPaged(search.columns, search.ToWhereString(), search.DefOrder, search.page, search.pagesize, true, out rowcount); // 评论uid集合 List <string> cmt_uids = new List <string>(); foreach (var cmt in comments) { cmt_uids.Add(cmt.cmt_uid); if (!string.IsNullOrEmpty(cmt.cmt_parentIds)) { cmt_uids.AddRange(cmt.cmt_parentIds.Split(',')); } } cmt_uids = cmt_uids.Distinct().ToList(); var jsonSerializer = new JavaScriptSerializer(); var json = ""; // 获取所有评论uid的评论 List <CommentInfo> commentList = null; commentList = DataAccess_News.Comments_Selectbycmt_uidStrs(sourceId, cmt_uids.ToArray()); foreach (CommentInfo comment in commentList) { comment.cmt_createUser = (comment.cmt_createUserID == -1) ? "匿名用户" : comment.cmt_createUser; comment.cmt_content = HtmlHelper.DecodeHTMLString(comment.cmt_content, false).Replace("<br/>", "\n"); // 解析编码后的危险字符 comment.cmt_checkRemark = Util.UserFace_Get(comment.cmt_createUserID); //存放用户头像 } json = jsonSerializer.Serialize(comments); /* * 组装成网易盖楼形式 */ int idCount = comments.Count; // 楼层数 List <List <CommentInfo> > newPosts = new List <List <CommentInfo> >(); for (int index = 0; index < idCount; index++) { string cmt_parentIds = comments[index].cmt_parentIds; // 获取所有父楼层Id List <string> idList = new List <string>(); // 所有楼层id列表 if (!string.IsNullOrEmpty(cmt_parentIds)) { idList.AddRange(cmt_parentIds.Split(',')); } // 加上主楼 idList.Add(comments[index].cmt_uid); Dictionary <string, CommentInfo> cmt = commentList.ToDictionary(a => a.cmt_uid); List <CommentInfo> result = new List <CommentInfo>(); CommentInfo info = null; for (int idIndex = 0; idIndex < idList.Count; idIndex++) { if (!cmt.TryGetValue(idList[idIndex], out info)) { continue; } result.Add(info); } newPosts.Add(result); } json = "{\"list\":" + jsonSerializer.Serialize(newPosts) + ",\"page\":" + page + ",\"pageSize\":" + limit + ",\"total\":" + rowcount + ",\"sourceId\":\"" + sourceId + "\"}"; return(new MemoryStream(Encoding.UTF8.GetBytes(json))); }
protected void RptCommentManage_ItemDataBound(object sender, RepeaterItemEventArgs e) { if ((e.Item.ItemType == ListItemType.Item) || (e.Item.ItemType == ListItemType.AlternatingItem)) { ExtendedLiteral literal = e.Item.FindControl("LblCommentHead") as ExtendedLiteral; Label label = e.Item.FindControl("LblStatus") as Label; Label label2 = e.Item.FindControl("LblManage") as Label; ExtendedLiteral literal2 = e.Item.FindControl("LblRestore") as ExtendedLiteral; Label label3 = e.Item.FindControl("LblRestoreBottom") as Label; ExtendedLiteral literal3 = e.Item.FindControl("LblContent") as ExtendedLiteral; ExtendedLiteral literal4 = e.Item.FindControl("LblContentTitle") as ExtendedLiteral; ExtendedLiteral literal5 = e.Item.FindControl("LblRestoreTitle") as ExtendedLiteral; CommentInfo dataItem = (CommentInfo)e.Item.DataItem; string nodeIds = dataItem.NodeId.ToString(); if (!this.m_Administrator) { NodeInfo cacheNodeById = Nodes.GetCacheNodeById(dataItem.NodeId); if (cacheNodeById.ParentId > 0) { nodeIds = cacheNodeById.ParentPath + "," + nodeIds; } } string title = ContentManage.GetCommonModelInfoById(dataItem.GeneralId).Title; string str3 = "CommentID=" + dataItem.CommentId.ToString() + "&GeneralID=" + dataItem.GeneralId.ToString() + "&NodeID=" + BasePage.RequestInt32("NodeID").ToString() + "&Title=" + base.Server.UrlEncode(title) + "&UserId=" + dataItem.UserId.ToString(); if ((this.m_PrevId != dataItem.GeneralId) && (this.m_PrevId != 0)) { label3.Visible = true; label3.Text = "</table></td></tr></table><br/>"; } if ((this.m_PrevId != dataItem.GeneralId) || (this.m_PrevId == 0)) { StringBuilder builder = new StringBuilder(); builder.Append("<table class='border' width='100%' border='0' align='center' cellpadding='0' cellspacing='0'>"); builder.Append("<tr class='title'>"); builder.Append("<td width='80%' height='22'>"); builder.Append(" <a " + this.CheckCommentPermissions(nodeIds, this.m_NodeCommentManage, "href='ContentView.aspx?GeneralID=" + dataItem.GeneralId.ToString() + "'") + " >"); StringBuilder builder2 = new StringBuilder(); builder2.Append("</a> 总评分:" + Comment.ScoreCount(dataItem.GeneralId).ToString() + "</td>"); builder2.Append("<td width='20%' align='right'>"); builder2.Append("<a " + this.CheckCommentPermissions(nodeIds, this.m_NodeCommentManage, "href='CommentManage.aspx?Action=DelAll&" + str3 + "' onclick=\"return confirm('确定要删除此项目下的所有评论吗?');\"") + ">删除此项目下的所有评论</a> </td>"); builder2.Append("</tr><tr><td colspan='2'>"); builder2.Append("<table border='0' cellspacing='1' width='100%' cellpadding='0' style='word-break:break-all'>"); builder2.Append("</td>"); builder2.Append("</tr>"); literal.Visible = true; literal.BeginTag = builder.ToString(); literal.Text = title; literal.EndTag = builder2.ToString(); } this.m_PrevId = dataItem.GeneralId; StringBuilder builder3 = new StringBuilder(); string replyUserName = ""; if (dataItem.UserName == "游客") { builder3.Append("[游客] "); replyUserName = dataItem.ReplyUserName; } else { builder3.Append("[会员] "); replyUserName = dataItem.UserName; } StringBuilder builder4 = new StringBuilder(); builder4.Append(" 于 " + dataItem.UpdateDateTime.ToString("yyyy年MM月dd日 HH时mm分ss秒") + " 发表如下评论内容,同时评分:" + dataItem.Score.ToString() + "分"); builder4.Append("<br/>"); literal4.BeginTag = builder3.ToString(); literal4.Text = replyUserName; literal4.EndTag = builder4.ToString(); literal3.BeginTag = " <span >"; if (dataItem.Content.Length > 120) { literal3.Text = dataItem.Content.Substring(0, 120) + "..."; } else { literal3.Text = dataItem.Content; } literal3.EndTag = "</span>"; if (!dataItem.Status) { label.Text = "<span style='color:red'>\x00d7</span>"; } else { label.Text = "√"; } StringBuilder builder5 = new StringBuilder(); builder5.Append("<table width='100%' border='0' cellpadding='0' cellspacing='0'><tr>"); builder5.Append("<td align='center' style='width:30px;'>"); if (string.IsNullOrEmpty(dataItem.Reply)) { builder5.Append("<a " + this.CheckCommentPermissions(nodeIds, this.m_NodeCommentReply, "href='CommentRestore.aspx?" + str3 + "'") + ">回复</a>"); } builder5.Append("</td>"); builder5.Append("<td align='center' style='width:35px;'><a " + this.CheckCommentPermissions(nodeIds, this.m_NodeCommentManage, "href='CommentModify.aspx?Action=Modify&" + str3 + "'") + " >修改</a></td>"); builder5.Append("<td align='center' style='width:35px;'><a " + this.CheckCommentPermissions(nodeIds, this.m_NodeCommentManage, "href='CommentManage.aspx?Action=Del&" + str3 + "' onclick=\"return confirm('确定要删除此评论吗?');\"") + " >删除</a></td>"); builder5.Append("<td align='center' style='width:50px;'>"); if (!dataItem.Status) { builder5.Append("<a " + this.CheckCommentPermissions(nodeIds, this.m_NodeCommentCheck, "href='CommentManage.aspx?Action=SetPassed&" + str3 + "'") + " onclick=\"if(!confirm('确定要通过此评论吗?')){return false;}\" >通过审核</a>"); } else { builder5.Append("<a " + this.CheckCommentPermissions(nodeIds, this.m_NodeCommentCheck, "href='CommentManage.aspx?Action=CancelPassed&" + str3 + "'") + " onclick=\"if(!confirm('确定要取消此评论吗?')){return false;}\" >取消审核</a>"); } builder5.Append("</td>"); builder5.Append("</tr></table>"); label2.Text = builder5.ToString(); if (!string.IsNullOrEmpty(dataItem.Reply)) { string reply = dataItem.Reply; if (dataItem.Reply.Length > 20) { reply = reply.Substring(0, 20) + ".."; } StringBuilder builder6 = new StringBuilder(); builder6.Append("<tr class='tdbg' onmouseout=\"this.className='tdbg'\" onmouseover=\"this.className='tdbgmouseover'\">"); builder6.Append("<td align='center'> </td>"); builder6.Append(" <td colspan='2' align='left'>[管理员] "); literal5.BeginTag = builder6.ToString(); literal5.Text = dataItem.ReplyAdmin; literal5.EndTag = " 于 " + dataItem.ReplyDateTime.ToString("yyyy年MM月dd日 HH时mm分ss秒"); literal2.BeginTag = " 回复:<br/>"; literal2.Text = dataItem.Reply; StringBuilder builder7 = new StringBuilder(); builder7.Append("<td align='center'>"); builder7.Append("<table width='100%' border='0' cellpadding='0' cellspacing='0'><tr><td align='center' style='width:30px;'></td>"); builder7.Append("<td align='center' style='width:35px;'><a " + this.CheckCommentPermissions(nodeIds, this.m_NodeCommentManage, "href='CommentReplyModify.aspx?Action=Reply&" + str3 + "'") + " >修改</a></td>"); builder7.Append("<td align='center' style='width:35px;'><a " + this.CheckCommentPermissions(nodeIds, this.m_NodeCommentManage, "href='CommentManage.aspx?Action=DelReply&" + str3 + "' onclick=\"return confirm('确定要删除此评论的管理员回复吗?');\" ") + " >删除</a></td>"); builder7.Append("<td align='center' style='width:50px;'></td></tr></table></td>"); builder7.Append("</tr>"); literal2.EndTag = builder7.ToString(); literal2.Visible = true; literal5.Visible = true; } } }
/// <summary> /// 评论顶操作 /// </summary> /// <param name="rData"></param> /// <returns></returns> public Stream DoAgree(RequestData rData) { // 解析得到评论ID var data = rData.details.Split('|'); string cmt_uid = data[0].ToSafety(); // 得到上下文 WebOperationContext woc = WebOperationContext.Current; //设置响应格式,消除了返回为string的有反斜杠情况 woc.OutgoingResponse.ContentType = "application/json; charset=utf-8"; string json = ""; if (cmt_uid == string.Empty) { json = Util.GetResultStr("“顶”失败:参数错误!"); return(new MemoryStream(Encoding.UTF8.GetBytes(json))); } // int result = DataAccess_News.FavorLog_Insert(cmt_uid); if (result > 0) { int relt = DataAccess_News.Comments_AddAccept(cmt_uid); // 评论记录中评论“支持”字段值增1 if (relt > 0) { json = " { \"success\" : true, \"errors\" : { \"text\" : \"“顶”成功!\", \"num\" : 1 } }"; CommentInfo comment = DataAccess_News.Comments_Selectbycmt_uid(cmt_uid); if ((comment != null) && (comment.cmt_accept > 10)) // 顶超过10设为热评 { // 判断是否已设为热评 List <CommentInfo> comments = DataAccess_News.RecommendComments_Selectbycmt_uid(cmt_uid); if ((comments == null) || (comments.Count < 1)) { // 设为热评 RecommendCommentInfo rcomment = new RecommendCommentInfo(); rcomment.cmt_accept = comment.cmt_accept; rcomment.cmt_checkRemark = comment.cmt_checkRemark; rcomment.cmt_checkTime = comment.cmt_checkTime; rcomment.cmt_checkUser = comment.cmt_checkUser; rcomment.cmt_content = comment.cmt_content; rcomment.cmt_createTime = comment.cmt_createTime; rcomment.cmt_createUser = comment.cmt_createUser; rcomment.cmt_createUserID = comment.cmt_createUserID; rcomment.cmt_id = comment.cmt_id; rcomment.cmt_ip = comment.cmt_ip; rcomment.cmt_ipArea = comment.cmt_ipArea; rcomment.cmt_parentIds = comment.cmt_parentIds; rcomment.cmt_sourceId = comment.cmt_sourceId; rcomment.cmt_sourceType = comment.cmt_sourceType; rcomment.cmt_status = comment.cmt_status; rcomment.cmt_title = comment.cmt_title; rcomment.cmt_uid = comment.cmt_uid; rcomment.rcmt_createUser = comment.cmt_createUser; rcomment.rcmt_createTime = DateTime.Now; DataAccess_News.RecommendComments_Insert(rcomment); } } return(new MemoryStream(Encoding.UTF8.GetBytes(json))); } json = Util.GetResultStr("“顶”失败,请稍候再试"); return(new MemoryStream(Encoding.UTF8.GetBytes(json))); } json = " { \"success\" : true, \"errors\" : { \"text\" : \"“顶”已成功!\", \"num\" : 0 } }"; return(new MemoryStream(Encoding.UTF8.GetBytes(json))); }
private void AddComment(XmlDocument xmlDoc) { CommentInfo commentInfo = new CommentInfo(); commentInfo.CommentTitle = GetNodeInnerText(xmlDoc, "//commenttitle"); if (!HttpContext.Current.User.Identity.IsAuthenticated) { commentInfo.UserName = "******"; } else { commentInfo.UserName = PEContext.Current.User.UserName; } commentInfo.Content = GetNodeInnerText(xmlDoc, "//content"); commentInfo.Email = GetNodeInnerText(xmlDoc, "//email"); commentInfo.Face = GetNodeInnerText(xmlDoc, "//face"); commentInfo.GeneralId = DataConverter.CLng(GetNodeInnerText(xmlDoc, "//gid")); commentInfo.NodeId = DataConverter.CLng(GetNodeInnerText(xmlDoc, "//nid")); commentInfo.TopicId = DataConverter.CLng(GetNodeInnerText(xmlDoc, "//tid")); commentInfo.IsPrivate = DataConverter.CBoolean(GetNodeInnerText(xmlDoc, "//private", "true")); commentInfo.Position = DataConverter.CLng(GetNodeInnerText(xmlDoc, "//position")); commentInfo.Score = DataConverter.CLng(GetNodeInnerText(xmlDoc, "//score", "3")); commentInfo.IP = this.GetClientIP(); commentInfo.UpdateDateTime = DateTime.Now.ToLocalTime(); commentInfo.ReplyUserName = GetNodeInnerText(xmlDoc, "//username", "游客"); int num = string.Compare(commentInfo.UserName, "游客", StringComparison.OrdinalIgnoreCase); string str = ""; NodeInfo cacheNodeById = Nodes.GetCacheNodeById(ContentManage.GetCommonModelInfoById(commentInfo.GeneralId).NodeId); commentInfo.Status = cacheNodeById.Settings.CommentNeedCheck; UserPurviewInfo userPurview = null; if (num != 0) { userPurview = PEContext.Current.User.UserInfo.UserPurview; if (userPurview.CommentNeedCheck) { commentInfo.Status = true; } else { commentInfo.Status = !cacheNodeById.Settings.CommentNeedCheck; } } else if (!cacheNodeById.Settings.EnableTouristsComment) { str = "noTourists"; } else { commentInfo.Status = !cacheNodeById.Settings.CommentNeedCheck; } bool enableComment = false; bool commentNeedCheck = false; if (userPurview != null) { enableComment = userPurview.EnableComment; commentNeedCheck = userPurview.CommentNeedCheck; } if (string.IsNullOrEmpty(str)) { if (cacheNodeById.Settings.EnableComment || enableComment) { if (Comment.Add(commentInfo)) { if (commentInfo.Status || commentNeedCheck) { str = "ok"; } else { str = "check"; } } else { str = "err"; } } else { str = "nopurview"; } } this.XmlResponseWriter.WriteElementString("status", str); }
public async Task <IActionResult> List(CommentInfo commentInfo) { var data = await commentService.List(commentInfo); return(JsonDate(data)); }
public void CommentCreate_WithWhiteListTerm_AddsCorrectNotes() { var siteName = "h2g2"; var siteId = 1; var uid = "uid"; var text = " Bomb "; var siteList = mocks.DynamicMock<ISiteList>(); var readerCreator = mocks.DynamicMock<IDnaDataReaderCreator>(); var site = mocks.DynamicMock<ISite>(); var reader = mocks.DynamicMock<IDnaDataReader>(); var cacheManager = mocks.DynamicMock<ICacheManager>(); var callingUser = mocks.DynamicMock<ICallingUser>(); var commentForum = new CommentForum { Id = uid, SiteName = siteName }; var commentInfo = new CommentInfo { text = text }; callingUser.Stub(x => x.IsSecureRequest).Return(true); callingUser.Stub(x => x.UserID).Return(1); callingUser.Stub(x => x.IsUserA(UserTypes.SuperUser)).Return(false).Constraints(Is.Anything()); cacheManager.Stub(x => x.GetData("")).Return(null).Constraints(Is.Anything()); site.Stub(x => x.SiteID).Return(siteId); site.Stub(x => x.IsEmergencyClosed).Return(false); site.Stub(x => x.IsSiteScheduledClosed(DateTime.Now)).Return(false); site.Stub(x => x.ModClassID).Return(3); reader.Stub(x => x.HasRows).Return(true); reader.Stub(x => x.Read()).Return(true).Repeat.Once(); readerCreator.Stub(x => x.CreateDnaDataReader("commentcreate")).Return(reader); siteList.Stub(x => x.GetSite(siteName)).Return(site); mocks.ReplayAll(); var comments = new Comments(null, readerCreator, cacheManager, siteList); comments.CallingUser = callingUser; comments.CreateComment(commentForum, commentInfo); readerCreator.AssertWasCalled(x => x.CreateDnaDataReader("commentcreate")); reader.AssertWasCalled(x => x.AddParameter("modnotes", "Filtered terms: bomb")); }
/// <summary> /// 插入评论 /// </summary> public async Task <CommentView> InsertAsync(CommentEditModel model, Guid loginUserId) { if (model == null) { throw new ArgumentNullException(nameof(model)); } string html = this.htmlService.ClearHtml(model.Content); if (string.IsNullOrWhiteSpace(html)) { throw new Exception("评论内容不能为空"); } DateTime now = DateTime.Now; using (var work = this.dbFactory.StartWork()) { Person person = await work.Person.SingleByIdAsync(loginUserId); if (person == null || person.IsDelete || person.IsMute) { throw new Exception("该用户没有发贴权限"); } Post post = await work.Post.SingleByIdAsync(model.PostId); if (post == null || post.PostStatus != Enums.PostStatus.Publish) { throw new Exception("该帖子不存在,或禁止评论"); } using (var trans = work.BeginTransaction()) { try { // 插入评论 Comment comment = new Comment { Id = GuidHelper.CreateSequential(), CreateTime = now, HtmlContent = html, IsDelete = false, LikeNum = 0, ModifyTime = null, ParentId = model.ParentId, PersonId = loginUserId, PostId = model.PostId, TextContent = this.htmlService.HtmlToText(html) }; await work.Comment.InsertAsync(comment, trans); // 插入活动 CommentInfo info = new CommentInfo { CommentId = comment.Id, PostId = post.Id, PostTitle = post.Title }; Activity activity = new Activity { Id = GuidHelper.CreateSequential(), ActivityType = Enums.ActivityType.Comment, DoTime = now, PersonId = loginUserId, PostId = post.Id }; await work.Activity.InsertAsync(activity, trans); // 递增用户回复数 await work.Connection.IncreaseAsync(nameof(PersonData), nameof(PersonData.AnswerNum), nameof(PersonData.PersonId), person.Id, trans); // 递增帖子回复数 await work.Connection.IncreaseAsync(nameof(Post), nameof(Post.CommentNum), nameof(Post.Id), post.Id, trans); trans.Commit(); return(await work.CommentView.SingleByIdAsync(comment.Id)); } catch { trans.Rollback(); throw; } } } }
public void CommentCreate_NotSignedInUserWithDisplayName_ReturnCorrectObject() { var siteName = "h2g2"; var uid = "uid"; var text = "test comment"; var displayName = "notsignedin"; var siteList = mocks.DynamicMock<ISiteList>(); var readerCreator = mocks.DynamicMock<IDnaDataReaderCreator>(); var site = mocks.DynamicMock<ISite>(); var reader = mocks.DynamicMock<IDnaDataReader>(); var cacheManager = mocks.DynamicMock<ICacheManager>(); var callingUser = mocks.DynamicMock<ICallingUser>(); var commentForum = new CommentForum { Id = uid, SiteName = siteName, allowNotSignedInCommenting=true, NotSignedInUserId=1 }; var commentInfo = new CommentInfo { text = text }; commentInfo.User = new User { DisplayName = displayName }; callingUser.Stub(x => x.IsSecureRequest).Return(true); callingUser.Stub(x => x.UserID).Return(1); callingUser.Stub(x => x.IsUserA(UserTypes.SuperUser)).Return(false).Constraints(Is.Anything()); cacheManager.Stub(x => x.GetData("")).Return(null).Constraints(Is.Anything()); site.Stub(x => x.IsEmergencyClosed).Return(false); site.Stub(x => x.IsSiteScheduledClosed(DateTime.Now)).Return(false); reader.Stub(x => x.HasRows).Return(true); reader.Stub(x => x.Read()).Return(true).Repeat.Once(); reader.Stub(x => x.GetInt32NullAsZero("postid")).Return(1); readerCreator.Stub(x => x.CreateDnaDataReader("commentcreate")).Return(reader); site.Stub(x => x.SiteID).Return(1); siteList.Stub(x => x.GetSiteOptionValueString(1, "General", "ComplaintUrl")).Return("http://www.bbc.co.uk/dna/[sitename]/comments/UserComplaintPage?PostID=[postid]&s_start=1"); siteList.Stub(x => x.GetSite(siteName)).Return(site); mocks.ReplayAll(); var comments = new Comments(null, readerCreator, cacheManager, siteList); comments.CallingUser = callingUser; var comment = comments.CreateComment(commentForum, commentInfo); Assert.IsNotNull(comment); Assert.AreEqual(displayName, comment.User.DisplayName); readerCreator.AssertWasCalled(x => x.CreateDnaDataReader("commentcreate")); reader.AssertWasCalled(x => x.AddParameter("nickname", displayName)); }
/// <summary> /// insert comment list /// </summary> /// <param name="ci"></param> /// <returns></returns> public bool InsertCommentList(CommentInfo ci) { return(dal.InsertCommentList(ci) > 0); }
public void CommentCreate_BannedUser_ReturnCorrectError() { var siteName = "h2g2"; var uid = "uid"; var siteList = mocks.DynamicMock<ISiteList>(); var readerCreator = mocks.DynamicMock<IDnaDataReaderCreator>(); var site = mocks.DynamicMock<ISite>(); var reader = mocks.DynamicMock<IDnaDataReader>(); var cacheManager = mocks.DynamicMock<ICacheManager>(); var callingUser = mocks.DynamicMock<ICallingUser>(); var commentForum = new CommentForum { Id = uid, SiteName = siteName }; var commentInfo = new CommentInfo { text = "test" }; callingUser.Stub(x => x.IsSecureRequest).Return(true); callingUser.Stub(x => x.UserID).Return(1); callingUser.Stub(x => x.IsUserA(UserTypes.BannedUser)).Return(true); cacheManager.Stub(x => x.GetData("")).Return(null).Constraints(Is.Anything()); site.Stub(x => x.IsEmergencyClosed).Return(false); site.Stub(x => x.IsSiteScheduledClosed(DateTime.Now)).Return(false); reader.Stub(x => x.HasRows).Return(true); reader.Stub(x => x.Read()).Return(true).Repeat.Once(); readerCreator.Stub(x => x.CreateDnaDataReader("commentcreate")).Return(reader); siteList.Stub(x => x.GetSite(siteName)).Return(site); mocks.ReplayAll(); var comments = new Comments(null, readerCreator, cacheManager, siteList); comments.CallingUser = callingUser; try { comments.CreateComment(commentForum, commentInfo); throw new Exception("No exception thrown"); } catch (ApiException ex) { Assert.AreEqual(ErrorType.UserIsBanned, ex.type); } readerCreator.AssertWasNotCalled(x => x.CreateDnaDataReader("commentcreate")); }
private void ExtractItems() { bool extractText = false; bool extractImgs = false; bool extractVideo = false; bool extractSharedItem = false; switch (momentInfo.momentType) { case MomentType.TextOnly: extractText = true; break; case MomentType.WithImg: extractText = true; extractImgs = true; break; case MomentType.WithShortVideo: extractText = true; extractVideo = true; break; case MomentType.Shared: extractText = true; extractSharedItem = true; break; } for (int i = 0; i < _object.Count; i++) { Type currentNodeType = _object[i].GetType(); if (currentNodeType == typeof(NSDictionary)) { NSDictionary currentItem = (NSDictionary)_object[i]; if (currentItem.ContainsKey("bDeleted"))//评论或点赞 { DateTime time = TimeUtil.TimeStamp2Datetime(currentItem["createTime"].ToString()); string type = currentItem["type"].ToString(); if (type.ToString() == "1")//点赞 { IExtractor <LikedInfo> likeExtractor = new LikeExtractor(_object, i, time); likes.Add(likeExtractor.Extract()); } else if (type.ToString() == "2")//评论 { IExtractor <CommentInfo> commentExtractor = new CommentExtractor(_object, i, time); CommentInfo comment = commentExtractor.Extract(); if (comment != null) { comments.Add(comment); } } } else if (extractText && currentItem.ContainsValue("WCAppInfo"))//文字 { IExtractor <string> textExtractor = new TextExtractor(_object, i, momentInfo.posterInfo); momentInfo.momentText = textExtractor.Extract(); } else if (extractImgs && currentItem.ContainsKey("encIdx"))//附图 { IExtractor <Uri> imgExtractor = new ImgExtractor(_object, i); Uri imgUrl = imgExtractor.Extract(); if (imgUrl != null) { imgs.Add(imgUrl); } } else if (extractVideo && currentItem.ContainsValue("WCUrl"))//视频 { IExtractor <Uri> shortVideoExtractor = new ShortVideoExtractor(_object, i); momentInfo.shortVideoUrl = shortVideoExtractor.Extract(); } //else if (extractSharedItem)//分享 //{ // IExtractor<SharedItem> sharedExtractor = new SharedExtractor(_object, i); // momentInfo.sharedItem = sharedExtractor.Extract(); //} } else if (extractSharedItem && currentNodeType == typeof(NSString)) { NSString currentItem = (NSString)_object[i]; if (currentItem.Content == "WeChat Sight")//微视分享 { IExtractor <SharedItem> weishiSharedExtractor = new WeishiSharedExtractor(_object, i); momentInfo.sharedItem = weishiSharedExtractor.Extract(); } } } }
public void AddComment(CommentInfo commentInfo) { commentRepository.Add(ArticleMapper.Convert(commentInfo)); }
private Comment CommentInfoToComment(CommentInfo commentInfo) { return(Mapper.Map <CommentInfo, Comment>(commentInfo)); }
protected void RptCommentContent_ItemDataBound(object sender, RepeaterItemEventArgs e) { if ((e.Item.ItemType == ListItemType.Item) || (e.Item.ItemType == ListItemType.AlternatingItem)) { Label label = e.Item.FindControl("LblNum") as Label; Image image = e.Item.FindControl("ImgUserFace") as Image; Label label2 = e.Item.FindControl("LblCommentContent") as Label; ExtendedLabel label3 = e.Item.FindControl("LblUserExp") as ExtendedLabel; Label label4 = e.Item.FindControl("LblUserRegTime") as Label; ExtendedLabel label5 = e.Item.FindControl("LblReply") as ExtendedLabel; CommentInfo dataItem = (CommentInfo)e.Item.DataItem; Label label6 = e.Item.FindControl("LblSustain") as Label; Label label7 = e.Item.FindControl("LblOppose") as Label; Label label8 = e.Item.FindControl("LblNeutralismNetizen") as Label; Label label9 = e.Item.FindControl("LblPKZone") as Label; Label label10 = e.Item.FindControl("LblPKAgree") as Label; Label label11 = e.Item.FindControl("LblPKOppose") as Label; Label label12 = e.Item.FindControl("LblExcerpt") as Label; Label label13 = e.Item.FindControl("LblRestore") as Label; Label label14 = e.Item.FindControl("LblDelete") as Label; string str = "CommentID=" + dataItem.CommentId.ToString() + "&GeneralId=" + this.m_GeneralId.ToString() + "&Title=" + base.Server.UrlEncode(BaseUserControl.RequestString("Title")); this.m_floorNumber++; label6.Text = CommentPKZone.GetPKCount(dataItem.CommentId, 1).ToString(); label7.Text = CommentPKZone.GetPKCount(dataItem.CommentId, -1).ToString(); label8.Text = CommentPKZone.GetPKCount(dataItem.CommentId, 0).ToString(); label.Text = "第<span style='color:Red'>" + this.m_floorNumber.ToString() + "</span>楼"; if (!string.IsNullOrEmpty(dataItem.UserFace)) { image.Width = Unit.Pixel(80); image.ImageUrl = DataSecurity.UrlEncode(dataItem.UserFace); } else { image.Width = Unit.Pixel(80); image.Height = Unit.Pixel(90); image.ImageUrl = this.Path + "/Images/Comment/01.gif"; } Label label15 = e.Item.FindControl("LblContent") as Label; label15.Text = dataItem.Content; label2.Text = "信息:" + dataItem.PassedItems; if (SiteConfig.SiteOption.EnablePointMoneyExp) { label3.Text = "积分:" + dataItem.UserExp; label3.EndTag = "<br/>"; } label4.Text = "时间:" + dataItem.UserRegTime.ToString("yyyy-MM-dd"); if (!dataItem.ReplyIsPrivate && !string.IsNullOrEmpty(dataItem.Reply)) { StringBuilder builder = new StringBuilder(); builder.Append("<table class='Reply' cellspacing='0' cellpadding='6' width='95%' border='0'>"); builder.Append("<tr>"); builder.Append(" <td class='ReplyAdminTd' >"); builder.Append(" <span class='ReplyAdmin'>管理员回复</span>:<br/>"); StringBuilder builder2 = new StringBuilder(); builder2.Append("<br/>"); builder2.Append("<p align='right'>" + dataItem.ReplyDateTime.ToString() + "</span>"); builder2.Append("</td>"); builder2.Append("</tr>"); builder2.Append("</table>"); label5.BeginTag = builder.ToString(); label5.Text = dataItem.Reply; label5.EndTag = builder2.ToString(); } label9.Text = " <a href='../Contents/CommentPKZoneManage.aspx?" + str.ToString() + "'> PK Zone</a>"; label10.Text = " <a href='../Contents/CommentPKZoneManage.aspx?" + str.ToString() + "' onkeydown=\"return Agree(event);\" onmouseover=\"PopupArea(event, 'Agree" + dataItem.CommentId.ToString() + "')\" onmouseout = \"jsAreaMouseOut(event)\"> 支持</a>"; label11.Text = " <a href='../Contents/CommentPKZoneManage.aspx?" + str.ToString() + "' onkeydown=\"return Oppose(event);\" onmouseover=\"PopupArea(event, 'Oppose" + dataItem.CommentId.ToString() + "')\" onmouseout = \"jsAreaMouseOut(event)\"> 反对</a>"; label12.Text = " <a href='../Contents/CommentExcerpt.aspx?" + str.ToString() + "'> 信息引用</a>"; label13.Text = " <a href='../Contents/CommentRestore.aspx?" + str.ToString() + "'> 回复</a>"; if (!string.IsNullOrEmpty(PEContext.Current.Admin.UserName)) { label14.Text = "<a href='" + this.ViewFile + "?Action=Delete&" + str + "' onclick=\"return confirm('确定要删除此评论吗?');\">删除</a>"; Label label16 = e.Item.FindControl("LblAuditing") as Label; if (dataItem.Status) { label16.Text = "<span style='color:green'><a href='" + BaseUserControl.AppendSecurityCode(this.ViewFile + "?Action=UnAudited&" + str) + "'>取消审核</a></span>"; } else { label16.Text = "<span style='color:blue'><a href='" + BaseUserControl.AppendSecurityCode(this.ViewFile + "?Action=Audited&" + str) + "'>通过审核</a></span>"; } Label label17 = e.Item.FindControl("LblIsElite") as Label; if (dataItem.IsElite) { label17.Text = "<span style='color:green'><a href='" + BaseUserControl.AppendSecurityCode(this.ViewFile + "?Action=UnPremier&" + str) + "'>取消精华</a></span>"; } else { label17.Text = "<span style='color:blue'><a href='" + BaseUserControl.AppendSecurityCode(this.ViewFile + "?Action=Premier&" + str) + "'>设置为精华</a></span>"; } } } }
public CommentInfo GetPost(CommentInfo commentInfo) { Post post = forumUOW.PostRepositary.Get(commentInfo.PostId); return(Mapper.Map <Post, CommentInfo>(post)); }