private static GetPost ( string filename ) : Post, | ||
filename | string | |
Résultat | Post, |
public async Task <IHttpActionResult> Get(string token, string postId) { if (string.IsNullOrEmpty(token) || postId == null) { return(BadRequest("Token or post id missing.")); } string userId = await Utils.VerifyAndDecrypt(token); if (string.IsNullOrEmpty(userId)) { return(BadRequest("Token not valid.")); } try { var post = _postMng.GetPost(postId); return(Ok(post)); } catch (IncorrectDetailsException e) { return(BadRequest(e.Message)); } catch (Exception e) { return(Content(HttpStatusCode.InternalServerError, e.Message)); } }
/// <summary> /// 加载feed /// </summary> protected void LoadFeed() { int categoryId = RequestHelper.QueryInt("categoryid", -1); int postId = RequestHelper.QueryInt("postid", -1); string action = RequestHelper.QueryString("action", true); // Response.Clear(); Response.ContentType = "text/xml"; if (SettingManager.GetSetting().RssStatus == 1) { switch (action) { case "comment": List <CommentInfo> commentList = CommentManager.GetCommentList(SettingManager.GetSetting().RssRowCount, 1, -1, postId, 0, 1, -1, null); PostInfo commentPost = PostManager.GetPost(postId); Response.Write("<rss version=\"2.0\" xmlns:dc=\"http://purl.org/dc/elements/1.1/\" xmlns:trackback=\"http://madskills.com/public/xml/rss/module/trackback/\" xmlns:wfw=\"http://wellformedweb.org/CommentAPI/\" xmlns:slash=\"http://purl.org/rss/1.0/modules/slash/\">\r\n"); Response.Write(" <channel>\r\n"); Response.Write(" <title><![CDATA[" + (commentPost == null ? SettingManager.GetSetting().SiteName : commentPost.Title) + "的评论]]></title>\r\n"); Response.Write(" <link><![CDATA[" + (commentPost == null ? ConfigHelper.SiteUrl : commentPost.Url) + "]]></link>\r\n"); Response.Write(" <description><![CDATA[" + SettingManager.GetSetting().SiteDescription + "]]></description>\r\n"); Response.Write(" <pubDate>" + DateTime.Now.ToString("r") + "</pubDate>\r\n"); Response.Write(" <generator>Loachs</generator>\r\n"); Response.Write(" <language>zh-cn</language>\r\n"); foreach (CommentInfo comment in commentList) { Response.Write(" <item>\r\n"); Response.Write(" <title><![CDATA[" + comment.Name + "对" + comment.Post.Title + "的评论]]></title>\r\n"); Response.Write(" <link><![CDATA[" + comment.Url + "]]></link>\r\n"); Response.Write(" <guid><![CDATA[" + comment.Url + "]]></guid>\r\n"); Response.Write(" <author><![CDATA[" + comment.Name + "]]></author>\r\n"); Response.Write(string.Format(" <description><![CDATA[{0}]]></description>\r\n", comment.Content)); Response.Write(" <pubDate>" + comment.CreateDate.ToString("r") + "</pubDate>\r\n"); Response.Write(" </item>\r\n"); } Response.Write(" </channel>\r\n"); Response.Write("</rss>\r\n"); break; default: List <PostInfo> list = PostManager.GetPostList(SettingManager.GetSetting().RssRowCount, categoryId, -1, -1, 1, -1, 0); templatePath = Server.MapPath(ConfigHelper.SitePath + "common/config/"); th = new TemplateHelper(templatePath); LoadDefault(); th.Put(TagFields.FEED_POSTS, list); Display("feed.config"); break; } } else { Response.Write("<rss>error</rss>\r\n"); } // Response.End(); }
/// <summary> /// 文章连接 /// </summary> /// <param name="postId"></param> /// <returns></returns> protected string GetPostLink(int postId) { PostInfo post = PostManager.GetPost(postId); if (post != null) { return(string.Format(" 评: {0}", StringHelper.CutString(post.Title, 20, "..."))); } return(string.Empty); }
public PostData GetPost(int id) { PostData pd = new PostData() { id = id }; PostManager pm = new PostManager(); PostData p = pm.GetPost(pd); return(p); }
public TransactionObject ToggleFavPost(int ID, int userID) { TransactionObject response = new TransactionObject(); try { Post favPost = postManager.GetPost(ID); User currentUser = userManager.GetUser(userID); FavouriteFeeds ff = currentUser.FavouriteFeeds; if (ff == null) { ff = new FavouriteFeeds(); ff.User = currentUser; currentUser.FavouriteFeeds = ff; favFeedManager.AddFavouriteFeed(ff); } if (CheckExistence(ff.FavouritePosts, favPost)) { ff.FavouritePosts.Remove(favPost); favPost.FavouriteFeeds.Remove(ff); favPost.FavouritedCount--; } else { ff.FavouritePosts.Add(favPost); favPost.FavouriteFeeds.Add(ff); favPost.FavouritedCount++; } uow.Save(); response.IsSuccess = true; } catch (Exception ex) { response.IsSuccess = false; response.Explanation = base.GetExceptionMessage(ex); } return(response); }
public ActionResult ViewPost(int postID) { if (Session["CurrentUserName"] == null) { return(RedirectToAction("Login", "Pastebook")); } POST post = new POST(); if (postID != 0) { post = postManager.GetPost(postID); } return(View(post)); }
public IActionResult Details(int?id) { if (id == null) { return(NotFound()); } var post = _postManager.GetPost((int)id); if (post == null) { return(NotFound()); } var detailsViewModel = new DetailsViewModel { Id = post.Id, Title = post.Title, ReleaseDate = post.ReleaseDate, Category = post.Category, HtmlDesc = post.HtmlDesc }; return(View(detailsViewModel)); }
public async override void Execute(object parameter) { try { var collection = (WebViewCollection)parameter; var postId = ParsePostId(collection.PostId); var postManager = new PostManager(); var post = await postManager.GetPost(postId); collection.WebView.InvokeScriptAsync("AddPostToThread", new[] { postId.ToString(), post.PostHtml }); } catch (Exception ex) { throw new Exception("Failed to get post", ex); } }
public async override void Execute(object parameter) { try { var collection = (WebViewCollection)parameter; var postId = ParsePostId(collection.PostId); var postManager = new PostManager(); var post = await postManager.GetPost(postId); collection.WebView.InvokeScriptAsync("AddPostToThread", new[] { postId.ToString(), post.PostHtml }); } catch (Exception ex) { throw new Exception("Failed to get post", ex); } }
protected void Delete() { PostInfo post = PostManager.GetPost(postId); if (post == null) { return; } if (PageUtils.CurrentUser.Type != (int)UserType.Administrator && PageUtils.CurrentUser.UserId != post.UserId) { Response.Redirect("postlist.aspx?result=444"); } PostManager.DeletePost(postId); Response.Redirect("postlist.aspx?result=3"); }
/// <summary> /// 绑定实体 /// </summary> protected void BindPost() { PostInfo p = PostManager.GetPost(postId); if (p != null) { txtTitle.Text = StringHelper.HtmlDecode(p.Title); txtSummary.Text = p.Summary; txtContents.Text = p.Content; chkStatus.Checked = p.Status == 1 ? true : false; ddlCategory.SelectedValue = p.CategoryId.ToString(); chkCommentStatus.Checked = p.CommentStatus == 1 ? true : false; txtCustomUrl.Text = StringHelper.HtmlDecode(p.Slug); chkTopStatus.Checked = p.TopStatus == 1 ? true : false; chkRecommend.Checked = p.Recommend == 1 ? true : false; chkHideStatus.Checked = p.HideStatus == 1 ? true : false; ddlUrlType.SelectedValue = p.UrlFormat.ToString(); ddlTemplate.SelectedValue = p.Template; //绑定标签,需改进 string tag = p.Tag; tag = tag.Replace("{", ""); string[] taglist = tag.Split('}'); foreach (string tagId in taglist) { TagInfo taginfo = TagManager.GetTag(StringHelper.StrToInt(tagId, 0)); // string tagName = Tags.GetTagName(Convert.ToInt32(tagID)); if (taginfo != null) { txtTags.Text += taginfo.Name + ","; } } txtTags.Text = txtTags.Text.TrimEnd(','); if (p.UserId != PageUtils.CurrentUser.UserId && PageUtils.CurrentUser.Type != (int)UserType.Administrator) { Response.Redirect("postlist.aspx?result=444"); } } }
/// <summary> /// metaWeblog.getPost /// </summary> /// <param name="postID">post guid in string format</param> /// <param name="userName">login username</param> /// <param name="password">login password</param> /// <returns>struct with post details</returns> internal MWAPost GetPost(string postID, string userName, string password) { ValidateRequest(userName, password); MWAPost sendPost = new MWAPost(); PostInfo post = PostManager.GetPost(StringHelper.StrToInt(postID, 0)); sendPost.postID = post.PostId.ToString(); sendPost.postDate = post.CreateDate; sendPost.title = StringHelper.HtmlDecode(post.Title); sendPost.description = post.Content; sendPost.link = post.Url; sendPost.slug = StringHelper.HtmlDecode(post.Slug); sendPost.excerpt = post.Summary; if (post.CommentStatus == 1) { sendPost.commentPolicy = "1"; } else { sendPost.commentPolicy = "0"; } sendPost.publish = post.Status == 1 ? true : false; List <string> cats = new List <string>(); cats.Add(StringHelper.HtmlDecode(post.Category.Name)); sendPost.categories = cats; List <string> tags = new List <string>(); for (int i = 0; i < post.Tags.Count; i++) { tags.Add(StringHelper.HtmlDecode(post.Tags[i].Name)); } sendPost.tags = tags; return(sendPost); }
protected void Page_Load(object sender, EventArgs e) { SetPageTitle("添加文章"); if (!IsPostBack) { LoadDefault(); if (Operate == OperateType.Update) { BindPost(); headerTitle = "修改文章"; btnEdit.Text = "修改"; SetPageTitle("修改文章"); switch (message) { case 1: ShowMessage(string.Format("添加成功! <a href=\"{0}\">{0}</a>", PostManager.GetPost(postId).Url)); break; case 2: ShowMessage(string.Format("修改成功! <a href=\"{0}\">{0}</a>", PostManager.GetPost(postId).Url)); break; } } //else if (Action == "delete") //{ // DeleteArticle(); //} //else //{ // ddlCategory.SelectedValue = CategoryID.ToString(); //} } }
private async void WebView_ScriptNotify(object sender, NotifyEventArgs e) { try { string stringJson = e.Value; var command = JsonConvert.DeserializeObject <ReplyView.ThreadCommand>(stringJson); switch (command.Command) { case "profile": Frame.Navigate(typeof(UserProfileView), command.Id); break; case "openPost": break; case "post_history": Frame.Navigate(typeof(UserPostHistoryPage), command.Id); break; case "rap_sheet": Frame.Navigate(typeof(RapSheetView), command.Id); break; case "quote": Frame.Navigate(typeof(ReplyView), command.Id); break; case "edit": Frame.Navigate(typeof(EditReplyPage), command.Id); break; case "scrollToPost": if (command.Id != null) { await ThreadFullView.InvokeScriptAsync("ScrollToDiv", new[] { string.Concat("#postId", command.Id) }); await ThreadSnapView.InvokeScriptAsync("ScrollToDiv", new[] { string.Concat("#postId", command.Id) }); } else if (!string.IsNullOrEmpty(_vm.ForumThreadEntity.ScrollToPostString)) { ThreadFullView.InvokeScriptAsync("ScrollToDiv", new[] { _vm.ForumThreadEntity.ScrollToPostString }); ThreadSnapView.InvokeScriptAsync("ScrollToDiv", new[] { _vm.ForumThreadEntity.ScrollToPostString }); } break; case "markAsLastRead": await _threadManager.MarkPostAsLastRead(_forumThread, Convert.ToInt32(command.Id)); int nextPost = Convert.ToInt32(command.Id) + 1; await ThreadFullView.InvokeScriptAsync("ScrollToDiv", new[] { string.Concat("#postId", nextPost.ToString()) }); await ThreadSnapView.InvokeScriptAsync("ScrollToDiv", new[] { string.Concat("#postId", nextPost.ToString()) }); NotifyStatusTile.CreateToastNotification("Post marked as last read! Now smash this computer and live your life!"); break; case "setFont": if (_localSettings.Values.ContainsKey("zoomSize")) { _zoomSize = Convert.ToInt32(_localSettings.Values["zoomSize"]); ThreadFullView.InvokeScriptAsync("ResizeWebviewFont", new[] { _zoomSize.ToString() }); ThreadSnapView.InvokeScriptAsync("ResizeWebviewFont", new[] { _zoomSize.ToString() }); } else { // _zoomSize = 20; } break; case "openThread": var query = Extensions.ParseQueryString(command.Id); if (query.ContainsKey("action") && query["action"].Equals("showPost")) { var postManager = new PostManager(); var html = await postManager.GetPost(Convert.ToInt32(query["postid"])); return; } var threadManager = new ThreadManager(); var threadEntity = new ForumThreadEntity(); var thread = await threadManager.GetThread(threadEntity, command.Id); if (thread == null) { var error = new MessageDialog("Specified post was not found in the live forums.") { DefaultCommandIndex = 1 }; await error.ShowAsync(); break; } string jsonObjectString = JsonConvert.SerializeObject(threadEntity); Frame.Navigate(typeof(ThreadPage), jsonObjectString); break; default: var msgDlg = new MessageDialog("Not working yet!") { DefaultCommandIndex = 1 }; await msgDlg.ShowAsync(); break; } } catch (Exception ex) { Debug.WriteLine(ex); } }
/// <summary> /// 添加或修改文章 /// </summary> /// <param name="blogID"></param> /// <param name="postID"></param> /// <param name="userName"></param> /// <param name="password"></param> /// <param name="sentPost"></param> /// <param name="publish"></param> /// <param name="operate"></param> /// <returns></returns> private int NewOrUpdatePost(string blogID, string postID, string userName, string password, MWAPost sentPost, bool publish, OperateType operate) { ValidateRequest(userName, password); PostInfo post = new PostInfo(); if (operate == OperateType.Update) { post = PostManager.GetPost(StringHelper.StrToInt(postID, 0)); } else { post.CommentCount = 0; post.ViewCount = 0; post.CreateDate = DateTime.Now; UserInfo user = UserManager.GetUser(userName); if (user != null) { post.UserId = user.UserId; } } post.Title = StringHelper.HtmlEncode(sentPost.title); post.Content = sentPost.description; post.Status = publish == true ? 1 : 0; post.Slug = PageUtils.FilterSlug(sentPost.slug, "post", true); post.Summary = sentPost.excerpt; post.UrlFormat = (int)PostUrlFormat.Default; post.Template = string.Empty; post.Recommend = 0; post.TopStatus = 0; post.HideStatus = 0; post.UpdateDate = DateTime.Now; if (sentPost.commentPolicy != "") { if (sentPost.commentPolicy == "1") { post.CommentStatus = 1; } else { post.CommentStatus = 0; } } foreach (string item in sentPost.categories) { CategoryInfo cat; if (LookupCategoryGuidByName(item, out cat)) { post.CategoryId = cat.CategoryId; } else { CategoryInfo newcat = new CategoryInfo(); newcat.Count = 0; newcat.CreateDate = DateTime.Now; newcat.Description = "由离线工具创建"; newcat.Displayorder = 1000; newcat.Name = StringHelper.HtmlEncode(item); newcat.Slug = PageUtils.FilterSlug(item, "cate", false); newcat.CategoryId = CategoryManager.InsertCategory(newcat); post.CategoryId = newcat.CategoryId; } } post.Tag = GetTagIdList(sentPost.tags); if (operate == OperateType.Update) { PostManager.UpdatePost(post); } else { post.PostId = PostManager.InsertPost(post); // SendEmail(p); } return(post.PostId); }
private async void WebView_ScriptNotify(object sender, NotifyEventArgs e) { if (_vm.ForumThreadEntity == null) { return; } if (e == null) { return; } string stringJson = e.Value; ThreadCommand command = null; try { command = JsonConvert.DeserializeObject <ThreadCommand>(stringJson); } catch (Exception ex) { AwfulDebugger.SendMessageDialogAsync("A thread javascript command failed", ex); } if (command == null) { return; } switch (command.Command) { case "quote": Frame.Navigate(typeof(ReplyPage), command.Id); break; case "edit": Frame.Navigate(typeof(EditPage), command.Id); break; case "setFont": SetFontSize(); break; case "scrollToPost": if (!string.IsNullOrEmpty(_vm.ForumThreadEntity.ScrollToPostString)) { try { await ThreadWebView.InvokeScriptAsync("ScrollToDiv", new[] { _vm.ForumThreadEntity.ScrollToPostString }); } catch (Exception ex) { AwfulDebugger.SendMessageDialogAsync("A thread javascript command failed", ex); } } break; case "markAsLastRead": await _threadManager.MarkPostAsLastRead(_forumThread, Convert.ToInt32(command.Id)); int nextPost = Convert.ToInt32(command.Id) + 1; try { await ThreadWebView.InvokeScriptAsync("ScrollToDiv", new[] { string.Concat("#postId", nextPost.ToString()) }); } catch (Exception ex) { AwfulDebugger.SendMessageDialogAsync("A thread javascript command failed", ex); return; } var message = new MessageDialog("Post marked as last read! Now go on and live your life!") { DefaultCommandIndex = 1 }; await message.ShowAsync(); break; case "openThread": var query = Extensions.ParseQueryString(command.Id); if (query.ContainsKey("action") && query["action"].Equals("showPost")) { var postManager = new PostManager(); try { var html = await postManager.GetPost(Convert.ToInt32(query["postid"])); } catch (Exception ex) { AwfulDebugger.SendMessageDialogAsync("A thread javascript command failed", ex); return; } return; } var threadManager = new ThreadManager(); var threadEntity = new ForumThreadEntity(); var thread = await threadManager.GetThread(threadEntity, command.Id); if (thread == null) { var error = new MessageDialog("Specified post was not found in the live forums.") { DefaultCommandIndex = 1 }; await error.ShowAsync(); break; } string jsonObjectString = JsonConvert.SerializeObject(threadEntity); Frame.Navigate(typeof(ThreadPage), jsonObjectString); break; default: var msgDlg = new MessageDialog("Not working yet!") { DefaultCommandIndex = 1 }; await msgDlg.ShowAsync(); break; } }
protected void btnEdit_Click(object sender, EventArgs e) { //老标签 string oldTag = string.Empty; PostInfo p = new PostInfo(); if (Operate == OperateType.Update) { p = PostManager.GetPost(postId); oldTag = p.Tag; } else { p.CommentCount = 0; p.ViewCount = 0; p.CreateDate = DateTime.Now; p.UserId = PageUtils.CurrentUserId; } p.CategoryId = StringHelper.StrToInt(ddlCategory.SelectedValue, 0); p.CommentStatus = chkCommentStatus.Checked ? 1 : 0; p.Content = txtContents.Text; p.Slug = PageUtils.FilterSlug(txtCustomUrl.Text, "post", true); p.Status = chkStatus.Checked ? 1 : 0; p.TopStatus = chkTopStatus.Checked ? 1 : 0; p.HideStatus = chkHideStatus.Checked ? 1 : 0; p.Summary = txtSummary.Text; p.Tag = GetTagIdList(txtTags.Text.Trim()); p.Title = StringHelper.HtmlEncode(txtTitle.Text); // p.TopStatus = chkTopStatus.Checked ? 1 : 0; p.UrlFormat = StringHelper.StrToInt(ddlUrlType.SelectedValue, 1); p.Template = ddlTemplate.SelectedValue; p.Recommend = chkRecommend.Checked ? 1 : 0; // p.Type = 0;// (int)PostType.Article; p.UpdateDate = DateTime.Now; if (chkSaveImage.Checked) { p.Content = SaveRemoteImage(p.Content); } if (Operate == OperateType.Update) { PostManager.UpdatePost(p); // TagManager.ResetTag(oldTag + p.Tag); Response.Redirect("postedit.aspx?operate=update&postid=" + postId + "&message=2"); } else { p.PostId = PostManager.InsertPost(p); SendEmail(p); // TagManager.ResetTag(p.Tag); Response.Redirect("postedit.aspx?operate=update&postid=" + p.PostId + "&message=1"); } }
public bool HandleRequest(Client client, HttpListenerContext context, params string[] args) { if (!UserManager.Connected(client)) { context.Send("not connected"); return(true); } User user = UserManager.GetUser(UserManager.GetUserID(client)); if (user == null) { context.Send("user not found"); return(true); } if (context.Request.HttpMethod == "GET") { if (args.Length == 0) { Post[] posts = PostManager.GetHomeFeedPosts(user); string output = JsonConvert.SerializeObject(posts.ToResponse()); context.Send(output); return(true); } int postId = 0; if (int.TryParse(args[0], out postId)) { Post post = PostManager.GetPost(postId); if (post == null) { return(true); } if (args.Length == 1) { context.Send(JsonConvert.SerializeObject(new Post[] { post }.ToResponse())); } else { switch (args[1]) { case "delete": if (post.UserId == user.Id) { PostManager.DeletePost(post); } break; } context.Redirect(context.Request.UrlReferrer.AbsoluteUri); } } } if (context.Request.HttpMethod == "POST") { if (args.Length == 0) { string data = string.Empty; using (StreamReader reader = new StreamReader(context.Request.InputStream, context.Request.ContentEncoding)) { data = reader.ReadToEnd(); } Dictionary <string, string> formData = WebHelper.ParsePostData(data); if (formData.ContainsKey("data") && !string.IsNullOrEmpty(formData["data"])) { PostManager.CreatePost(user, formData["data"]); } context.Redirect(context.Request.UrlReferrer.AbsoluteUri); return(true); } int postId = 0; if (int.TryParse(args[0], out postId)) { Post post = PostManager.GetPost(postId); string data = string.Empty; using (StreamReader reader = new StreamReader(context.Request.InputStream, context.Request.ContentEncoding)) { data = reader.ReadToEnd(); } Dictionary <string, string> formData = WebHelper.ParsePostData(data); if (formData.ContainsKey("data") && !string.IsNullOrEmpty(formData["data"])) { post.Data = formData["data"]; if (user.Id == post.UserId) { PostManager.UpdatePost(post); } } // context.Response.StatusCode = 204; // prevent page refresh by returning no content code context.Redirect(context.Request.UrlReferrer.AbsoluteUri); } } return(true); }
public ActionResult DeletePost(int id) { var posts = _postManager.GetPost(id); return(View(posts)); }
/// <summary> /// 加载文章 /// </summary> protected void LoadPost() { th.Put(TagFields.IS_POST, "1"); if (RequestHelper.IsPost && !RequestHelper.IsCrossSitePost) { AddComment(); } PostInfo post = null; int postId = -1; string name = RequestHelper.QueryString("name"); if (StringHelper.IsInt(name)) { post = PostManager.GetPost(StringHelper.StrToInt(name, 0)); } else { post = PostManager.GetPost(StringHelper.SqlEncode(name)); } if (post == null) { ResponseError("文章未找到", "囧!没有找到此文章!", 404); } if (post.Status == (int)PostStatus.Draft) { ResponseError("文章未发布", "囧!此文章未发布!"); } string cookie = "isviewpost" + post.PostId; int isview = StringHelper.StrToInt(PageUtils.GetCookie(cookie), 0); //未访问或按刷新统计 if (isview == 0 || SettingManager.GetSetting().SiteTotalType == 1) { PostManager.UpdatePostViewCount(post.PostId, 1); } //未访问 if (isview == 0 && SettingManager.GetSetting().SiteTotalType == 2) { PageUtils.SetCookie(cookie, "1", 1440); } th.Put(TagFields.POST, post); th.Put(TagFields.PAGE_TITLE, post.Title); string metaKeywords = string.Empty; foreach (TagInfo tag in post.Tags) { metaKeywords += tag.Name + ","; } if (metaKeywords.Length > 0) { metaKeywords = metaKeywords.TrimEnd(','); } th.Put(TagFields.META_KEYWORDS, metaKeywords); string metaDescription = post.Summary; if (string.IsNullOrEmpty(post.Summary)) { metaDescription = post.Content; } th.Put(TagFields.META_DESCRIPTION, StringHelper.CutString(StringHelper.RemoveHtml(metaDescription), 50).Replace("\n", "")); int recordCount = 0; List <CommentInfo> commentList = CommentManager.GetCommentList(SettingManager.GetSetting().PageSizeCommentCount, Pager.PageIndex, out recordCount, SettingManager.GetSetting().CommentOrder, -1, post.PostId, 0, -1, -1, null); th.Put(TagFields.COMMENTS, commentList); th.Put(TagFields.PAGER, Pager.CreateHtml(SettingManager.GetSetting().PageSizeCommentCount, recordCount, post.PageUrl + "#comments")); //同时判断评论数是否一致 if (recordCount != post.CommentCount) { post.CommentCount = recordCount; PostManager.UpdatePost(post); } th.Put(TagFields.LOACHS, new LoachsDataManager()); if (System.IO.File.Exists(Server.MapPath(string.Format("{0}/themes/{1}/template/{2}", ConfigHelper.SitePath, themeName, post.Template)))) { Display(post.Template); } else { Display("post.html"); } }
/// <summary> /// 添加评论 /// </summary> protected void AddComment() { int contentMaxLength = 1000; //内容最长长度 int postid = RequestHelper.FormInt("postid", 0); string author = StringHelper.CutString(RequestHelper.FormString("commentauthor"), 20); string email = StringHelper.CutString(RequestHelper.FormString("commentemail"), 50); string siteurl = StringHelper.CutString(RequestHelper.FormString("commentsiteurl"), 100); string content = RequestHelper.FormString("commentcontent"); int remeber = RequestHelper.FormInt("commentremember", 0); int emailnotify = RequestHelper.FormInt("commentemailnotify", 0); string verifycode = RequestHelper.FormString("commentverifycode"); int expires = 525600; //一年 if (remeber == 0) { expires = -1; } if (!PageUtils.IsLogin) { PageUtils.SetCookie(TagFields.COMMENT_AUTHOR, Server.UrlEncode(author), expires); PageUtils.SetCookie(TagFields.COMMENT_EMAIL, Server.UrlEncode(email), expires); PageUtils.SetCookie(TagFields.COMMENT_SITEURL, Server.UrlEncode(siteurl), expires); } // PageUtils.SetCookie("commentcontent", Server.UrlEncode(StringHelper.CutString(content, contentMaxLength, "...")), expires); //保留 //第一次发表评论,并失败时用到 th.Put(TagFields.COMMENT_AUTHOR, author); th.Put(TagFields.COMMENT_EMAIL, email); th.Put(TagFields.COMMENT_SITEURL, siteurl); th.Put(TagFields.COMMENT_CONTENT, content); if (SettingManager.GetSetting().EnableVerifyCode == 1 && (verifycode != PageUtils.VerifyCode || string.IsNullOrEmpty(verifycode))) { th.Put(TagFields.COMMENT_MESSAGE, "<div>验证码输入错误!</div>"); return; } if (!StringHelper.IsEmail(email)) { th.Put(TagFields.COMMENT_MESSAGE, "<div>邮箱格式错误!</div>"); return; } if (content.Length > contentMaxLength || content.Length == 0) { th.Put(TagFields.COMMENT_MESSAGE, "<div>评论不能为空且限制在" + contentMaxLength + "字以内!</div>"); return; } // PageUtils.SetCookie("commentcontent", string.Empty, -1); //清空 th.Put(TagFields.COMMENT_CONTENT, string.Empty); //清空 PostInfo post = PostManager.GetPost(postid); if (post == null) { Response.Redirect(ConfigHelper.SitePath); } CommentInfo c = new CommentInfo(); c.Content = StringHelper.TextToHtml(StringHelper.CutString(content, contentMaxLength, "...")); c.CreateDate = DateTime.Now; c.Email = StringHelper.HtmlEncode(email); c.EmailNotify = emailnotify; c.IpAddress = RequestHelper.IPAddress; c.ParentId = 0; c.PostId = postid; c.UserId = PageUtils.CurrentUserId; c.Name = author; if (!string.IsNullOrEmpty(siteurl) && siteurl.IndexOf("http://") == -1) { siteurl = "http://" + siteurl; } c.SiteUrl = StringHelper.HtmlEncode(siteurl); switch (SettingManager.GetSetting().CommentApproved) { case 1: c.Approved = (int)ApprovedStatus.Success; break; case 2: string[] blackwords = SettingManager.GetSetting().CommentSpamwords.Split(','); bool hasBlackword = false; foreach (string word in blackwords) { if (c.Content.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 = CommentManager.InsertComment(c); #region 发邮件 if (SettingManager.GetSetting().SendMailNotifyByComment == 1) //给订阅者发邮件 { //先不考虑审核的问题 List <CommentInfo> list = CommentManager.GetCommentList(int.MaxValue, 1, -1, postid, 0, -1, 1, string.Empty); List <string> emailList = new List <string>(); foreach (CommentInfo cmt in list) { if (!StringHelper.IsEmail(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 (SettingManager.GetSetting().SendMailAuthorByComment == 1) //给文章作者发邮件 { 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 = UserManager.GetUser(post.UserId); if (user != null && StringHelper.IsEmail(user.Email)) { EmailHelper.SendAsync(user.Email, subject, body); } } #endregion if (newID > 0) { if (post != null) { if (SettingManager.GetSetting().CommentOrder == 1) { Response.Redirect(post.Url + "#comment-" + newID); } else { int commentCount = CommentManager.GetCommentCount(postid, false); int pageCount = commentCount / SettingManager.GetSetting().PageSizeCommentCount; if (commentCount % SettingManager.GetSetting().PageSizeCommentCount > 0) { pageCount += 1; } string url = string.Format(post.PageUrl + "#comment-" + newID, pageCount); Response.Redirect(url); } } } }
public void ProcessRequest(HttpContext context) { HttpRequest request = context.Request; //http://localhost:32030/SL/AjaxCallHandler.ashx?action= action is one of the below conditions in switch //e.g.http://localhost:32030/SL/AjaxCallHandler.ashx?action=getcategories string action = request.Params["action"]; StreamReader sr = new StreamReader(request.InputStream); string jsonString = sr.ReadToEnd(); string responseJson = ""; IEnumerable <CategoryData> cd; switch (action.ToLower()) { case "getcategories": #region getcategories /* * post json * { * "PageSize":"10", * "PageIndex":"0" * } */ responseJson = JSONHelper.ToJsonString(_categoryManager.GetCategories(JSONHelper.ToObject <CategoryData>(jsonString))); break; #endregion case "getcategory": #region getcategory responseJson = JSONHelper.ToJsonString(_categoryManager.GetCategory(JSONHelper.ToObject <CategoryData>(jsonString))); #endregion break; case "addcategory": #region addcategory /* * post json * { * "categoryname":"xxxx", * "description":"aaaa" * } */ #endregion responseJson = JSONHelper.ToJsonString(_categoryManager.AddCategory(JSONHelper.ToObject <CategoryData>(jsonString))); break; case "updatecategory": #region updatecategory responseJson = JSONHelper.ToJsonString(_categoryManager.UpdateCategory(JSONHelper.ToObject <CategoryData>(jsonString))); #endregion break; case "deletecategory": #region deletecategory responseJson = JSONHelper.ToJsonString(_categoryManager.DeleteCategory((int)JSONHelper.ToObject <CategoryData>(jsonString).id)); #endregion break; case "getposts": #region getposts var postsTemp = _postManager.GetPosts(JSONHelper.ToObject <PostData>(jsonString)); cd = _categoryManager.GetCategories(new CategoryData()).DataList as IEnumerable <CategoryData>; IEnumerable <PostData> posts = postsTemp.DataList as IEnumerable <PostData>; foreach (PostData p in posts) { foreach (CategoryData c in cd) { if (p.categoryid == c.id) { p.categoryname = c.categoryname; } } } responseJson = JSONHelper.ToJsonString(postsTemp); #endregion break; case "getpost": #region getpost var post = _postManager.GetPost(JSONHelper.ToObject <PostData>(jsonString)); cd = _categoryManager.GetCategories(new CategoryData()).DataList as IEnumerable <CategoryData>; foreach (CategoryData c in cd) { if (c.id == post.categoryid) { post.categoryname = c.categoryname; } } responseJson = JSONHelper.ToJsonString(post); #endregion break; case "deletepost": #region deletepost responseJson = JSONHelper.ToJsonString(_postManager.DeletePost((int)JSONHelper.ToObject <PostData>(jsonString).id)); #endregion break; case "updatepost": #region updatepost responseJson = JSONHelper.ToJsonString(_postManager.UpdatePost(JSONHelper.ToObject <PostData>(jsonString))); #endregion break; case "addpost": #region addpost responseJson = JSONHelper.ToJsonString(_postManager.AddPost(JSONHelper.ToObject <PostData>(jsonString))); #endregion break; case "getpages": #region getpages responseJson = JSONHelper.ToJsonString(_pageManager.GetPages(JSONHelper.ToObject <PageData>(jsonString))); #endregion break; case "getpage": #region getpage responseJson = JSONHelper.ToJsonString(_pageManager.GetPage(JSONHelper.ToObject <PageData>(jsonString))); #endregion break; case "deletepage": #region deletepage responseJson = JSONHelper.ToJsonString(_pageManager.DeletePage((int)JSONHelper.ToObject <PageData>(jsonString).id)); #endregion break; case "updatepage": #region updatepost responseJson = JSONHelper.ToJsonString(_pageManager.UpdatePage(JSONHelper.ToObject <PageData>(jsonString))); #endregion break; case "addpage": #region addpost responseJson = JSONHelper.ToJsonString(_pageManager.AddPage(JSONHelper.ToObject <PageData>(jsonString))); #endregion break; case "adduser": #region adduser responseJson = JSONHelper.ToJsonString(_userManager.AddUser(JSONHelper.ToObject <UserData>(jsonString))); #endregion break; case "updateuser": #region updateuser responseJson = JSONHelper.ToJsonString(_userManager.UpdateUser(JSONHelper.ToObject <UserData>(jsonString))); #endregion break; case "getuser": #region getuser responseJson = JSONHelper.ToJsonString(_userManager.GetUser(JSONHelper.ToObject <UserData>(jsonString))); #endregion break; case "getusers": #region getusers responseJson = JSONHelper.ToJsonString(_userManager.GetUsers(JSONHelper.ToObject <UserData>(jsonString))); #endregion break; case "deleteuser": #region deleteuser responseJson = JSONHelper.ToJsonString(_userManager.DeleteUser((int)JSONHelper.ToObject <UserData>(jsonString).id)); #endregion break; } context.Response.Write(responseJson); }