private void UpdatePost(string name, FullPost post) { string filename = Server.MapPath("~/Content/" + name + ".md"); string[] lines = System.IO.File.ReadAllLines(filename); post.Name = name; post.Title = lines[0].Split(':')[1].Trim(); post.PostDate = DateTime.ParseExact(lines[2].Split(':')[1].Trim(), "yyyy-MM-dd", null); post.UpdateDate = DateTime.Today; post.Tags = lines[1].Split(':')[1].Split(',').Select(t => t.Trim()).ToArray(); StringBuilder excerpt = new StringBuilder(); StringBuilder content = new StringBuilder(); bool isExcerptRecorded = false; for (int i = 3; i < lines.Length; i++) { string line = lines[i]; if (line.Trim() == "<!-- more -->") { isExcerptRecorded = true; } content.AppendLine(line); if (!isExcerptRecorded) { excerpt.AppendLine(line); } } post.Excerpt = excerpt.ToString().Trim(); post.Content = content.ToString().Trim(); }
public async Task <IHttpActionResult> CreatePost([FromBody] FullPost postToCreate) { var createdPostId = await _mediator.SendAsync(new InsertPostCommand(postToCreate.Hyperlink, postToCreate.Description, postToCreate.ImagePath, postToCreate.Tags, postToCreate.Groups)); return(Ok(createdPostId)); }
public void Update(string name) { FullPost post = DbSession.Get <FullPost>(name); HashSet <string> storedTags = new HashSet <string>(); if (post == null) { post = new FullPost(); } else { storedTags.UnionWith(post.Tags); } UpdatePost(name, post); // 有以前的tag列表说明数据库里有这一篇,使用更新 if (storedTags.Count > 0) { DbSession.Update(post); } else { DbSession.Save(post); } // 抽取tag的区别 HashSet <string> currentTags = new HashSet <string>(post.Tags); UpdateTags(currentTags, storedTags); // 更新全文索引 UpdateIndex(post); }
//Query6:Получить следующую структуру (передать Id поста в параметры) //Пост //Самый длинный коммент поста //Самый залайканный коммент поста //Количество комментов под постом где или 0 лайков или длина текста< 80 public static PostStruct Query6(int postId) { PostStruct postStruct = new PostStruct(); try { var data = GetEntities(); FullPost currentPost = data.SelectMany(u => u.Posts) .Where(u => u.Id == postId) .FirstOrDefault(); postStruct.LongestComm = currentPost.Comments .OrderBy(c => c.Body.Length) .LastOrDefault(); postStruct.LikestComm = currentPost.Comments .OrderBy(c => c.Likes) .LastOrDefault(); postStruct.LowRatedCommsCount = currentPost.Comments .Where(p => p.Likes == 0 || p.Body.Length < 80).ToList().Count(); } catch (Exception ex) { Console.Clear(); Console.WriteLine(ex.Message); Console.ReadKey(); } return(postStruct); }
protected override async void OnAppearing() { base.OnAppearing(); var store = new Data.Real.PostsStore(); _post = await store.GetPost(_id); if (!string.IsNullOrEmpty(_post.github)) { ToolbarItems.Add(_gitHubButton); } if (!string.IsNullOrEmpty(_post.youtube)) { ToolbarItems.Add(_youTubeButton); } Title = $"{_post.Date.ToLocalTime():dd/MM/yyyy}"; PostTitle.Text = _post.Title; _page = "http://thatcsharpguy.com" + _id + "/m.html"; Site.Source = _page; Site.Navigating += ContentNavigating; }
public async Task <IHttpActionResult> UpdatePostById([FromBody] FullPost postToUpdate) { await _mediator.SendAsync(new UpdatePostByIdCommand(postToUpdate.PostId, postToUpdate.Hyperlink, postToUpdate.Description, postToUpdate.ImagePath, postToUpdate.Tags, postToUpdate.Groups)); return(Ok()); }
public ActionResult FullPost(int postId) { FullPost fullPost = new FullPost() { Post = postsRepository.Get.FirstOrDefault(p => p.PostId == postId), Comment = commentsRepository.Get.Where(p => p.PostId == postId), }; fullPost.Post.Text = fullPost.Post.Text.Replace("\r\n", "<br>"); ViewBag.CountComments = fullPost.Comment.Count(); return(View(fullPost)); }
private void UpdateIndex(FullPost post) { Field name = new Field("Name", post.Name, Field.Store.YES, Field.Index.NOT_ANALYZED); Field title = new Field("Title", post.Title, Field.Store.NO, Field.Index.ANALYZED); Field content = new Field("Content", post.Content, Field.Store.NO, Field.Index.ANALYZED); Field tags = new Field("Tags", String.Join(" ", post.Tags), Field.Store.NO, Field.Index.ANALYZED); Document document = new Document(); document.Add(name); document.Add(title); document.Add(content); document.Add(tags); Indexer.UpdateDocument(new Term("Name", post.Name), document); Indexer.Flush(true, true, true); Indexer.Optimize(); }
private void Show(FullPost fullPost) { if (fullPost != null) { Console.WriteLine(fullPost); if (fullPost.Comments != null && fullPost.Comments.Count() > 0) { Console.WriteLine("\tList of comments:"); foreach (var item in fullPost.Comments) { Console.WriteLine(item); } } } else { Console.WriteLine("Result: 0"); } }
//Query6:Получить следующую структуру (передать Id поста в параметры) //Пост //Самый длинный коммент поста //Самый залайканный коммент поста //Количество комментов под постом где или 0 лайков или длина текста< 80 private PostStruct Query6(int postId) { PostStruct postStruct = new PostStruct(); try { var data = getDataDelegate.Invoke(); FullPost currentPost = data.SelectMany(u => u.Posts) .Where(u => u.Id == postId) .FirstOrDefault(); postStruct.LongestComm = currentPost.Comments .OrderBy(c => c.Body.Length) .LastOrDefault(); postStruct.LikestComm = currentPost.Comments .OrderBy(c => c.Likes) .LastOrDefault(); List <Comment> subresult = currentPost.Comments .Where(p => p.Likes == 0 || p.Body.Length < 80).ToList(); Console.WriteLine($"Current: {currentPost} \nAll comments: "); foreach (var item in currentPost.Comments) { Console.WriteLine(item); } Console.WriteLine("\nSelected comments"); foreach (var item in subresult) { Console.WriteLine(item); } postStruct.LowRatedCommsCount = subresult.Count(); } catch (Exception ex) { Console.Clear(); Console.WriteLine(ex.Message); Console.ReadKey(); } return(postStruct); }
public static FullPostModel Map(FullPost post, IUrlHelper URL) { FullPostModel fpm = new FullPostModel(); QuestionModel qm = new QuestionModel { comments = Map(post.comments.Where(c => c.parentid == post.question.postid).ToList(), URL), body = post.question.body, creationdate = post.question.creationdate, score = post.question.score, title = post.question.title, username = post.question.username, userurl = URL.Link(Config.UserRoute, new { id = post.question.userid }) }; List <AnswerModel> ams = new List <AnswerModel>(); foreach (var answer in post.answers) { Console.WriteLine(answer.id); ams.Add(new AnswerModel { comments = Map(post.comments.Where(c => c.parentid == answer.postid).ToList(), URL), body = answer.body, creationdate = answer.creationdate, score = answer.score, username = answer.username, userurl = URL.Link(Config.UserRoute, new { id = answer.userid }) }); } fpm = new FullPostModel { questionmodel = qm, answermodels = ams, tags = post.tags, url = URL.Link(Config.PostRoute, new { id = post.question.postid }) }; return(fpm); }
public int CreatePost(FullPost post) { using (MooDB db = new MooDB()) { Problem problem; if (post.Problem == null) { problem = null; } else { problem = (from p in db.Problems where p.ID == post.Problem select p).SingleOrDefault<Problem>(); if (problem == null) throw new ArgumentException("无此题目"); } Post newPost = new Post() { Name = post.Name, OnTop = false, Problem = problem, Locked = false, ReplyTime = DateTime.Now }; Access.Required(db, newPost, Function.CreatePost); db.Posts.AddObject(newPost); db.SaveChanges(); return newPost.ID; } }
public void ModifyPost(string id, FullPost post) { int iid = int.Parse(id); using (MooDB db = new MooDB()) { Post thePost = (from p in db.Posts where p.ID == iid select p).SingleOrDefault<Post>(); if (thePost == null) throw new ArgumentException("无此帖子"); Access.Required(db, thePost, Function.ModifyPost); if (post.Name != null) { thePost.Name = post.Name; } if (post.OnTop != null) { thePost.OnTop = (bool)post.OnTop; } if (post.Locked != null) { thePost.Locked = (bool)post.Locked; } db.SaveChanges(); } }
//public IList<User> GetUsers(Func<User, bool> predicate, int page, int pagesize) //{ // using (var db = new DatabaseContext()) // { // return db.users.Where(predicate).ToList(); // } //} public FullPost GetPost(int id) { FullPost result = new FullPost(); using (var db = new DatabaseContext()) { var conn = (MySqlConnection)db.Database.GetDbConnection(); conn.Open(); var cmd = new MySqlCommand("call getfullpost(@1)", conn); cmd.Parameters.Add("@1", DbType.Int32).Value = id; using (var rdr = cmd.ExecuteReader()) { if (!rdr.Read()) { return(null); } //question Question question = new Question { id = rdr.GetInt32(rdr.GetOrdinal("id")), acceptedanswerid = rdr.IsDBNull(rdr.GetOrdinal("acceptedanswerid"))? -1 : rdr.GetInt32(rdr.GetOrdinal("acceptedanswerid")), body = rdr.GetString(rdr.GetOrdinal("body")), title = rdr.GetString(rdr.GetOrdinal("title")), score = rdr.GetInt32(rdr.GetOrdinal("score")), creationdate = rdr.GetDateTime(rdr.GetOrdinal("creationdate")), postid = rdr.GetInt32(rdr.GetOrdinal("postid")), userid = rdr.GetInt32(rdr.GetOrdinal("ownerid")), username = rdr.GetString(rdr.GetOrdinal("displayname")) }; //tags rdr.NextResult(); var tags = new List <string>(); while (rdr.Read()) { tags.Add(rdr.GetString(rdr.GetOrdinal("tag"))); } //answers rdr.NextResult(); var answers = new List <Answer>(); while (rdr.Read()) { answers.Add(new Answer { id = rdr.GetInt32(rdr.GetOrdinal("id")), body = rdr.GetString(rdr.GetOrdinal("body")), score = rdr.GetInt32(rdr.GetOrdinal("score")), creationdate = rdr.GetDateTime(rdr.GetOrdinal("creationdate")), postid = rdr.GetInt32(rdr.GetOrdinal("postid")), userid = rdr.GetInt32(rdr.GetOrdinal("ownerid")), parentid = rdr.GetInt32(rdr.GetOrdinal("parentid")), username = rdr.GetString(rdr.GetOrdinal("displayname")) }); } //comments rdr.NextResult(); var comments = new List <Comment>(); while (rdr.Read()) { comments.Add(new Comment { id = rdr.GetInt32(rdr.GetOrdinal("id")), body = rdr.GetString(rdr.GetOrdinal("body")), score = rdr.GetInt32(rdr.GetOrdinal("score")), creationdate = rdr.GetDateTime(rdr.GetOrdinal("creationdate")), postid = rdr.GetInt32(rdr.GetOrdinal("postid")), userid = rdr.GetInt32(rdr.GetOrdinal("ownerid")), parentid = rdr.GetInt32(rdr.GetOrdinal("parentid")), username = rdr.GetString(rdr.GetOrdinal("displayname")), }); } result = new FullPost { question = question, tags = tags, answers = answers, comments = comments }; } return(result); } }
//Query5:Получить следующую структуру (передать Id пользователя в параметры) // User // Последний пост пользователя(по дате) // Количество комментов под последним постом // Количество невыполненных тасков для пользователя // Самый популярный пост пользователя(там где больше всего комментов с длиной текста больше 80 символов) // Самый популярный пост пользователя(там где больше всего лайков) private UserStruct Query5(int userId) { UserStruct user = new UserStruct(); try { var data = getDataDelegate.Invoke(); SomeEntity usr = data.Where(u => u.Id == userId).FirstOrDefault(); List <FullPost> posts = usr.Posts.ToList(); if (posts != null && posts.Count() > 0) { FullPost lastPost = posts.OrderByDescending(p => p.CreatedAt).First(); if (lastPost != null) { user.LastPost = lastPost; if (lastPost.Comments != null) { user.LastPostCommentsCount = lastPost.Comments.Count(); } } List <FullPost> subresult = posts.OrderByDescending(p => p.Comments.Count()) .Where(c => c.Comments.Where(e => e.Body.Length > 80).Count() > 0) .ToList(); if (subresult != null && subresult.Count() > 0) { user.MostPopularByComms = subresult.GroupJoin(subresult.SelectMany(c => c.Comments), p => p.Id, c => c.PostId, (p, cl) => new { PostItem = p, CommsCounts = cl.Select(a => a.Body) .Where(b => b.Length > 80) .Count() } ).OrderBy(v => v.CommsCounts) .Last().PostItem; } user.MostPopularByLikes = posts.OrderByDescending(p => p.Likes).First(); } if (usr.Todos != null) { user.UnCompletedTasksCount = usr.Todos.Where(t => t.IsComplete == false).Count(); } } catch (Exception ex) { Console.Clear(); Console.WriteLine(ex.Message); Console.ReadKey(); } return(user); }