Пример #1
0
        public async Task <IActionResult> BlogPostBySlug(string slug)
        {
            if (slug == null)
            {
                _logger.LogWarning("Warning - BlogPost with null slug called.");

                return(NotFound());
            }

            var gbpbs = new GetBlogPostBySlugViewModelQuery
            {
                Slug = slug
            };

            var bpvm = await _qpa.ProcessAsync(gbpbs);

            if (bpvm == null)
            {
                _logger.LogWarning("Warning - BlogPost with slug {0} was not found.", slug);

                return(NotFound());
            }

            if (!bpvm.IsHtml)
            {
                bpvm.Content = CommonMarkConverter.Convert(bpvm.Content);
            }

            return(View("BlogPost", bpvm));
        }
Пример #2
0
        public void RenderMarkdown(string currentText, string filepath)
        {
            if (renderTask == null || renderTask.IsCompleted)
            {
                SaveLastVerticalScrollPosition();
                MakeAndDisplayScreenShot();

                var context = TaskScheduler.FromCurrentSynchronizationContext();
                renderTask = new Task <string>(() =>
                {
                    this.currentText     = currentText;
                    this.filepath        = filepath;
                    var result           = CommonMarkConverter.Convert(currentText);
                    var defaultBodyStyle = "";
                    var rr = string.Format(DEFAULT_HTML_BASE, Path.GetFileName(filepath), MainResources.DefaultCss, defaultBodyStyle, result);
                    return(rr);
                });
                renderTask.ContinueWith((renderedText) =>
                {
                    webBrowserPreview.DocumentText = renderedText.Result;
                    AdjustZoomForCurrentDpi();
                }, context);
                renderTask.Start();
            }
        }
Пример #3
0
        public string ContentToHtml()
        {
            switch (Language)
            {
            case Language.PlainText:
            case Language.Html:
                return(Content);

            case Language.Markdown:
                CommonMarkSettings.Default.OutputDelegate = (doc, output, settings) =>
                                                            new HtmlFormatter(output, settings).WriteDocument(doc);

                string content = Content;
                if (string.IsNullOrEmpty(content))
                {
                    return(null);
                }

                IEnumerable <string> lines = content
                                             .Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);

                lines   = lines.Select(l => l.TrimStart());
                content = String.Join(Environment.NewLine, lines);

                string html = CommonMarkConverter.Convert(content);
                return(html);

            default:
                throw new NotSupportedException(Language.ToString());
            }
        }
Пример #4
0
        public async Task <StorySummaryViewModel> Create(CreateViewModel model, string username, Guid userId)
        {
            UriBuilder uri = null;

            if (!string.IsNullOrEmpty(model.Url))
            {
                uri        = new UriBuilder(model.Url);
                uri.Scheme = "https";
                uri.Port   = uri.Port == 80 || uri.Port == 443 ? -1 : uri.Port;
            }

            var story = await StoriesDbContext.Stories.AddAsync(new Story()
            {
                Title = model.Title,
                DescriptionMarkdown = model.DescriptionMarkdown,
                Description         = CommonMarkConverter.Convert(model.DescriptionMarkdown),
                Url          = uri?.Uri.ToString(),
                UserId       = userId,
                UserIsAuthor = model.IsAuthor,
            });

            var rowCount = await StoriesDbContext.SaveChangesAsync();

            var hashIds = new Hashids(minHashLength: 5);

            VoteQueueService.QueueStoryVote(story.Entity.Id);

            return(MapToStorySummaryViewModel(story.Entity, hashIds.Encode(story.Entity.Id), userId, false));
        }
Пример #5
0
        /// <summary>
        /// Reads the content of the given file path, interprets as markdown and renders the equivalent HTML.
        /// </summary>
        /// <param name="helper">Html helper</param>
        /// <param name="path">The file with the markdown content to be rendered</param>
        /// <returns>The rendered HTML</returns>
        public static IHtmlString Markdown(this HtmlHelper helper, string path)
        {
            if (helper == null)
            {
                throw new ArgumentNullException("helper");
            }

            if (path == null)
            {
                throw new ArgumentNullException("path");
            }

            var view = helper.ViewContext.View as RazorView;

            if (view == null)
            {
                throw new NotARazorViewException();
            }
            else
            {
                var viewPath = helper.ViewContext.HttpContext.Server.MapPath(view.ViewPath);
                var dir      = Path.GetDirectoryName(viewPath);
                var fullpath = Path.Combine(dir, path);
                var unparsed = File.ReadAllText(fullpath);
                var parsed   = CommonMarkConverter.Convert(unparsed);
                return(new MvcHtmlString(parsed));
            }
        }
Пример #6
0
        public async Task <IActionResult> BlogPost(long?id)
        {
            if (id == null)
            {
                _logger.LogWarning("Warning - BlogPost with null Id called.");

                return(NotFound());
            }

            var gvbpbi = new GetBlogPostByIdViewModelQuery()
            {
                Id = (long)id
            };

            var bpvm = await _qpa.ProcessAsync(gvbpbi);

            if (bpvm == null)
            {
                _logger.LogWarning("Warning - BlogPost with Id {0} was not found.", id);

                return(NotFound());
            }

            bpvm.Content = CommonMarkConverter.Convert(bpvm.Content);

            return(View(bpvm));
        }
Пример #7
0
        public void Render(ViewContext viewContext, TextWriter writer)
        {
            if (writer == null)
            {
                throw new ArgumentNullException("writer");
            }

            // Reading the file content
            var text = File.ReadAllText(_filepath);

            // Page doctype
            var doctype = "<!doctype html>";

            // Page encoding
            var charset = "<meta charset=\"utf-8\" />";

            // Page title
            var title = "<title>" + Path.GetFileNameWithoutExtension(_filepath) + "</title>";

            // Page CSS (if any)
            var css = string.IsNullOrWhiteSpace(_cssHref) ?
                      string.Format(CultureInfo.InvariantCulture, "<style>\n{0}\n</style>", Resources.Style) :
                      string.Format(CultureInfo.InvariantCulture, "<link rel=\"stylesheet\" href=\"{0}\">", _cssHref);

            // Parsing the Markdown content
            var markdown = CommonMarkConverter.Convert(text);

            // Joining all up
            var content = string.Join("\n", doctype, charset, title, css, markdown);

            // Writing to the stream
            writer.Write(content);
        }
Пример #8
0
        public string Format(string content)
        {
            byte[] bytes       = Encoding.Default.GetBytes(content);
            var    utf8Content = Encoding.UTF8.GetString(bytes);

            return(CommonMarkConverter.Convert(utf8Content));
        }
Пример #9
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app)
        {
            var provider    = new PhysicalFileProvider(Directory.GetCurrentDirectory());
            var commonmarks = provider.GetDirectoryContents(@"commonmarks");

            app.UseStaticFiles();

            app.Run(async(context) =>
            {
                var pathElements = context.Request.Path.Value.Split('/');
                if (pathElements.Length != 2)
                {
                    return;
                }

                var requestName = pathElements[1];
                if (string.IsNullOrEmpty(requestName))
                {
                    requestName = "index";
                }

                if (commonmarks.Exists && commonmarks.Any(x => x.Name.Split('.')?[0] == requestName))
                {
                    var filePath = $"{provider.Root}commonmarks\\{requestName}.md";
                    using (var stream = File.OpenRead(filePath))
                        using (var reader = new StreamReader(stream))
                        {
                            var content  = await reader.ReadToEndAsync();
                            var htmlPart = CommonMarkConverter.Convert(content);
                            await context.Response.WriteAsync(string.Format(HtmlTemplate, requestName, htmlPart));
                        }
                }
            });
        }
Пример #10
0
        /// <summary>
        ///     Reads the content of the given file path, interprets as markdown and renders the equivalent HTML.
        /// </summary>
        /// <param name="helper">Html helper</param>
        /// <param name="path">The file with the markdown content to be rendered</param>
        /// <param name="dynamicValues">Dictionary of dynamic values to inject</param>
        /// <returns>The rendered HTML</returns>
        public static IHtmlString Markdown(this HtmlHelper helper, string path, Dictionary <string, string> dynamicValues)
        {
            if (helper == null)
            {
                throw new ArgumentNullException(nameof(helper));
            }
            if (path == null)
            {
                throw new ArgumentNullException(nameof(path));
            }
            var view = helper.ViewContext.View as RazorView;

            if (view == null)
            {
                throw new NotARazorViewException();
            }
            var viewPath             = helper.ViewContext.HttpContext.Server.MapPath(view.ViewPath);
            var dir                  = Path.GetDirectoryName(viewPath) ?? string.Empty;
            var fullpath             = Path.Combine(dir, path);
            var unparsed             = File.ReadAllText(fullpath);
            var dynamicValueInjector = new MarkdownDynamicContentHandler();

            unparsed = dynamicValueInjector.ProcessMarkdown(unparsed, dynamicValues);
            var parsed = CommonMarkConverter.Convert(unparsed);

            return(new MvcHtmlString(parsed));
        }
Пример #11
0
        public async Task <IActionResult> BlogPost(long?id)
        {
            if (id == null)
            {
                return(NotFound());
            }

            var post = await _context.BlogPosts
                       .AsNoTracking()
                       .Include(bp => bp.Author)
                       .Include(bp => bp.BlogPostCategory)
                       .ThenInclude(bpc => bpc.Category)
                       .Where(bp => bp.Id == id && bp.Public == true && bp.PublishOn < DateTime.Now)
                       .FirstOrDefaultAsync();

            if (post == null)
            {
                return(NotFound());
            }

            var bpvm = new ViewBlogPostViewModel()
            {
                Author      = $"{post.Author.FirstName} {post.Author.LastName}",
                Title       = post.Title,
                Description = post.Description,
                Content     = post.Content,
                ModifiedAt  = post.ModifiedAt,
                Categories  = post.BlogPostCategory.Select(c => c.Category).ToList()
            };

            bpvm.Content = CommonMarkConverter.Convert(bpvm.Content);

            return(View(bpvm));
        }
Пример #12
0
 public static Syntax.Block ParseDocument(string commonMark, CommonMarkSettings settings = null)
 {
     using (var reader = new System.IO.StringReader(Helpers.Normalize(commonMark)))
     {
         return(CommonMarkConverter.Parse(reader, settings));
     }
 }
Пример #13
0
 private void Timer1_Tick(object sender, EventArgs e)
 {
     if (CheckVersion.UpdateText != null && CheckVersion.UpdateText != "")
     {
         if (pictureBox1.Visible)
         {
             Width                    += 200;
             Height                   += 200;
             webBrowser1.Width        += 200;
             webBrowser1.Height       += 200;
             webBrowser1.DocumentText  = CommonMarkConverter.Convert(CheckVersion.UpdateText);
             metroProgressBar1.Visible = false;
             pictureBox1.Visible       = false;
             Movable                   = true;
         }
         else
         {
             autoClose++;
             if (autoClose > 10)
             {
                 Close();
             }
         }
     }
     else
     {
         if (LoadCompleted)
         {
             Close();
         }
     }
 }
        public override RadDocument Import(Stream input)
        {
            using (StreamReader reader = new StreamReader(input))
            {
                // Performs the first stage of the conversion - parses block elements from the source
                // and created the syntax tree.
                var blockDoc = CommonMarkConverter.ProcessStage1(reader);

                //Performs the second stage of the conversion - parses block element contents into
                //inline elements.
                CommonMarkConverter.ProcessStage2(blockDoc);

                string       tempFileName = System.IO.Path.GetTempFileName();
                StreamWriter writer       = new StreamWriter(tempFileName);
                using (writer)
                {
                    // Performs the last stage of the conversion - converts the syntax tree to HTML
                    // representation.
                    CommonMarkConverter.ProcessStage3(blockDoc, writer);
                }

                RadDocument document;
                using (FileStream stream = File.OpenRead(tempFileName))
                {
                    document = htmlProvider.Import(stream);
                }
                File.Delete(tempFileName);

                return(document);
            }
        }
        private void CreateArticleData()
        {
            ExecuteOnStepProgress(90);
            ExecuteOnStepMessage(StepInput.HtmlStrings.CreatingArticleData);

            var projectDescription = StepInput.SDProject.Descriptions.GetElementOrDefault(StepInput.CurrentLanguage) ?? new SDTemplate(string.Empty);
            var homeData           = new ArticleData()
            {
                Title    = "Home",
                SubTitle = StepInput.HtmlStrings.Description,
                Content  = CommonMarkConverter.Convert(projectDescription.Transform(Helper.TransformLinkToken)).ToObjectString()
            };

            File.WriteAllText(Path.Combine(StepInput.OutputPath, "data", "articles", "home.json"), homeData.TransformText().MinifyJson());

            var articles = StepInput.SDProject.Articles.GetElementOrDefault(StepInput.CurrentLanguage);

            if (articles != null)
            {
                foreach (var article in articles)
                {
                    AddArticle(article);
                }
            }
        }
Пример #16
0
        /// <summary>
        /// Main Lambda Handler
        /// </summary>
        /// <param name="apigProxyEvent"></param>
        /// <returns>APIGatewayResponse</returns>
        public APIGatewayProxyResponse Handler(APIGatewayProxyRequest apigProxyEvent)
        {
            dynamic json  = JValue.Parse(apigProxyEvent.Body);
            string  title = json.title;

            Console.WriteLine(title);

            string htmlBody = CommonMarkConverter.Convert(title);

            bool sendEmail = ldClient.BoolVariation("send-email", user, false);

            if (sendEmail)
            {
                Mailer mail = new Mailer("New LD Change", title, htmlBody);
                mail.Send().Wait();
            }
            else
            {
                Console.WriteLine("Not sending email, Feature Flag is OFF");
            }

            return(new APIGatewayProxyResponse
            {
                Body = title,
                StatusCode = 200,
            });
        }
Пример #17
0
        public UpdateResult Write(IList <DocumentEntry> entries)
        {
            var oldPage = _api.Get(_cfg.PageId);
            var oldHash = _hasher.Hash(oldPage.body.view.value);

            var sb = new StringBuilder();

            foreach (var documentEntry in entries)
            {
                sb.AppendLine(documentEntry.Title);
                sb.AppendLine(documentEntry.Content);
            }

            var convertedContent = CommonMarkConverter.Convert(sb.ToString(), CommonMarkSettings.Default);
            var hash             = _hasher.Hash(convertedContent);

            //TODO: Figure out how to detect if this has changed or not. Hashing the confluence content is not the correct approach.
            //TODO: Maybe just look for a key/value pair you can REGEX out that is in the footer
            if (hash == oldHash)
            {
                Debug.WriteLine("HASHes match, ignoring.");
                return(new UpdateResult(ContentResult.Duplicate));
            }

            _api.Put(oldPage, sb.ToString());

            return(new UpdateResult(ContentResult.Ok));
        }
Пример #18
0
        /// <summary>
        /// Reads a CommonMark Markdown document into a Workbook format,
        /// with extension support for YAML blocks.
        /// </summary>
        public void Read(TextReader textReader)
        {
            FirstCell = null;
            LastCell  = null;

            var document       = CommonMarkConverter.Parse(textReader, CommonMarkSettings);
            var codeBlocks     = new List <Block> ();
            var markdownBlocks = new List <Block> ();

            for (var block = document.FirstChild; block != null; block = block.NextSibling)
            {
                if (IsCodeOrMetadataBlock(block, out var languageName, out var extraInfo))
                {
                    AppendCell(markdownBlocks);
                    markdownBlocks.Clear();

                    block.StringContent.TrimEnd();

                    if (block.Tag == BlockTag.YamlBlock)
                    {
                        AppendCell(new YamlMetadataCell(block));
                    }
                    else
                    {
                        AppendCell(new CodeCell(block, languageName, extraInfo));
                    }

                    codeBlocks.Add(block);
                }
Пример #19
0
        private static string GetMarkupFromMarkdown(string examId, string text)
        {
            var document = CommonMarkConverter.Parse(text);

            // walk the document node tree
            foreach (var node in document.AsEnumerable())
            {
                if (
                    // start and end of each node may be visited separately
                    node.IsOpening
                    // blocks are elemets like paragraphs and lists, inlines are
                    // elements like emphasis, links, images.
                    && node.Inline != null &&
                    node.Inline.Tag == InlineTag.Image)
                {
                    node.Inline.TargetUrl = $"/api/Exams/{examId}/Image?path={WebUtility.UrlEncode(Path.GetFileName(node.Inline.TargetUrl))}";
                }
            }

            using (var writer = new System.IO.StringWriter())
            {
                // write the HTML output
                CommonMarkConverter.ProcessStage3(document, writer);
                return(writer.ToString());
            }
        }
Пример #20
0
        private void SetWebViewSourceFromMarkdown()
        {
            string swapCssFunction =
                @"
function _sw(e){ 
    var cssFile = '" + _baseUrl + "'+e+'.css'; " +
                @"document.getElementById('_ss').setAttribute('href',cssFile);
}";
            string head = @"
<head>
    <meta name='viewport' content='width=device-width, initial-scale=1.0, user-scalable=no'>
    <link id='_ss' rel='stylesheet' href='#' >
    <script>" + swapCssFunction + @"</script>
</head>";

            var body = @"
<body>" +
                       CommonMarkConverter.Convert(Markdown) +
                       "</body>";

            Source = new HtmlWebViewSource {
                Html = "<html>" + head + body + "</html>", BaseUrl = _baseUrl
            };

            SetStylesheet();
        }
Пример #21
0
        public Motd(string message)
        {
            InitializeComponent();

            var position = new Point(12, 12);
            var size     = new Size(472, 304);

            if (Shared.isWindows)
            {
                webBrowser = new WebBrowser()
                {
                    Location = position, Size = size, Url = new Uri("about:blank")
                };
                webBrowser.Navigating += webBrowser_Navigating;
                Controls.Add(webBrowser);
                Color  color = this.BackColor;
                string text  = CommonMarkConverter.Convert(message);
                this.html = String.Format(
                    Properties.Resources.motdTemplateHTML,
                    Properties.Resources.motdTemplateCSS,
                    this.Text,
                    text,
                    $"rgb({color.R},{color.G},{color.B})");
            }
            else
            {
                textBox = new TextBox()
                {
                    Location = position, Size = size, ReadOnly = true, BackColor = SystemColors.Window, Multiline = true, ScrollBars = ScrollBars.Both
                };
                Controls.Add(textBox);
                textBox.Text = message;
            }
        }
Пример #22
0
        private List <string> ConvertFile(string fileContent)
        {
            //get full html string from file
            var fileHTML = string.Empty;

            using (var writer = new StringWriter())
            {
                CommonMarkConverter.ProcessStage3(CommonMarkConverter.Parse(fileContent), writer);
                fileHTML += writer.ToString();
            }

            //split the html doc based on headers
            HtmlDocument agilityDoc = new HtmlDocument();

            agilityDoc.LoadHtml(fileHTML);
            var           nodes    = agilityDoc.DocumentNode.ChildNodes.ToArray();
            List <string> sections = nodes.Skip(1).Aggregate(nodes.Take(1).Select(x => x.OuterHtml).ToList(), (a, n) =>
            {
                if (n.Name.ToLower() == "h1" || n.Name.ToLower() == "h2")
                {
                    a.Add("");
                }
                a[a.Count - 1] += n.OuterHtml; return(a);
            });

            return(sections);
        }
Пример #23
0
        public static void markdown2html(ApplicationContext context, ActiveEventArgs e)
        {
            // Making sure we clean up and remove all arguments passed in after execution
            using (new ArgsRemover(e.Args, false)) {
                // Assumes there's only one document, or creates one result of it.
                var md = XUtil.Single <string> (context, e.Args);

                // Making sure we correctly resolve URLs, if user specified a [root-url] argument.
                var root = e.Args.GetExChildValue("root-url", context, "");
                CommonMarkSettings settings = CommonMarkSettings.Default;
                if (root != "")
                {
                    // Unrolling path.
                    root = context.RaiseEvent("p5.io.unroll-path", new Node("", root)).Get <string> (context);

                    // To make sure we don't change global settings.
                    settings             = settings.Clone();
                    settings.UriResolver = delegate(string arg) {
                        if (arg.StartsWithEx("http://") || arg.StartsWithEx("https://"))
                        {
                            return(arg);
                        }
                        return(root + arg.TrimStart('/'));
                    };
                }

                // Doing actual conversion.
                e.Args.Value = CommonMarkConverter.Convert(md, settings);
            }
        }
Пример #24
0
        public ArticleModule() : base("Article")
        {
            Func <ArticlecModel, ArticlecModel> Save = x => {
                if (x.Id == Guid.Empty)
                {
                    x.Id         = Guid.NewGuid();
                    x.CreateDate = DateTime.Now;
                    x.UpdateDate = DateTime.Now;
                    return(db.Insert(x));
                }
                else
                {
                    x            = db.Get <ArticlecModel>(y => y.Id == x.Id);
                    x.UpdateDate = DateTime.Now;
                    return(db.Update(x));
                }
            };

            Func <ArticlecModel, dynamic> ConvertViewModel = x => {
                var result = new {
                    a    = x,
                    html = CommonMarkConverter.Convert(x.Content)
                };
                return(result);
            };

            Get["/{title}"] = param => {
                string title = param.title;
                var    model = db.Get <ArticlecModel>(x => x.Title == title);
                return(View["Article/Index", ConvertViewModel(model)]);
            };

            Get["/Insert"] = param => {
                return(View["Article/Insert", new ArticlecModel()]);
            };

            Get["/{title}/Edit"] = param => {
                string title = param.title;
                var    model = db.Get <ArticlecModel>(x => x.Title == title);
                return(View["Article/Insert", model]);
            };

            Get["/{title}/Delete"] = param => {
                string title = param.title;
                var    model = db.Get <ArticlecModel>(x => x.Title == title);
                db.Delete <ArticlecModel>(model.Id);
                return(View["Home/Index"]);
            };

            Post["/Insert"] = param => {
                var model = this.Bind <ArticlecModel>();
                model = Save(model);
                if (model == null)
                {
                    throw new Exception("程序炸了");
                }
                return(View["Article/Index", ConvertViewModel(model)]);
            };
        }
Пример #25
0
        public Document CreateDocumentFromStream(TextReader reader)
        {
            var commonMarkDocument = CommonMarkConverter.Parse(reader);

            var converter = new ConvertFromCommonMarkToOrderly();

            return(converter.Convert(commonMarkDocument));
        }
Пример #26
0
        public async Task <string> Convert(string text)
        {
            var result = string.Empty;

            await Task.Run(() => { result = CommonMarkConverter.Convert(text); });

            return(result);
        }
Пример #27
0
        /// <summary>
        /// Get converted HTML for readme.md string content.
        /// </summary>
        /// <param name="readMeMd">ReadMe.md content.</param>
        /// <returns>HTML content.</returns>
        internal static string GetReadMeHtml(string readMeMd)
        {
            var encodedMarkdown = HttpUtility.HtmlEncode(readMeMd);
            var regex           = new Regex("<a href=([\"\']).*?\\1");
            var converted       = CommonMarkConverter.Convert(encodedMarkdown);

            return(regex.Replace(converted, "$0" + " rel=\"nofollow\""));
        }
Пример #28
0
        public async Task <string> Convert(Page page)
        {
            var result = string.Empty;

            await Task.Run(() => { result = CommonMarkConverter.Convert(page.Body); });

            return(result);
        }
 private Block ParseDocument(string text)
 {
     using (var reader = new StringReader(Normalize(text)))
     {
         var ast = CommonMarkConverter.ProcessStage1(reader, _commonMarkSettings);
         CommonMarkConverter.ProcessStage2(ast, _commonMarkSettings);
         return(ast);
     }
 }
Пример #30
0
        public IHtmlContent RenderMarkdown(string content)
        {
            byte[] bytes       = Encoding.Default.GetBytes(content);
            var    utf8Content = Encoding.UTF8.GetString(bytes);

            var html = CommonMarkConverter.Convert(utf8Content);

            return(new HtmlString(html));
        }