public void Transform_givenLinksInline_generatesExpectedResult() { var text = LoadText("Links_inline_style.md"); var markdown = new Markdown(); var result = markdown.Transform(text); Approvals.Verify(AsXaml(result)); }
public void Transform_givenImages_generatesExpectedResult() { var text = LoadText("Images.md"); var markdown = new Markdown(); var result = markdown.Transform(text); Approvals.Verify(AsXaml(result)); }
public void ParagraphsWithHtmlBreakInMarkdown() { var input = "Foo\nbar\n\nHello\n\n<br />\nWorld"; var expected = "<p>Foo\nbar</p>\n<p>Hello</p>\n<p><br />\nWorld</p>\n"; var parser = new Markdown(); var actual = parser.Transform(input); Assert.AreEqual(expected, actual); }
public void HeaderSixWithAnchor() { var input = "###### Header{#Header}"; var expected = "<h6 id=\"Header\">Header</h6>\n"; var parser = new Markdown(); var actual = parser.Transform(input); Assert.AreEqual(expected, actual); }
public void HeaderSix() { var input = "###### Header"; var expected = "<h6>Header</h6>\n"; var parser = new Markdown(); var actual = parser.Transform(input); Assert.AreEqual(expected, actual); }
public void CodeBlockFenceWithLanguageSpecifier() { var input = "```C#\n[Header1](#Header2)\n# Header1{#Header2}\n```"; var expected = "<pre><code class=\"language-C#\">[Header1](#Header2)\n# Header1{#Header2}</code></pre>\n"; var parser = new Markdown(); var actual = parser.Transform(input); Assert.AreEqual(expected, actual); }
public void EscapedCodeBlockSpan() { var input = @"The quick brown \`fox\` jumped over the lazy dog."; var expected = "<p>The quick brown `fox` jumped over the lazy dog.</p>\n"; var parser = new Markdown(); var actual = parser.Transform(input); Assert.AreEqual(expected, actual); }
public void CodeBlockSpanWithEscapedContent() { var input = @"The quick brown `` \`fox\` `` jumped over the lazy dog."; var expected = "<p>The quick brown <code>\\`fox\\` </code> jumped over the lazy dog.</p>\n"; var parser = new Markdown(); var actual = parser.Transform(input); Assert.AreEqual(expected, actual); }
public void CodeBlockFense() { var input = "```\n[Header1](#Header2)\n# Header1{#Header2}\n```"; var expected = "<pre><code>[Header1](#Header2)\n# Header1{#Header2}</code></pre>"; var parser = new Markdown(); var actual = parser.Transform(input); Assert.AreEqual(expected, actual); }
static void Main(string[] args) { string markdown = File.ReadAllText(args[0]); var md = new Markdown(); string html = md.Transform(markdown); Console.WriteLine(html); }
public void DoesNothingIfMetadataKeyDoesNotExist() { // Given IDocument document = Substitute.For<IDocument>(); document.ContainsKey("meta").Returns(false); IExecutionContext context = Substitute.For<IExecutionContext>(); Markdown markdown = new Markdown("meta"); // When markdown.Execute(new[] { document }, context).ToList(); // Make sure to materialize the result list // Then context.Received(0).GetDocument(Arg.Any<IDocument>(), Arg.Any<string>()); context.Received(0).GetDocument(Arg.Any<IDocument>(), Arg.Any<IEnumerable<KeyValuePair<string, object>>>()); }
public void SetUp() { markdown = new Markdown(); message1 = new MessageViewModel { AuthorName = "Dianne", ID = 1, RoomID = 12345, Text = "Test!" }; mockRoomViewModelReader = new Mock<IRoomViewModelReader>(); var roomMessages = new MessageViewModel[] { message1 }; mockRoomViewModelReader.Setup(reader => reader.GetRoomMessages(It.IsAny<int>())).Returns(roomMessages); }
public void DoesRenderSpecialAttributesIfExtensionsActive() { // Given string input = @"[link](url){#id .class}"; string output = @"<p><a href=""url"" id=""id"" class=""class"">link</a></p> ".Replace(Environment.NewLine, "\n"); IDocument document = Substitute.For<IDocument>(); document.Content.Returns(input); IExecutionContext context = Substitute.For<IExecutionContext>(); Markdown markdown = new Markdown().UseExtensions(); // When markdown.Execute(new[] { document }, context).ToList(); // Make sure to materialize the result list // Then context.Received(1).GetDocument(Arg.Any<IDocument>(), Arg.Any<string>()); context.Received().GetDocument(document, output); }
public void EscapesAtByDefault() { // Given string input = @"Looking @Good, Man!"; string output = @"<p>Looking @Good, Man!</p> "; IDocument document = Substitute.For<IDocument>(); document.Content.Returns(input); IExecutionContext context = Substitute.For<IExecutionContext>(); Markdown markdown = new Markdown(); // When markdown.Execute(new[] { document }, context).ToList(); // Make sure to materialize the result list // Then context.Received(1).GetDocument(Arg.Any<IDocument>(), Arg.Any<string>()); context.Received().GetDocument(document, output); }
public void DoesNotEscapeAtIfDisabled() { // Given string input = @"Looking @Good, Man!"; string output = @"<p>Looking @Good, Man!</p> "; IDocument document = Substitute.For<IDocument>(); document.Content.Returns(input); IExecutionContext context = Substitute.For<IExecutionContext>(); Markdown markdown = new Markdown().EscapeAt(false); // When markdown.Execute(new[] { document }, context).ToList(); // Make sure to materialize the result list // Then document.Received(1).Clone(Arg.Any<string>()); document.Received().Clone(output); }
public void RendersMarkdown() { // Given string input = @"Line 1 *Line 2* # Line 3"; string output = @"<p>Line 1 <em>Line 2</em></p> <h1>Line 3</h1> ".Replace(Environment.NewLine, "\n"); IDocument document = Substitute.For<IDocument>(); document.Content.Returns(input); IExecutionContext context = Substitute.For<IExecutionContext>(); Markdown markdown = new Markdown(); // When markdown.Execute(new[] { document }, context).ToList(); // Make sure to materialize the result list // Then context.Received(1).GetDocument(Arg.Any<IDocument>(), Arg.Any<string>()); context.Received().GetDocument(document, output); }
public Preprocessor(Markdown markdown) { filter = new Filter(); filter.Add("PUBLISH", publish => { var publishTypes = publish.Split(',').Select(e => e.Trim()).ToArray(); foreach (var publishType in publishTypes) { if (!markdown.AllSupportedAvailability.Contains( publishType, StringComparer.OrdinalIgnoreCase)) { throw new FilterPredicateException( Language.Message("PublishTypeNotRecognized", publishType)); } } return markdown.PublishFlags.Any( allowedPublishType => publishTypes.Any(pt => allowedPublishType.Equals(pt, StringComparison.OrdinalIgnoreCase))); }); }
public static string ConvertToPlainText(string markdown) { return(Markdown.ToPlainText(markdown, Pipeline)); }
/// <summary> /// @UE3 Parse each individual row of meta data /// </summary> /// <param name="match"></param> /// <returns></returns> private string ParseMetadataRow(Match match, TransformationData data, bool full = true) { var metaValue = match.Groups["MetadataValue"].Value; var metaDataCategory = match.Groups["MetadataKey"].Value; if (metaDataCategory.Contains(' ')) { data.ErrorList.Add( Markdown.GenerateError( Language.Message("MetadataNamesMustNotContainSpaces", metaDataCategory), MessageClass.Warning, metaDataCategory, data.ErrorList.Count, data)); } var metaDataCategoryLowerCase = metaDataCategory.ToLower(); // If value is blank change to paragraph for table creation classification form if (!String.IsNullOrWhiteSpace(match.Groups["MetadataValue"].Value)) { if (metaDataCategoryLowerCase == "title") { DocumentTitle = metaValue; } if (metaDataCategoryLowerCase == "seo-title") { SEOTitle = metaValue; } if (metaDataCategoryLowerCase == "crumbs") { CrumbsLinks.Add(metaValue); } if (metaDataCategoryLowerCase == "related" && full) { RelatedLinks.Add(data.Markdown.ProcessRelated(metaValue, data)); } if (metaDataCategoryLowerCase == "prereq" && full) { PrereqLinks.Add(data.Markdown.ProcessPrereqs(metaValue, data)); } if (metaDataCategoryLowerCase == "version") { EngineVersions.Add(Hash.FromAnonymousObject(new { version = metaValue, label = metaValue.Replace('.', '_') })); } if (metaDataCategoryLowerCase == "skilllevel") { SkillLevels.Add(metaValue); } if (metaDataCategoryLowerCase == "tags") { Tags.Add(CultureInfo.CurrentCulture.TextInfo.ToTitleCase(metaValue)); } } // Add meta data to the list, we require some specific meta data keys to be unique others can be duplicates if (metaDataCategoryLowerCase.Equals("title") || metaDataCategoryLowerCase.Equals("seo-title") || metaDataCategoryLowerCase.Equals("description") || metaDataCategoryLowerCase.Equals("seo-description") || metaDataCategoryLowerCase.Equals("template") || metaDataCategoryLowerCase.Equals("forcepublishfiles")) { if (MetadataMap.ContainsKey(metaDataCategoryLowerCase)) { data.ErrorList.Add( new ErrorDetail( Language.Message("DuplicateMetadataDetected", metaDataCategory), MessageClass.Info, "", "", 0, 0)); } else { var valueList = new List <string>(); valueList.Add(match.Groups["MetadataValue"].Value); MetadataMap.Add(metaDataCategoryLowerCase, valueList); } } else { if (MetadataMap.ContainsKey(metaDataCategoryLowerCase)) { MetadataMap[metaDataCategoryLowerCase].Add(match.Groups["MetadataValue"].Value); } else { var valueList = new List <string>(); valueList.Add(match.Groups["MetadataValue"].Value); MetadataMap.Add(metaDataCategoryLowerCase, valueList); } } // Return empty string, we are removing the meta data from the document return(""); }
private static string RenderMarkdown(string input) { return(Markdown.ToHtml(input)); }
public string ToHtml(string name, string md) => Markdown.ToHtml(md, GetOrAdd(name));
public static string ConvertToMarkdown(XmlNode Node, string Indent = "") { return(Markdown.ParseXml(Node, Indent, ResolveDoxygenLink)); }
public async Task <IActionResult> Search(string content) { if (content == null) { return(RedirectToAction(nameof(Index))); } var model = new IndexModel { ProblemModels = new List <ProblemModel>() }; if (long.TryParse(content, out long number)) { var p = _context.Problems.FirstOrDefault(p => p.Id == number); var pipeline = new MarkdownPipelineBuilder().UseAdvancedExtensions().UseBootstrap().Build(); var html = Markdown.ToHtml(p.Description, pipeline); var raw = Markdown.ToPlainText(p.Description); var author = await _userManager.FindByIdAsync(p.AuthorId); model.ProblemModels.Add(new ProblemModel { Id = p.Id, Title = p.Title, Description = p.Description, ContentRaw = raw, ContentHtml = html, AuthorId = p.AuthorId, Author = author.UserName, ExampleData = p.ExampleData, JudgeProfile = p.JudgeProfile, PassRate = p.PassRate, PublishTime = p.PublishTime }); } foreach (var p in _context.Problems.Where(x => x.Title.Contains(content)).ToList()) { var pipeline = new MarkdownPipelineBuilder().UseAdvancedExtensions().UseBootstrap().Build(); var html = Markdown.ToHtml(p.Description, pipeline); var raw = Markdown.ToPlainText(p.Description); var author = await _userManager.FindByIdAsync(p.AuthorId); model.ProblemModels.Add(new ProblemModel { Id = p.Id, Title = p.Title, Description = p.Description, ContentRaw = raw, ContentHtml = html, AuthorId = p.AuthorId, Author = author.UserName, ExampleData = p.ExampleData, JudgeProfile = p.JudgeProfile, PassRate = p.PassRate, PublishTime = p.PublishTime }); } return(View(model)); }
public RoomViewModelReaderMarkdownDecorator(IRoomViewModelReader @delegate, Markdown markdown) { this.@delegate = @delegate; this.markdown = markdown; }
private void ListView_SelectionChanged(object sender, SelectionChangedEventArgs e) { if (!(ListView.SelectedItem is Problem problem)) { return; } ProblemName.Text = problem.ProblemName; SpecialJudge.Text = problem.SpecialJudge; ExtraFiles.Text = StringArrCastToString(problem.ExtraFiles); InputFileName.Text = problem.InputFileName; OutputFileName.Text = problem.OutputFileName; CompileCommand.Text = problem.CompileCommand; AddDate.Content = problem.AddDate; DataSetsNumber.Text = problem.DataSets?.Length.ToString() ?? "0"; Level.Value = Convert.ToInt32(problem.Level); LevelShow.Content = Level.Value; Public.IsChecked = (problem.Option & 1) != 0; Description.Text = string.IsNullOrEmpty(problem.Description) ? Connection.GetProblemDescription(problem.ProblemId) : problem.Description; var pipeline = new MarkdownPipelineBuilder().UseAdvancedExtensions().Build(); var result = Properties.Resources.MarkdownStyleHead + "\n" + Markdown.ToHtml(Description.Text, pipeline) + "\n" + Properties.Resources.MarkdownStyleTail; var curDir = AppDomain.CurrentDomain.BaseDirectory.Replace("\\", "/"); if (curDir.EndsWith("/")) { curDir = curDir.Substring(0, curDir.Length - 1); } result = result.Replace("${ExtensionsDir}", "file://" + curDir + "/Extensions"); curDir = Environment.GetEnvironmentVariable("temp"); if (curDir.EndsWith("\\")) { curDir = curDir.Substring(0, curDir.Length - 1); } if (!string.IsNullOrEmpty(_curAddress)) { try { File.Delete(_curAddress); } catch { //ignored } } _curAddress = curDir + "\\" + Guid.NewGuid().ToString() + ".html"; File.WriteAllText(_curAddress, result, Encoding.Unicode); DescriptionViewer.Navigate(new Uri(_curAddress)); var a = problem.DataSets?.Length ?? 0; DataSetsNumber.Text = a.ToString(); while (ListBox.Items.Count > a) { foreach (var t in ListBox.Items) { if ((t as Grid)?.Name == $"Data{ListBox.Items.Count}") { (t as Grid).Children.Clear(); } } ListBox.Items.RemoveAt(ListBox.Items.Count - 1); } while (ListBox.Items.Count < a) { var strreader = new StringReader( Properties.Resources.DataSetControl.Replace("${index}", (ListBox.Items.Count + 1).ToString())); var xmlreader = new XmlTextReader(strreader); var obj = XamlReader.Load(xmlreader); ListBox.Items.Add((UIElement)obj); } for (var i = 0; i < ListBox.Items.Count; i++) { foreach (var t in ListBox.Items) { if ((t as Grid)?.Name != $"Data{i + 1}") { continue; } var b = (t as Grid).FindName($"Input{i + 1}") as TextBox; if (b != null) { b.Text = problem.DataSets?[i]?.InputFile ?? string.Empty; } b = (t as Grid).FindName($"Output{i + 1}") as TextBox; if (b != null) { b.Text = problem.DataSets?[i]?.OutputFile ?? string.Empty; } b = (t as Grid).FindName($"Time{i + 1}") as TextBox; if (b != null) { b.Text = problem.DataSets?[i]?.TimeLimit.ToString() ?? string.Empty; } b = (t as Grid).FindName($"Memory{i + 1}") as TextBox; if (b != null) { b.Text = problem.DataSets?[i]?.MemoryLimit.ToString() ?? string.Empty; } b = (t as Grid).FindName($"Score{i + 1}") as TextBox; if (b != null) { b.Text = problem.DataSets?[i]?.Score.ToString(CultureInfo.CurrentCulture) ?? string.Empty; } } } }
public void RunTestFile(string filename) { var parser = new Markdown(); var relactivePath = "../../TestFiles/"; var inputFile = relactivePath + filename + ".text"; var resultFile = relactivePath + filename + ".html"; var expected = File.ReadAllText(resultFile); var markdown = File.ReadAllText(inputFile); var actual = parser.Transform(markdown); // This is here so we can easily compare the difference in GIT. //File.WriteAllText(resultFile, actual); Assert.AreEqual(expected, actual); }
public void Version() { var parser = new Markdown(); Assert.IsTrue(parser.Version.StartsWith("1.16")); }
public void DoesNotRenderDefinitionListWithoutExtensions() { // Given string input = @"Apple : Pomaceous fruit of plants of the genus Malus in the family Rosaceae."; string output = @"<p>Apple : Pomaceous fruit of plants of the genus Malus in the family Rosaceae.</p> ".Replace(Environment.NewLine, "\n"); IDocument document = Substitute.For<IDocument>(); document.Content.Returns(input); IExecutionContext context = Substitute.For<IExecutionContext>(); Markdown markdown = new Markdown(); // When markdown.Execute(new[] { document }, context).ToList(); // Make sure to materialize the result list // Then context.Received(1).GetDocument(Arg.Any<IDocument>(), Arg.Any<string>()); context.Received().GetDocument(document, output); }
public MarkdownViewer() { Markdown = new Markdown(); }
public void RendersMarkdownFromMetadataToNewKey() { // Given string input = @"Line 1 *Line 2* # Line 3"; string output = @"<p>Line 1 <em>Line 2</em></p> <h1>Line 3</h1> ".Replace(Environment.NewLine, "\n"); IDocument document = Substitute.For<IDocument>(); document.ContainsKey("meta").Returns(true); document.String("meta").Returns(input); IExecutionContext context = Substitute.For<IExecutionContext>(); Markdown markdown = new Markdown("meta", "meta2"); // When markdown.Execute(new[] { document }, context).ToList(); // Make sure to materialize the result list // Then context.Received(0).GetDocument(Arg.Any<IDocument>(), Arg.Any<string>()); context.Received(1).GetDocument(Arg.Any<IDocument>(), Arg.Any<IEnumerable<KeyValuePair<string, object>>>()); context.Received().GetDocument(Arg.Any<IDocument>(), Arg.Is<IEnumerable<KeyValuePair<string, object>>>(x => x.SequenceEqual(new MetadataItems { { "meta2", output } }))); }
private void tableRowMarkdown(String name, String value, Profile profile) { String text; if (value == null) text = ""; else { text = value.Replace("||", "\r\n\r\n"); while (text.Contains("[[[")) { String left = text.Substring(0, text.IndexOf("[[[")); String linkText = text.Substring(text.IndexOf("[[[") + 3, text.IndexOf("]]]")); String right = text.Substring(text.IndexOf("]]]") + 3); var url = _pkp.GetLinkForProfileReference(profile, linkText); text = left + "[" + linkText + "](" + url + ")" + right; } } var mark = new Markdown(); //set preferences of your markdown mark.SafeMode = true; mark.ExtraMode = true; var formatted = mark.Transform(WebUtility.HtmlEncode(text)); write(" <tr><td>" + name + "</td><td>" + formatted + "</td></tr>\r\n"); }
public static string Transform(string original) { var markdown = new Markdown(); return(markdown.Transform(original)); }
/// <summary> /// @UE3 Parse each individual row of meta data /// </summary> /// <param name="match"></param> /// <returns></returns> private string ParseMetadataRow(Match match, TransformationData data) { var metaValue = match.Groups["MetadataValue"].Value; var metaDataCategory = match.Groups["MetadataKey"].Value; if (metaDataCategory.Contains(' ')) { data.ErrorList.Add( Markdown.GenerateError( Language.Message("MetadataNamesMustNotContainSpaces", metaDataCategory), MessageClass.Warning, metaDataCategory, data.ErrorList.Count, data)); } var metaDataCategoryLowerCase = metaDataCategory.ToLower(); // If value is blank change to paragraph for table creation classification form if (!String.IsNullOrWhiteSpace(match.Groups["MetadataValue"].Value)) { if (metaDataCategoryLowerCase == "title") { DocumentTitle = metaValue; } if (metaDataCategoryLowerCase == "crumbs") { CrumbsLinks.Add(metaValue); } if (metaDataCategoryLowerCase == "related") { RelatedLinks.Add(data.Markdown.ProcessRelated(metaValue, data)); } } // Add meta data to the list, we require some specific meta data keys to be unique others can be duplicates if (metaDataCategoryLowerCase.Equals("title") || metaDataCategoryLowerCase.Equals("description") || metaDataCategoryLowerCase.Equals("template") || metaDataCategoryLowerCase.Equals("forcepublishfiles")) { if (MetadataMap.ContainsKey(metaDataCategoryLowerCase)) { data.ErrorList.Add( new ErrorDetail( Language.Message("DuplicateMetadataDetected", metaDataCategory), MessageClass.Info, "", "", 0, 0)); } else { var valueList = new List <string>(); valueList.Add(match.Groups["MetadataValue"].Value); MetadataMap.Add(metaDataCategoryLowerCase, valueList); } } else { if (MetadataMap.ContainsKey(metaDataCategoryLowerCase)) { MetadataMap[metaDataCategoryLowerCase].Add(match.Groups["MetadataValue"].Value); } else { var valueList = new List <string>(); valueList.Add(match.Groups["MetadataValue"].Value); MetadataMap.Add(metaDataCategoryLowerCase, valueList); } } // Return empty string, we are removing the meta data from the document return(""); }
public static LocalEmbedBuilder AddCodeBlockField(this LocalEmbedBuilder eb, string name, string value) => eb.AddField(name, Markdown.CodeBlock("csharp", value));
public override IEnumerable <string> Extract(string s) => string.IsNullOrWhiteSpace(s) ? Enumerable.Empty <string>() // Only select *closed* fenced blocks : Markdown.Parse(s, _markdownPipeline).OfType <FencedCodeBlock>().Where(fcb => !fcb.IsOpen).Select(fcb => fcb.Lines.ToString());
public async Task HandleAsync(IMessageContext context, SendEmail command) { var client = CreateSmtpClient(); if (client == null) { return; } var baseConfig = _configStore.Load <BaseConfiguration>(); // Emails have been disabled. Typically just in LIVE. if (string.IsNullOrEmpty(baseConfig.SupportEmail)) { return; } var email = new MailMessage { From = new MailAddress(baseConfig.SupportEmail), Subject = command.EmailMessage.Subject }; if (command.EmailMessage.ReplyTo != null) { var address = new MailAddress(command.EmailMessage.ReplyTo.Address, command.EmailMessage.ReplyTo.Name); email.ReplyToList.Add(address); } var markdownHtml = Markdown.ToHtml(command.EmailMessage.TextBody ?? ""); if (string.IsNullOrEmpty(command.EmailMessage.HtmlBody) && markdownHtml == command.EmailMessage.TextBody) { email.Body = command.EmailMessage.TextBody; email.IsBodyHtml = false; await client.SendMailAsync(email); return; } if (string.IsNullOrEmpty(command.EmailMessage.HtmlBody)) { command.EmailMessage.HtmlBody = markdownHtml; } var av = AlternateView.CreateAlternateViewFromString(command.EmailMessage.HtmlBody, null, MediaTypeNames.Text.Html); if (!string.IsNullOrEmpty(command.EmailMessage.TextBody)) { email.Body = command.EmailMessage.TextBody; } foreach (var resource in command.EmailMessage.Resources) { var contentType = new ContentType(MimeMapping.GetMimeType(Path.GetExtension(resource.Name))); var ms = new MemoryStream(resource.Content, 0, resource.Content.Length, false); var linkedResource = new LinkedResource(ms) { ContentId = resource.Name, ContentType = contentType }; av.LinkedResources.Add(linkedResource); } email.AlternateViews.Add(av); // Send one email per recipient to not share addresses. foreach (var recipient in command.EmailMessage.Recipients) { email.To.Clear(); if (int.TryParse(recipient.Address, out var accountId)) { var query = new GetAccountEmailById(accountId); var emailAddress = await context.QueryAsync(query); email.To.Add(new MailAddress(emailAddress, recipient.Name)); } else { email.To.Add(new MailAddress(recipient.Address, recipient.Name)); } await client.SendMailAsync(email); } }
public Task <string> TransformAsync(Guid postId, string content) => Task.FromResult(Markdown.ToHtml(content, _markdown));
public static EMCodeBlockParserMatch CreateFencedMatch(Match match) { var outdentSpaces = match.Groups[1].Value; var codeBlock = match.Groups[2].Value; if (string.IsNullOrWhiteSpace(codeBlock)) { return(null); } codeBlock = Regex.Replace(codeBlock, "^" + outdentSpaces, "", RegexOptions.Multiline); codeBlock = Markdown.EncodeCode(codeBlock); codeBlock = Normalizer.TrimNewLines(codeBlock); return(new EMCodeBlockParserMatch(match.Index, Normalizer.TrailingWhitespaceRemove(match.Value), Markdown.Unescape(codeBlock))); }
private string ConvertMarkdownToHtml(string html) { var markdown = Markdown.ToHtml(html); return(markdown); }
public SundownNetTest() { md = new Markdown(new HtmlRenderer()); Name = "SundownNet"; }
public async Task <CommandResult <IPost> > Handle(CreateOrUpdatePostRequest request, CancellationToken cancellationToken = default(CancellationToken)) { var errors = new List <string>(); try { bool isNew = false; var project = await _projectService.GetProjectSettings(request.ProjectId); var post = request.Post; ContentHistory history = null; if (post == null) { isNew = true; post = new Post() { BlogId = request.ProjectId, Title = request.ViewModel.Title, MetaDescription = request.ViewModel.MetaDescription, Slug = ContentUtils.CreateSlug(request.ViewModel.Title), CreatedByUser = request.UserName }; } else { history = post.CreateHistory(request.UserName); } if (!string.IsNullOrEmpty(request.ViewModel.Slug)) { // remove any bad characters request.ViewModel.Slug = ContentUtils.CreateSlug(request.ViewModel.Slug); if (request.ViewModel.Slug != post.Slug) { var slugIsAvailable = await _blogService.SlugIsAvailable(request.ViewModel.Slug); if (!slugIsAvailable) { request.ModelState.AddModelError("Slug", _localizer["The page slug was not changed because the requested slug is already in use."]); } } } if (request.ModelState.IsValid) { post.Title = request.ViewModel.Title; post.CorrelationKey = request.ViewModel.CorrelationKey; post.ImageUrl = request.ViewModel.ImageUrl; post.ThumbnailUrl = request.ViewModel.ThumbnailUrl; post.IsFeatured = request.ViewModel.IsFeatured; post.ContentType = request.ViewModel.ContentType; post.TeaserOverride = request.ViewModel.TeaserOverride; post.SuppressTeaser = request.ViewModel.SuppressTeaser; post.LastModified = DateTime.UtcNow; post.LastModifiedByUser = request.UserName; if (!string.IsNullOrEmpty(request.ViewModel.Slug)) { post.Slug = request.ViewModel.Slug; } var categories = new List <string>(); if (!string.IsNullOrEmpty(request.ViewModel.Categories)) { if (_editOptions.ForceLowerCaseCategories) { categories = request.ViewModel.Categories.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(x => x.Trim().ToLower()) .Where(x => !string.IsNullOrWhiteSpace(x) && x != "," ) .Distinct() .ToList(); } else { categories = request.ViewModel.Categories.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(x => x.Trim()) .Where(x => !string.IsNullOrWhiteSpace(x) && x != "," ) .Distinct() .ToList(); } } post.Categories = categories; var shouldFirePublishEvent = false; switch (request.ViewModel.SaveMode) { case SaveMode.SaveDraft: post.DraftContent = request.ViewModel.Content; post.DraftAuthor = request.ViewModel.Author; break; case SaveMode.PublishLater: post.DraftContent = request.ViewModel.Content; post.DraftAuthor = request.ViewModel.Author; if (request.ViewModel.NewPubDate.HasValue) { var tzId = await _timeZoneIdResolver.GetUserTimeZoneId(CancellationToken.None); post.DraftPubDate = _timeZoneHelper.ConvertToUtc(request.ViewModel.NewPubDate.Value, tzId); } if (!post.PubDate.HasValue) { post.IsPublished = false; } break; case SaveMode.PublishNow: post.Content = request.ViewModel.Content; post.Author = request.ViewModel.Author; if (!post.PubDate.HasValue) { post.PubDate = DateTime.UtcNow; } else if (post.PubDate > DateTime.UtcNow) { post.PubDate = DateTime.UtcNow; } post.IsPublished = true; shouldFirePublishEvent = true; post.DraftAuthor = null; post.DraftContent = null; post.DraftPubDate = null; break; } if (project.TeaserMode != TeaserMode.Off) { // need to generate the teaser on save string html = null; if (post.ContentType == "markdown") { var mdPipeline = new MarkdownPipelineBuilder().UseAdvancedExtensions().Build(); html = Markdown.ToHtml(post.Content, mdPipeline); } else { html = post.Content; } var teaserResult = _teaserService.GenerateTeaser( project.TeaserTruncationMode, project.TeaserTruncationLength, html, Guid.NewGuid().ToString(),//cache key post.Slug, project.LanguageCode, false //logWarnings ); post.AutoTeaser = teaserResult.Content; } if (history != null) { await _historyCommands.Create(request.ProjectId, history).ConfigureAwait(false); } if (isNew) { await _blogService.Create(post); } else { await _blogService.Update(post); } if (shouldFirePublishEvent) { await _blogService.FirePublishEvent(post); await _historyCommands.DeleteDraftHistory(request.ProjectId, post.Id).ConfigureAwait(false); } } return(new CommandResult <IPost>(post, request.ModelState.IsValid, errors)); } catch (Exception ex) { _log.LogError($"{ex.Message}:{ex.StackTrace}"); errors.Add(_localizer["Updating a page failed. An error has been logged."]); return(new CommandResult <IPost>(null, false, errors)); } }
public void LoadMarkdown(string content) { // first, clear ourselves unloadAllChildren (); value = content; // run the parser on the content Markdown md = new Markdown (); Dictionary<string, LinkDefinition> definitions; md.ExtraMode = true; // Our job is to interface with MarkdownDeep, grab the necessary bits, and call the simplied API in MarkdownStyle StringBuilder currentString = new StringBuilder (); Block currentBlock = null; PUGameObject container = this as PUGameObject; RectTransform containerRT = contentObject.transform as RectTransform; Stack<BlockType> listStack = new Stack<BlockType>(); container.size = containerRT.rect.size; Action CommitMarkdownBlock = () => { if (currentBlock == null) { return; } if (currentBlock.blockType == BlockType.p) { mdStyle.Create_P(container, currentString.ToString()); } if (currentBlock.blockType == BlockType.h1) { mdStyle.Create_H1(container, currentString.ToString()); } if (currentBlock.blockType == BlockType.h2) { mdStyle.Create_H2(container, currentString.ToString()); } if (currentBlock.blockType == BlockType.h3) { mdStyle.Create_H3(container, currentString.ToString()); } if (currentBlock.blockType == BlockType.h4) { mdStyle.Create_H4(container, currentString.ToString()); } if (currentBlock.blockType == BlockType.h5) { mdStyle.Create_H5(container, currentString.ToString()); } if (currentBlock.blockType == BlockType.h6) { mdStyle.Create_H6(container, currentString.ToString()); } if (currentBlock.blockType == BlockType.hr) { mdStyle.Create_HR(container); } if (currentBlock.blockType == BlockType.quote) { mdStyle.Begin_Blockquote(container); } if (currentBlock.blockType == BlockType.quote_end) { mdStyle.End_Blockquote(container); } if (currentBlock.blockType == BlockType.ul) { listStack.Push(currentBlock.blockType); mdStyle.Begin_UnorderedList(container); } if (currentBlock.blockType == BlockType.ul_end) { listStack.Pop(); mdStyle.End_UnorderedList(container); } if (currentBlock.blockType == BlockType.ul_li) { mdStyle.Create_UL_LI(container, currentString.ToString()); } if (currentBlock.blockType == BlockType.ol) { listStack.Push(currentBlock.blockType); mdStyle.Begin_OrderedList(container); } if (currentBlock.blockType == BlockType.ol_end) { listStack.Pop(); mdStyle.End_OrderedList(container); } if (currentBlock.blockType == BlockType.ol_li) { mdStyle.Create_OL_LI(container, currentString.ToString()); } if (currentBlock.blockType == BlockType.codeblock) { mdStyle.Create_CodeBlock(container, currentBlock.Content); } if(currentBlock.blockType == BlockType.table_spec){ mdStyle.Create_Table(container, currentBlock.data as TableSpec); } if(currentBlock.blockType == BlockType.dt){ mdStyle.Create_DefinitionTerm(container, currentString.ToString()); } if(currentBlock.blockType == BlockType.dd){ mdStyle.Create_DefinitionData(container, currentString.ToString()); } }; mdStyle.Begin (container); string htmlTranslation = md.Transform (content, out definitions, (block, token, tokenString) => { if(block != null){ //Debug.Log ("block: " + block.blockType + " :: " + block.Content); CommitMarkdownBlock(); currentBlock = block; currentString.Length = 0; } if(token != null) { //Debug.Log ("token: " + token.type); if(token.type == TokenType.img){ LinkInfo link = token.data as LinkInfo; mdStyle.Create_IMG(container, link.def.url, link.link_text); } if(token.type == TokenType.Text){ currentString.Append(tokenString, token.startOffset, token.length); } if(token.type == TokenType.code_span){ mdStyle.Tag_Code(container, currentString, true); currentString.Append(tokenString, token.startOffset, token.length); mdStyle.Tag_Code(container, currentString, false); } if(token.type == TokenType.open_strong){ mdStyle.Tag_Strong(container, currentString, true); } if(token.type == TokenType.close_strong){ mdStyle.Tag_Strong(container, currentString, false); } if(token.type == TokenType.br){ mdStyle.Tag_BreakingReturn(container, currentString); } if(token.type == TokenType.link){ LinkInfo link = token.data as LinkInfo; mdStyle.Tag_Link(container, currentString, link.def.url, link.link_text); } if(token.type == TokenType.open_em){ mdStyle.Tag_Emphasis(container, currentString, true); } if(token.type == TokenType.close_em){ mdStyle.Tag_Emphasis(container, currentString, false); } } }); CommitMarkdownBlock(); mdStyle.End (container); CalculateContentSize (); }
public static string ConvertToHtml(string markdown) { return(Markdown.ToHtml(markdown, Pipeline)); }
public void AppendMessage(DiscordMessage message) { if(message.author != null && App.ClientConfiguration.Settings.IgnoredUserIDs.Contains(message.author.ID)) { return; } DiscordChannel channel = message.Channel() as DiscordChannel; var markdownParser = new Markdown(channel.parent, null); var blocks = markdownParser.Transform(message, $"{message.id};{channel.ID}"); richTextBox.Document.Blocks.AddRange(blocks); ToolTip = $"Sent at {message.timestamp}"; MessageIDs.Add(message.id); Messages.Add(message); }
public async ValueTask <AdminCommandResult> ReplyToModmailAsync(int id, [Remainder, MustBe(StringLength.ShorterThan, LocalEmbedBuilder.MAX_DESCRIPTION_LENGTH)] string message) { var modmail = await Context.Database.Modmails.FindAsync(id); if (modmail is null) { return(CommandErrorLocalized("modmail_notfound")); } if (Context.IsPrivate && modmail.UserId != Context.User.Id) { return(CommandErrorLocalized("modmail_notfound")); } if (!Context.IsPrivate && modmail.GuildId != Context.Guild.Id) { return(CommandErrorLocalized("modmail_notfound")); } CachedTextChannel loggingChannel = null; if (Context.IsPrivate) { if (!(await Context.Database.GetLoggingChannelAsync(modmail.GuildId, LogType.Modmail) is CachedTextChannel logChannel)) { return(CommandErrorLocalized("requireloggingchannel_notfound", args: LogType.Modmail)); } if (modmail.ClosedBy.HasValue) { return(modmail.ClosedBy.Value == ModmailTarget.User ? CommandErrorLocalized("modmail_closed_user") : CommandErrorLocalized("modmail_closed_guild")); } loggingChannel = logChannel; } else { if (modmail.ClosedBy.HasValue) { return(modmail.ClosedBy.Value == ModmailTarget.User ? CommandErrorLocalized("modmail_closed_user_guild") : CommandErrorLocalized("modmail_closed_guild")); } } Context.Database.ModmailMessages.Add(new ModmailMessage(Context.IsPrivate ? ModmailTarget.User : ModmailTarget.Modteam, message, modmail)); await Context.Database.SaveChangesAsync(); if (Context.IsPrivate) { await loggingChannel.SendMessageAsync(embed : new LocalEmbedBuilder() .WithColor(new Color(0x8ED0FF)) .WithAuthor(new LocalEmbedAuthorBuilder { IconUrl = modmail.IsAnonymous ? Discord.GetDefaultUserAvatarUrl(Context.User.Discriminator) : Context.User.GetAvatarUrl(), Name = modmail.IsAnonymous ? Context.Localize("modmail_anonymous") : Context.User.Tag.Sanitize() }) .WithDescription(message) .WithTitle(Context.Localize("modmail_title", modmail.Id)) .WithFooter(Context.Localize("modmail_reply_command", Markdown.Code($"{Context.Prefix}mm reply {modmail.Id} [...]"), Markdown.Code($"{Context.Prefix}mm close {modmail.Id}"))) .WithTimestamp(DateTimeOffset.UtcNow) .Build()); } else { _ = Task.Run(async() => { var user = await Context.Client.GetOrDownloadUserAsync(modmail.UserId); _ = user.SendMessageAsync(embed: new LocalEmbedBuilder() .WithColor(new Color(0x8ED0FF)) .WithAuthor(new LocalEmbedAuthorBuilder { IconUrl = Context.Guild.GetIconUrl(), Name = $"{Context.Guild.Name} modteam" }) .WithDescription(message) .WithTitle(Context.Localize("modmail_title", modmail.Id)) .WithFooter(Context.Localize("modmail_reply_command", Markdown.Code($"{Context.Prefix}mm reply {modmail.Id} [...]"), Markdown.Code($"{Context.Prefix}mm close {modmail.Id}"))) .WithTimestamp(DateTimeOffset.UtcNow) .Build()); }); } return(CommandSuccessLocalized("modmail_reply_success")); }
public void RendersMarkdownFromMetadata() { // Given string input = @"Line 1 *Line 2* # Line 3"; string output = @"<p>Line 1 <em>Line 2</em></p> <h1>Line 3</h1> "; IDocument document = Substitute.For<IDocument>(); document.ContainsKey("meta").Returns(true); document.String("meta").Returns(input); IExecutionContext context = Substitute.For<IExecutionContext>(); Markdown markdown = new Markdown("meta"); // When markdown.Execute(new[] { document }, context).ToList(); // Make sure to materialize the result list // Then document.Received(0).Clone(Arg.Any<string>()); document.Received(1).Clone(Arg.Any<MetadataItems>()); document.Received().Clone(Arg.Is<MetadataItems>(x => x.SequenceEqual(new MetadataItems { { "meta", output } }))); }
static string GetTitle(string current) { var trim = current.Substring(1).Trim(); return(Markdown.StripMarkdown(trim)); }
public static string GetSymbolDescriptionAndCatchExceptionIntoMarkdownErrors(string path, string originalUserEntry, DescriptionType descriptionType, TransformationData transformationDataForThisRun, Markdown parser, HashSet<string> foundSymbolPaths = null) { var outputText = ""; var isError = false; var isInfo = false; var errorId = 0; try { var match = SymbolPathPattern.Match(path); if (!match.Success) { throw new InvalidDoxygenPath(path); } var symbolPath = match.Groups["symbolPath"].Value; var overloadSpec = match.Groups["overloadSpecification"].Value; var symbol = DoxygenDbCache.GetSymbolFromPath(symbolPath); if (foundSymbolPaths != null) { foundSymbolPaths.Add(symbolPath); } if (symbol.IsOverloadedMember) { if (string.IsNullOrWhiteSpace(overloadSpec)) { throw new DoxygenAmbiguousSymbolException(path, symbol.GetOverloadSpecificationOptions()); } outputText = symbol.GetSymbolDescription(descriptionType, overloadSpec); } else { outputText = symbol.GetSymbolDescription(descriptionType); } } catch (Exception e) { errorId = transformationDataForThisRun.ErrorList.Count; transformationDataForThisRun.ErrorList.Add( Markdown.GenerateError( Language.Message("DoxygenQueryError", e.Message), MessageClass.Error, originalUserEntry, errorId, transformationDataForThisRun)); isError = true; // rethrowing if not known exception if (!(e is InvalidDoxygenPath) && !(e is SymbolNotFoundInDoxygenXmlFile) && !(e is DoxygenAmbiguousSymbolException)) { throw; } } if (parser.ThisIsPreview && (isInfo || isError)) { return Templates.ErrorHighlight.Render(Hash.FromAnonymousObject( new { errorId = errorId, errorText = outputText })); } return outputText; }
/// <summary> /// 目录页面 /// </summary> /// <param name="code">分享码</param> /// <returns></returns> public IActionResult Index(string code) { //文档集编号 var DsCode = RouteData.Values["id"]?.ToString(); //页编码 var DsdId = RouteData.Values["sid"]?.ToString() ?? ""; if (string.IsNullOrWhiteSpace(DsCode)) { return(Redirect("/doc")); } var sck = "SharedCode_" + DsCode; //有分享码 if (!string.IsNullOrWhiteSpace(code)) { Response.Cookies.Append(sck, code); } else { code = Request.Cookies[sck]?.ToString(); } //跳转带斜杠 if (DsCode.Length == 19 && DsdId == "" && !Request.Path.Value.EndsWith("/")) { return(Redirect(Request.Path.Value + "/")); } var baseUrl = string.Join("/", Request.Path.Value.Split('/').ToList().Take(4)) + "/"; var ds = db.DocSet.Find(DsCode); if (ds == null) { return(Content("bad")); } //分享码 var isShare = !string.IsNullOrWhiteSpace(ds.Spare1) && ds.Spare1 == code; if (!isShare && ds.DsOpen != 1) { if (HttpContext.User.Identity.IsAuthenticated) { var uinfo = Apps.LoginService.Get(HttpContext); if (uinfo.UserId != ds.Uid) { return(Content("unauthorized")); } } else { return(Content("unauthorized")); } } var ismd = DsdId.EndsWith(".md"); var listSeo = new List <string>(); if (DsdId.StartsWith("README") || string.IsNullOrWhiteSpace(DsdId)) { var ct = new List <string> { "# " + ds.DsName, string.IsNullOrWhiteSpace(ds.DsRemark)? "" : $"#### {ds.DsRemark}", "", ds.DsCreateTime.Value.ToString("yyyy-MM-dd HH:mm:ss") }; var ctmd = string.Join(Environment.NewLine, ct); listSeo.Add(Markdown.ToHtml(ctmd)); if (ismd) { return(Content(ctmd)); } } if (DsdId.StartsWith("_sidebar") || DsdId.Length == 19) { //文档集目录 var DocTree = db.DocSetDetail .Where(x => x.DsCode == DsCode) .OrderBy(x => x.DsdOrder) .Select(x => new DocTreeVM { DsdId = x.DsdId, DsdPid = x.DsdPid, DsCode = x.DsCode, DsdTitle = x.DsdTitle, DsdOrder = x.DsdOrder, IsCatalog = string.IsNullOrEmpty(x.DsdContentMd) }).ToList(); var ct = TreeToMd(baseUrl, DocTree, Guid.Empty.ToString()); //ct.RemoveRange(0, 10); var ctmd = string.Join(Environment.NewLine, ct); listSeo.Add(Markdown.ToHtml(ctmd).Replace(".md\"", "\"")); if (ismd) { return(Content(ctmd)); } } if (DsdId.Length == 19 || DsdId.Length == 22) { var mdid = DsdId.Replace(".md", ""); var mdmo = db.DocSetDetail.FirstOrDefault(x => x.DsdId == mdid); var uptime = "<span title='" + mdmo.DsdCreateTime.Value.ToString("yyyy-MM-dd HH:mm:ss") + "'><i class='fa fa-clock-o'></i> 创建于:" + mdmo.DsdCreateTime.Value.ToString("yyyy年MM月dd日") + "</span>"; if (mdmo.DsdUpdateTime != mdmo.DsdCreateTime) { uptime += " <span title='" + mdmo.DsdUpdateTime.Value.ToString("yyyy-MM-dd HH:mm:ss") + "'><i class='fa fa-clock-o'></i> 更新于:" + mdmo.DsdUpdateTime.Value.ToString("yyyy年MM月dd日") + "</span>"; } uptime += " <span><i class='fa fa-sort-amount-asc'></i> 排序号:" + mdmo.DsdOrder + "</span>"; var mdtitle = string.Join(Environment.NewLine, new List <string>() { "<h1>" + mdmo.DsdTitle + "</h1>", uptime, "<hr/>", "", "" }); listSeo.Add(mdtitle + mdmo.DsdContentHtml); if (ismd) { return(Content(mdtitle + mdmo.DsdContentMd)); } } //文档标题 ViewData["Title"] = ds.DsName; ViewData["DocSeo"] = string.Join(Environment.NewLine, listSeo); return(View()); }
public static string Markdown2Text(string markdown) { return(Markdown.ToPlainText(markdown).Trim(' ', '\n', '\r')); }
private async ValueTask <AdminCommandResult> AddPermissionAsync(string name, bool isEnabled, PermissionFilter filter, ulong?targetId) { Permission permission; var type = Enum.Parse <PermissionType>(Context.Alias, true); if (type == PermissionType.Command) { var commandMatches = Commands.FindCommands(name); if (commandMatches.Count == 0) { return(CommandErrorLocalized("permissions_command_notfound")); } permission = new Permission(Context.Guild?.Id, type, isEnabled, string.Join(' ', commandMatches[0].Command.FullAliases[0]).ToLower(), filter, targetId); } else { if (!(Commands.GetAllModules() .FirstOrDefault(x => x.Name.Equals(name, StringComparison.OrdinalIgnoreCase)) is { } module)) { return(CommandErrorLocalized("permissions_module_notfound")); } permission = new Permission(Context.Guild?.Id, type, isEnabled, module.Name.ToLower(), filter, targetId); } Context.Database.Permissions.Add(permission); await Context.Database.SaveChangesAsync(); var filterText = filter switch { PermissionFilter.Global => Context.Localize("permissions_global"), PermissionFilter.Guild => Context.Guild.Name.Sanitize(), PermissionFilter.Role => Context.Guild.GetRole(targetId.Value).Name.Sanitize(), PermissionFilter.Channel => Context.Guild.GetTextChannel(targetId.Value).Mention, PermissionFilter.User => Context.Guild.GetMember(targetId.Value)?.Tag.Sanitize() ?? "???", _ => throw new ArgumentOutOfRangeException() }; if (string.IsNullOrWhiteSpace(name)) { return(CommandSuccessLocalized(permission.IsEnabled ? "permissions_all_enabled" : "permissions_all_disabled", args: filterText)); } switch (permission.Type) { case PermissionType.Command: return(CommandSuccessLocalized(permission.IsEnabled ? "permissions_command_enabled" : "permissions_command_disabled", args: new object[] { Markdown.Code(permission.Name), Markdown.Bold(filterText) })); case PermissionType.Module: return(CommandSuccessLocalized(permission.IsEnabled ? "permissions_module_enabled" : "permissions_module_disabled", args: new object[] { Markdown.Code(permission.Name), Markdown.Bold(filterText) })); default: throw new ArgumentOutOfRangeException(); } }
public static LocalEmbedBuilder AddInlineCodeBlockField(this LocalEmbedBuilder eb, string name, object value) => eb.AddField(name, Markdown.CodeBlock("csharp", value.ToString()), true);
public MarkdownClassicProcessor() { this.RenderDelay = System.TimeSpan.FromSeconds(0.1); this._markdownProcessor = new Markdown(); this.ApplySettings(); }
public override void AppendHTML(StringBuilder builder, Stack <EMInclude> includesStack, TransformationData data) { if (singleLine) { builder.Append( Templates.CustomTag.Render(Hash.FromAnonymousObject(new { tagName = "code", content = Markdown.Unescape(rawText) })).Trim()); } else { builder.Append( Templates.PrettyPrintCodeBlock.Render(Hash.FromAnonymousObject(new { content = rawText }))); } }
public static Product ToProduct(this catalogDto.Product productDto, Language currentLanguage, Currency currentCurrency, Store store) { var result = new Product(currentCurrency, currentLanguage) { Id = productDto.Id, TitularItemId = productDto.TitularItemId, CatalogId = productDto.CatalogId, CategoryId = productDto.CategoryId, DownloadExpiration = productDto.DownloadExpiration, DownloadType = productDto.DownloadType, EnableReview = productDto.EnableReview ?? false, Gtin = productDto.Gtin, HasUserAgreement = productDto.HasUserAgreement ?? false, IsActive = productDto.IsActive ?? false, IsBuyable = productDto.IsBuyable ?? false, ManufacturerPartNumber = productDto.ManufacturerPartNumber, MaxNumberOfDownload = productDto.MaxNumberOfDownload ?? 0, MaxQuantity = productDto.MaxQuantity ?? 0, MeasureUnit = productDto.MeasureUnit, MinQuantity = productDto.MinQuantity ?? 0, Name = productDto.Name, PackageType = productDto.PackageType, ProductType = productDto.ProductType, ShippingType = productDto.ShippingType, TaxType = productDto.TaxType, TrackInventory = productDto.TrackInventory ?? false, VendorId = productDto.Vendor, WeightUnit = productDto.WeightUnit, Weight = (decimal?)productDto.Weight, Height = (decimal?)productDto.Height, Width = (decimal?)productDto.Width, Length = (decimal?)productDto.Length, Sku = productDto.Code, Outline = productDto.Outlines.GetOutlinePath(store.Catalog), SeoPath = productDto.Outlines.GetSeoPath(store, currentLanguage, null), }; result.Url = "~/" + (result.SeoPath ?? "product/" + result.Id); if (productDto.Properties != null) { result.Properties = productDto.Properties .Where(x => string.Equals(x.Type, "Product", StringComparison.InvariantCultureIgnoreCase)) .Select(p => ToProperty(p, currentLanguage)) .ToList(); result.VariationProperties = productDto.Properties .Where(x => string.Equals(x.Type, "Variation", StringComparison.InvariantCultureIgnoreCase)) .Select(p => ToProperty(p, currentLanguage)) .ToList(); } if (productDto.Images != null) { result.Images = productDto.Images.Select(ToImage).ToArray(); result.PrimaryImage = result.Images.FirstOrDefault(); } if (productDto.Assets != null) { result.Assets = productDto.Assets.Select(ToAsset).ToList(); } if (productDto.Variations != null) { result.Variations = productDto.Variations.Select(v => ToProduct(v, currentLanguage, currentCurrency, store)).ToList(); } if (!productDto.SeoInfos.IsNullOrEmpty()) { var seoInfoDto = productDto.SeoInfos.Select(x => x.JsonConvert <coreDto.SeoInfo>()) .GetBestMatchingSeoInfos(store, currentLanguage) .FirstOrDefault(); if (seoInfoDto != null) { result.SeoInfo = seoInfoDto.ToSeoInfo(); } } if (result.SeoInfo == null) { result.SeoInfo = new SeoInfo { Title = productDto.Id, Language = currentLanguage, Slug = productDto.Code }; } if (productDto.Reviews != null) { // Reviews for currentLanguage (or Invariant language as fall-back) for each ReviewType var descriptions = productDto.Reviews .Where(r => !string.IsNullOrEmpty(r.Content)) .Select(r => new EditorialReview { Language = new Language(r.LanguageCode), ReviewType = r.ReviewType, Value = Markdown.ToHtml(r.Content, _markdownPipeline) }); //Select only best matched description for current language in the each description type foreach (var descriptionGroup in descriptions.GroupBy(x => x.ReviewType)) { var description = descriptionGroup.FindWithLanguage(currentLanguage); if (description != null) { result.Descriptions.Add(description); } } result.Description = (result.Descriptions.FirstOrDefault(x => x.ReviewType.EqualsInvariant("FullReview")) ?? result.Descriptions.FirstOrDefault())?.Value; } return(result); }
private async Task LoadBlogPost() { BlogPost = await _httpClient.GetJsonAsync <BlogPost>(Urls.BlogPost.Replace("{id}", PostId)); BlogPost.Post = Markdown.ToHtml(BlogPost.Post); }
public void DoesNothingIfMetadataKeyDoesNotExist() { // Given IDocument document = Substitute.For<IDocument>(); document.ContainsKey("meta").Returns(false); IExecutionContext context = Substitute.For<IExecutionContext>(); Markdown markdown = new Markdown("meta"); // When markdown.Execute(new[] { document }, context).ToList(); // Make sure to materialize the result list // Then document.Received(0).Clone(Arg.Any<string>()); document.Received(0).Clone(Arg.Any<MetadataItems>()); }
private DocumentationViewModel GetPost(string filePath, string docName = null) { var model = new DocumentationViewModel(); if (_fileSystem.FileExists(filePath)) { var contents = string.Empty; using (var fileStream = System.IO.File.Open(filePath, FileMode.OpenOrCreate, FileAccess.Read, FileShare.Read)) using (var streamReader = new StreamReader(fileStream, Encoding.UTF8)) { contents = streamReader.ReadToEnd(); } var urlOnePattern = @"\[\[(.*?)\|(.*?)\]\]"; MatchCollection urlOnePatternMatches = Regex.Matches(contents, urlOnePattern); foreach (Match match in urlOnePatternMatches) { var hyphenatedValue = new StringBuilder(); Char previousChar = '^'; foreach (var valueChar in match.Groups[2].Value.ToString()) { // Filenames that contain both a "-" and camel casing if (match.Groups[2].Value.Contains("-") && Char.IsLower(previousChar) && Char.IsUpper(valueChar)) { hyphenatedValue.Append("-"); } if (Char.IsUpper(valueChar) && hyphenatedValue.Length != 0 && !Char.IsUpper(previousChar) && !match.Groups[2].Value.Contains("-")) { hyphenatedValue.Append("-"); } if (Char.IsDigit(valueChar) && !Char.IsDigit(previousChar) && hyphenatedValue.Length != 0) { hyphenatedValue.Append("-"); } previousChar = valueChar; hyphenatedValue.Append(valueChar.to_string()); } contents = contents.Replace(match.Value, "[" + match.Groups[1].Value + "](/docs/" + hyphenatedValue.ToString().ToLower() + ")"); } var urlTwoPattern = @"\[(.*?)\]\((.*?)\)"; MatchCollection urlTwoPatternMatches = Regex.Matches(contents, urlTwoPattern); foreach (Match match in urlTwoPatternMatches) { contents = contents.Replace(match.Groups[2].Value, match.Groups[2].Value .Replace("f-a-q", "faq") .Replace("p-s1", "ps1") .Replace("---", "-") .Replace("--", "-")); } contents = contents .Replace("<!--remove", "") .Replace("remove-->", "") .Replace("~~~sh", "~~~language-none") .Replace("(images/", "(/content/images/docs/"); // Get Url model.UrlPath = GetUrl(filePath, docName); // Convert using Markdig model.Post = Markdown.ToHtml(contents, MarkdownPipeline); // Remove "." from header ID's var headerPattern = @"(<h\d id=)(.*?)(>)"; MatchCollection matches = Regex.Matches(model.Post, headerPattern); foreach (Match match in matches) { model.Post = Regex.Replace(model.Post, match.Groups[2].Value, match.Groups[2].Value.Replace(".", "")); } } return(model); }
private Boolean LoadPageFromTextFile() { String relativePath = String.Format("~/Pages/{0}", Request["name"].Replace(".html",".txt")); String physicalPath = Server.MapPath(relativePath); if ( File.Exists(physicalPath) ) { FileInfo file = new FileInfo(physicalPath); String name = CreatePageTitleText(file.Name); String title = name; Page.Title = "Shift iQ | " + title; String text = File.ReadAllText(physicalPath); Markdown markdown = new Markdown(); PageBody.Text = markdown.Transform(text); ((HtmlGenericControl)Page.Master.FindControl("BannerTitle")).InnerHtml = title; String description = ControlHelper.TruncateString(ControlHelper.GetDescriptionFromHtml(PageBody.Text), 245); if (PageBody.Text != null && PageBody.Text.Length > 245) description = ControlHelper.AppendWithEllipsis(description); ControlHelper.AddOpenGraphMetaData( Page, "website", Page.Request.RawUrl, "/app_themes/insite/images/header-logo-shift.png", title, description ); return true; } return false; }