/// <summary> /// Parses all pages, finding cross links in descriptions. /// </summary> private async Task BuildPageReferences(IServiceProvider sp) { var db = sp.GetService <AppDbContext>(); if (await db.PageReferences.AnyAsync()) { return; } var pages = await db.Pages.Select(x => new { x.Id, x.Key, x.Description }) .ToDictionaryAsync(x => x.Key, x => x); foreach (var p in pages.Values) { var links = MarkdownService.GetPageReferences(p.Description); foreach (var link in links) { if (!pages.TryGetValue(link, out var linkRef)) { continue; } db.PageReferences.Add(new PageReference { Id = Guid.NewGuid(), SourceId = p.Id, DestinationId = linkRef.Id }); } } await db.SaveChangesAsync(); }
public ArticleRevisionDiffApiModel( ArticleId articleId, ArticleRevisionDate oldRevisionDate, ArticleRevisionDate newRevisionDate, Repository repository) { var oldRevision = repository.GetArticleRevision(articleId, oldRevisionDate); string oldHtml = ((oldRevision != null) ? MarkdownService.MakeTextHtmlLinebreaks(oldRevision.MarkdownContent) : null) ?? string.Empty; var newRevision = repository.GetArticleRevision(articleId, newRevisionDate); string newHtml = ((newRevision != null) ? MarkdownService.MakeTextHtmlLinebreaks(newRevision.MarkdownContent) : null) ?? string.Empty; var diff = new Helpers.HtmlDiff(oldHtml, newHtml); string diffHtml = diff.Build(); this.HtmlDiff = diffHtml; this.OldText = (oldRevision != null) ? oldRevision.CreatedAt.ToString(ArticleRevisionDate.FormattedDateTimeFormat) : null; this.NewText = (newRevision != null) ? newRevision.CreatedAt.ToString(ArticleRevisionDate.FormattedDateTimeFormat) : null; }
static LuceneDocument() { var indexedField = new FieldType { IsIndexed = true, IsStored = true, IsTokenized = true }; var storedField = new FieldType { IsStored = true, IsIndexed = true }; KnownFields = new Dictionary <string, Func <Page, Field> > { { "Id", p => new Field("Id", p.Id.ToString(), storedField) }, { "Key", p => new Field("Key", p.Key, indexedField) }, { "Title", p => new Field("Title", p.Title, indexedField) { Boost = 500 } }, { "Aliases", p => new Field("Aliases", GetPageAliases(p).JoinString(", "), indexedField) { Boost = 250 } }, { "PageType", p => new Field("PageType", p.Type.ToString(), storedField) }, { "Description", p => new Field("Description", MarkdownService.Strip(p.Description), indexedField) } }; }
public PagePresenterService(AppDbContext db, MarkdownService markdown, RelationsPresenterService relations, TreePresenterService tree) { _db = db; _markdown = markdown; _relations = relations; _tree = tree; }
public PagePresenterService(AppDbContext db, IMapper mapper, MarkdownService markdown, RelationsPresenterService relations) { _db = db; _mapper = mapper; _markdown = markdown; _relations = relations; }
public BlogPostController(IOptions <SiteOptions> options, DatabaseContext database, JobSchedulerService <MailJob, MailJobContext> scheduler, AuthenticationService authentication, MarkdownService markdown) { this.options = options; this.database = database; this.scheduler = scheduler; this.authentication = authentication; this.markdown = markdown; }
public dynamic GetRevisionPreview([FromUri] ArticleId slug, [FromUri] ArticleRevisionDate revisionDate) { var articleRevision = this.GetEnsuredArticleRevision(slug, revisionDate); var text = articleRevision.CreatedAt.ToString(ArticleRevisionDate.FormattedDateTimeFormat); var htmlContent = MarkdownService.MakeTextHtmlLinebreaks(articleRevision.MarkdownContent); return(new { text, htmlContent }); }
public void Given_NullParameter_Constructor_ShouldThrow_ArgumentNullException() { Action action1 = () => { var service = new MarkdownService(null, this._fileHelper.Object); }; action1.ShouldThrow <ArgumentNullException>(); Action action2 = () => { var service = new MarkdownService(this._markdownHelper.Object, null); }; action2.ShouldThrow <ArgumentNullException>(); }
public WikiDownArticleHtmlString(ArticleRevision articleRevision, Repository repository) { if (articleRevision == null) { throw new ArgumentNullException("articleRevision"); } if (repository == null) { throw new ArgumentNullException("repository"); } this.html = MarkdownService.MakeHtml(articleRevision.MarkdownContent); this.repository = repository; }
/// <summary> /// Adds a page to the index. /// </summary> public async Task AddPageAsync(Page page) { var doc = new PageDocument { Id = page.Id, Key = page.Key, Title = page.Title, Aliases = GetPageAliases(page).JoinString(", "), PageType = (int)page.Type, Description = MarkdownService.Strip(page.Description), }; await _client.IndexAsync(doc, i => i.Index(PAGE_INDEX)); }
protected override async Task OnParametersSetAsync() { if (!string.IsNullOrEmpty(Text)) { var texts = Regex.Split(Text, "({{.*?}})"); foreach (var text in texts) { var element = new Element(); var isEmbed = Regex.Match(text, "{{.*?}}"); element.IsEmbed = isEmbed.Success; element.Text = isEmbed.Success ? text : await MarkdownService.RenderAsync(text); Elements.Add(element); } } }
public async Task <JsonResult> SendEmail(Models.Email.Email model) { // Credentials: IEmailer emailer = new Emailer(); var message = new EmailInfo() { From = model.FromEmail, FromName = model.FromName, Subject = model.Subject, HtmlBody = MarkdownService.GetHtmlFromMarkdown(model.Body), }; message.To.Add(SiteEmail); int count = 0; if (!model.SendAsTest) { foreach (var group in model.RecipientGroups) { var emails = _gm.GetUserEmailsInGroup(group); var emailTasks = emails.Select(to => { count++; message.To.Clear(); message.To.Add(to); return(emailer.SendEmailAsync(message)); }); await Task.WhenAll(emailTasks); } return(Json(count)); } else { var userId = new Guid(User.Identity.GetUserId()); message.To.Clear(); message.To.Add(_profileManager.GetUserProfile(userId).Email); await emailer.SendEmailAsync(message); return(Json(1)); } }
private void SaveSoftLinks(IContent content) { var contentData = content as IContentData; if (contentData == null) { return; } foreach (var propertyData in contentData.Property) { var data = propertyData as PropertyMarkdown; if (data != null) { var markdownAsHtml = MarkdownService.Transform(data.Value as string); var htmlReader = new HtmlStreamReader(markdownAsHtml); var linkFragments = htmlReader.OfType <ElementFragment>().Where(f => f.NameEquals("a")).ToList(); if (linkFragments.Any()) { var softLinks = new List <SoftLink>(); foreach (var elementFragment in linkFragments) { if (elementFragment.HasAttributes) { var attribute = elementFragment.Attributes["href"]; if (IsValidLinkAttribute(attribute) && PermanentLinkUtility.IsMappableUrl(new UrlBuilder(attribute.UnquotedValue))) { softLinks.Add(new SoftLink { OwnerContentLink = content.ContentLink.CreateReferenceWithoutVersion(), OwnerLanguage = content is ILocalizable ? ((ILocalizable)content).Language : null, SoftLinkType = ReferenceType.PageLinkReference, Url = attribute.UnquotedValue }); } } } ContentSoftLinkRepository.Save(content.ContentLink.CreateReferenceWithoutVersion(), content is ILocalizable ? ((ILocalizable)content).Language : null, softLinks); } } } }
private MarkupResult MarkupCore(string markdown, FileAndType ft, bool omitParse) { try { var mr = MarkdownService.Markup(markdown, ft.File); if (omitParse) { return(mr); } return(Parse(mr, ft)); } catch (Exception ex) { System.Diagnostics.Debug.Fail("Markup failed!"); var message = $"Markup failed: {ex.Message}."; Logger.LogError(message); throw new DocumentException(message, ex); } }
private MarkupResult MarkupCore(string markdown, FileAndType ft, bool omitParse) { try { var mr = MarkdownService.Markup(markdown, ft.File); if (omitParse) { return(mr); } return(Parse(mr, ft)); } catch (Exception ex) { System.Diagnostics.Debug.Fail("Markup failed!"); Logger.LogWarning($"Markup failed:{Environment.NewLine} Markdown: {markdown}{Environment.NewLine} Details:{ex.ToString()}"); return(new MarkupResult { Html = markdown }); } }
/// <summary> /// Returns the list of pages references by the contents of current page. /// </summary> private async Task <IEnumerable <PageReference> > GetPageReferencesAsync(string body, Page page) { var refs = MarkdownService.GetPageReferences(body); var pages = await _db.Pages .Where(x => refs.Contains(x.Key)) .Select(x => new { x.Id, x.Key }) .ToListAsync(); foreach (var p in pages) { _cache.Remove <PageReferencesVM>(p.Key); } return(pages.Select(x => new PageReference { Id = Guid.NewGuid(), DestinationId = x.Id, Source = page })); }
public WikiDownArticleHtmlString(ArticleResult articleResult, Repository repository) { if (articleResult == null) { throw new ArgumentNullException("articleResult"); } if (articleResult.ArticleRevision == null) { throw new ArgumentOutOfRangeException( "articleResult", "ArticleResult cannot have a null ArticleRevision."); } if (repository == null) { throw new ArgumentNullException("repository"); } this.html = MarkdownService.MakeHtml(articleResult.ArticleRevision.MarkdownContent); this.repository = repository; }
public IReadOnlyCollection <ArticleRevision> DebugSaveAllArticleRevisions() { using (var session = this.GetMaxRequestsSession()) { var query = session.Query <ArticleRevisionsIndex.Result, ArticleRevisionsIndex>() .Where(x => x.IsActive) .Take(int.MaxValue); var articleRevisions = query.As <ArticleRevision>().ToList(); foreach (var revision in articleRevisions) { revision.TextContent = MarkdownService.MakeTextFlat(revision.MarkdownContent); session.Store(revision); } session.SaveChanges(); return(articleRevisions); } }
public ArticleRevision( ArticleId articleId, IPrincipal principal, string markdownContent, string editSummary = null) { if (articleId == null) { throw new ArgumentNullException("articleId"); } if (principal == null) { throw new ArgumentNullException("principal"); } this.ArticleId = articleId.Id; this.CreatedByUserName = principal.Identity.Name; this.EditSummary = editSummary; this.MarkdownContent = markdownContent; this.TextContent = MarkdownService.MakeTextFlat(this.MarkdownContent); this.CreatedAt = DateTime.UtcNow; }
public string MarkupToHtml(string markdown, string file) { return(MarkdownService.Markup(markdown, file).Html); }
public void Given_Parameters_Constructor_ShouldThrow_NoException() { Action action = () => { var service = new MarkdownService(this._markdownHelper.Object, this._fileHelper.Object); }; action.ShouldNotThrow <Exception>(); }
public QuizzesController() { db = new Context(); markdownService = new MarkdownService(); }
public MarkdownTagHelper(MarkdownService markdownService) { this._markdownService = markdownService; }
public QuizzesController(Context db) { this.db = db; markdownService = new MarkdownService(); }
public StrifeInfoController(MarkdownService markdownService) { _markdownService = markdownService; }
//When deployed on server //private const string jsonFile = @"Data.json"; //private const string jsonDirr = @"~/Json/"; //private const string MDDB = jsonDirr + jsonFile; //private const string MD2 = @"~/MD2/"; //private const string MD = @"~/MD/"; public IndexModule() { //async syntax //Get["/aa", true] = async (parameters, ct) => "Hello World!"; Models.Errors errorMsg = new Models.Errors(); //var ses = Request.Session; Get["/"] = _ => { Request.Session["filter"] = ""; Request.Session["LoggedInStatus"] = false; return(View["default"]); }; Get["/ms_iot_Community_Samples"] = _ => { bool getList = false; if (Models.BlogPost.BlogPostz == null) { getList = true; } else if (Models.BlogPost.BlogPostz.Count() == 0) { getList = true; } if (getList) { string[] files1 = Directory.GetFiles(jsonDirr, jsonFile); if (files1.Length != 1) { return(View["IndexList"]); } string document = ""; document = File.ReadAllText(MDDB); JsonSerializerSettings set = new JsonSerializerSettings(); set.MissingMemberHandling = MissingMemberHandling.Ignore; Models.BlogPost[] md = JsonConvert.DeserializeObject <Models.BlogPost[]>(document, set); var mdd = from n in md select n; //Objects.BlogPost.BlogPostz = md.Select(data => data)).ToList() Models.BlogPost.BlogPostz = md.ToList <Models.BlogPost>(); Request.Session["filter"] = ""; } return(View["/ms_iot_Community_Samples/ms_iot_Community_Samples", errorMsg]); //Models.BlogPost.ViewBlogPostz((string) Request.Session["filter"])]; }; /******************* * Get["/ms_iot_Community_Samples/load"] = _ => * { * string[] files1 = Directory.GetFiles( jsonDirr, jsonFile); * if (files1.Length != 1) * return View["IndexList"]; * string document = ""; * document= File.ReadAllText(MDDB); * * JsonSerializerSettings set = new JsonSerializerSettings(); * set.MissingMemberHandling = MissingMemberHandling.Ignore; * Models.BlogPost[] md = JsonConvert.DeserializeObject<Models.BlogPost[]>(document, set); * * var mdd = from n in md select n; * Models.BlogPost.BlogPostz = md.ToList<Models.BlogPost>(); * Models.BlogPost.ResetBlogPostz(); * Request.Session["filter"] = ""; * return View["/ms_iot_Community_Samples/IndexList"]; * }; **/ Get["/ms_iot_Community_Samples/default"] = _ => { Request.Session["filter"] = ""; Request.Session["LoggedInStatus"] = false; return(View["default"]); }; Get["/ms_iot_Community_Samples/login/{referer}"] = parameters => { string referer = parameters.referer; if (referer == "0") { referer = "ms_iot_Community_Samples"; } else { referer = "IndexList"; } return(View["/ms_iot_Community_Samples/login", referer]); }; Get["/ms_iot_Community_Samples/logout/{referer}"] = parameters => { string referer = parameters.referer; if (referer == "0") { referer = "ms_iot_Community_Samples"; } else { referer = "IndexList"; } //Models.Errors.LoggedInStatus = false; Request.Session["filter"] = ""; Request.Session["LoggedInStatus"] = false; errorMsg.Message = "Logged out."; errorMsg.Source = "/Logout"; errorMsg.LoggedInStatus = false; if (referer == "ms_iot_Community_Samples") { return(View["/ms_iot_Community_Samples/" + referer, errorMsg]); } else { return(View["/ms_iot_Community_Samples/" + referer, Models.BlogPost.ViewBlogPostz((string)Request.Session["filter"])]); } }; Get["/ms_iot_Community_Samples/onlogin/{referer}/{user}/{pwd}"] = parameters => { string user = parameters.user; string pwd = parameters.pwd; string referer = parameters.referer; Request.Session["filter"] = ""; Request.Session["LoggedInStatus"] = false; #if ISDEPLOYED //http://www.dotnetprofessional.com/blog/post/2008/03/03/Encrypt-sections-of-WebConfig-or-AppConfig.aspx NameValueCollection secureAppSettings = (NameValueCollection)ConfigurationManager.GetSection("secureAppSettings"); string admin = (string)secureAppSettings["Admin.UserName"]; string adminPwd = (string)secureAppSettings["Admin.Pwd"]; #else string admin = (string)ConfigurationManager.AppSettings["Admin.UserName"]; string adminPwd = (string)ConfigurationManager.AppSettings["Admin.Pwd"]; #endif user = user.Trim(); pwd = pwd.Trim(); if ((user == admin) && (pwd == adminPwd)) { Request.Session["LoggedInStatus"] = true; errorMsg.Message = "Logged in."; errorMsg.Source = "/OnLogin"; errorMsg.LoggedInStatus = true; } else { Request.Session["LoggedInStatus"] = false; errorMsg.Message = "Login failed!"; errorMsg.Source = "/OnLogin"; errorMsg.LoggedInStatus = false; return(View["/ms_iot_Community_Samples/ErrorPage", errorMsg]); } if (referer == "ms_iot_Community_Samples") { return(View["/ms_iot_Community_Samples/ms_iot_Community_Samples", errorMsg]); } else { return(View["/ms_iot_Community_Samples/IndexList", Models.BlogPost.ViewBlogPostz((string)Request.Session["filter"])]); } }; Get["/ms_iot_Community_Samples/convert"] = _ => { if (!(bool)Request.Session["LoggedInStatus"]) { errorMsg.Message = "Not logged in!"; errorMsg.Source = "/Convert"; return(View["/ms_iot_Community_Samples/ErrorPage", errorMsg]); } string[] files0 = Directory.GetFiles(jsonDirr, "*.*"); foreach (string file in files0) { File.Delete(file); } string[] files1 = Directory.GetFiles(MD2, "*.*"); foreach (string file in files1) { File.Delete(file); } char[] lineSep = new char[] { '\r', '\n' }; string[] files = Directory.GetFiles(MD, "*.MD"); //File.AppendAllText(MDDB, "[\r\n"); int count = files.Length; bool abortFile = false; Models.BlogPost.ClearBlogPostz(); foreach (string file in files) { abortFile = false; try { string filename = Path.GetFileNameWithoutExtension(file); count--; string fileTxt = File.ReadAllText(file); //Get database between 1st and second lines of --- int startIndex = fileTxt.IndexOf(DBSep, 0); if (startIndex < 0) { continue; } int endIndex = fileTxt.IndexOf(DBSep, startIndex + DBSep.Length); if (endIndex < 0) { continue; } string DB2 = fileTxt.Substring(startIndex, endIndex - startIndex + DBSep.Length) + "\r\n"; string DB = fileTxt.Substring(startIndex + DBSep.Length, endIndex - startIndex - DBSep.Length).Trim(); fileTxt = fileTxt.Substring(endIndex + DBSep.Length); string[] lines = DB.Split(lineSep); Models.BlogPost blogpost = new Models.BlogPost(); blogpost.filename = filename; foreach (string line in lines) { string newLine = line.Trim(); if (newLine != "") { string[] parts = newLine.Split(new char[] { ':' }); string vname = parts[0].Trim(); string vvalue = parts[1].Trim(); try { var fields = typeof(Models.BlogPost).GetFields( BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); var field = from n in fields where n.Name.Substring(1).Replace(">k__BackingField", "") == vname select n; if (field.Count() == 1) { field.First().SetValue(blogpost, vvalue); } } catch (Exception ex) { //Abort lines loop abortFile = true; break; } } } if (abortFile) { //Abort this db record break; } string name = Path.GetFileName(file); File.WriteAllText(MD2 + name, fileTxt); } catch (Exception ex) { //Skip this file and continue with next continue; } } Request.Session["filter"] = ""; string json = JsonConvert.SerializeObject(Models.BlogPost.BlogPostz); File.AppendAllText(MDDB, json); Request.Session["filter"] = ""; return(View["/ms_iot_Community_Samples/IndexList", Models.BlogPost.ViewBlogPostz((string)Request.Session["filter"])]); }; Get["/ms_iot_Community_Samples/display/{name}"] = parameters => { var contentProvider = new FileContentProvider(MD2, null); var converter = new MarkdownService(contentProvider); var document = converter.GetDocument(parameters.name); return(document.Content); }; Get["/ms_iot_Community_Samples/GitHub", true] = async(parameters, ct) => { if (!(bool)Request.Session["LoggedInStatus"]) { errorMsg.Message = "Not logged in!"; errorMsg.Source = "/GitHub"; return(View["/ms_iot_Community_Samples/ErrorPage", errorMsg]); } #if ISDEPLOYED NameValueCollection secureAppSettings = (NameValueCollection)ConfigurationManager.GetSection("secureAppSettings"); string githuUrl = (string)secureAppSettings["GitHub.Url"]; string githubRepo = (string)secureAppSettings["GitHub.Repository"]; string githubUsr = (string)secureAppSettings["GitHub.UserName"]; string githubPwd = (string)secureAppSettings["GitHub.Pwd"]; #else string githuUrl = (string)ConfigurationManager.AppSettings["GitHub.Url"]; string githubRepo = (string)ConfigurationManager.AppSettings["GitHub.MDsRepository"]; string githubUsr = (string)ConfigurationManager.AppSettings["GitHub.UserName"]; string githubPwd = (string)ConfigurationManager.AppSettings["GitHub.Pwd"]; #endif //http://haacked.com/archive/2014/04/24/octokit-oauth/ string clientId = "2c0baac7c20dd4fb52b5"; string clientSecret = "f14d3e9055a292128abe472ab0b000a2a8c87166"; //f14d3e9055a292128abe472ab0b000a2a8c87166 //readonly GitHubClient client3 = new GitHubClient(new ProductHeaderValue(githubRepo), new Uri(githuUrl)); //https://github.com/octokit/octokit.net var github = new GitHubClient(new ProductHeaderValue(githubRepo)); var user = await github.User.Get(githubUsr); var client = new GitHubClient(new ProductHeaderValue(githubRepo)); var basicAuth = new Credentials(githubUsr, githubPwd); // NOTE: not real credentials client3.Credentials = basicAuth; //var client = new GitHubClient(new ProductHeaderValue("dotnet-test-functional")); //client.Credentials = GithubHelper.Credentials; //http://stackoverflow.com/questions/24830617/reading-code-from-repository var repos = await client3.Repository.GetAllForCurrent(); var repo = from n in repos where n.Name == githubRepo select n; if (repo.Count() == 1) { var AllContent = await client.Repository.Content.GetAllContents(repo.First().Id);//.GetAllContent(repos[0].Owner.Login, repos[0].Name); var textOfFirstFile = AllContent[0].Content; var textOfFirstFileName = AllContent[0].Name; var AllContent2 = await client.Repository.Content.GetAllContents(repo.First().Id, textOfFirstFileName); var textOfFirstFile2 = AllContent[1].Content; var textOfFirstFile2Name = AllContent[1].Name; var AllContent3 = await client.Repository.Content.GetAllContents(repo.First().Id, textOfFirstFile2Name); } //var pull = await client3.PullRequest.GetAllForRepository("djaus2", "ms-iot-community-samples"); //var client2 = new GitHubClient(new ProductHeaderValue("ms-iot-community-samples")); //var tokenAuth = new Credentials("token"); // NOTE: not real token //client2.Credentials = tokenAuth; Request.Session["LoggedInStatus"] = false; Request.Session["filter"] = ""; return(View["/ms_iot_Community_Samples/IndexList", Models.BlogPost.ViewBlogPostz((string)Request.Session["filter"])]); }; Get["/ms_iot_Community_Samples/Sort/{field}"] = parameters => { string sortString = parameters.field; Models.FilterAndSortInfo fi; if ((string)Request.Session["filter"] == null) { fi = new Models.FilterAndSortInfo(); } else if ((string)Request.Session["filter"] == "") { fi = new Models.FilterAndSortInfo(); } else { JsonSerializerSettings set = new JsonSerializerSettings(); set.MissingMemberHandling = MissingMemberHandling.Ignore; fi = JsonConvert.DeserializeObject <Models.FilterAndSortInfo>((string)Request.Session["filter"], set); } //For filter remove any pre-existing sorting (but for sort don't remove pre-existing sorting). fi.SortString = sortString; string json = JsonConvert.SerializeObject(fi); Request.Session["filter"] = json; return(View["/ms_iot_Community_Samples/IndexList", Models.BlogPost.ViewBlogPostz((string)Request.Session["filter"])]); }; Get["/ms_iot_Community_Samples/ClearSort"] = _ => { if ((string)Request.Session["filter"] != null) { if ((string)Request.Session["filter"] == "") { ((Models.FilterAndSortInfo)Request.Session["filter"]).SortString = ""; } } return(View["/ms_iot_Community_Samples/IndexList", Models.BlogPost.ViewBlogPostz((string)Request.Session["filter"])]); }; Get["/ms_iot_Community_Samples/Show/{id}"] = parameters => { string id = parameters.id; Models.BlogPost blogPost = Models.BlogPost.Get(id); if (blogPost != null) { return(View["/ms_iot_Community_Samples/Index", blogPost]); } else { return(View["/ms_iot_Community_Samples/IndexList", Models.BlogPost.ViewBlogPostz((string)Request.Session["filter"])]); } }; Get["/ms_iot_Community_Samples/reset"] = _ => { Request.Session["filter"] = ""; return(View["/ms_iot_Community_Samples/IndexList", Models.BlogPost.ViewBlogPostz((string)Request.Session["filter"])]); }; Get["/ms_iot_Community_Samples/clear"] = _ => { Request.Session["filter"] = ""; Models.BlogPost.ClearBlogPostz(); return(View["/ms_iot_Community_Samples/IndexList", Models.BlogPost.ViewBlogPostz((string)Request.Session["filter"])]); }; Get["/ms_iot_Community_Samples/list"] = _ => { string filter = (string)Request.Session["filter"]; return(View["/ms_iot_Community_Samples/IndexList", Models.BlogPost.ViewBlogPostz((string)Request.Session["filter"])]); }; Get["/ms_iot_Community_Samples/ClearFilter"] = _ => { //Same as reset Request.Session["filter"] = ""; return(View["/ms_iot_Community_Samples/IndexList", Models.BlogPost.ViewBlogPostz((string)Request.Session["filter"])]); }; Get["/ms_iot_Community_Samples/Filter/{idfilter}/{titlefilter}/{summaryfilter}/{codefilter}/{tagsfilter}/{tagsfilter2}"] = parameters => { char[] sep = new char[] { '~' }; string[] tupl; var filters = new List <Tuple <string, string> >(); string filter = parameters.idfilter; filter = filter.Replace("Z", "+"); filter = filter.Replace("z", "/"); filter = filter.Trim(); if (filter != "") { tupl = filter.Split(sep); if (tupl.Length == 2) { if (tupl[0] != "") { if (Models.BlogPost.Fields.Contains(tupl[0])) { if (tupl[1] != "") { filters.Add(new Tuple <string, string>(tupl[0], tupl[1])); } } } } } filter = parameters.titlefilter; filter = filter.Replace("Z", "+"); filter = filter.Replace("z", "/"); filter = filter.Trim(); if (filter != "") { tupl = filter.Split(sep); if (tupl.Length == 2) { if (tupl[0] != "") { if (Models.BlogPost.Fields.Contains(tupl[0])) { if (tupl[1] != "") { filters.Add(new Tuple <string, string>(tupl[0], tupl[1])); } } } } } filter = parameters.summaryfilter; filter = filter.Replace("Z", "+"); filter = filter.Replace("z", "/"); filter = filter.Trim(); if (filter != "") { tupl = filter.Split(sep); if (tupl.Length == 2) { if (tupl[0] != "") { if (Models.BlogPost.Fields.Contains(tupl[0])) { if (tupl[1] != "") { filters.Add(new Tuple <string, string>(tupl[0], tupl[1])); } } } } } filter = parameters.codefilter; filter = filter.Replace("Z", "+"); filter = filter.Replace("Y", "/"); filter = filter.Trim(); if (filter != "") { tupl = filter.Split(sep); if (tupl.Length == 2) { if (tupl[0] != "") { if (Models.BlogPost.Fields.Contains(tupl[0])) { if (tupl[1] != "") { filters.Add(new Tuple <string, string>(tupl[0], tupl[1])); } } } } } filter = parameters.tagsfilter; filter = filter.Replace("Z", "+"); filter = filter.Replace("Y", "/"); filter = filter.Trim(); if (filter != "") { tupl = filter.Split(sep); if (tupl.Length == 2) { if (tupl[0] != "") { if (Models.BlogPost.Fields.Contains(tupl[0])) { if (tupl[1] != "") { filters.Add(new Tuple <string, string>(tupl[0], tupl[1])); } } } } } filter = parameters.tagsfilter2; filter = filter.Replace("Z", "+"); filter = filter.Replace("z", "/"); filter = filter.Trim(); if (filter != "") { tupl = filter.Split(sep); if (tupl.Length == 2) { if (tupl[0] != "") { if (Models.BlogPost.Fields.Contains(tupl[0])) { if (tupl[1] != "") { filters.Add(new Tuple <string, string>(tupl[0], tupl[1])); } } } } } Models.FilterAndSortInfo fi; if ((string)Request.Session["filter"] == null) { fi = new Models.FilterAndSortInfo(); } else if ((string)Request.Session["filter"] == "") { fi = new Models.FilterAndSortInfo(); } else { JsonSerializerSettings set = new JsonSerializerSettings(); set.MissingMemberHandling = MissingMemberHandling.Ignore; fi = JsonConvert.DeserializeObject <Models.FilterAndSortInfo>((string)Request.Session["filter"], set); } //For filter remove any pre-existing sorting (but for sort don't remove pre-existing sorting) fi.Filters = filters; fi.SortString = ""; string json = JsonConvert.SerializeObject(fi); Request.Session["filter"] = json; return(View["/ms_iot_Community_Samples/IndexList", Models.BlogPost.ViewBlogPostz((string)Request.Session["filter"])]); }; }
public MediaPresenterService(AppDbContext db, MarkdownService markdown) { _db = db; _markdown = markdown; }
public CommandResult Execute(NewPostCommand command) { //TODO:应该验证TitleSlug是否唯一 var contentProvider = new FileContentProvider(null, Encoding.UTF8); var parser = new MarkdownService(contentProvider); var content = parser.ToHtml(command.MarkDown); var post = new BlogPost { Id = ObjectId.NewObjectId(), AuthorEmail = command.Author.Email, AuthorDisplayName = command.Author.DisplayName, MarkDown = command.MarkDown, Content = content, PubDate = command.PubDate.CloneToUtc(), Status = command.Published ? PublishStatus.Published : PublishStatus.Draft, Title = command.Title, TitleSlug = command.TitleSlug.IsNullOrWhitespace() ? command.Title.Trim().ToSlug() : command.TitleSlug.Trim().ToSlug(), DateUTC = DateTime.UtcNow }; using (var db = new LiteDatabase(_dbConfig.DbPath)) { if (!command.Tags.IsNullOrWhitespace()) { var tags = command.Tags.AsTags(); post.Tags = tags.Keys.ToArray(); var tagCol = db.GetCollection <Tag>(DBTableNames.Tags); foreach (var kv in tags) { var slug = kv.Key; var tag = kv.Value; if (string.IsNullOrWhiteSpace(tag)) { continue; } var entry = tagCol.FindOne(t => t.Slug.Equals(slug)); if (entry != null) { entry.PostCount++; tagCol.Update(entry); } else { entry = new Tag { Id = ObjectId.NewObjectId(), Slug = slug, Name = tag, PostCount = 1 }; tagCol.Insert(entry); } } tagCol.EnsureIndex(t => t.PostCount); } else { post.Tags = new string[] { }; } var blogPostCol = db.GetCollection <BlogPost>(DBTableNames.BlogPosts); blogPostCol.Insert(post); return(CommandResult.SuccessResult); } }
public MarkdownController() { markdownService = new MarkdownService(); }
public CommandResult Execute(EditPostCommand command) { using (var db = new LiteDatabase(_dbConfig.DbPath)) { var blogPostCol = db.GetCollection <BlogPost>(DBTableNames.BlogPosts); var post = blogPostCol.FindById(command.PostId); if (post == null) { throw new ApplicationException("Post with id: {0} was not found".FormatWith(command.PostId)); } if (post.Tags != null) { var tagCol = db.GetCollection <Tag>(DBTableNames.Tags); foreach (var tag in post.Tags) { var slug = tag.ToSlug(); var tagEntry = tagCol.FindOne(x => x.Slug.Equals(slug)); if (tagEntry != null) { tagEntry.PostCount--; tagCol.Update(tagEntry); } } } var contentProvider = new FileContentProvider(null, Encoding.UTF8); var parser = new MarkdownService(contentProvider); var content = parser.ToHtml(command.MarkDown); //TODO:应该验证TitleSlug是否是除了本文外唯一的 post.MarkDown = command.MarkDown; post.Content = content; post.PubDate = command.PubDate.CloneToUtc(); post.Status = command.Published ? PublishStatus.Published : PublishStatus.Draft; post.Title = command.Title; post.TitleSlug = command.TitleSlug.Trim().ToSlug(); if (!command.Tags.IsNullOrWhitespace()) { var tags = command.Tags.AsTags(); post.Tags = tags.Keys.ToArray(); var tagCol = db.GetCollection <Tag>(DBTableNames.Tags); foreach (var kv in tags) { var slug = kv.Key; var tag = kv.Value; var entry = tagCol.FindOne(x => x.Slug.Equals(slug)); if (entry != null) { entry.PostCount++; tagCol.Update(entry); } else { entry = new Tag { Id = ObjectId.NewObjectId(), Slug = slug, Name = tag, PostCount = 1 }; tagCol.Insert(entry); } } } else { post.Tags = new string[] { }; } db.GetCollection <BlogPost>(DBTableNames.BlogPosts).Update(post); return(CommandResult.SuccessResult); } }