public void Simple() { var markdown = new Markdown { NewWindowForExternalLinks = true }; Console.WriteLine(markdown.Transform("##Header")); Console.WriteLine(markdown.Transform("`<T>`")); Console.WriteLine(markdown.Transform("[a](http://e1.ru)")); }
public static IHtmlString CompiledContent(this IDynamicContent contentItem, bool trustContent = false) { if (contentItem == null) return NonEncodedHtmlString.Empty; switch (contentItem.ContentType) { case DynamicContentType.Markdown: var md = new Markdown { AutoHeadingIDs = true, ExtraMode = true, NoFollowLinks = !trustContent, SafeMode = false, NewWindowForExternalLinks = true, }; var contents = contentItem.Content; // TODO contents = CodeBlockFinder.Replace(contents, match => GenerateCodeBlock(match.Groups[1].Value.Trim(), match.Groups[2].Value)); contents = md.Transform(contents); return new NonEncodedHtmlString(contents); case DynamicContentType.Html: return trustContent ? new NonEncodedHtmlString(contentItem.Content) : NonEncodedHtmlString.Empty; } return NonEncodedHtmlString.Empty; }
public static MvcHtmlString CompiledContent(this IDynamicContent contentItem, bool trustContent) { if (contentItem == null) return MvcHtmlString.Empty; switch (contentItem.ContentType) { case DynamicContentType.Markdown: var md = new Markdown { AutoHeadingIDs = true, ExtraMode = true, NoFollowLinks = !trustContent, SafeMode = false, NewWindowForExternalLinks = true, }; var contents = contentItem.Body; contents = CodeBlockFinder.Replace(contents, match => GenerateCodeBlock(match.Groups[1].Value.Trim(), match.Groups[2].Value)); try { contents = md.Transform(contents); } catch (Exception) { contents = string.Format("<pre>{0}</pre>", HttpUtility.HtmlEncode(contents)); } return MvcHtmlString.Create(contents); case DynamicContentType.Html: return trustContent ? MvcHtmlString.Create(contentItem.Body) : MvcHtmlString.Empty; } return MvcHtmlString.Empty; }
public static string ResolveMarkdown(this string content, IDocsOutput output, string currentSlug) { // http://www.toptensoftware.com/markdowndeep/api var md = new Markdown { AutoHeadingIDs = true, ExtraMode = true, NoFollowLinks = false, SafeMode = false, HtmlClassTitledImages = "figure", UrlRootLocation = output.RootUrl, }; if (!string.IsNullOrWhiteSpace(output.RootUrl)) { if (!string.IsNullOrWhiteSpace(currentSlug) && !currentSlug.Equals("index")) md.UrlBaseLocation = output.RootUrl + "/" + currentSlug.Replace('\\', '/'); else md.UrlBaseLocation = output.RootUrl; } ////if (!string.IsNullOrWhiteSpace(output.ImagesPath)) // md.QualifyUrl = delegate(string image) { return output.ImagesPath + "/" + image; }; md.PrepareImage = (tag, titledImage) => PrepareImage(output.ImagesPath, tag); return md.Transform(content); }
public ActionResult Show(string page) { if (page == "" || page == null) page = "README"; string path = string.Concat(HttpContext.Request.PhysicalApplicationPath, "\\Docs\\", page, ".md"); string contents; try { using (StreamReader sr = new StreamReader(path)) { Markdown md = new Markdown(); contents = md.Transform(sr.ReadToEnd()); } ViewBag.ConvertedMarkdown = contents; return View(); } catch (Exception ex) { this.Response.StatusCode = 404; ViewBag.ConvertedMarkdown = "File not found."; return View(); } }
static void Main(string[] args) { Markdown m = new Markdown(); m.SafeMode = false; m.ExtraMode = true; m.AutoHeadingIDs = true; // m.SectionHeader = "<div class=\"header\">{0}</div>\n"; // m.SectionHeadingSuffix = "<div class=\"heading\">{0}</div>\n"; // m.SectionFooter = "<div class=\"footer\">{0}</div>\n\n"; // m.SectionHeader = "\n<div class=\"section_links\"><a href=\"/edit?section={0}\">Edit</a></div>\n"; // m.HtmlClassTitledImages = "figure"; // m.DocumentRoot = "C:\\users\\bradr\\desktop"; // m.DocumentLocation = "C:\\users\\bradr\\desktop\\100D5000"; // m.MaxImageWidth = 500; string markdown=FileContents("input.txt"); string str = m.Transform(markdown); Console.Write(str); var sections = MarkdownDeep.Markdown.SplitSections(markdown); for (int i = 0; i < sections.Count; i++) { Console.WriteLine("---- Section {0} ----", i); Console.Write(sections[i]); Console.WriteLine("\n"); } Console.WriteLine("------------------"); }
private Negotiator GetDocument(IDocumentFolder documentFolder, string path) { var markdown = documentFolder.ReadAllText(path); var converter = new Markdown(); var html = converter.Transform(markdown); return View["Index", new { Title = path, Content = html }]; }
public static string ValueForColumn(this string[] rowValues, IMarkdownTable table, string[] possibleHeaderNames, List <string> usedColumns = null, bool removeMarkdownSyntax = true) { if (usedColumns == null) { usedColumns = new List <string>(); } var headers = table.ColumnHeaders; foreach (var headerName in possibleHeaderNames.Except(usedColumns)) { int index = headers.IndexOf(headerName); if (index >= 0 && index < rowValues.Length) { // Check to see if we need to clean up / remove any formatting marks string tableCellContents = rowValues[index]; if (removeMarkdownSyntax && !string.IsNullOrEmpty(tableCellContents)) { tableCellContents = converter.Transform(tableCellContents).TrimEnd(); } usedColumns.Add(headerName); return(tableCellContents); } } Debug.WriteLine("Failed to find header matching '{0}' in table with headers: {1}", possibleHeaderNames.ComponentsJoinedByString(","), table.ColumnHeaders.ComponentsJoinedByString(",")); return(null); }
public static string Markdown(string text) { if (text == null) return ""; var md = new Markdown(); return md.Transform(text.Trim()); }
static void TestMarkdownDeep() { var result = new Result { Name = "MarkdownDeep" }; var stopwatch = Stopwatch.StartNew(); var warmup = new MarkdownDeep.Markdown { ExtraMode = true, MarkdownInHtml = true, SafeMode = false, }; stopwatch.Stop(); result.WarmUp = stopwatch.ElapsedMilliseconds; warmup.Transform(testTexts.First()); stopwatch = Stopwatch.StartNew(); var markdownify = new MarkdownDeep.Markdown { ExtraMode = true, MarkdownInHtml = true, SafeMode = false, }; stopwatch.Stop(); result.Construction = stopwatch.ElapsedMilliseconds; stopwatch = Stopwatch.StartNew(); markdownify.Transform(testTexts.First()); stopwatch.Stop(); result.FirstRun = stopwatch.ElapsedMilliseconds; stopwatch = Stopwatch.StartNew(); foreach (var text in testTexts) { markdownify.Transform(text); } stopwatch.Stop(); result.BulkRun = stopwatch.ElapsedMilliseconds; result.Average = GetAverage(stopwatch.ElapsedMilliseconds); results.Add(result); }
/// <summary> /// Converts the markdown to HTML. /// </summary> /// <param name="toConvert">The markdown string to convert.</param> /// <param name="destinationDocumentPath">The document path (without the document filename).</param> /// <param name="siteRoot">The site root.</param> /// <param name="sourceDocumentFilename">the filename of the source markdown file</param> /// <param name="createdAnchorCollector">The created anchor collector, for ToC sublinks for H2 headers.</param> /// <param name="convertLocalLinks">if set to <c>true</c>, convert local links to md files to target files.</param> /// <param name="navigationContext">The navigation context.</param> /// <returns></returns> public static string ConvertMarkdownToHtml(string toConvert, string destinationDocumentPath, string siteRoot, string sourceDocumentFilename, List <Heading> createdAnchorCollector, bool convertLocalLinks, NavigationContext navigationContext) { var localLinkProcessor = new Func <string, string>(s => { var result = s; if (!string.IsNullOrWhiteSpace(result)) { switch (navigationContext.PathSpecification) { case PathSpecification.Full: break; case PathSpecification.Relative: break; case PathSpecification.RelativeAsFolder: // Step 1: we need to move up 1 additional folder (get out of current subfolder) var relativeAsFolderIndex = result.StartsWith("./") ? 2 : 0; result = result.Insert(relativeAsFolderIndex, "../"); // Step 2: we need an additional layer to go into (filename is now a folder) result = ResolveTargetURL(result, false, navigationContext); // Step 3: get the final url result = result.GetFinalTargetUrl(navigationContext); break; default: throw new ArgumentOutOfRangeException(nameof(navigationContext.PathSpecification), navigationContext.PathSpecification, null); } } return(result); }); var parser = new MarkdownDeep.Markdown { ExtraMode = true, GitHubCodeBlocks = true, AutoHeadingIDs = true, NewWindowForExternalLinks = true, DocNetMode = true, ConvertLocalLinks = convertLocalLinks, LocalLinkProcessor = localLinkProcessor, DestinationDocumentLocation = destinationDocumentPath, DocumentRoot = siteRoot, SourceDocumentFilename = sourceDocumentFilename, HtmlClassTitledImages = "figure", }; var toReturn = parser.Transform(toConvert); createdAnchorCollector.AddRange(parser.Headings.ConvertToHierarchy()); return(toReturn); }
private void ShowReleaseNotesDialog_Load(object sender, EventArgs e) { string contents = File.ReadAllText(_path); var md = new Markdown(); _temp = TempFile.WithExtension("htm"); //enhance: will leek a file to temp File.WriteAllText(_temp.Path, md.Transform(contents)); _browser.Url = new Uri(_temp.Path); }
/// <summary> /// Transforms a string of Markdown into HTML. /// </summary> /// <param name="text">The Markdown that should be transformed.</param> /// <returns>The HTML representation of the supplied Markdown.</returns> public static IHtmlString Markdown(string text) { // Transform the supplied text (Markdown) into HTML. var markdownTransformer = new Markdown(); var html = markdownTransformer.Transform(text); // Wrap the html in an MvcHtmlString otherwise it'll be HtmlEncoded and displayed to the user as HTML :( return html.ToHtmlString(); }
private void ShowReleaseNotesDialog_Load(object sender, EventArgs e) { string contents = File.ReadAllText(_path); var md = new Markdown(); // Disposed of during dialog Dispose() _temp = TempFile.WithExtension("htm"); File.WriteAllText(_temp.Path, GetBasicHtmlFromMarkdown(md.Transform(contents))); _browser.Url = new Uri(_temp.Path); }
public static string Markdown(this string txt) { if (string.IsNullOrEmpty(txt)) return string.Empty; // spaces in urls will not work with MarkdownDeep txt = Regex.Replace(txt, @"\(http(.*)\)", match => match.ToString().Replace(" ", "%20")); // single linebreaks become double linebreaks to conform LeTour markdown var md = new Markdown(); txt = md.Transform(txt); txt = Regex.Replace(txt, @"(?<!(</p>))\n(?!\n)", match => "<br/>"); return txt; }
public void TransformMarkdown() { var markdownEngine = new Markdown { ExtraMode = true, AutoHeadingIDs = true, CodeBlockLanguageAttr = " data-language=\"{0}\"" }; this.Body = markdownEngine.Transform(this.Body); }
public void Render(Document input, Document output) { output.Extension = ".html"; var mark = new Markdown(); //set preferences of your markdown mark.SafeMode = true; mark.ExtraMode = true; string mdtext = input.Text; output.Text = mark.Transform(mdtext); }
public KnowledgeBase() { string code = Helpers.GlobalHelper.RequestParam("code"); string appDataPath = System.Web.HttpContext.Current.Server.MapPath("~/assets"); string readFilePath = ""; string input = "Something went wrong"; if (code == "pptpwindows") { readFilePath = System.IO.Path.Combine(appDataPath, "knowledgebase", "pptp", "windows.md"); input = System.IO.File.ReadAllText(readFilePath); } else if (code == "pptpandroid") { readFilePath = System.IO.Path.Combine(appDataPath, "knowledgebase", "pptp", "android.md"); input = System.IO.File.ReadAllText(readFilePath); } else if (code == "pptpubuntu") { readFilePath = System.IO.Path.Combine(appDataPath, "knowledgebase", "pptp", "ubuntu.md"); input = System.IO.File.ReadAllText(readFilePath); } else if (code == "openvpnubuntu") { readFilePath = System.IO.Path.Combine(appDataPath, "knowledgebase", "openvpn", "ubuntu.md"); input = System.IO.File.ReadAllText(readFilePath); } else if (code == "openvpnwindows") { readFilePath = System.IO.Path.Combine(appDataPath, "knowledgebase", "openvpn", "windows.md"); input = System.IO.File.ReadAllText(readFilePath); } else if (code == "openvpnandroid") { readFilePath = System.IO.Path.Combine(appDataPath, "knowledgebase", "openvpn", "android.md"); input = System.IO.File.ReadAllText(readFilePath); } var md = new MarkdownDeep.Markdown(); md.ExtraMode = true; md.SafeMode = false; _output = md.Transform(input); }
public override void Render(Context context, StreamReader reader, StreamWriter writer) { var mark = new Markdown(); //set preferences of your markdown mark.SafeMode = true; mark.ExtraMode = true; string mdtext = reader.ReadToEnd(); string htmlmd = mark.Transform(mdtext); writer.Write(htmlmd); }
public KnowledgeBase(string code, string appDataPath) { string readFilePath = ""; string input = "Something went wrong"; if (code == "pptpwindows") { readFilePath = System.IO.Path.Combine(appDataPath, "knowledgebase", "pptp", "windows.md"); input = System.IO.File.ReadAllText(readFilePath); } else if (code == "pptpandroid") { readFilePath = System.IO.Path.Combine(appDataPath, "knowledgebase", "pptp", "android.md"); input = System.IO.File.ReadAllText(readFilePath); } else if (code == "pptpubuntu") { readFilePath = System.IO.Path.Combine(appDataPath, "knowledgebase", "pptp", "ubuntu.md"); input = System.IO.File.ReadAllText(readFilePath); } else if (code == "openvpnubuntu") { readFilePath = System.IO.Path.Combine(appDataPath, "knowledgebase", "openvpn", "ubuntu.md"); input = System.IO.File.ReadAllText(readFilePath); } else if (code == "openvpnwindows") { readFilePath = System.IO.Path.Combine(appDataPath, "knowledgebase", "openvpn", "windows.md"); input = System.IO.File.ReadAllText(readFilePath); } else if (code == "openvpnandroid") { readFilePath = System.IO.Path.Combine(appDataPath, "knowledgebase", "openvpn", "android.md"); input = System.IO.File.ReadAllText(readFilePath); } var md = new MarkdownDeep.Markdown(); md.ExtraMode = true; md.SafeMode = false; _output = md.Transform(input); }
public static string FormatMessage(String originalMessage, bool processContent = true) { //Test changes to this code against this markdown thread content: //https://voat.co/v/test/comments/53891 if (processContent && !String.IsNullOrEmpty(originalMessage)) { originalMessage = ContentProcessor.Instance.Process(originalMessage, ProcessingStage.Outbound, null); } var newWindow = false; if (System.Web.HttpContext.Current != null && System.Web.HttpContext.Current.User.Identity.IsAuthenticated) { newWindow = UserHelper.LinksInNewWindow(System.Web.HttpContext.Current.User.Identity.Name); } var m = new Markdown { PrepareLink = new Func<HtmlTag, bool>(x => { //Remove [Title](javascript:alter('hello')) exploit string href = x.attributes["href"]; if (!String.IsNullOrEmpty(href)) { //I think it needs the javascript: prefix to work at all but there might be more holes as this is just a simple check. if (href.ToLower().Trim().StartsWith("javascript:")) { x.attributes["href"] = "#"; //add it to the output for verification? x.attributes.Add("data-ScriptStrip", String.Format("/* script detected: {0} */", href)); } } return true; }), ExtraMode = true, SafeMode = true, NewWindowForExternalLinks = newWindow, NewWindowForLocalLinks = newWindow }; try { return m.Transform(originalMessage); } catch (Exception ex) { return "Content contains unsafe or unknown tags."; } }
public static MvcHtmlString CompiledMarkdownContent(this string str, bool trustContent = false) { if (str == null) return MvcHtmlString.Empty; var md = new Markdown { AutoHeadingIDs = true, ExtraMode = true, NoFollowLinks = !trustContent, SafeMode = false, NewWindowForExternalLinks = true, }; var contents = md.Transform(str); return MvcHtmlString.Create(contents); }
private static string FormatMarkdown(string content) { var md = new Markdown(); string result; try { result = md.Transform(content); } catch (Exception) { result = string.Format("<pre>{0}</pre>", HttpUtility.HtmlEncode(content)); } return result; }
public static MvcHtmlString RenderMarkdown(this HtmlHelper helper, string filename) { // Load source text var text = File.ReadAllText(helper.ViewContext.HttpContext.Server.MapPath(filename)); // Setup processor var md = new Markdown(); md.SafeMode = false; md.ExtraMode = true; md.AutoHeadingIDs = true; md.MarkdownInHtml = true; md.NewWindowForExternalLinks = true; // Write it return new MvcHtmlString(md.Transform(text)); }
public string DoTransformation() { if (File.Exists(_filePath)) { string text = File.ReadAllText(_filePath); var clean = Regex.Replace(text, MarkdownLogic.RegEx, new MatchEvaluator(match => LinkEvaluator(match, PrefixLinks)), RegexOptions.Singleline | RegexOptions.IgnorePatternWhitespace); Markdown md = new Markdown(); string transform = md.Transform(clean); return transform; } return "<h2>Not Found</h2>"; }
/// <summary> /// performs a rough benchmark of the Markdown engine using small, medium, and large input samples /// please DO NOT MODIFY the input samples or the benchmark itself as this will invalidate previous /// benchmark runs! /// </summary> static void Benchmark(string text, int iterations) { var m = new Markdown(); var sw = new Stopwatch(); sw.Start(); for (int i = 0; i < iterations; i++) m.Transform(text); sw.Stop(); Console.WriteLine("input string length: " + text.Length); Console.Write(iterations + " iteration" + (iterations == 1 ? "" : "s") + " in " + sw.ElapsedMilliseconds + " ms"); if (iterations == 1) Console.WriteLine(); else Console.WriteLine(" (" + Convert.ToDouble(sw.ElapsedMilliseconds) / Convert.ToDouble(iterations) + " ms per iteration)"); }
public static IHtmlString ContentBlob(this HtmlHelper helper, string path) { var context = helper.ViewContext.HttpContext; var file = context.Server.MapPath(string.Format("~/app_content/{0}.md", path)); if ( File.Exists(file) ) { using (StreamReader sr = new StreamReader(file)) { string text = sr.ReadToEnd(); var markdown = new MarkdownDeep.Markdown(); return MvcHtmlString.Create(markdown.Transform(text)); } } return MvcHtmlString.Create("<em>Missing " + file + "</em>"); }
public void Execute() { Mapper.CreateMap<Post, PostDetailViewModel>() .ForMember(vm=>vm.Tags, p=>p.Ignore()); var md = new Markdown(); md.SafeMode = true; md.ExtraMode = true; Mapper.CreateMap<Post, PostListViewModel>() .ForMember(vm=>vm.Content, opt=>opt.MapFrom(p=> md.Transform( p.Content.Length>500 ? p.Content.Substring(0,500) : p.Content))); Mapper.CreateMap<PostInput, Post>() .ForMember(p=>p.Tags, i=>i.Ignore()) .ForMember(p => p.LocationOfWriting, opt => opt.MapFrom(i => new Location { Latitude = i.Latitude, Longitude = i.Longitude })); Mapper.CreateMap<Post, PostInput>() .ForMember(i => i.Latitude, opt => opt.MapFrom(p => p.LocationOfWriting.Latitude)) .ForMember(i => i.Longitude, opt => opt.MapFrom(p => p.LocationOfWriting.Longitude)); }
static void TestMarkdownDeep() { var result = new Result {Name = "MarkdownDeep"}; var stopwatch = Stopwatch.StartNew(); var warmup = new MarkdownDeep.Markdown { ExtraMode = true, MarkdownInHtml = true, SafeMode = false, }; stopwatch.Stop(); result.WarmUp = stopwatch.ElapsedMilliseconds; warmup.Transform(testTexts.First()); stopwatch = Stopwatch.StartNew(); var markdownify = new MarkdownDeep.Markdown { ExtraMode = true, MarkdownInHtml = true, SafeMode = false, }; stopwatch.Stop(); result.Construction = stopwatch.ElapsedMilliseconds; stopwatch = Stopwatch.StartNew(); markdownify.Transform(testTexts.First()); stopwatch.Stop(); result.FirstRun = stopwatch.ElapsedMilliseconds; stopwatch = Stopwatch.StartNew(); foreach (var text in testTexts) { markdownify.Transform(text); } stopwatch.Stop(); result.BulkRun = stopwatch.ElapsedMilliseconds; result.Average = GetAverage(stopwatch.ElapsedMilliseconds); results.Add(result); }
public void ProcessRequest(HttpContext context) { var lastSlashIndex = context.Request.Url.AbsolutePath.LastIndexOf('/'); var fileName = context.Request.Url.AbsolutePath.Substring(lastSlashIndex + 1); var filePath = context.Server.MapPath(Path.Combine("Markdown",fileName)); string markdownString = String.Empty; try { markdownString = File.ReadAllText(filePath); } catch (FileNotFoundException exc) { } var markdownTransformer = new Markdown(); string html = markdownTransformer.Transform(markdownString); context.Response.Write(html); }
public static string ResolveMarkdown(this string content, IDocsOutput output, string trail, string versionUrl) { // http://www.toptensoftware.com/markdowndeep/api var md = new Markdown { AutoHeadingIDs = true, ExtraMode = true, NoFollowLinks = false, SafeMode = false, HtmlClassTitledImages = "figure", UrlRootLocation = output.RootUrl, }; if (!string.IsNullOrWhiteSpace(output.RootUrl)) { md.PrepareLink = tag => PrepareLink(tag, output.RootUrl, trail, versionUrl); } md.PrepareImage = (tag, titledImage) => PrepareImage(output.ImagesPath, tag); return md.Transform(content); }
public ActionResult Edit(GameViewModel gamevm) { Game game = gamevm.Game; if (ModelState.IsValid) { Markdown md = new MarkdownDeep.Markdown(); game.Report = md.Transform(game.ReportMarkdown); gamedao.Update(game); return(RedirectToAction("Details", "Game", new { id = game.Id })); } else { Game g = gamedao.GetById(game.Id); gamevm.Stats = g.Stats.ToList(); gamevm.PlayerStats = g.PlayerStats.ToList(); ViewBag.PeriodsItems = listItems.UnsetPeriods(g.Stats.ToList <GameStats>()); ViewBag.PlayersItems = listItems.UnsetPlayers(g.PlayerStats.ToList <PlayerStats>()); ViewBag.PlaceItems = listItems.Places(); return(View(gamevm)); } }
/// <summary> /// Converts the markdown to HTML. /// </summary> /// <param name="toConvert">The markdown string to convert.</param> /// <param name="destinationDocumentPath">The document path (without the document filename).</param> /// <param name="siteRoot">The site root.</param> /// <param name="sourceDocumentFilename">the filename of the source markdown file</param> /// <param name="createdAnchorCollector">The created anchor collector, for ToC sublinks for H2 headers.</param> /// <param name="convertLocalLinks">if set to <c>true</c>, convert local links to md files to target files.</param> /// <returns></returns> public static string ConvertMarkdownToHtml(string toConvert, string destinationDocumentPath, string siteRoot, string sourceDocumentFilename, List <Heading> createdAnchorCollector, bool convertLocalLinks) { var parser = new MarkdownDeep.Markdown { ExtraMode = true, GitHubCodeBlocks = true, AutoHeadingIDs = true, NewWindowForExternalLinks = true, DocNetMode = true, ConvertLocalLinks = convertLocalLinks, DestinationDocumentLocation = destinationDocumentPath, DocumentRoot = siteRoot, SourceDocumentFilename = sourceDocumentFilename, HtmlClassTitledImages = "figure", }; var toReturn = parser.Transform(toConvert); createdAnchorCollector.AddRange(parser.Headings.ConvertToHierarchy()); return(toReturn); }
/// <summary> /// /// </summary> /// <param name="id"></param> /// <param name="errorFromCommentInput">true, if errors occurred while saving comment</param> /// <returns></returns> public ActionResult Detail(int id, bool errorFromCommentInput=false) { //ViewBag.FaceBookAppId = ConfigurationManager.AppSettings["facebook.appid"]; //ViewBag.FaceBookAppSecret = ConfigurationManager.AppSettings["facebook.appsecret"]; var post = DbContext.Posts.SingleOrDefault(p => p.Id == id); if (post == null) return HttpNotFound(); var md = new Markdown(); md.SafeMode = true; md.ExtraMode = true; post.Content = md.Transform(post.Content); var postDetailViewModel = Mapper.Map<Post, PostDetailViewModel>(post); postDetailViewModel.Tags = post.Tags.ConverTagToStringArray(); // set Commenter to post comment var commentInputData = TempData["commentInputData"] as CommentInput; // tempdata when modelstateerror occurred in /Comment/Write if (errorFromCommentInput && commentInputData != null) { var modelStateErrors = TempData["commentInputDataErrors"] as Dictionary<string, string>; foreach (var item in modelStateErrors) { ModelState.AddModelError(item.Key, item.Value); } postDetailViewModel.CommentInput = commentInputData as CommentInput; } else { SetCommenter(postDetailViewModel); } return View("Detail", postDetailViewModel); }
public static MvcHtmlString CompiledContent(this IDynamicContent contentItem, bool trustContent = false) { if (contentItem == null) return MvcHtmlString.Empty; switch (contentItem.ContentType) { case DynamicContentType.Markdown: var md = new Markdown { AutoHeadingIDs = true, ExtraMode = true, NoFollowLinks = !trustContent, SafeMode = false, NewWindowForExternalLinks = true, }; var contents = contentItem.Content; contents = md.Transform(contents); return MvcHtmlString.Create(contents); case DynamicContentType.Html: return trustContent ? MvcHtmlString.Create(contentItem.Content) : MvcHtmlString.Empty; } return MvcHtmlString.Empty; }
public static IHtmlString CompiledStringContent(string content, DynamicContentType contentType, bool trustContent = false, int cropAt = 0) { switch (contentType) { case DynamicContentType.Markdown: var md = new Markdown { AutoHeadingIDs = true, ExtraMode = true, NoFollowLinks = !trustContent, SafeMode = false, NewWindowForExternalLinks = true, FormatCodeBlock = null, PrepareImage = (tag, b) => { string style = string.Empty; tag.attributes.TryGetValue("style", out style); style += "max-width:100%;"; tag.attributes["style"] = style; return true; }, }; if (cropAt > 0 && content.Length > cropAt) { content = content.Substring(0, cropAt) + "..."; } var contents = CodeBlockFinder.Replace(content, match => GenerateCodeBlock(match.Groups[1].Value.Trim(), match.Groups[2].Value)); contents = md.Transform(contents); return new NonEncodedHtmlString(contents); case DynamicContentType.Html: return trustContent ? new NonEncodedHtmlString(content) : NonEncodedHtmlString.Empty; } return NonEncodedHtmlString.Empty; }
public static IHtmlString MarkdownToHtml(this HtmlHelper helper, string markdownText) { Markdown markdown = new Markdown() { ExtraMode = true, SafeMode = true }; return MvcHtmlString.Create(markdown.Transform(markdownText)); }