private string PreProcess(XhtmlString xhtmlString)
        {
            // The store value of an XhtmlString contains placeholder content for certain dynamic content.  We want to
            // pre-load this data to before we send it off to the app.  In order to load personalized content, dynamic controls, etc.,
            // we use the following methods to get the "rendered results" of the XhtmlString property
            var htmlHelper = Helpers.MvcHelper.GetHtmlHelper();
            string mvcHtmlResults = EPiServer.Web.Mvc.Html.XhtmlStringExtensions.XhtmlString(htmlHelper, xhtmlString).ToHtmlString();

            // replace image URLs with a full URL path
            string workingResults = Regex.Replace(mvcHtmlResults, "<img(.+?)src=[\"\']/(.+?)[\"\'](.+?)>", "<img $1 src=\"http://ascend-dev.adagetechnologies.com/$2\" $3>");

            // find all internal href items
            var regexMatches = Regex.Matches(mvcHtmlResults, "href=[\"\'](.*?)[\"\']");
            var resolver = EPiServer.ServiceLocation.ServiceLocator.Current.GetInstance<UrlResolver>();

            // for each item attempt to determine if they are an internal page link
            foreach(Match eachUrlMatch in regexMatches)
            {
                UrlBuilder eachUrl = new UrlBuilder(eachUrlMatch.Groups[1].Value);
                var currentRoute = resolver.Route(eachUrl);
                if (currentRoute != null)
                {
                    string internalContentLink = string.Format("href=\"index.html#/app/content/{0}\"", currentRoute.ContentLink.ID);
                    workingResults = workingResults.Replace(eachUrlMatch.Value, internalContentLink);
                }
            }

            return workingResults;
        }
예제 #2
0
        private string GetConfirmationText(PriceHedgePage currentPage, string agreement)
        {
            if (string.IsNullOrEmpty(agreement))
            {
                return(string.Empty);
            }
            XhtmlString confirmationXhtml = null;

            if (agreement.Equals(AgreementType.Depaavtal))
            {
                confirmationXhtml = currentPage.ConfirmationTextForDepaavtal;
            }
            else if (agreement.Equals(AgreementType.Poolavtal))
            {
                confirmationXhtml = currentPage.ConfirmationTextForPoolavtal;
            }
            else if (agreement.Equals(AgreementType.SportAndForwardAvtal))
            {
                confirmationXhtml = currentPage.ConfirmationTextForSportavtal;
            }
            else if (agreement.Equals(AgreementType.PrissakringDepaavtal))
            {
                confirmationXhtml = currentPage.ConfirmationTextForPrissakringDepaavtal;
            }
            return(confirmationXhtml?.ToString() ?? string.Empty);
        }
        /// <summary>
        /// Sets the default property values on the page data.
        /// </summary>
        /// <param name="contentType">The type of content.</param>
        public override void SetDefaultValues(ContentType contentType)
        {
            Title         = PageTypeName;
            SubTitle      = $"This is the subtitle of {PageTypeName}";
            Description   = new XhtmlString($"This is the description of {PageTypeName}");
            ButtonCaption = "View More";

            base.SetDefaultValues(contentType);
        }
 public override void SetDefaultValues(ContentType contentType)
 {
     base.SetDefaultValues(contentType);
     ButtonText  = "Subscribe Now!";
     Title       = "Sign Up for our Newsletter";
     Lead        = "Don't miss out on our latest news and offers.";
     InlineText  = "Enter your email address";
     ErrorText   = new XhtmlString("<strong>Oh no!</strong> We apologize sincerely, but your subcription could not be confirmed. Please check your email address. If you're unable to sign up, please <a href=\"/contactus\">contact us</a> and we'll get it sorted out.");
     SuccessText = new XhtmlString("<strong>Thank you!</strong> You'll soon receive a notification about the subscription. If you have not recieved anything from us in a couple of minutes, please check your spam folder.");
 }
예제 #5
0
        public static XhtmlString WrapContent(XhtmlString xhtmlString,
                                              string wrapperClass,
                                              string blockWrapperClass,
                                              IEnumerable <Type> blockTypesToExclude)
        {
            blockTypesToExclude = blockTypesToExclude?.ToList() ?? new List <Type>();
            var textWrapperStart  = new StaticFragment($"<div class=\"{wrapperClass}\">");
            var textWrapperEnd    = new StaticFragment("</div>");
            var blockWrapperStart = blockWrapperClass != null
                ? new StaticFragment($"<section class=\"{blockWrapperClass}\">")
                : new StaticFragment("");
            var blockWrapperEnd = blockWrapperClass != null
                ? new StaticFragment("</section>")
                : new StaticFragment("");

            xhtmlString = xhtmlString.CreateWritableClone();

            var isNextBlock = xhtmlString.Fragments.LastOrDefault() is ContentFragment;

            xhtmlString.Fragments.Add(isNextBlock
                ? blockWrapperEnd
                : textWrapperEnd);

            for (var i = xhtmlString.Fragments.Count - 3; i >= 0; i--)
            {
                var currentFragment = xhtmlString.Fragments[i];
                var isCurrentBlock  = currentFragment is ContentFragment;

                if (!isCurrentBlock && string.IsNullOrWhiteSpace(currentFragment.InternalFormat))
                {
                    continue;
                }

                if (isCurrentBlock && blockTypesToExclude.Any(t => t.IsInstanceOfType(((ContentFragment)currentFragment).GetContent())))
                {
                    continue;
                }

                if (isCurrentBlock)
                {
                    xhtmlString.Fragments.Insert(i + 1, isNextBlock ? blockWrapperStart : textWrapperStart);
                    xhtmlString.Fragments.Insert(i + 1, blockWrapperEnd);
                }
                else if (isNextBlock)
                {
                    xhtmlString.Fragments.Insert(i + 1, blockWrapperStart);
                    xhtmlString.Fragments.Insert(i + 1, textWrapperEnd);
                }

                isNextBlock = isCurrentBlock;
            }

            xhtmlString.Fragments.Insert(0, isNextBlock ? blockWrapperStart : textWrapperStart);
            return(xhtmlString);
        }
예제 #6
0
        public static XhtmlString StripTags(this XhtmlString self, params string[] tags)
        {
            if (self == null)
            {
                return(null);
            }

            var pattern = string.Format("</?(?:{0})( [^>]+)?>", string.Join("|", tags));

            return(new XhtmlString(Regex.Replace(self.ToString(), pattern, "", RegexOptions.IgnoreCase)));
        }
예제 #7
0
        public static XhtmlString CleanupForIntroduction(this object obj)
        {
            if (obj is string)
            {
                // Sometimes the intro is a string, wrap string in xhtml to benfit from
                // all the goodness in CleanUpForMainBody
                var xhtml = new XhtmlString((string)obj);
                return(xhtml.CleanupForMainBody());
            }

            return(obj.CleanupForMainBody());
        }
예제 #8
0
        public string UpdateBlogPage(string headline, XhtmlString body, int pageId)
        {
            var parentRef = _pageService.GetBlogPageRef();
            var blogPage = _contentRepository.Get<ViewBlogPage>(new PageReference(pageId));

            var writableClone = blogPage.CreateWritableClone() as ViewBlogPage;

            writableClone.Title = headline;
            writableClone.BlogBody = body;
            writableClone.Author = System.Web.HttpContext.Current.User.Identity.Name;
            var pageref = _contentRepository.Save(writableClone, SaveAction.Publish, AccessLevel.NoAccess);
            return writableClone.LinkURL.ToString();
        }
        public string GetPlainTextContent(XhtmlString xhtmlString, IContentExtractorController extractor)
        {
            if (xhtmlString == null)
            {
                return(string.Empty);
            }
            var texts           = new List <string>();
            var staticFragments = new List <string>();

            var xhtmlFragments = xhtmlString
                                 .Fragments
                                 .GetFilteredFragments(PrincipalInfo.AnonymousPrincipal);

            foreach (var fragment in xhtmlFragments)
            {
                switch (fragment)
                {
                case ContentFragment contentFragment when ContentReference.IsNullOrEmpty(contentFragment.ContentLink):
                    continue;

                case ContentFragment contentFragment:
                {
                    if (staticFragments.Any())
                    {
                        texts.Add(RemoveScripts(staticFragments));
                        staticFragments.Clear();
                    }

                    var content = _contentLoader.Get <IContent>(contentFragment.ContentLink);

                    texts.Add(extractor.ExtractBlock(content));
                    break;
                }

                case StaticFragment staticFragment:
                    var html = staticFragment.InternalFormat;
                    staticFragments.Add(html);
                    break;
                }
            }

            if (staticFragments.Any())
            {
                texts.Add(RemoveScripts(staticFragments));
            }

            var joinedText = string.Join(ContentExtractorController.BlockExtractedTextFragmentsSeparator,
                                         texts.Select(t => t.Trim()));

            return(StripHtml(joinedText));
        }
예제 #10
0
        public static MvcHtmlString TransformedXhtmlString(this HtmlHelper html, XhtmlString xhtmlString,
                                                           string xhtmlWrapperClass = null, string blocksWrapperClass = null, IEnumerable <Type> blockTypesToExclude = null)
        {
            if (xhtmlString == null)
            {
                return(MvcHtmlString.Empty);
            }

            if (xhtmlWrapperClass != null || blocksWrapperClass != null)
            {
                xhtmlString = WrapContent(xhtmlString, xhtmlWrapperClass, blocksWrapperClass, blockTypesToExclude);
            }

            return(TransformHtmlString(html.XhtmlString(xhtmlString).ToHtmlString(), html));
        }
        public static void DonutForContent(this HtmlHelper htmlHelper, IContent content)
        {
            var serialisedContent = EpiServerDonutHelper.SerializeBlockContentReference(content);

            using (var textWriter = new StringWriter())
            {
                var cutomHtmlHelper = EpiServerDonutHelper.CreateHtmlHelper(htmlHelper.ViewContext.Controller, textWriter);
                EpiServerDonutHelper.RenderContentData(cutomHtmlHelper, content, string.Empty);

                var outputString = string.Format("<!--Donut#{0}#-->{1}<!--EndDonut-->", serialisedContent, textWriter);

                var htmlString = new XhtmlString(outputString);
                htmlHelper.RenderXhtmlString(htmlString);
            }
        }
예제 #12
0
        public FeatureProductViewModel(FeatureProductBlock featureProductBlock)
        {
            //var referenceConverter = ServiceLocator.Current.GetInstance<ReferenceConverter>();
            _featureProductBlock = featureProductBlock;
            var         _contentRepository = ServiceLocator.Current.GetInstance <IContentRepository>();
            UrlResolver urlResolver        = ServiceLocator.Current.GetInstance <UrlResolver>();

            if (ContentReference.IsNullOrEmpty(_featureProductBlock.MenuFeatureLink) == false)
            {
                EntryContentBase product = _contentRepository.Get <EntryContentBase>(_featureProductBlock.MenuFeatureLink);

                ImageUrl    = GetImageUrl(product, urlResolver);
                FeatureText = _featureProductBlock.MenuFeatureText;
                ProductUrl  = urlResolver.GetUrl(product.ContentLink);
            }
        }
        private static string ToStringAsViewedByAnonymous(this PropertyData propertyData)
        {
            if (propertyData.IsNull)
            {
                return(string.Empty);
            }
            XhtmlString xhtmlString = propertyData.Value as XhtmlString;

            if (xhtmlString != null)
            {
                return(EPiServer.Find.Helpers.Text.StringExtensions.StripHtml(XhtmlStringExtensions.AsViewedByAnonymous(xhtmlString)));
            }
            else
            {
                return(((object)propertyData).ToString());
            }
        }
예제 #14
0
        public static string ToBlocksIncludedString(this XhtmlString xhtmlString)
        {
            var sb = new StringBuilder();

            if (xhtmlString != null && xhtmlString.Fragments.Any())
            {
                var contentLoader = ServiceLocator.Current.GetInstance <IContentLoader>();
                foreach (IStringFragment fragment in xhtmlString.Fragments.GetFilteredFragments(PrincipalInfo.AnonymousPrincipal))
                {
                    if (fragment is ContentFragment)
                    {
                        var contentFragment = fragment as ContentFragment;
                        if (contentFragment.ContentLink != null &&
                            contentFragment.ContentLink != ContentReference.EmptyReference)
                        {
                            var referencedContent = contentLoader.Get <IContent>(contentFragment.ContentLink);
                            //                            sb.Append(referencedContent.SearchText + " ");
                            if (referencedContent is CodeWrapBlock)
                            {
                                var searchText = (referencedContent as CodeWrapBlock).Content;
                                if (!string.IsNullOrWhiteSpace(searchText))
                                {
                                    sb.Append(searchText + " ");
                                }
                            }
                            else if (referencedContent is BlogQuoteBlock)
                            {
                                var searchText = (referencedContent as BlogQuoteBlock).Quote;
                                if (!string.IsNullOrWhiteSpace(searchText))
                                {
                                    sb.Append(searchText + " ");
                                }
                            }
                        }
                    }
                    else if (fragment is StaticFragment)
                    {
                        var staticFragment = fragment as StaticFragment;
                        sb.Append(staticFragment.InternalFormat + " ");
                    }
                }
            }
            return(sb.ToString());
        }
예제 #15
0
        private static IEnumerable <TestCaseData> PlainTextContentSource()
        {
            var imgWithTextAfter = new XhtmlString();

            imgWithTextAfter.Fragments.Add(new StaticFragment("<img src=\""));
            imgWithTextAfter.Fragments.Add(new UrlFragment("~/link/1b108a4b8f9a4b47802f0112f5b07d11.aspx"));
            imgWithTextAfter.Fragments.Add(new StaticFragment("\" alt=\"alt\"/><p>text</p>"));

            yield return(new TestCaseData(imgWithTextAfter, "text").SetName("Img with plain text after"));

            var imgWithTextBeforeAndAfter = new XhtmlString();

            imgWithTextBeforeAndAfter.Fragments.Add(new StaticFragment("<p>1</p>"));
            imgWithTextBeforeAndAfter.Fragments.Add(new StaticFragment("<img src=\""));
            imgWithTextBeforeAndAfter.Fragments.Add(new UrlFragment("~/link/1b108a4b8f9a4b47802f0112f5b07d11.aspx"));
            imgWithTextBeforeAndAfter.Fragments.Add(new StaticFragment("\" alt=\"alt\"/><p>2</p>"));

            yield return(new TestCaseData(imgWithTextBeforeAndAfter, "1 2").SetName("Img with plain text in before and after"));
        }
예제 #16
0
        public string CreateBlogPage(string headline, XhtmlString body)
        {
            var parentPageContainer = _pageService.GetBlogPageRef();
            var contentTypeId = _contentTypeRepository.Load(typeof(ViewBlogPage)).ID;
            var parentPage = _contentRepository.GetDefault<ViewBlogPage>(parentPageContainer, contentTypeId);

            if (!PageReference.IsNullOrEmpty(parentPageContainer))
            {
                parentPage.Name = headline;
                parentPage.Title = headline;
                parentPage.BlogBody = body;
                parentPage.Author = System.Web.HttpContext.Current.User.Identity.Name;
                // Set the URL segment (page name in address)
                parentPage.URLSegment = UrlSegment.CreateUrlSegment(parentPage);

                // Publish the page regardless of current user's permissions
                var newPageRef = _contentRepository.Save(parentPage, SaveAction.Publish, AccessLevel.NoAccess);
            }
            return parentPage.LinkURL.ToString();
        }
    public static IHtmlString CustomXhtmlString(this HtmlHelper helper, XhtmlString value)
    {
      var htmlString = helper.XhtmlString(value).ToHtmlString();
      
      var headline = LocalizationService.Current
        .GetString("/views/common/linklist/headline");
      
      var cq = new CQ(htmlString, HtmlParsingMode.Document);
      cq.Find("ul.link-list").Each(list =>
        {
          var box = CQ.CreateFragment(
            "<div class=\"link-list\">" 
            + "<h4><span class=\"glyphicon glyphicon-link\"></span> " 
            + headline
            + "</h4></div>");
          list.RemoveClass("link-list");
          box.Append(list.OuterHTML);
          list.Cq().ReplaceWith(box);
        });

      return new MvcHtmlString(cq.Find("body").Html());
    }
        public static IHtmlString CustomXhtmlString(this HtmlHelper helper, XhtmlString value)
        {
            var htmlString = helper.XhtmlString(value).ToHtmlString();

            var headline = LocalizationService.Current
                           .GetString("/views/common/linklist/headline");

            var cq = new CQ(htmlString, HtmlParsingMode.Document);

            cq.Find("ul.link-list").Each(list =>
            {
                var box = CQ.CreateFragment(
                    "<div class=\"link-list\">"
                    + "<h4><span class=\"glyphicon glyphicon-link\"></span> "
                    + headline
                    + "</h4></div>");
                list.RemoveClass("link-list");
                box.Append(list.OuterHTML);
                list.Cq().ReplaceWith(box);
            });

            return(new MvcHtmlString(cq.Find("body").Html()));
        }
        private bool ValidateXhtmlString(XhtmlString xhtml)
        {
            if (xhtml == null || xhtml.IsEmpty)
            {
                return(true);
            }

            var doc = new HtmlDocument();

            doc.LoadHtml(xhtml.ToString());

            // if there are images without alt tags, invalid
            IEnumerable <HtmlNode> imgs = doc.DocumentNode.Descendants("img");

            if (imgs != null && imgs.Any())
            {
                if (imgs.Any(i => i.Attributes["alt"] == null || string.IsNullOrWhiteSpace(i.Attributes["alt"].Value)))
                {
                    return(false);
                }
            }

            return(true);
        }
 public StandardPageBuilder WithMainBody(string m)
 {
     this._mainBody = new XhtmlString(m);
     return(this);
 }
 public StandardPageBuilder WithMainBody(XhtmlString m)
 {
     this._mainBody = m;
     return(this);
 }
예제 #22
0
 public object GetValue(XhtmlString xhtmlString)
 {
     //TODO Fix parsing of images/blocks/links etc so we can provide pretty links.
     return(xhtmlString.ToHtmlString());
 }
 public static IEnumerable <ContentFragment> GetFragments(this XhtmlString instance, IPrincipal principal = null)
 {
     return(principal == null
         ? instance.Fragments.OfType <ContentFragment>()
         : instance.Fragments.GetFilteredFragments(principal).OfType <ContentFragment>());
 }
예제 #24
0
 public static string AsViewedByAnonymous(this XhtmlString xhtmlString)
 {
     return(xhtmlString.ToHtmlString(PrincipalInfo.AnonymousPrincipal));
 }
예제 #25
0
 public override void SetDefaultValues(ContentType contentType)
 {
     base.SetDefaultValues(contentType);
     ButtonText = "Subscribe Now!";
     Title = "Sign Up for our Newsletter";
     Lead = "Don't miss out on our latest news and offers.";
     InlineText = "Enter your email address";
     ErrorText = new XhtmlString("<strong>Oh no!</strong> We apologize sincerely, but your subcription could not be confirmed. Please check your email address. If you're unable to sign up, please <a href=\"/contactus\">contact us</a> and we'll get it sorted out.");
     SuccessText = new XhtmlString("<strong>Thank you!</strong> You'll soon receive a notification about the subscription. If you have not recieved anything from us in a couple of minutes, please check your spam folder.");
 }
 public static string AsHighlighted(this XhtmlString xhtmlString, HighlightSpec highlightSpec)
 {
     throw new ClientException("The AsHighlighted method should only be used in projection expressions");
 }
예제 #27
0
        /// <summary>
        /// Generates the PDF.
        /// </summary>
        /// <param name="page">
        /// The page.
        /// </param>
        /// <returns>
        /// The pdf in bytes.
        /// </returns>
        public static byte[] GeneratePdf(PageData page)
        {
            List <KeyValuePair <string, string> > propertyValues = page.GetPropertyValues();

            IContentRepository contentRepository = ServiceLocator.Current.GetInstance <IContentRepository>();
            PageData           startPage         = contentRepository.Get <PageData>(ContentReference.StartPage);

            using (MemoryStream memoryStream = new MemoryStream())
            {
                using (Document document = new Document(PageSize.A4))
                {
                    PdfWriter.GetInstance(document, memoryStream);

                    document.AddCreationDate();

                    string      author    = page["Author"] as string;
                    string      title     = page["Title"] as string;
                    XhtmlString pdfHeader = startPage["PdfHeader"] as XhtmlString;
                    XhtmlString pdfFooter = startPage["PdfFooter"] as XhtmlString;

                    if (!string.IsNullOrWhiteSpace(author))
                    {
                        document.AddAuthor(author);
                    }

                    document.AddTitle(!string.IsNullOrWhiteSpace(title) ? title : page.Name);

                    document.Open();

                    Dictionary <string, object> providers = new Dictionary <string, object>
                    {
                        {
                            HTMLWorker.IMG_PROVIDER,
                            new ImageProvider(
                                document)
                        }
                    };

                    StyleSheet styleSheet = OutputHelper.GetStyleSheet();

                    try
                    {
                        Paragraph paragraph = new Paragraph(!string.IsNullOrWhiteSpace(title) ? title : page.Name);
                        document.Add(paragraph);

                        // Add the header
                        if (pdfHeader != null && !pdfHeader.IsEmpty)
                        {
                            using (StringReader stringReader = new StringReader(pdfHeader.ToHtmlString()))
                            {
                                foreach (IElement element in
                                         HTMLWorker.ParseToList(stringReader, styleSheet, providers))
                                {
                                    document.Add(element);
                                }
                            }
                        }

                        // Add the selected properties
                        foreach (KeyValuePair <string, string> content in propertyValues)
                        {
                            using (StringReader stringReader = new StringReader(content.Value))
                            {
                                foreach (IElement element in
                                         HTMLWorker.ParseToList(stringReader, styleSheet, providers))
                                {
                                    document.Add(element);
                                }
                            }

                            document.Add(new Chunk(Environment.NewLine));
                        }

                        // Add the footer
                        if (pdfFooter != null && !pdfFooter.IsEmpty)
                        {
                            using (StringReader stringReader = new StringReader(pdfFooter.ToHtmlString()))
                            {
                                foreach (IElement element in
                                         HTMLWorker.ParseToList(stringReader, styleSheet, providers))
                                {
                                    document.Add(element);
                                }
                            }
                        }
                    }
                    catch (Exception exception)
                    {
                        Paragraph paragraph = new Paragraph("Error!" + exception.Message);
                        Chunk     text      = paragraph.Chunks[0];
                        if (text != null)
                        {
                            text.Font.Color = BaseColor.RED;
                        }

                        document.Add(paragraph);
                    }

                    document.CloseDocument();
                }

                return(memoryStream.ToArray());
            }
        }
예제 #28
0
        public void GetPlainTextContentShouldReturnValidText(XhtmlString testString, string expectedString)
        {
            var strippedText = _xhtmlStringExtractor.GetPlainTextContent(testString, _contentExtractorController);

            Assert.That(strippedText, Is.EqualTo(expectedString));
        }
 public static string AsCropped(this XhtmlString xhtmlString, int maxLength)
 {
     throw new ClientException("The AsCropped method should only be used in projection expressions, such as when using the Select method.");
 }
예제 #30
0
 public ArticlePageViewModel(string heading, string preamble, XhtmlString mainBody)
 {
     Heading  = heading;
     Preamble = preamble;
     MainBody = mainBody;
 }