Esempio n. 1
0
        private void renderPage(object sender, System.Timers.ElapsedEventArgs e)
        {
            DateTime lastWrite = File.GetLastWriteTime(fileName);

            if (lastWrite != latestWrite)
            {
                latestWrite = lastWrite;

                var md = new MarkdownDeep.Markdown();
                md.SafeMode = false;

                TextReader infile = new StreamReader(fileName);
                String     input  = infile.ReadToEnd();
                infile.Close();

                String output;
                if (jekyllMode)
                {
                    output = md.Transform(Regex.Replace(input, @"---[\p{IsBasicLatin}]+---\r", ""));
                }
                else
                {
                    output = md.Transform(input);
                }
                webTargetPage.DocumentText = output;
            }
        }
        public ActionResult Multiple()
        {
            // View the user editable content

            // Create and setup Markdown translator
            var md = new MarkdownDeep.Markdown();

            md.SafeMode  = true;
            md.ExtraMode = true;

            // Transform the content and pass to the view
            ViewData["Content"]  = md.Transform(m_Content);
            ViewData["Content2"] = md.Transform(m_Content2);
            return(View());
        }
        private static void ContentService_Saving(IContentService sender, SaveEventArgs <IContent> e)
        {
            if (UmbracoConfig.For.ArticulateOptions().AutoGenerateExcerpt)
            {
                foreach (var c in e.SavedEntities
                         .Where(c => c.ContentType.Alias.InvariantEquals("ArticulateRichText") || c.ContentType.Alias.InvariantEquals("ArticulateMarkdown")))
                {
                    //fill in the excerpt if it is empty
                    if (c.GetValue <string>("excerpt").IsNullOrWhiteSpace())
                    {
                        if (c.HasProperty("richText"))
                        {
                            var val = c.GetValue <string>("richText");
                            c.SetValue("excerpt", UmbracoConfig.For.ArticulateOptions().GenerateExcerpt(val));
                        }
                        else
                        {
                            var val = c.GetValue <string>("markdown");
                            var md  = new MarkdownDeep.Markdown();
                            val = md.Transform(val);
                            c.SetValue("excerpt", UmbracoConfig.For.ArticulateOptions().GenerateExcerpt(val));
                        }
                    }

                    //now fill in the social description if it is empty with the excerpt
                    if (c.GetValue <string>("socialDescription").IsNullOrWhiteSpace())
                    {
                        c.SetValue("socialDescription", c.GetValue <string>("excerpt"));
                    }
                }
            }
        }
Esempio n. 4
0
        public static void RunResourceTest(string resourceName)
        {
            string input    = Utils.LoadTextResource(resourceName);
            string expected = Utils.LoadTextResource(System.IO.Path.ChangeExtension(resourceName, "html"));

            var md = new MarkdownDeep.Markdown();

            md.SafeMode          = resourceName.IndexOf("(SafeMode)") >= 0;
            md.ExtraMode         = resourceName.IndexOf("(ExtraMode)") >= 0;
            md.GitHubCodeBlocks  = resourceName.IndexOf("(GitHubMode)") >= 0;
            md.DocNetMode        = resourceName.IndexOf("(DocNetMode") >= 0;
            md.ConvertLocalLinks = resourceName.IndexOf("(ConvertLocalLinks") >= 0;
            md.MarkdownInHtml    = resourceName.IndexOf("(MarkdownInHtml)") >= 0;
            md.AutoHeadingIDs    = resourceName.IndexOf("(AutoHeadingIDs)") >= 0;
            if (resourceName.IndexOf("(Titled)") >= 0)
            {
                md.HtmlClassTitledImages = "figure";
            }
            if (md.DocNetMode)
            {
                md.GitHubCodeBlocks = true;
            }

            string actual         = md.Transform(input);
            string actual_clean   = Utils.strip_redundant_whitespace(actual);
            string expected_clean = Utils.strip_redundant_whitespace(expected);

            string sep = new string('-', 30) + "\n";

            Console.WriteLine("Input:\n" + sep + input);
            Console.WriteLine("Actual:\n" + sep + actual);
            Console.WriteLine("Expected:\n" + sep + expected);

            Assert.AreEqual(expected_clean, actual_clean);
        }
Esempio n. 5
0
        private SyndicationFeed GenerateFeed()
        {
            var currentBlog = this.CurrentBlog;

            var md = new MarkdownDeep.Markdown();
            List <SyndicationItem> posts = new List <SyndicationItem>();

            foreach (var post in _postRepository.FeedPosts(currentBlog.Id).OrderByDescending(p => p.Posted).Take(25).AsEnumerable())
            {
                var item = new SyndicationItem(post.Title, post.Body, new Uri(currentBlog.AuthoritiveUrl.TrimEnd('/') + "/" + post.Path.TrimStart('/')));

                item.Title           = new TextSyndicationContent(post.Title);
                item.Content         = new TextSyndicationContent(md.Transform(post.Body), TextSyndicationContentKind.Html);
                item.PublishDate     = new DateTimeOffset(post.Posted);
                item.LastUpdatedTime = new DateTimeOffset(post.Posted);
                item.Id = post.PostGuid.ToString();

                posts.Add(item);
            }


            return(new SyndicationFeed("StaticVoid", "A blog on .Net", new Uri(currentBlog.AuthoritiveUrl), posts)
            {
                Language = "en-US",
                LastUpdatedTime = posts.Any() ? posts.Max(p => p.LastUpdatedTime) : new DateTime(2012, 12, 21),
                Id = currentBlog.BlogGuid.ToString()
            });
        }
		private SyndicationFeed GenerateFeed()        
        {
            var currentBlog = this.CurrentBlog;

            var md = new MarkdownDeep.Markdown();
            List<SyndicationItem> posts = new List<SyndicationItem>();
            foreach (var post in _postRepository.FeedPosts(currentBlog.Id).OrderByDescending(p => p.Posted).Take(25).AsEnumerable())
            {
                var item = new SyndicationItem(post.Title, post.Body, new Uri(currentBlog.AuthoritiveUrl.TrimEnd('/') + "/" + post.Path.TrimStart('/')));

                item.Title = new TextSyndicationContent(post.Title);
                item.Content = new TextSyndicationContent(md.Transform(post.Body), TextSyndicationContentKind.Html);
                item.PublishDate = new DateTimeOffset(post.Posted);
                item.LastUpdatedTime = new DateTimeOffset(post.Posted);
                item.Id = post.PostGuid.ToString();
                                
                posts.Add(item);
            }


            return new SyndicationFeed("StaticVoid", "A blog on .Net", new Uri(currentBlog.AuthoritiveUrl), posts)
			{
				Language = "en-US",
                LastUpdatedTime = posts.Any() ? posts.Max(p=>p.LastUpdatedTime) : new DateTime(2012,12,21),
                Id = currentBlog.BlogGuid.ToString()
			};
		}
Esempio n. 7
0
        public static string FormatMessage(String originalMessage)
        {
            m.ExtraMode = true;
            m.SafeMode  = true;

            return(m.Transform(originalMessage));
        }
        public void PreviewForUnpublishedPostTest()
        {
            IRepository<Post> postRepo = new SimpleRepository<Post>(new InMemoryRepositoryDataSource<Post>(new List<Post> { 
                new Post { Status = PostStatus.Published, Path ="2013/04/10/some-other-post", Posted = new DateTime(2013,4,10), Author = new User{ Email = "" }, BlogId = 1 },
                new Post { 
                    Id = 1,
                    Status = PostStatus.Unpublished, 
                    Path ="2013/04/14/some-post", 
                    Posted = new DateTime(2013,4,14), 
                    Author = new User{ Email = "", FirstName = "Joe", LastName = "Bloggs" },
                    DraftBody = "asdf",
                    DraftTitle = "qwerty", 
                    BlogId = 1
                }
            }));

            PostController sut = new PostController(postRepo, null, _blogRepo, _mockHttpContext.Object);
            var result = (ViewResult)sut.Preview(1);

            Assert.IsNotNull(result);
            var model = result.Model as PostModel;
            Assert.IsNotNull(model);

            var md = new MarkdownDeep.Markdown();
            Assert.AreEqual("Joe Bloggs", model.Author.Name);
            Assert.AreEqual(md.Transform("asdf"), model.Body);
            Assert.AreEqual("qwerty", model.Title);
        }
Esempio n. 9
0
 private void SetMessage(string text)
 {
     var md = new MarkdownDeep.Markdown();
     md.ExtraMode = true;
     md.SafeMode = false;
     ViewBag.Message = md.Transform(text);
 }
Esempio n. 10
0
        public static void RunTestJS(string input, bool SafeMode, bool ExtraMode, bool MarkdownInHtml, bool AutoHeadingIDs)
        {
            string normalized_input = input.Replace("\r\n", "\n").Replace("\r", "\n");

            // Work out the expected output using C# implementation
            var md = new MarkdownDeep.Markdown();
            md.SafeMode = SafeMode;
            md.ExtraMode = ExtraMode;
            md.MarkdownInHtml = MarkdownInHtml;
            md.AutoHeadingIDs = AutoHeadingIDs;
            string expected = md.Transform(normalized_input);

            // Transform using javascript implementation
            string actual = TransformUsingJS(input, SafeMode, ExtraMode, MarkdownInHtml, AutoHeadingIDs);

            actual = actual.Replace("\r", "");
            expected = expected.Replace("\r", "");

            string sep = new string('-', 30) + "\n";

            Console.WriteLine("Input:\n" + sep + input);
            Console.WriteLine("Actual:\n" + sep + actual);
            Console.WriteLine("Expected:\n" + sep + expected);

            // Check it
            Assert.AreEqual(expected, actual);
        }
Esempio n. 11
0
 void ContentService_Saving(IContentService sender, SaveEventArgs <Umbraco.Core.Models.IContent> e)
 {
     foreach (var c in e.SavedEntities)
     {
         //fill in the excerpt if required
         if (c.ContentType.Alias.InvariantEquals("ArticulateRichText") ||
             c.ContentType.Alias.InvariantEquals("ArticulateMarkdown"))
         {
             if (c.GetValue <string>("excerpt").IsNullOrWhiteSpace())
             {
                 if (c.HasProperty("richText"))
                 {
                     var val = c.GetValue <string>("richText");
                     c.SetValue("excerpt", val == null
                         ? string.Empty
                         : string.Join("", val.StripHtml().StripNewLines().Take(200)));
                 }
                 else
                 {
                     var val = c.GetValue <string>("markdown");
                     var md  = new MarkdownDeep.Markdown();
                     val = md.Transform(val);
                     c.SetValue("excerpt", val == null
                         ? string.Empty
                         : string.Join("", val.StripHtml().StripNewLines().Take(200)));
                 }
             }
         }
     }
 }
        private void AddBlogPosts(IContent archiveNode, BlogMLDocument blogMlDoc, string tagGroup)
        {
            const int pageSize  = 1000;
            var       pageIndex = 0;

            IContent[] posts;
            do
            {
                long total;
                posts = _applicationContext.Services.ContentService.GetPagedChildren(archiveNode.Id, pageIndex, pageSize, out total, "createDate").ToArray();

                foreach (var child in posts)
                {
                    string content = "";
                    if (child.ContentType.Alias.InvariantEquals("ArticulateRichText"))
                    {
                        //TODO: this would also need to export all macros
                        content = child.GetValue <string>("richText");
                    }
                    else if (child.ContentType.Alias.InvariantEquals("ArticulateMarkdown"))
                    {
                        content = child.GetValue <string>("markdown");
                        var markdown = new MarkdownDeep.Markdown();
                        content = markdown.Transform(content);
                    }

                    var blogMlPost = new BlogMLPost()
                    {
                        Id             = child.Key.ToString(),
                        Name           = new BlogMLTextConstruct(child.Name),
                        Title          = new BlogMLTextConstruct(child.Name),
                        ApprovalStatus = BlogMLApprovalStatus.Approved,
                        PostType       = BlogMLPostType.Normal,
                        CreatedOn      = child.CreateDate,
                        LastModifiedOn = child.UpdateDate,
                        Content        = new BlogMLTextConstruct(content, BlogMLContentType.Html),
                        Excerpt        = new BlogMLTextConstruct(child.GetValue <string>("excerpt")),
                        Url            = new Uri(_umbracoContext.UrlProvider.GetUrl(child.Id), UriKind.RelativeOrAbsolute)
                    };

                    var author = blogMlDoc.Authors.FirstOrDefault(x => x.Title != null && x.Title.Content.InvariantEquals(child.GetValue <string>("author")));
                    if (author != null)
                    {
                        blogMlPost.Authors.Add(author.Id);
                    }

                    var categories = _applicationContext.Services.TagService.GetTagsForEntity(child.Id, tagGroup);
                    foreach (var category in categories)
                    {
                        blogMlPost.Categories.Add(category.Id.ToString());
                    }

                    //TODO: Tags isn't natively supported

                    blogMlDoc.AddPost(blogMlPost);
                }

                pageIndex++;
            } while (posts.Length == pageSize);
        }
Esempio n. 13
0
        public static void RunResourceTest(string resourceName)
        {
            string input = Utils.LoadTextResource(resourceName);
            string expected = Utils.LoadTextResource(System.IO.Path.ChangeExtension(resourceName, "html"));

            var md = new MarkdownDeep.Markdown();
            md.SafeMode = resourceName.IndexOf("(SafeMode)") >= 0;
            md.ExtraMode = resourceName.IndexOf("(ExtraMode)") >= 0;
            md.GitHubCodeBlocks = resourceName.IndexOf("(GitHubMode)") >= 0;
            md.DocNetMode = resourceName.IndexOf("(DocNetMode") >= 0;
            md.MarkdownInHtml = resourceName.IndexOf("(MarkdownInHtml)") >= 0;
            md.AutoHeadingIDs = resourceName.IndexOf("(AutoHeadingIDs)") >= 0;
            if(resourceName.IndexOf("(Titled)") >= 0)
            {
                md.HtmlClassTitledImages = "figure";
            }
            if(md.DocNetMode)
            {
                md.GitHubCodeBlocks = true;
            }

            string actual = md.Transform(input);
            string actual_clean = Utils.strip_redundant_whitespace(actual);
            string expected_clean = Utils.strip_redundant_whitespace(expected);

            string sep = new string('-', 30) + "\n";

            Console.WriteLine("Input:\n" + sep + input);
            Console.WriteLine("Actual:\n" + sep + actual);
            Console.WriteLine("Expected:\n" + sep + expected);

            Assert.AreEqual(expected_clean, actual_clean);
        }
Esempio n. 14
0
        private void renderPage(object sender, System.Timers.ElapsedEventArgs e)
        {
            DateTime lastWrite = File.GetLastWriteTime(fileName);
            if (lastWrite != latestWrite)
            {
                latestWrite = lastWrite;

                var md = new MarkdownDeep.Markdown();
                md.SafeMode = false;

                TextReader infile = new StreamReader(fileName);
                String input = infile.ReadToEnd();
                infile.Close();

                String output;
                if (jekyllMode)
                {
                    output = md.Transform(Regex.Replace(input, @"---[\p{IsBasicLatin}]+---\r", ""));
                }
                else
                {
                    output = md.Transform(input);
                }
                webTargetPage.DocumentText = output;
            }
        }
Esempio n. 15
0
 public static string FromMarkdown(this HtmlHelper helper, string markdown)
 {
     var md = new MarkdownDeep.Markdown();
     md.SafeMode = true;
     md.ExtraMode = true;
     return md.Transform(markdown);
 }
Esempio n. 16
0
        /// <summary>
        /// Populate the view given the specified text.
        /// </summary>
        /// <param name="contents"></param>
        /// <param name="editingEnabled"></param>
        /// <returns></returns>
        private bool PopulateView(string contents, bool editingEnabled)
        {
            if (contents.Contains(@"{\rtf"))
            {
                richTextBox1.Rtf = contents;
            }
            else
            {
                var doc     = new MigraDoc.DocumentObjectModel.Document();
                var section = doc.AddSection();
                if (contents.Contains("<html>"))
                {
                    HtmlToMigraDoc.Convert(contents, section, ImagePath);
                }
                else
                {
                    MarkdownDeep.Markdown markDown = new MarkdownDeep.Markdown();
                    markDown.ExtraMode = true;
                    string html = markDown.Transform(contents);
                    editingEnabled = true;
                    HtmlToMigraDoc.Convert(html, section, ImagePath);
                }
                RtfDocumentRenderer renderer = new RtfDocumentRenderer();
                richTextBox1.Rtf = renderer.RenderToString(doc, null);
            }

            return(editingEnabled);
        }
Esempio n. 17
0
        public static void RunResourceTest(string resourceName)
        {
            string input    = Utils.LoadTextResource(resourceName);
            string expected = Utils.LoadTextResource(System.IO.Path.ChangeExtension(resourceName, "html"));

            var md = new MarkdownDeep.Markdown();

            md.SafeMode       = resourceName.IndexOf("(SafeMode)") >= 0;;
            md.ExtraMode      = resourceName.IndexOf("(ExtraMode)") >= 0;;
            md.MarkdownInHtml = resourceName.IndexOf("(MarkdownInHtml)") >= 0;
            md.AutoHeadingIDs = resourceName.IndexOf("(AutoHeadingIDs)") >= 0;
            md.RespectOrderedListStartValues = resourceName.IndexOf("(OLStart)") >= 0;

            string actual         = md.Transform(input);
            string actual_clean   = Utils.strip_redundant_whitespace(actual);
            string expected_clean = Utils.strip_redundant_whitespace(expected);

            string sep = new string('-', 30) + "\n";

            Console.WriteLine("Input:\n" + sep + input);
            Console.WriteLine("Actual:\n" + sep + actual);
            Console.WriteLine("Expected:\n" + sep + expected);

            Assert.AreEqual(expected_clean, actual_clean);
        }
Esempio n. 18
0
        public ActionResult Preview(int id)
        {
            var currentBlog = CurrentBlog;
            int blogId      = currentBlog.Id;

            var post = _postRepository.PostsForBlog(currentBlog.Id, p => p.Author).FirstOrDefault(p => p.Id == id);

            if (post == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.NotFound));
            }

            var md = new MarkdownDeep.Markdown();

            return(View("Post", new PostModel
            {
                Body = md.Transform(post.DraftBody),
                Description = post.DraftDescription,
                Title = post.DraftTitle,
                Posted = DateTime.Now,
                CanonicalUrl = post.Canonical,
                OtherPosts = new List <PartialPostForLinkModel>(),
                Author = new PostAuthor
                {
                    GravatarUrl = post.Author.Email.GravitarUrlFromEmail(),
                    Name = post.Author.FullName(),
                    GooglePlusProfileUrl = post.Author.GooglePlusProfileUrl
                }
            }));
        }
        public static void RunTestJS(string input, bool SafeMode, bool ExtraMode, bool MarkdownInHtml, bool AutoHeadingIDs)
        {
            string normalized_input = input.Replace("\r\n", "\n").Replace("\r", "\n");

            // Work out the expected output using C# implementation
            var md = new MarkdownDeep.Markdown();

            md.SafeMode       = SafeMode;
            md.ExtraMode      = ExtraMode;
            md.MarkdownInHtml = MarkdownInHtml;
            md.AutoHeadingIDs = AutoHeadingIDs;
            string expected = md.Transform(normalized_input);

            // Transform using javascript implementation
            string actual = TransformUsingJS(input, SafeMode, ExtraMode, MarkdownInHtml, AutoHeadingIDs);

            actual   = actual.Replace("\r", "");
            expected = expected.Replace("\r", "");

            string sep = new string('-', 30) + "\n";

            Console.WriteLine("Input:\n" + sep + input);
            Console.WriteLine("Actual:\n" + sep + actual);
            Console.WriteLine("Expected:\n" + sep + expected);

            // Check it
            Assert.AreEqual(expected, actual);
        }
Esempio n. 20
0
        private void SetMessage(string text)
        {
            var md = new MarkdownDeep.Markdown();

            md.ExtraMode    = true;
            md.SafeMode     = false;
            ViewBag.Message = md.Transform(text);
        }
Esempio n. 21
0
        private void PrepareJobSearchView(JobSearch jobSearch)
        {
            var md = new MarkdownDeep.Markdown();

            ViewBag.JobSearchId = jobSearch.Id;
            ViewBag.Title       = jobSearch.Title;
            ViewBag.PublicNotes = new MvcHtmlString(md.Transform(jobSearch.PublicNotes));
        }
Esempio n. 22
0
        public static string GetHtmlFromMarkdown(string markdownText)
        {
            var md = new MarkdownDeep.Markdown();
            md.ExtraMode = true;
            md.SafeMode = false;

            return md.Transform(markdownText);
        }
Esempio n. 23
0
        public static string MarkdownTransform(this HtmlHelper html, string paramToTransform)
        {
            var markdown = new MarkdownDeep.Markdown();
            markdown.SafeMode = false;
            markdown.ExtraMode = true;

            return markdown.Transform(paramToTransform);
        }
Esempio n. 24
0
        private static string ParseMarkdown(string markdown)
        {
            var md = new MarkdownDeep.Markdown();
            md.ExtraMode = true;
            md.SafeMode = false;

            return md.Transform(markdown);
        }
Esempio n. 25
0
        public static string FromMarkdown(this HtmlHelper helper, string markdown)
        {
            var md = new MarkdownDeep.Markdown();

            md.SafeMode  = true;
            md.ExtraMode = true;
            return(md.Transform(markdown));
        }
Esempio n. 26
0
        public string Transform(string markdown)
        {
            var markdownDeep = new MarkdownDeep.Markdown {
                ExtraMode = true
            };

            return(markdownDeep.Transform(markdown));
        }
Esempio n. 27
0
        private void TextUpdate(object sender, EventArgs e)
        {
            MarkdownDeep.Markdown markDown = new MarkdownDeep.Markdown();
            markDown.ExtraMode = true;
            string html = markDown.Transform(memoView1.MemoText);

            PopulateView(html);
        }
Esempio n. 28
0
        private void PrepareJobSearchView(JobSearch jobSearch)
        {
            var md = new MarkdownDeep.Markdown();

            ViewBag.JobSearchId          = jobSearch.Id;
            ViewBag.Title                = jobSearch.Title;
            ViewBag.PublicNotes          = new MvcHtmlString(md.Transform(jobSearch.PublicNotes));
            ViewBag.TechnicalSkillLevels = TechnicalSkillLevelExtensions.GetValues();
        }
Esempio n. 29
0
        private static string ParseMarkdown(string markdown)
        {
            var md = new MarkdownDeep.Markdown();

            md.ExtraMode = true;
            md.SafeMode  = false;

            return(md.Transform(markdown));
        }
Esempio n. 30
0
        public static string FormatMessage(String originalMessage)
        {
            MarkdownDeep.Markdown m = new MarkdownDeep.Markdown();

            m.ExtraMode = true;
            m.SafeMode = true;

            return m.Transform(originalMessage);
        }
Esempio n. 31
0
        public static string GetHtmlFromMarkdown(string markdownText)
        {
            var md = new MarkdownDeep.Markdown();

            md.ExtraMode = true;
            md.SafeMode  = false;

            return(md.Transform(markdownText));
        }
        public PagedSet<EventInfo> GetEvents(int skip, int take, bool includeExpired, bool includeRsvpCount, bool includeDeleted)
        {
            var posts = _context.Events
                .Where(w => w.PublishStartTime <= DateTime.Now || w.PublishStartTime == null || includeExpired)
                .Where(w => w.PublishEndTime >= DateTime.Now || w.PublishEndTime == null || includeExpired)
                .Where(w => includeDeleted || !w.IsDeleted)
                .OrderByDescending(o => o.PublishStartTime)
                .Include(cbu => cbu.CreatedByUser)
                .Include(g => g.Groups)
                
                .Select(s => s);

            int totalPosts = posts.Count();

            var md = new MarkdownDeep.Markdown();
            md.ExtraMode = true;
            md.SafeMode = false;

            var mappedPosts = posts.Skip(skip).Take(take).ToList()
                .Select(s =>
                   new EventInfo()
                    {
                        PublishStartTime = s.PublishStartTime,
                        Body = s.Body,
                        HtmlBody = md.Transform(s.Body),
                        HtmlBodySummary = md.Transform(s.Body.Length <= 500 ? s.Body : s.Body.Substring(0, 500).TrimEnd() + "...."),
                        CreatedByUserId = s.CreatedByUserId,
                        CreatedByUserName = GetUserName(s.CreatedByUser),
                        EventEndTime = (s as Event).EventEndTime,
                        EventStartTime = (s as Event).EventStartTime,
                        Id = s.Id,
                        Title = s.Title,
                        GroupTags = s.Groups.Select(g=> g.Id), 
                        PublishEndTime =  s.PublishEndTime,
                        IsDeleted = s.IsDeleted,
                        AvailableGroups = AvailableGroups,
                        VimeoId = (s as Event).VimeoId, 
                        TotalRsvpCount = includeRsvpCount ?  _context.Rsvps.Count(w => w.EventId == s.Id): 0
                        
                    });

            return new PagedSet<EventInfo>(totalPosts,skip, take,  mappedPosts);
        }
Esempio n. 33
0
        private static void ConvertToHtml(string inputfilename, string outputfilename)
        {
            string mdText = File.ReadAllText(inputfilename);
            var    md     = new MarkdownDeep.Markdown();

            md.ExtraMode = true;
            string output = md.Transform(mdText);

            File.WriteAllText(outputfilename, output);
        }
 public static List<PostEntity> GetPagesFromCache(this ICacheService cacheService, IPost postRepository, string keyName, bool isMarkdown)
 {
     var markdown = new MarkdownDeep.Markdown{ ExtraMode = true };
     var pages = cacheService.Get(keyName, () => postRepository.GetPages());
     if (isMarkdown)
     {
         pages.ForEach(p => p.PostContent = markdown.Transform(p.PostContent));
     }
     return pages;
 }
Esempio n. 35
0
 public override void SetValue(object value)
 {
     if (value != null)
     {
         string html           = (string)value;
         var    MarkDownEngine = new MarkdownDeep.Markdown();
         html = MarkDownEngine.Transform(html);
         webView.LoadHtmlString(html, new Foundation.NSUrl(""));
     }
 }
Esempio n. 36
0
        public PagedSet <EventInfo> GetEvents(int skip, int take, bool includeExpired, bool includeRsvpCount, bool includeDeleted)
        {
            var posts = _context.Events
                        .Where(w => w.PublishStartTime <= DateTime.Now || w.PublishStartTime == null || includeExpired)
                        .Where(w => w.PublishEndTime >= DateTime.Now || w.PublishEndTime == null || includeExpired)
                        .Where(w => includeDeleted || !w.IsDeleted)
                        .OrderByDescending(o => o.PublishStartTime)
                        .Include(cbu => cbu.CreatedByUser)
                        .Include(g => g.Groups)

                        .Select(s => s);

            int totalPosts = posts.Count();

            var md = new MarkdownDeep.Markdown();

            md.ExtraMode = true;
            md.SafeMode  = false;

            var mappedPosts = posts.Skip(skip).Take(take).ToList()
                              .Select(s =>
                                      new EventInfo()
            {
                PublishStartTime  = s.PublishStartTime,
                Body              = s.Body,
                HtmlBody          = md.Transform(s.Body),
                HtmlBodySummary   = md.Transform(s.Body.Length <= 500 ? s.Body : s.Body.Substring(0, 500).TrimEnd() + "...."),
                CreatedByUserId   = s.CreatedByUserId,
                CreatedByUserName = GetUserName(s.CreatedByUser),
                EventEndTime      = (s as Event).EventEndTime,
                EventStartTime    = (s as Event).EventStartTime,
                Id              = s.Id,
                Title           = s.Title,
                GroupTags       = s.Groups.Select(g => g.Id),
                PublishEndTime  = s.PublishEndTime,
                IsDeleted       = s.IsDeleted,
                AvailableGroups = AvailableGroups,
                VimeoId         = (s as Event).VimeoId,
                TotalRsvpCount  = includeRsvpCount ?  _context.Rsvps.Count(w => w.EventId == s.Id): 0
            });

            return(new PagedSet <EventInfo>(totalPosts, skip, take, mappedPosts));
        }
        public ActionResult Index(DiscussionData data)
        {
            Compression.SetCompression();
            var code = Model.GetCode(data.Guid, true);

            if (code == null)
            {
                throw new HttpException(404, "not found");
            }

            if (!string.IsNullOrEmpty(data.NewComment))
            {
                if (!SessionManager.IsUserInSession())
                {
                    return(this.Redirect(Utils.Utils.BaseUrl + @"login"));
                }
                Model.SaveComment(new Comment()
                {
                    User_Id = (int)SessionManager.UserId,
                    Text    = data.NewComment,
                    Code_Id = code.ID
                });
                return(this.Redirect(Utils.Utils.BaseUrl + @"discussion/" + code.Guid + "#comment_" + Model.Comment_Last_Id(code.ID)));
            }


            if (!code.IsOnAWall)
            {
                data.Title = "Discussion not available";
            }
            else
            {
                data.Title = code.Title;
            }

            data.Related      = Model.GeRelated(code.ID);
            data.Votes        = code.Votes;
            data.VoteUp       = code.Voted;
            data.ShowComments = code.IsOnAWall;
            data.Code         = code.Program;
            data.Date         = code.Date;
            data.Language     = code.Lang;

            data.Comments = Model.GetComments(data.Guid);

            var md = new MarkdownDeep.Markdown();

            md.ExtraMode = true;
            md.SafeMode  = true;
            foreach (var c in data.Comments)
            {
                c.Text = md.Transform(c.Text);
            }
            return(View(data));
        }
 protected override XElement CreateElement(CmsContext context, CmsPart part)
 {
     var md = new MarkdownDeep.Markdown
     {
         ExtraMode = true,
         SafeMode = false,
         NewWindowForExternalLinks = true,
         FormatCodeBlock = (markdown, s) => FormatCodeBlock(context, markdown, s)
     };
     return Parse(md.Transform(part.Value));
 }
Esempio n. 39
0
        public static string ConvertMdToHtml(this string text)
        {
            // Create and setup Markdown translator
            var md = new MarkdownDeep.Markdown();

            md.SafeMode  = true;
            md.ExtraMode = true;

            // Transform the content and pass to the view
            return(md.Transform(text));
        }
Esempio n. 40
0
        private IEnumerable <EventInfo> MapEventToEventInfo(IEnumerable <Event> sourceEvent)
        {
            var md = new MarkdownDeep.Markdown {
                ExtraMode = true, SafeMode = false
            };

            return(sourceEvent.Select(s => new EventInfo()
            {
                PublishStartTime = s.PublishStartTime,
                Body = s.Body,
                HtmlBody = md.Transform(s.Body),
                HtmlBodySummary = md.Transform(s.Body.Length <= 500 ? s.Body : s.Body.Substring(0, 500)),
                CreatedByUserId = s.CreatedByUserId,
                EventEndTime = (s as Event).EventEndTime,
                EventStartTime = (s as Event).EventStartTime,
                Id = s.Id,
                Title = s.Title,
                AvailableGroups = AvailableGroups
            }));
        }
        public ActionResult Index()
        {
            // View the user editable content

            // Create and setup Markdown translator
            var md = new MarkdownDeep.Markdown { SafeMode = true, ExtraMode = true };

            // Transform the content and pass to the view
            ViewBag.Content = md.Transform(m_Content);
            return View();
        }
Esempio n. 42
0
        private void richTxt_markdown_TextChanged(object sender, EventArgs e)
        {
            string str = richTxt_markdown.Text;

            MarkdownDeep.Markdown markdown = new MarkdownDeep.Markdown()
            {
                ExtraMode = true
            };
            richTxt_html.Text        = markdown.Transform(str);
            webBrowser1.DocumentText = markdown.Transform(str);

            toolStripStatusLabel1.Text = "BMarkdownEditor";
            if (Utils.EditorIO.FilePath != null)
            {
                toolStripStatusLabel2.Text = "<未保存>" + Utils.EditorIO.FilePath;
            }
            else
            {
                toolStripStatusLabel2.Text = "<未保存>未命名文件";
            }
        }
        /// <summary>
        /// Returns contents of the readme parsed to HTML
        /// </summary>
        /// <returns></returns>
        public string ProvideParsedReadme()
        {
            string readmeLocation = Path.Combine(_absoluteRepositoryPath, "README.md");

            if (!File.Exists(readmeLocation))
            {
                return(String.Empty);
            }
            var md = new MarkdownDeep.Markdown();

            return(md.Transform(File.ReadAllText(readmeLocation)));
        }
Esempio n. 44
0
        public override void Warmup(MarkdownTestSuite suite)
        {
            markdown = new MarkdownDeep.Markdown();
            var tests = suite.HtmlTests;

            for (int testNum = 0; testNum < tests.Length; testNum++)
            {
                var test      = tests[testNum];
                var generated = markdown.Transform(test.Text);
                MarkdownTests.CompareHtml(test.Html, generated);
            }
        }
        public IContentProvider FillProvider(IContentProvider provider)
        {
            var md = new MarkdownDeep.Markdown
            {
                ExtraMode = true,
                SafeMode  = false,
            };

            provider.Content = md.Transform(File.ReadAllText(_Path));

            return(provider);
        }
Esempio n. 46
0
 public String ReadAndTransformMarkdownFile(String path)
 {
     var md = File.ReadAllText(path);
     try
     {
         var markdown = new MarkdownDeep.Markdown();
         return markdown.Transform(md);
     }
     catch
     {
         return md;
     }
 }
Esempio n. 47
0
        /// <summary>
        /// Converts the markdown text to HTML.
        /// </summary>
        /// <param name="preClassName">Optional parameter to insert an HTML class for all 'pre' tags.</param>
        /// <param name="extraMode">Defaults to false.</param>
        /// <param name="safeMode">Defaults to true.</param>
        /// <returns></returns>
        public static string MarkdownToHtml(this string markdown, string preClassName = "", bool extraMode = false, bool safeMode = true)
        {
            var md = new MarkdownDeep.Markdown();
            md.ExtraMode = extraMode;
            md.SafeMode = safeMode;

            var html = md.Transform(markdown);

            if (!string.IsNullOrEmpty(preClassName))
                html = html.Replace("<pre>", "<pre class=\"" + preClassName + "\">");

            return html;
        }
        public static string markdown_Transform(this string markdown)
        {
            var md = new MarkdownDeep.Markdown
                         {
                             SafeMode       = SafeMode,       // was false in the MarkdownDeep demo app
                             ExtraMode      = ExtraMode,          // was true, was creating some probs with HTML conversion (too agreesive on spaces)
                             AutoHeadingIDs = true,
                             MarkdownInHtml = true,
                             NewWindowForExternalLinks = true,

                         };
            return md.Transform(markdown);
        }
Esempio n. 49
0
 private async void RenderMarkdown()
 {
     if (!string.IsNullOrEmpty(MarkdownFilePath)) // check if MarkdownFilePath is set or not
     {
         var m = new MarkdownDeep.Markdown(); // alternative: MarkdownSharp.Markdown(); rest of the syntax is the same
         string markdown = await Helpers.ReadAllLinesAsync(MarkdownFilePath);
         _renderedMarkdown = m.Transform(markdown);
         _html = "<html>\n<head>\n<style>\n"+ _css + "</style>\n</head>\n<body oncontextmenu='return true'>\n" + _renderedMarkdown + "</body>\n</html>";
         Viewer.LoadHtml(_html, "http://renderpage/");
         _pageLoaded = true;
         ExportToHTML.IsEnabled = true;
     }
 }
Esempio n. 50
0
        public static void RenderMarkdown(this HtmlHelper helper, string filename)
        {
            // Load source text
            var text = System.IO.File.ReadAllText(helper.ViewContext.HttpContext.Server.MapPath(filename));

            // Setup processor
            var md = new MarkdownDeep.Markdown();
            md.SafeMode = false;
            md.ExtraMode = true;
            md.AutoHeadingIDs = true;
            md.MarkdownInHtml = true;
            md.NewWindowForExternalLinks = true;

            // Write it
            helper.ViewContext.HttpContext.Response.Write(md.Transform(text));
        }
Esempio n. 51
0
        public static AchievementView ConverToAchievementView(this Achievement achievement, int gravatarSize = 40, bool convertMarkdown = false)
        {
            var md = new MarkdownDeep.Markdown();

            return new AchievementView
            {
                Id = achievement.Id,
                Comment = (convertMarkdown ? md.Transform(achievement.Comment) : achievement.Comment),
                DateCreated = achievement.DateCreated,
                UserName = achievement.User.UserName,
                GravatarUrl = achievement.User.Email.ToGravatarUrl(gravatarSize),
                Resolution = achievement.Resolution.ToString(),
                IsOnCourse = achievement.Resolution == Resolution.OnCourse,
                PrettyDate = achievement.DateCreated.FriendlyParse()
            };
        }
Esempio n. 52
0
 public String ReadAndTransformMarkdownFile(String path)
 {
     var md = File.ReadAllText(path);
     try
     {
         var markdown = new MarkdownDeep.Markdown()
         {
             FormatCodeBlock = (mdd, s) =>
             {
                 return "<pre class=\"prettyprint\"><code>" + s + "</code></pre>";
             }
         };
         return markdown.Transform(md);
     }
     catch
     {
         return md;
     }
 }
Esempio n. 53
0
        /// <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>
        /// <returns></returns>
        public static string ConvertMarkdownToHtml(string toConvert, string destinationDocumentPath, string siteRoot, string sourceDocumentFilename, 
                                                   List<Tuple<string, string>> createdAnchorCollector)
        {
            var parser = new MarkdownDeep.Markdown
                         {
                             ExtraMode = true,
                             GitHubCodeBlocks = true,
                             AutoHeadingIDs = true,
                             NewWindowForExternalLinks = true,
                             DocNetMode = true,
                             DestinationDocumentLocation = destinationDocumentPath,
                             DocumentRoot = siteRoot,
                             SourceDocumentFilename = sourceDocumentFilename,
                             HtmlClassTitledImages = "figure",
                         };

            var toReturn = parser.Transform(toConvert);
            createdAnchorCollector.AddRange(parser.CreatedH2IdCollector);
            return toReturn;
        }
        public void Send(string LogMessage, int parentProject, string posterName)
        {
            LogEntry newEntry = new LogEntry();
            newEntry.Content = LogMessage;
            newEntry.ParentProject = parentProject;
            string text = posterName.Replace("WARE", "WARE\\");
            newEntry.PostedBy = db.Users.Where(b => b.Username == text).First();
            newEntry.PostedOn = DateTime.Now;

            db.LogEntries.Add(newEntry);
            db.SaveChanges();

            var md = new MarkdownDeep.Markdown();
            md.ExtraMode = true;
            md.SafeMode = false;

            string MarkdownOutput = md.Transform(LogMessage);
            string output = "<div style='display: none;' class='custom-panels panel panel-default'><div class='panel-body' style='margin-bottom: 12px;'>" + MarkdownOutput + "<br /><i class='pull-right' style='font-size: smaller;'>Posted by " + newEntry.PostedBy.FirstName + " " + newEntry.PostedBy.LastName + " on " + newEntry.PostedOn.ToShortDateString() + "</i></div></div>";
            Clients.All.send(output, parentProject);
        }
 /// <summary>
 /// Converts a value. 
 /// </summary>
 /// <returns>
 /// A converted value. If the method returns null, the valid null value is used.
 /// </returns>
 /// <param name="value">The value produced by the binding source.</param><param name="targetType">The type of the binding target property.</param><param name="parameter">The converter parameter to use.</param><param name="culture">The culture to use in the converter.</param>
 public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
 {
     try
     {
         var markdown = value as string;
         if (markdown != null)
         {
             var md = new MarkdownDeep.Markdown();
             md.ExtraMode = true;
             md.NewWindowForExternalLinks = true;
             md.NewWindowForLocalLinks = true;
             var body = md.Transform( markdown );
             var html = GetHtmlHeader() + body + Properties.Resources.IssueHtmlFooter;
             return html;
         }
     }
     catch (FormatException e)
     {
         _log.Write(LogLevel.Warn, "Failed to create Markdown HTML", e );
     }
     return string.Empty;
 }
        public ActionResult Index(DefaultModel model)
        {
            if(model == null || string.IsNullOrWhiteSpace(model.PostMarkdown))
            {
                model = new DefaultModel();
                model.PostMarkdown = m_Content;
            }
            else
            {
                var md = new MarkdownDeep.Markdown();

                md.ExtraMode = true;
                md.SafeMode = true;

                string output = md.Transform(model.PostMarkdown);
                ViewBag.Content = output;

                ViewBag.Saved = true;
            }

            // save the content to db or any other persistence
            return View(model);
        }
Esempio n. 57
0
        public static void RunJavascriptTest(string input, bool safeMode, bool extraMode, bool markdownInHtml, bool autoHeadingIDs)
        {
            var normalizedInput = input.Replace("\r\n", "\n").Replace("\r", "\n");

            var md = new MarkdownDeep.Markdown();
            md.SafeMode = safeMode;
            md.ExtraMode = extraMode;
            md.MarkdownInHtml = markdownInHtml;
            md.AutoHeadingIDs = autoHeadingIDs;
            var expected = md.Transform(normalizedInput);

            var actual = TransformUsingJavascriptRuntime(input, safeMode, extraMode, markdownInHtml, autoHeadingIDs);

            actual = actual.Replace("\r", "");
            expected = expected.Replace("\r", "");

            var sep = new string('-', 30) + "\n";

            Console.WriteLine("Input:\n" + sep + input);
            Console.WriteLine("Actual:\n" + sep + actual);
            Console.WriteLine("Expected:\n" + sep + expected);

            Assert.AreEqual(expected, actual);
        }
Esempio n. 58
0
        public static void RunResourceTest(string resourceName)
        {
            var input = LoadTextResource(resourceName);

            var expected = LoadTextResource(Path.ChangeExtension(resourceName, "html"));

            var md = new MarkdownDeep.Markdown();
            md.SafeMode = resourceName.IndexOf("(SafeMode)") >= 0; ;
            md.ExtraMode = resourceName.IndexOf("(ExtraMode)") >= 0; ;
            md.MarkdownInHtml = resourceName.IndexOf("(MarkdownInHtml)") >= 0;
            md.AutoHeadingIDs = resourceName.IndexOf("(AutoHeadingIDs)") >= 0;

            var actual = md.Transform(input);
            var actualClean = actual.StripRedundantWhitespace();
            var expectedClean = expected.StripRedundantWhitespace();

            var sep = new string('-', 30) + "\n";

            Console.WriteLine("Input:\n" + sep + input);
            Console.WriteLine("Actual:\n" + sep + actual);
            Console.WriteLine("Expected:\n" + sep + expected);

            Assert.AreEqual(expectedClean, actualClean);
        }
Esempio n. 59
0
        //----------------------------------------------------------------------
        // BackgroundWorker browser preview
        //----------------------------------------------------------------------
        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            string ResultText = (string)e.Argument;
            string MkResultText = "";

            string BackgroundColorString;
            string EncodingName;

            //編集中のファイル名
            //Editing file name
            string FileName = (_MarkDownTextFilePath == "" ? "" : Path.GetFileName(_MarkDownTextFilePath));
            //DOCTYPE
            HtmlHeader htmlHeader = new HtmlHeader();
            string DocType = htmlHeader.GetHtmlHeader(MarkDownSharpEditor.AppSettings.Instance.HtmlDocType);

            //マーキングの色づけ
            //Marker's color
            if (MarkDownSharpEditor.AppSettings.Instance.fHtmlHighLightColor == true)
            {
                Color ColorBackground = Color.FromArgb(MarkDownSharpEditor.AppSettings.Instance.HtmlHighLightColor);
                BackgroundColorString = ColorTranslator.ToHtml(ColorBackground);
            }
            else
            {
                BackgroundColorString = "none";
            }

            //指定のエンコーディング
            //Codepage
            int CodePageNum = MarkDownSharpEditor.AppSettings.Instance.CodePageNumber;
            try
            {
                Encoding enc = Encoding.GetEncoding(CodePageNum);
                //ブラウザ表示に対応したエンコーディングか
                //Is the encoding supported browser?
                if (enc.IsBrowserDisplay == true)
                {
                    EncodingName = enc.WebName;
                }
                else
                {
                    EncodingName = "utf-8";
                }
            }
            catch
            {
                //エンコーディングの取得に失敗した場合
                //Default encoding if failing to get encoding
                EncodingName = "utf-8";
            }
            //Header
            string header = string.Format(
            @"{0}
            <html>
            <head>
            <meta http-equiv='Content-Type' content='text/html; charset={1}' />
            <link rel='stylesheet' href='{2}' type='text/css' />
            <style type='text/css'>
             ._mk {{background-color:{3}}}
            </style>
            <title>{4}</title>
            </head>
            <body>
            ",
            DocType,               //DOCTYPE
            EncodingName,          //エンコーディング ( encoding )
            _SelectedCssFilePath,   //適用中のCSSファイル ( Selected CSS file )
            BackgroundColorString, //編集箇所の背景色 ( background color in Editing )
            FileName);             //タイトル(=ファイル名) ( title = file name )

            //Footer
            string footer = "</body>\n</html>";

            //-----------------------------------
            //Markdown parse ( default )
            //Markdown mkdwn = new Markdown();
            //-----------------------------------

            //-----------------------------------
            // MarkdownDeep
            // Create an instance of Markdown
            //-----------------------------------
            var mkdwn = new MarkdownDeep.Markdown();
            // Set options
            mkdwn.ExtraMode = MarkDownSharpEditor.AppSettings.Instance.fMarkdownExtraMode;
            mkdwn.SafeMode = false;
            //-----------------------------------

            ResultText = mkdwn.Transform(ResultText);
            //表示するHTMLデータを作成
            //Creat HTML data
            ResultText = header + ResultText + footer;

            //パースされた内容から編集行を探す
            //Search editing line in parsed data
            string OneLine;
            StringReader sr = new StringReader(ResultText);
            StringWriter sw = new StringWriter();
            while ((OneLine = sr.ReadLine()) != null)
            {
                if (OneLine.IndexOf("<!-- edit -->") >= 0)
                {
                    MkResultText += ("<div class='_mk'>" + OneLine + "</div>\n");
                }
                else
                {
                    MkResultText += (OneLine + "\n");
                }
            }

            //エンコーディングしつつbyte値に変換する(richEditBoxは基本的にutf-8 = 65001)
            //Encode and convert it to 'byte' value ( richEditBox default encoding is utf-8 = 65001 )
            byte[] bytesData = Encoding.GetEncoding(CodePageNum).GetBytes(MkResultText);

            //-----------------------------------
            // Write to temporay file
            if (_fNoTitle == false)
            {
                //テンポラリファイルパスを取得する
                //Get temporary file path
                if (_TemporaryHtmlFilePath == "")
                {
                    _TemporaryHtmlFilePath = Get_TemporaryHtmlFilePath(_MarkDownTextFilePath);
                }
                //他のプロセスからのテンポラリファイルの参照と削除を許可して開く(でないと飛ぶ)
                //Open temporary file to allow references from other processes
                using (FileStream fs = new FileStream(
                    _TemporaryHtmlFilePath,
                    FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.Read | FileShare.Delete))
                {
                    fs.Write(bytesData, 0, bytesData.Length);
                    e.Result = _TemporaryHtmlFilePath;
                }
            }
            //-----------------------------------
            // Navigate and view in browser
            else
            {
                //Write data as it is, if the editing data is no title
                ResultText = Encoding.GetEncoding(CodePageNum).GetString(bytesData);
                e.Result = ResultText;
            }
        }
Esempio n. 60
0
        //----------------------------------------------------------------------
        // HTML形式出力 ( Output to HTML file )
        //----------------------------------------------------------------------
        private bool OutputToHtmlFile(string FilePath, string SaveToFilePath, bool fToClipboard = false)
        {
            if (File.Exists(FilePath) == false)
            {
                return (false);
            }

            //出力内容 ( Output data )
            string ResultText = "";
            //HTMLタグ ( HTML Header tag )
            string HeaderString = "";
            string FooterString = "";
            //文字コード ( Character encoding )
            string EncodingName;
            Encoding encRead = Encoding.UTF8;
            Encoding encHtml = Encoding.UTF8;

            //-----------------------------------
            //編集中のファイルパス or 投げ込まれたファイルパス
            //Editing file path or Drag & Dropped files
            string FileName = Path.GetFileName(FilePath);

            //-----------------------------------
            //DOCTYPE
            HtmlHeader htmlHeader = new HtmlHeader();
            string DocType = htmlHeader.GetHtmlHeader(MarkDownSharpEditor.AppSettings.Instance.HtmlDocType);
            //Web用の相対パス
            //Relative url
            string CssPath = RerativeFilePath(FilePath, _SelectedCssFilePath);

            //-----------------------------------
            //指定のエンコーディング
            //Codepage
            int CodePageNum = MarkDownSharpEditor.AppSettings.Instance.CodePageNumber;
            try
            {
                encHtml = Encoding.GetEncoding(CodePageNum);
                //ブラウザ表示に対応したエンコーディングか
                //Is the encoding supported browser?
                if (encHtml.IsBrowserDisplay == true)
                {
                    EncodingName = encHtml.WebName;
                }
                else
                {
                    EncodingName = "utf-8";
                    encHtml = Encoding.UTF8;
                }
            }
            catch
            {
                //エンコーディングの取得に失敗した場合はデフォルト
                //Default encoding if failing to get encoding
                EncodingName = "utf-8";
                encHtml = Encoding.UTF8;
            }

            //HTMLのヘッダを挿入する
            //Insert HTML Header
            if (MarkDownSharpEditor.AppSettings.Instance.fHtmlOutputHeader == true)
            {
                //CSSファイルを埋め込む
                //Embeding CSS file contents
                if (MarkDownSharpEditor.AppSettings.Instance.HtmlCssFileOption == 0)
                {
                    string CssContents = "";

                    if (File.Exists(_SelectedCssFilePath) == true)
                    {
                        using (StreamReader sr = new StreamReader(_SelectedCssFilePath, encHtml))
                        {
                            CssContents = sr.ReadToEnd();
                        }
                    }

                    //ヘッダ ( Header )
                    HeaderString = string.Format(
            @"{0}
            <html>
            <head>
            <meta http-equiv='Content-Type' content='text/html; charset={1}' />
            <title>{2}</title>
            <style>
            <!--
            {3}
            -->
            </style>
            </head>
            <body>
            ",
                        DocType,         //DOCTYPE
                        EncodingName,    //エンコーディング ( Encoding )
                        FileName,        //タイトル(=ファイル名) ( Title = file name )
                        CssContents);	   //CSSの内容 ( Contents of CSS file )
                }
                //metaタグ(外部リンキング)(Meta tag: external linking )
                else
                {
                    //ヘッダ ( Header )
                    HeaderString = string.Format(
            @"{0}
            <html>
            <head>
            <meta http-equiv='Content-Type' content='text/html; charset={1}' />
            <link rel='stylesheet' href='{2}' type='text/css' />
            <title>{3}</title>
            </head>
            <body>
            ",
                DocType,         //DOCTYPE
                EncodingName,    //エンコーディング ( Encoding )
                CssPath,         //CSSファイル(相対パス)( Relative url )
                FileName);		   //タイトル(=ファイル名) ( Title = file name )
                }
                //フッタ ( Footer )
                FooterString = "</body>\n</html>";
            }
            else
            {
                HeaderString = "";
                FooterString = "";
            }

            //-----------------------------------
            //Markdown parse ( default )
            //Markdown mkdwn = new Markdown();
            //-----------------------------------

            //-----------------------------------
            // MarkdownDeep
            // Create an instance of Markdown
            //-----------------------------------
            var mkdwn = new MarkdownDeep.Markdown();
            // Set options
            mkdwn.ExtraMode = MarkDownSharpEditor.AppSettings.Instance.fMarkdownExtraMode;
            mkdwn.SafeMode = false;
            //-----------------------------------

            //編集中のファイル(richEditBoxの内容)
            //Editing file path
            if (_MarkDownTextFilePath == FilePath)
            {
                ResultText = mkdwn.Transform(richTextBox1.Text);
                //エンコーディング変換(richEditBoxは基本的にutf-8)
                //Convert encoding ( richEditBox default encoding is utf-8 = 65001 )
                ResultText = ConvertStringToEncoding(ResultText, Encoding.UTF8.CodePage, CodePageNum);
            }
            else
            {
                //テキストファイルを開いてその文字コードに従って読み込み
                //Detect encoding in the text file
                byte[] bs;
                using (FileStream fs = new FileStream(FilePath, FileMode.Open, FileAccess.Read))
                {
                    bs = new byte[fs.Length];
                    fs.Read(bs, 0, bs.Length);
                }
                //文字コードを取得する
                //Get charcter encoding
                encRead = GetCode(bs);
                //取得したバイト列を文字列に変換
                //Convert byte values to character
                ResultText = encRead.GetString(bs);

                //UTF-8でないならいったん変換してパース
                //Convert it if encoding is not utf-8
                if (encRead != Encoding.UTF8)
                {
                    ResultText = ConvertStringToEncoding(ResultText, encRead.CodePage, CodePageNum);
                }
                ResultText = mkdwn.Transform(ResultText);
            }

            //ヘッダ+本文+フッタ
            //Header + Contents + Footer
            ResultText = HeaderString + ResultText + FooterString;
            //出力するHTMLファイルの文字コードに合わせる
            //Ajust encoding to output HTML file
            ResultText = ConvertStringToEncoding(ResultText, Encoding.UTF8.CodePage, CodePageNum);

            if (fToClipboard == true)
            {	//クリップボードに書き込む
                //Set data to clipbord
                Clipboard.SetText(ResultText);
            }
            else
            {	//ファイルに書き込む
                //Write file
                using (StreamWriter sw = new StreamWriter(SaveToFilePath, false, encHtml))
                {
                    sw.Write(ResultText);
                }
            }
            return (true);
        }