示例#1
0
        private string Convert(object source, bool preview)
        {
            if (source == null)
            {
                return(null);
            }

            var sourceString = source.ToString();

            // ensures string is parsed for {localLink} and urls and media are resolved correctly
            sourceString = TemplateUtilities.ParseInternalLinks(sourceString, preview, Current.UmbracoContext);
            sourceString = TemplateUtilities.ResolveUrlsFromTextString(sourceString);
            sourceString = TemplateUtilities.ResolveMediaFromTextString(sourceString);

            // ensure string is parsed for macros and macros are executed correctly
            sourceString = RenderRteMacros(sourceString, preview);

            // find and remove the rel attributes used in the Umbraco UI from img tags
            var doc = new HtmlDocument();

            doc.LoadHtml(sourceString);

            if (doc.ParseErrors.Any() == false && doc.DocumentNode != null)
            {
                // Find all images with rel attribute
                var imgNodes = doc.DocumentNode.SelectNodes("//img[@rel]");

                var modified = false;
                if (imgNodes != null)
                {
                    foreach (var img in imgNodes)
                    {
                        var nodeId = img.GetAttributeValue("rel", string.Empty);
                        if (int.TryParse(nodeId, out _))
                        {
                            img.Attributes.Remove("rel");
                            modified = true;
                        }
                    }
                }

                // Find all a and img tags with a data-udi attribute
                var dataUdiNodes = doc.DocumentNode.SelectNodes("(//a|//img)[@data-udi]");
                if (dataUdiNodes != null)
                {
                    foreach (var node in dataUdiNodes)
                    {
                        node.Attributes.Remove("data-udi");
                        modified = true;
                    }
                }

                if (modified)
                {
                    return(doc.DocumentNode.OuterHtml);
                }
            }

            return(sourceString);
        }
示例#2
0
        /// <summary>
        /// Occurs when a new update is added to the Live Editing update collection.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="UpdateAddedEventArgs"/> instance containing the event data.</param>
        protected void Updates_UpdateAdded(object sender, UpdateAddedEventArgs e)
        {
            ItemUpdate update = e.Update as ItemUpdate;

            if (update != null)
            {
                List <Item> affectedItems = Utility.FindControls <Item>(item => item.GetParsedNodeId() == update.NodeId &&
                                                                        item.Field == update.Field,
                                                                        Page.Master);
                foreach (Item affectedItem in affectedItems)
                {
                    // render the item, temporarily disabling the live editing special output
                    StringWriter itemRenderOutput       = new StringWriter();
                    bool         liveEditingWasDisabled = affectedItem.LiveEditingDisabled;
                    affectedItem.LiveEditingDisabled = true;
                    affectedItem.RenderControl(new HtmlTextWriter(itemRenderOutput));
                    affectedItem.LiveEditingDisabled = liveEditingWasDisabled;

                    // add the item's contents to the output
                    HtmlGenericControl itemUpdate = new HtmlGenericControl("umbraco:itemupdate");
                    itemUpdate.Attributes["itemId"] = affectedItem.ItemId.ToString();
                    itemUpdate.InnerHtml            = TemplateUtilities.ParseInternalLinks(itemRenderOutput.ToString());
                    itemUpdate.EnableViewState      = false;
                    m_Manager.AddClientOutput(itemUpdate);
                }
            }
        }
示例#3
0
        /// <summary>
        /// Processes the value.
        /// </summary>
        /// <returns>
        /// The <see cref="object" /> representing the processed value.
        /// </returns>
        public override object ProcessValue()
        {
            if (typeof(IHtmlString).IsAssignableFrom(this.Context.PropertyInfo.PropertyType))
            {
                if (this.Value is string text && string.IsNullOrWhiteSpace(text) == false)
                {
                    text = text
                           .Replace("\r\n", "<br />")
                           .Replace("\n", "<br />")
                           .Replace("\r", "<br />");

                    return(new HtmlString(text));
                }

                if (this.Value is HtmlString)
                {
                    var html = this.Value.ToString();

                    if (string.IsNullOrWhiteSpace(html) == false)
                    {
                        html = TemplateUtilities.ParseInternalLinks(html);
                    }

                    return(new HtmlString(html));
                }

                if (this.Value is DynamicXml)
                {
                    return(((DynamicXml)this.Value).ToHtml());
                }
            }

            return(this.Value);
        }
示例#4
0
        protected override void Render(HtmlTextWriter writer)
        {
            // do the original rendering
            TextWriter sw = new StringWriter();

            base.Render(new HtmlTextWriter(sw));
            string text = sw.ToString();

            // filter / parse internal links - although this should be done elsewhere!
            text = TemplateUtilities.ParseInternalLinks(text);

            // filter / add preview banner
            if (UmbracoContext.Current.InPreviewMode)
            {
                LogHelper.Debug <UmbracoDefault>("Umbraco is running in preview mode.", true);

                if (Response.ContentType.InvariantEquals("text/html"))                 // ASP.NET default value
                {
                    int pos = text.ToLower().IndexOf("</body>");
                    if (pos > -1)
                    {
                        string htmlBadge =
                            String.Format(UmbracoSettings.PreviewBadge,
                                          IOHelper.ResolveUrl(SystemDirectories.Umbraco),
                                          IOHelper.ResolveUrl(SystemDirectories.UmbracoClient),
                                          Server.UrlEncode(UmbracoContext.Current.HttpContext.Request.Path));

                        text = text.Substring(0, pos) + htmlBadge + text.Substring(pos, text.Length - pos);
                    }
                }
            }

            // render
            writer.Write(text);
        }
示例#5
0
        public override object ConvertSourceToIntermediate(IPublishedElement owner, PublishedPropertyType propertyType, object source, bool preview)
        {
            if (source == null)
            {
                return(null);
            }

            var sourceString = source.ToString();

            // ensures string is parsed for {localLink} and urls and media are resolved correctly
            sourceString = TemplateUtilities.ParseInternalLinks(sourceString, preview, Current.UmbracoContext);
            sourceString = TemplateUtilities.ResolveUrlsFromTextString(sourceString);
            sourceString = TemplateUtilities.ResolveMediaFromTextString(sourceString);

            // ensure string is parsed for macros and macros are executed correctly
            sourceString = RenderRteMacros(sourceString, preview);

            // find and remove the rel attributes used in the Umbraco UI from img tags
            var doc = new HtmlDocument();

            doc.LoadHtml(sourceString);

            if (doc.ParseErrors.Any() == false && doc.DocumentNode != null)
            {
                // Find all images with rel attribute
                var imgNodes = doc.DocumentNode.SelectNodes("//img[@rel]");

                if (imgNodes != null)
                {
                    var modified = false;

                    foreach (var img in imgNodes)
                    {
                        var firstOrDefault = img.Attributes.FirstOrDefault(x => x.Name == "rel");
                        if (firstOrDefault != null)
                        {
                            var rel = firstOrDefault.Value;

                            // Check that the rel attribute is a integer before removing
                            int nodeId;
                            if (int.TryParse(rel, out nodeId))
                            {
                                img.Attributes.Remove("rel");
                                modified = true;
                            }
                        }
                    }

                    if (modified)
                    {
                        return(doc.DocumentNode.OuterHtml);
                    }
                }
            }

            return(sourceString);
        }
 public object Convert(object value)
 {
     using (var cRef = _umbracoContextFactory.EnsureUmbracoContext())
     {
         var parsedHtml = TemplateUtilities.ParseInternalLinks(
             value.ToString(),
             cRef.UmbracoContext.UrlProvider);
         return(parsedHtml);
     }
 }
        public void ParseLocalLinks(string input, string result)
        {
            var serviceCtxMock = new TestObjects(null).GetServiceContextMock();

            //setup a mock entity service from the service context to return an integer for a GUID
            var entityService = Mock.Get(serviceCtxMock.EntityService);
            //entityService.Setup(x => x.GetId(It.IsAny<Guid>(), It.IsAny<UmbracoObjectTypes>()))
            //    .Returns((Guid id, UmbracoObjectTypes objType) =>
            //    {
            //        return Attempt.Succeed(1234);
            //    });

            //setup a mock url provider which we'll use fo rtesting
            var testUrlProvider = new Mock <IUrlProvider>();

            testUrlProvider
            .Setup(x => x.GetUrl(It.IsAny <UmbracoContext>(), It.IsAny <IPublishedContent>(), It.IsAny <UrlProviderMode>(), It.IsAny <string>(), It.IsAny <Uri>()))
            .Returns((UmbracoContext umbCtx, IPublishedContent content, UrlProviderMode mode, string culture, Uri url) => UrlInfo.Url("/my-test-url"));

            var globalSettings = SettingsForTests.GenerateMockGlobalSettings();

            var contentType      = new PublishedContentType(666, "alias", PublishedItemType.Content, Enumerable.Empty <string>(), Enumerable.Empty <PublishedPropertyType>(), ContentVariation.Nothing);
            var publishedContent = Mock.Of <IPublishedContent>();

            Mock.Get(publishedContent).Setup(x => x.Id).Returns(1234);
            Mock.Get(publishedContent).Setup(x => x.ContentType).Returns(contentType);
            var contentCache = Mock.Of <IPublishedContentCache>();

            Mock.Get(contentCache).Setup(x => x.GetById(It.IsAny <int>())).Returns(publishedContent);
            Mock.Get(contentCache).Setup(x => x.GetById(It.IsAny <Guid>())).Returns(publishedContent);
            var snapshot = Mock.Of <IPublishedSnapshot>();

            Mock.Get(snapshot).Setup(x => x.Content).Returns(contentCache);
            var snapshotService = Mock.Of <IPublishedSnapshotService>();

            Mock.Get(snapshotService).Setup(x => x.CreatePublishedSnapshot(It.IsAny <string>())).Returns(snapshot);

            using (var umbCtx = UmbracoContext.EnsureContext(
                       Umbraco.Web.Composing.Current.UmbracoContextAccessor,
                       Mock.Of <HttpContextBase>(),
                       snapshotService,
                       new Mock <WebSecurity>(null, null, globalSettings).Object,
                       //setup a quick mock of the WebRouting section
                       Mock.Of <IUmbracoSettingsSection>(section => section.WebRouting == Mock.Of <IWebRoutingSection>(routingSection => routingSection.UrlProviderMode == "AutoLegacy")),
                       //pass in the custom url provider
                       new[] { testUrlProvider.Object },
                       globalSettings,
                       new TestVariationContextAccessor(),
                       true))
            {
                var output = TemplateUtilities.ParseInternalLinks(input, umbCtx.UrlProvider);

                Assert.AreEqual(result, output);
            }
        }
示例#8
0
        public void ParseLocalLinks(string input, string result)
        {
            //setup a mock url provider which we'll use for testing
            var testUrlProvider = new Mock <IUrlProvider>();

            testUrlProvider
            .Setup(x => x.GetUrl(It.IsAny <UmbracoContext>(), It.IsAny <IPublishedContent>(), It.IsAny <UrlMode>(), It.IsAny <string>(), It.IsAny <Uri>()))
            .Returns((UmbracoContext umbCtx, IPublishedContent content, UrlMode mode, string culture, Uri url) => UrlInfo.Url("/my-test-url"));

            var globalSettings = SettingsForTests.GenerateMockGlobalSettings();

            var contentType      = new PublishedContentType(666, "alias", PublishedItemType.Content, Enumerable.Empty <string>(), Enumerable.Empty <PublishedPropertyType>(), ContentVariation.Nothing);
            var publishedContent = Mock.Of <IPublishedContent>();

            Mock.Get(publishedContent).Setup(x => x.Id).Returns(1234);
            Mock.Get(publishedContent).Setup(x => x.ContentType).Returns(contentType);
            var contentCache = Mock.Of <IPublishedContentCache>();

            Mock.Get(contentCache).Setup(x => x.GetById(It.IsAny <int>())).Returns(publishedContent);
            Mock.Get(contentCache).Setup(x => x.GetById(It.IsAny <Guid>())).Returns(publishedContent);
            var snapshot = Mock.Of <IPublishedSnapshot>();

            Mock.Get(snapshot).Setup(x => x.Content).Returns(contentCache);
            var snapshotService = Mock.Of <IPublishedSnapshotService>();

            Mock.Get(snapshotService).Setup(x => x.CreatePublishedSnapshot(It.IsAny <string>())).Returns(snapshot);
            var media = Mock.Of <IPublishedContent>();

            Mock.Get(media).Setup(x => x.Url).Returns("/media/1001/my-image.jpg");
            var mediaCache = Mock.Of <IPublishedMediaCache>();

            Mock.Get(mediaCache).Setup(x => x.GetById(It.IsAny <Guid>())).Returns(media);

            var umbracoContextAccessor = new TestUmbracoContextAccessor();
            var umbracoContextFactory  = new UmbracoContextFactory(
                umbracoContextAccessor,
                snapshotService,
                new TestVariationContextAccessor(),
                new TestDefaultCultureAccessor(),
                Mock.Of <IUmbracoSettingsSection>(section => section.WebRouting == Mock.Of <IWebRoutingSection>(routingSection => routingSection.UrlProviderMode == "Auto")),
                globalSettings,
                new UrlProviderCollection(new[] { testUrlProvider.Object }),
                new MediaUrlProviderCollection(Enumerable.Empty <IMediaUrlProvider>()),
                Mock.Of <IUserService>());

            using (var reference = umbracoContextFactory.EnsureUmbracoContext(Mock.Of <HttpContextBase>()))
            {
                var output = TemplateUtilities.ParseInternalLinks(input, reference.UmbracoContext.UrlProvider, mediaCache);

                Assert.AreEqual(result, output);
            }
        }
        public override object ConvertSourceToIntermediate(IPublishedElement owner, PublishedPropertyType propertyType, object source, bool preview)
        {
            if (source == null)
            {
                return(null);
            }
            var sourceString = source.ToString();

            // ensures string is parsed for {localLink} and urls are resolved correctly
            sourceString = TemplateUtilities.ParseInternalLinks(sourceString, preview, UmbracoContext.Current);
            sourceString = TemplateUtilities.ResolveUrlsFromTextString(sourceString);

            return(sourceString);
        }
        public override object ConvertDataToSource(PublishedPropertyType propertyType, object source, bool preview)
        {
            if (source == null)
            {
                return(null);
            }
            var sourceString = source.ToString();

            // ensures string is parsed for {localLink} and urls are resolved correctly
            sourceString = TemplateUtilities.ParseInternalLinks(sourceString, preview);
            sourceString = TemplateUtilities.ResolveUrlsFromTextString(sourceString);

            return(sourceString);
        }
示例#11
0
        /// <summary>
        /// Renders the macro script.
        /// </summary>
        /// <param name="helper">The helper.</param>
        /// <param name="language">The language.</param>
        /// <param name="fileLocation">The file location.</param>
        /// <param name="parameters">The parameters.</param>
        /// <returns></returns>
        public static IHtmlString RenderMacroScript(this UmbracoHelper helper, string language, string fileLocation, IDictionary <string, object> parameters)
        {
            var ctrl = new umbraco.presentation.templateControls.Macro()
            {
                Language     = language,
                FileLocation = fileLocation,
            };

            foreach (var parameter in parameters)
            {
                ctrl.Attributes.Add(parameter.Key, parameter.Value.ToString());
            }

            return(new HtmlString(TemplateUtilities.ParseInternalLinks(ctrl.RenderToString())));
        }
示例#12
0
        private static object GetTypedVaue(string alias, object value)
        {
            switch (alias)
            {
            case GridAliases.Headline:
            case GridAliases.Quote:
                return(value.ToString());

            case GridAliases.Rte:
                return(new MvcHtmlString(TemplateUtilities.ParseInternalLinks(value.ToString())));

            default:
                return(string.Empty);
            }
        }
示例#13
0
        /// <summary>
        /// Processes the value.
        /// </summary>
        /// <returns>
        /// The <see cref="object" /> representing the processed value.
        /// </returns>
        public override object ProcessValue()
        {
            if (typeof(IHtmlString).IsAssignableFrom(Context.PropertyDescriptor.PropertyType))
            {
                if (Value.IsNullOrEmptyString())
                {
                    return(null);
                }

                if (Value is string)
                {
                    var text = Value.ToString();

                    if (!string.IsNullOrWhiteSpace(text))
                    {
                        text = text.Replace("\n", "<br/>\n");
                    }

                    return(new HtmlString(text));
                }

                if (Value is HtmlString)
                {
                    var html = Value.ToString();

                    if (!string.IsNullOrWhiteSpace(html))
                    {
                        html = TemplateUtilities.ParseInternalLinks(html);
                    }

                    return(new HtmlString(html));
                }

                if (Value is DynamicXml)
                {
                    return(((DynamicXml)Value).ToHtml());
                }
            }

            return(Value);
        }
        public override object ProcessValue()
        {
            if (string.IsNullOrEmpty(Value?.ToString()))
            {
                return(null);
            }

            var gridContentModel = JsonConvert.DeserializeObject <GridContentModel>(Value.ToString());

            foreach (var control in (from section in gridContentModel.Sections from row in section.Rows from area in row.Areas from control in area.Controls select control).Where(control => control.Value != null))
            {
                switch (control.Editor.Alias)
                {
                case GridEditorAliases.Embed:
                case GridEditorAliases.Quote:
                    control.QuoteOrEmbed = control.Value.ToString();
                    break;

                case GridEditorAliases.Media:
                    var gridContentMediaValue = JsonConvert.DeserializeObject <GridContentMediaValue>(control.Value.ToString());
                    var mediaImage            = _modelConverter.ToModel <GridContentMediaValue>(_mediaService.Media(gridContentMediaValue.Id));
                    mediaImage.Caption = gridContentMediaValue.Caption;
                    control.MediaImage = mediaImage;
                    break;

                case GridEditorAliases.Rte:
                    control.Html = new MvcHtmlString(TemplateUtilities.ParseInternalLinks(control.Value.ToString()));
                    break;

                case GridEditorAliases.Headline:
                    control.Text = control.Value.ToString();
                    break;

                default:
                    throw new ArgumentException("unknown grid editor aliases", control.Editor.Alias);
                }
            }

            return(gridContentModel);
        }
示例#15
0
        /// <summary>
        /// Renders the macro with the specified alias, passing in the specified parameters.
        /// </summary>
        /// <param name="alias">The alias.</param>
        /// <param name="parameters">The parameters.</param>
        /// <returns></returns>
        public IHtmlString RenderMacro(string alias, IDictionary <string, object> parameters)
        {
            if (alias == null)
            {
                throw new ArgumentNullException("alias");
            }
            var containerPage = new FormlessPage();
            var m             = macro.GetMacro(alias);

            if (_umbracoContext.PageId == null)
            {
                throw new InvalidOperationException("Cannot render a macro when UmbracoContext.PageId is null.");
            }
            if (_umbracoContext.PublishedContentRequest == null)
            {
                throw new InvalidOperationException("Cannot render a macro when there is no current PublishedContentRequest.");
            }
            var macroProps = new Hashtable();

            foreach (var i in parameters)
            {
                //TODO: We are doing at ToLower here because for some insane reason the UpdateMacroModel method of macro.cs
                // looks for a lower case match. WTF. the whole macro concept needs to be rewritten.
                macroProps.Add(i.Key.ToLower(), i.Value);
            }
            var macroControl = m.renderMacro(macroProps,
                                             UmbracoContext.Current.PublishedContentRequest.UmbracoPage.Elements,
                                             _umbracoContext.PageId.Value);

            containerPage.Controls.Add(macroControl);
            using (var output = new StringWriter())
            {
                _umbracoContext.HttpContext.Server.Execute(containerPage, output, false);

                //Now, we need to ensure that local links are parsed
                return(new HtmlString(
                           TemplateUtilities.ParseInternalLinks(
                               output.ToString())));
            }
        }
        public void ParseLocalLinks(string input, string result)
        {
            var serviceCtxMock = MockHelper.GetMockedServiceContext();

            //setup a mock entity service from the service context to return an integer for a GUID
            var entityService = Mock.Get(serviceCtxMock.EntityService);

            entityService.Setup(x => x.GetIdForKey(It.IsAny <Guid>(), It.IsAny <UmbracoObjectTypes>()))
            .Returns((Guid id, UmbracoObjectTypes objType) =>
            {
                return(Attempt.Succeed(1234));
            });

            //setup a mock url provider which we'll use fo rtesting
            var testUrlProvider = new Mock <IUrlProvider>();

            testUrlProvider.Setup(x => x.GetUrl(It.IsAny <UmbracoContext>(), It.IsAny <int>(), It.IsAny <Uri>(), It.IsAny <UrlProviderMode>()))
            .Returns((UmbracoContext umbCtx, int id, Uri url, UrlProviderMode mode) =>
            {
                return("/my-test-url");
            });

            using (var appCtx = new ApplicationContext(new DatabaseContext(new Mock <IScopeProviderInternal>().Object, Mock.Of <ILogger>(), Mock.Of <ISqlSyntaxProvider>(), "test"),
                                                       serviceCtxMock,
                                                       CacheHelper.CreateDisabledCacheHelper(),
                                                       new ProfilingLogger(Mock.Of <ILogger>(), Mock.Of <IProfiler>())))
                using (var umbCtx = UmbracoContext.EnsureContext(
                           Mock.Of <HttpContextBase>(), appCtx, new Mock <WebSecurity>(null, null).Object,
                           //setup a quick mock of the WebRouting section
                           Mock.Of <IUmbracoSettingsSection>(section => section.WebRouting == Mock.Of <IWebRoutingSection>(routingSection => routingSection.UrlProviderMode == "AutoLegacy")),
                           //pass in the custom url provider
                           new[] { testUrlProvider.Object },
                           true))
                {
                    var output = TemplateUtilities.ParseInternalLinks(input, umbCtx.UrlProvider);

                    Assert.AreEqual(result, output);
                }
        }
示例#17
0
        /// <summary>
        /// Converts the given object to the type of this converter, using the specified context and culture information.
        /// </summary>
        /// <param name="context">An <see cref="T:System.ComponentModel.ITypeDescriptorContext" /> that provides a format context.</param>
        /// <param name="culture">The <see cref="T:System.Globalization.CultureInfo" /> to use as the current culture.</param>
        /// <param name="value">The <see cref="T:System.Object" /> to convert.</param>
        /// <returns>
        /// An <see cref="T:System.Object" /> that represents the converted value.
        /// </returns>
        public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
        {
            if (value == null)
            {
                return(null);
            }

            if (value is string)
            {
                var text = value.ToString();

                if (!string.IsNullOrWhiteSpace(text))
                {
                    var umbracoHelper = ConverterHelper.UmbracoHelper;
                    text = umbracoHelper.ReplaceLineBreaksForHtml(text);
                }

                return(new HtmlString(text));
            }

            if (value is HtmlString)
            {
                var html = value.ToString();

                if (!string.IsNullOrWhiteSpace(html))
                {
                    html = TemplateUtilities.ParseInternalLinks(html);
                }

                return(new HtmlString(html));
            }

            if (value is DynamicXml)
            {
                return(((DynamicXml)value).ToHtml());
            }

            return(base.ConvertFrom(context, culture, value));
        }
        /// <summary>
        /// Converts the given object to the type of this converter, using the specified context and culture information.
        /// </summary>
        /// <param name="context">An <see cref="T:System.ComponentModel.ITypeDescriptorContext" /> that provides a format context.</param>
        /// <param name="culture">The <see cref="T:System.Globalization.CultureInfo" /> to use as the current culture.</param>
        /// <param name="value">The <see cref="T:System.Object" /> to convert.</param>
        /// <returns>
        /// An <see cref="T:System.Object" /> that represents the converted value.
        /// </returns>
        public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
        {
            if (value.IsNullOrEmptyString())
            {
                return(null);
            }

            if (value is string)
            {
                var text = value.ToString();

                if (!string.IsNullOrWhiteSpace(text))
                {
                    text = text.Replace("\n", "<br/>\n");
                }

                return(new HtmlString(text));
            }

            if (value is HtmlString)
            {
                var html = value.ToString();

                if (!string.IsNullOrWhiteSpace(html))
                {
                    html = TemplateUtilities.ParseInternalLinks(html);
                }

                return(new HtmlString(html));
            }

            if (value is DynamicXml)
            {
                return(((DynamicXml)value).ToHtml());
            }

            return(base.ConvertFrom(context, culture, value));
        }
示例#19
0
        public override object ConvertDataToSource(PublishedPropertyType propertyType, object source, bool preview)
        {
            if (source == null)
            {
                return(null);
            }
            var sourceString = source.ToString();

            // ensures string is parsed for {localLink} and urls are resolved correctly
            sourceString = TemplateUtilities.ParseInternalLinks(sourceString);
            sourceString = TemplateUtilities.ResolveUrlsFromTextString(sourceString);

            try
            {
                // Find, load and run any instances of IRichTextHtmlFormatter in the current scope
                var lookupType = typeof(IRichTextHtmlFormatter);
                var assemblies = AppDomain.CurrentDomain.GetAssemblies().Where(assembly => assembly.FullName.StartsWith("Escc."));
                IEnumerable <Type> formatters = assemblies.SelectMany(assembly => assembly.GetTypes()).Where(t => lookupType.IsAssignableFrom(t) && !t.IsInterface);

                foreach (var formatterType in formatters)
                {
                    var formatter = (IRichTextHtmlFormatter)Activator.CreateInstance(formatterType);
                    sourceString = formatter.Format(sourceString);
                }
            }
            catch (ReflectionTypeLoadException ex)
            {
                // If some assembly we load is referencing missing code, report the error and allow the page to load
                foreach (var nestedException in ex.LoaderExceptions)
                {
                    nestedException.ToExceptionless().Submit();
                }
            }

            return(sourceString);
        }
        /// <summary>
        /// Renders the macro with the specified alias, passing in the specified parameters.
        /// </summary>
        /// <param name="m">The macro.</param>
        /// <param name="parameters">The parameters.</param>
        /// <param name="umbracoPage">The legacy umbraco page object that is required for some macros</param>
        /// <returns></returns>
        internal IHtmlString RenderMacro(macro m, IDictionary <string, object> parameters, page umbracoPage)
        {
            if (umbracoPage == null)
            {
                throw new ArgumentNullException("umbracoPage");
            }
            if (m == null)
            {
                throw new ArgumentNullException("m");
            }

            if (_umbracoContext.PageId == null)
            {
                throw new InvalidOperationException("Cannot render a macro when UmbracoContext.PageId is null.");
            }

            var macroProps = new Hashtable();

            foreach (var i in parameters)
            {
                //TODO: We are doing at ToLower here because for some insane reason the UpdateMacroModel method of macro.cs
                // looks for a lower case match. WTF. the whole macro concept needs to be rewritten.


                //NOTE: the value could have html encoded values, so we need to deal with that
                macroProps.Add(i.Key.ToLowerInvariant(), (i.Value is string) ? HttpUtility.HtmlDecode(i.Value.ToString()) : i.Value);
            }
            var macroControl = m.renderMacro(macroProps,
                                             umbracoPage.Elements,
                                             _umbracoContext.PageId.Value);

            string html;

            if (macroControl is LiteralControl)
            {
                // no need to execute, we already have text
                html = (macroControl as LiteralControl).Text;
            }
            else
            {
                var containerPage = new FormlessPage();
                containerPage.Controls.Add(macroControl);

                using (var output = new StringWriter())
                {
                    // .Execute() does a PushTraceContext/PopTraceContext and writes trace output straight into 'output'
                    // and I do not see how we could wire the trace context to the current context... so it creates dirty
                    // trace output right in the middle of the page.
                    //
                    // The only thing we can do is fully disable trace output while .Execute() runs and restore afterwards
                    // which means trace output is lost if the macro is a control (.ascx or user control) that is invoked
                    // from within Razor -- which makes sense anyway because the control can _not_ run correctly from
                    // within Razor since it will never be inserted into the page pipeline (which may even not exist at all
                    // if we're running MVC).
                    //
                    // I'm sure there's more things that will get lost with this context changing but I guess we'll figure
                    // those out as we go along. One thing we lose is the content type response output.
                    // http://issues.umbraco.org/issue/U4-1599 if it is setup during the macro execution. So
                    // here we'll save the content type response and reset it after execute is called.

                    var contentType    = _umbracoContext.HttpContext.Response.ContentType;
                    var traceIsEnabled = containerPage.Trace.IsEnabled;
                    containerPage.Trace.IsEnabled = false;
                    _umbracoContext.HttpContext.Server.Execute(containerPage, output, true);
                    containerPage.Trace.IsEnabled = traceIsEnabled;
                    //reset the content type
                    _umbracoContext.HttpContext.Response.ContentType = contentType;

                    //Now, we need to ensure that local links are parsed
                    html = TemplateUtilities.ParseInternalLinks(output.ToString());
                }
            }

            return(new HtmlString(html));
        }
示例#21
0
        /// <summary>
        /// Renders the macro with the specified alias, passing in the specified parameters.
        /// </summary>
        /// <param name="alias">The alias.</param>
        /// <param name="parameters">The parameters.</param>
        /// <returns></returns>
        public IHtmlString RenderMacro(string alias, IDictionary <string, object> parameters)
        {
            if (alias == null)
            {
                throw new ArgumentNullException("alias");
            }

            var m = macro.GetMacro(alias);

            if (_umbracoContext.PageId == null)
            {
                throw new InvalidOperationException("Cannot render a macro when UmbracoContext.PageId is null.");
            }
            if (_umbracoContext.PublishedContentRequest == null)
            {
                throw new InvalidOperationException("Cannot render a macro when there is no current PublishedContentRequest.");
            }
            var macroProps = new Hashtable();

            foreach (var i in parameters)
            {
                //TODO: We are doing at ToLower here because for some insane reason the UpdateMacroModel method of macro.cs
                // looks for a lower case match. WTF. the whole macro concept needs to be rewritten.
                macroProps.Add(i.Key.ToLower(), i.Value);
            }
            var macroControl = m.renderMacro(macroProps,
                                             UmbracoContext.Current.PublishedContentRequest.UmbracoPage.Elements,
                                             _umbracoContext.PageId.Value);

            string html;

            if (macroControl is LiteralControl)
            {
                // no need to execute, we already have text
                html = (macroControl as LiteralControl).Text;
            }
            else
            {
                var containerPage = new FormlessPage();
                containerPage.Controls.Add(macroControl);

                using (var output = new StringWriter())
                {
                    // .Execute() does a PushTraceContext/PopTraceContext and writes trace output straight into 'output'
                    // and I do not see how we could wire the trace context to the current context... so it creates dirty
                    // trace output right in the middle of the page.
                    //
                    // The only thing we can do is fully disable trace output while .Execute() runs and restore afterwards
                    // which means trace output is lost if the macro is a control (.ascx or user control) that is invoked
                    // from within Razor -- which makes sense anyway because the control can _not_ run correctly from
                    // within Razor since it will never be inserted into the page pipeline (which may even not exist at all
                    // if we're running MVC).
                    //
                    var traceIsEnabled = containerPage.Trace.IsEnabled;
                    containerPage.Trace.IsEnabled = false;
                    _umbracoContext.HttpContext.Server.Execute(containerPage, output, false);
                    containerPage.Trace.IsEnabled = traceIsEnabled;

                    //Now, we need to ensure that local links are parsed
                    html = TemplateUtilities.ParseInternalLinks(output.ToString());
                }
            }

            return(new HtmlString(html));
        }
 protected virtual string GetRteParsedValue(GridControlRichTextValue value)
 {
     return(value == null ? null : TemplateUtilities.ParseInternalLinks(value.Value, Current.UmbracoContext.UrlProvider));
 }