public static Control GetMacroControl(int pageId, string aliasOrPath, params object[] properties)
        {
            //converting object[] into a single hash table merging common property names,
            //overwriting previously inserted values.

            //stupid macro propertiespropertyAliases are not case sensative !!!
            Hashtable attribs = new Hashtable();

            if (properties != null)
            {
                foreach (var prop in properties)
                {
                    var dic = prop.ToDictionary();

                    foreach (var d in dic)
                    {
                        var key = d.Key.ToLower();
                        if (attribs.ContainsKey(key))
                        {
                            attribs[key] = d.Value;
                        }
                        else
                        {
                            attribs.Add(key, d.Value);
                        }
                    }
                }
            }

            umbraco.macro macro;

            //fit is starts with ~/ then we assume we are trying to render a file and not an aliased macro
            if (aliasOrPath.StartsWith("~/"))
            {
                //this code is adapted from the macro user control
                macro = new umbraco.macro();
                macro.GenerateMacroModelPropertiesFromAttributes(attribs);
                macro.Model.ScriptName = aliasOrPath;
                macro.Model.MacroType  = MacroTypes.Script;
                if (attribs["Cache"].IsNotNull())
                {
                    if (attribs["Cache"] is int)
                    {
                        macro.Model.CacheDuration = (int)attribs["Cache"];
                    }
                }
            }
            else
            {
                macro = umbraco.macro.GetMacro(aliasOrPath);
            }

            macro.UpdateMacroModel(attribs);

            return(macro.renderMacro(attribs, pageId));
        }
        public static Control GetMacroControl(int pageId, string aliasOrPath, params object[] properties)
        {
            //converting object[] into a single hash table merging common property names,
            //overwriting previously inserted values.

            //stupid macro propertiespropertyAliases are not case sensative !!!
            Hashtable attribs = new Hashtable();
            if (properties != null)
            {
                foreach (var prop in properties)
                {
                    var dic = prop.ToDictionary();

                    foreach (var d in dic)
                    {
                        var key = d.Key.ToLower();
                        if (attribs.ContainsKey(key))
                            attribs[key] = d.Value;
                        else
                            attribs.Add(key, d.Value);
                    }
                }
            }

            umbraco.macro macro;

            //fit is starts with ~/ then we assume we are trying to render a file and not an aliased macro
            if (aliasOrPath.StartsWith("~/"))
            {
                //this code is adapted from the macro user control
                macro = new umbraco.macro();
                macro.GenerateMacroModelPropertiesFromAttributes(attribs);
                macro.Model.ScriptName = aliasOrPath;
                macro.Model.MacroType = MacroTypes.Script;
                if (attribs["Cache"].IsNotNull())
                {
                    if (attribs["Cache"] is int)
                    {
                        macro.Model.CacheDuration = (int)attribs["Cache"];
                    }
                }
            }
            else
            {
                macro = umbraco.macro.GetMacro(aliasOrPath);
            }

            macro.UpdateMacroModel(attribs);

            return macro.renderMacro(attribs, pageId);
        }
Пример #3
0
        /// <summary>
        /// Gets a rendered macro as html for rendering in the rich text editor
        /// </summary>
        /// <param name="macroAlias"></param>
        /// <param name="pageId"></param>
        /// <param name="macroParams">
        /// To send a dictionary as a GET parameter the query should be structured like:
        /// 
        /// ?macroAlias=Test&pageId=3634&macroParams[0].key=myKey&macroParams[0].value=myVal&macroParams[1].key=anotherKey&macroParams[1].value=anotherVal
        /// 
        /// </param>
        /// <returns></returns>
        public HttpResponseMessage GetMacroResultAsHtmlForEditor(string macroAlias, int pageId, [FromUri]IDictionary<string, object> macroParams)
        {
            // note - here we should be using the cache, provided that the preview content is in the cache...

            var doc = Services.ContentService.GetById(pageId);
            if (doc == null)
            {
                throw new HttpResponseException(HttpStatusCode.NotFound);
            }

            //need to get a legacy macro object - eventually we'll have a new format but nto yet
            var macro = new macro(macroAlias);
            if (macro == null)
            {
                throw new HttpResponseException(HttpStatusCode.NotFound);
            }

            //if it isn't supposed to be rendered in the editor then return an empty string
            if (macro.DontRenderInEditor)
            {
                var response = Request.CreateResponse();
                //need to create a specific content result formatted as html since this controller has been configured
                //with only json formatters.
                response.Content = new StringContent(string.Empty, Encoding.UTF8, "text/html");

                return response;
            }

            //because macro's are filled with insane legacy bits and pieces we need all sorts of wierdness to make them render.
            //the 'easiest' way might be to create an IPublishedContent manually and populate the legacy 'page' object with that
            //and then set the legacy parameters.

            var legacyPage = new global::umbraco.page(doc);                    
            UmbracoContext.HttpContext.Items["pageID"] = doc.Id;
            UmbracoContext.HttpContext.Items["pageElements"] = legacyPage.Elements;
            UmbracoContext.HttpContext.Items[global::Umbraco.Core.Constants.Conventions.Url.AltTemplate] = null;

            var result = Request.CreateResponse();
            //need to create a specific content result formatted as html since this controller has been configured
            //with only json formatters.
            result.Content = new StringContent(
                Umbraco.RenderMacro(macro, macroParams, legacyPage).ToString(),
                Encoding.UTF8,
                "text/html");
            return result;
        }
 /// <summary>
 /// Removes the cache amongst servers for a macro item
 /// </summary>
 /// <param name="dc"></param>
 /// <param name="macro"></param>
 public static void RemoveMacroCache(this DistributedCache dc, macro macro)
 {
     if (macro != null && macro.Model != null)
     {
         dc.RefreshByJson(new Guid(DistributedCache.MacroCacheRefresherId),
             MacroCacheRefresher.SerializeToJsonPayload(macro));
     }
 } 
Пример #5
0
 // gets the control for the macro, using GetXsltTransform methods for execution
 public Control loadMacroXSLT(macro macro, MacroModel model, Hashtable pageElements)
 {
     return LoadMacroXslt(macro, model, pageElements, false);
 }
Пример #6
0
        // gets the control for the macro, using GetXsltTransform methods for execution
        // will pick XmlDocument or Navigator mode depending on the capabilities of the published caches
        internal Control LoadMacroXslt(macro macro, MacroModel model, Hashtable pageElements, bool throwError)
        {
            if (XsltFile.Trim() == string.Empty)
            {
                TraceWarn("macro", "Xslt is empty");
                return new LiteralControl(string.Empty);
            }

            using (DisposableTimer.DebugDuration<macro>("Executing XSLT: " + XsltFile))
            {
                XmlDocument macroXml = null;

                // get master xml document
                var cache = UmbracoContext.Current.ContentCache.InnerCache as Umbraco.Web.PublishedCache.XmlPublishedCache.PublishedContentCache;
                if (cache == null) throw new Exception("Unsupported IPublishedContentCache, only the Xml one is supported.");
                XmlDocument umbracoXml = cache.GetXml(UmbracoContext.Current, UmbracoContext.Current.InPreviewMode);
                macroXml = new XmlDocument();
                macroXml.LoadXml("<macro/>");
                foreach (var prop in macro.Model.Properties)
                {
                    AddMacroXmlNode(umbracoXml, macroXml, prop.Key, prop.Type, prop.Value);
                }

                if (HttpContext.Current.Request.QueryString["umbDebug"] != null && GlobalSettings.DebugMode)
                {
                    var outerXml = macroXml.OuterXml;
                    return
                        new LiteralControl("<div style=\"border: 2px solid green; padding: 5px;\"><b>Debug from " +
                                           macro.Name +
                                           "</b><br/><p>" + HttpContext.Current.Server.HtmlEncode(outerXml) +
                                           "</p></div>");
                }

                try
                {
                    var xsltFile = getXslt(XsltFile);

                    using (DisposableTimer.DebugDuration<macro>("Performing transformation"))
                    {
                        try
                        {
                            var transformed = GetXsltTransformResult(macroXml, xsltFile);
                            var result = CreateControlsFromText(transformed);

                            return result;
                        }
                        catch (Exception e)
                        {
                            Exceptions.Add(e);
                            LogHelper.WarnWithException<macro>("Error parsing XSLT file", e);
                            
                            var macroErrorEventArgs = new MacroErrorEventArgs { Name = Model.Name, Alias = Model.Alias, ItemKey = Model.Xslt, Exception = e, Behaviour = UmbracoSettings.MacroErrorBehaviour };
                            var macroControl = GetControlForErrorBehavior("Error parsing XSLT file: \\xslt\\" + XsltFile, macroErrorEventArgs);
                            //if it is null, then we are supposed to throw the (original) exception
                            // see: http://issues.umbraco.org/issue/U4-497 at the end
                            if (macroControl == null && throwError)
                            {
                                throw;
                            }
                            return macroControl;
                        }   
                    }                    
                }
                catch (Exception e)
                {
                    Exceptions.Add(e);
                    LogHelper.WarnWithException<macro>("Error loading XSLT " + Model.Xslt, true, e);

                    // Invoke any error handlers for this macro
                    var macroErrorEventArgs = new MacroErrorEventArgs { Name = Model.Name, Alias = Model.Alias, ItemKey = Model.Xslt, Exception = e, Behaviour = UmbracoSettings.MacroErrorBehaviour };
                    var macroControl = GetControlForErrorBehavior("Error reading XSLT file: \\xslt\\" + XsltFile, macroErrorEventArgs);
                    //if it is null, then we are supposed to throw the (original) exception
                    // see: http://issues.umbraco.org/issue/U4-497 at the end
                    if (macroControl == null && throwError)
                    {
                        throw;
                    }
                    return macroControl;
                }
            }            
        }
Пример #7
0
 private static string ShowNoMacroContent(macro currentMacro)
 {
     return "<span style=\"color: green\"><strong>" + currentMacro.Name +
            "</strong><br />No macro content available for WYSIWYG editing</span>";
 }
Пример #8
0
        public Control loadMacroXSLT(macro macro, MacroModel model, Hashtable pageElements)
        {
            if (XsltFile.Trim() != string.Empty)
            {
                // Get main XML
                XmlDocument umbracoXML = content.Instance.XmlContent;

                // Create XML document for Macro
                var macroXML = new XmlDocument();
                macroXML.LoadXml("<macro/>");

                foreach (DictionaryEntry macroDef in macro.properties)
                {
                    var prop = model.Properties.Find(m => m.Key == (string)macroDef.Key.ToString().ToLower());
                    // zb-00037 #29875 : values have already been parsed + no need to parse ""
                    string propValue = prop != null ? prop.Value : "";
                    if (!String.IsNullOrEmpty(propValue))
                    {
                        if (propValue != string.Empty)
                            addMacroXmlNode(umbracoXML, macroXML, macroDef.Key.ToString(), macroDef.Value.ToString(),
                                            propValue);
                        else
                            addMacroXmlNode(umbracoXML, macroXML, macroDef.Key.ToString(), macroDef.Value.ToString(),
                                            string.Empty);
                    }
                }

                if (HttpContext.Current.Request.QueryString["umbDebug"] != null && GlobalSettings.DebugMode)
                {
                    return
                        new LiteralControl("<div style=\"border: 2px solid green; padding: 5px;\"><b>Debug from " +
                                           macro.Name +
                                           "</b><br/><p>" + Page.Server.HtmlEncode(macroXML.OuterXml) + "</p></div>");
                }
                else
                {
                    try
                    {
                        XslCompiledTransform xsltFile = getXslt(XsltFile);

                        try
                        {
                            Control result = CreateControlsFromText(GetXsltTransformResult(macroXML, xsltFile));

                            HttpContext.Current.Trace.Write("umbracoMacro", "After performing transformation");

                            return result;
                        }
                        catch (Exception e)
                        {
                            // inner exception code by Daniel Lindström from SBBS.se
                            Exception ie = e;
                            while (ie != null)
                            {
                                HttpContext.Current.Trace.Warn("umbracoMacro InnerException", ie.Message, ie);
                                ie = ie.InnerException;
                            }
                            return new LiteralControl("Error parsing XSLT file: \\xslt\\" + XsltFile);
                        }
                    }
                    catch (Exception e)
                    {
                        HttpContext.Current.Trace.Warn("umbracoMacro", "Error loading XSLT " + xsltFile, e);
                        return new LiteralControl("Error reading XSLT file: \\xslt\\" + XsltFile);
                    }
                }
            }
            else
            {
                Page.Trace.Warn("macro", "Xslt is empty");
                return new LiteralControl(string.Empty);
            }
        }
Пример #9
0
        public static string GetRenderedMacro(int MacroId, page umbPage, Hashtable attributes, int pageId)
        {
            var m = new macro(MacroId);
            Control c = m.renderMacro(attributes, umbPage.Elements, pageId);
            TextWriter writer = new StringWriter();
            var ht = new HtmlTextWriter(writer);
            c.RenderControl(ht);
            string result = writer.ToString();

            // remove hrefs
            string pattern = "href=\"([^\"]*)\"";
            MatchCollection hrefs =
                Regex.Matches(result, pattern, RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace);
            foreach (Match href in hrefs)
                result = result.Replace(href.Value, "href=\"javascript:void(0)\"");

            return result;
        }
Пример #10
0
        /// <summary>
        /// Executes the specified macro.
        /// </summary>
        /// <param name="macro">The macro.</param>
        /// <param name="currentPage">The current page.</param>
        /// <returns>Returns a string of the executed macro XSLT.</returns>
        public string Execute(MacroModel macro, INode currentPage)
        {
            try
            {
                string fileLocation = null;

                if (!string.IsNullOrEmpty(macro.ScriptName))
                {
                    fileLocation = string.Concat("../", macro.ScriptName);
                }
                else if (!string.IsNullOrEmpty(macro.ScriptCode))
                {
                    var xslt = CheckXsltFragment(macro.ScriptCode.Trim());
                    var md5 = library.md5(xslt);
                    var filename = string.Concat("inline-", md5, ".xslt");
                    fileLocation = this.CreateTemporaryFile(xslt, filename, true).Replace("~", "..");
                }

                if (string.IsNullOrEmpty(fileLocation))
                {
                    return string.Empty;
                }

                var tempMacro = new macro { Model = { Xslt = fileLocation } };

                // copy the macro properties across
                foreach (var property in macro.Properties)
                {
                    tempMacro.Model.Properties.Add(new MacroPropertyModel(property.Key, property.Value));
                }

                var ctrl = tempMacro.loadMacroXSLT(tempMacro, macro, (Hashtable)HttpContext.Current.Items["pageElements"]);

                this.Success = true;

                return ctrl.RenderToString();
            }
            catch (Exception ex)
            {
                this.ResultException = ex;
                this.Success = false;

                return string.Format("<div style=\"border: 1px solid #990000\">Error loading XSLT {0}<br />{1}</div>", macro.ScriptName, GlobalSettings.DebugMode ? ex.Message : string.Empty);
            }
        }
Пример #11
0
        internal Control LoadMacroXslt(macro macro, MacroModel model, Hashtable pageElements, bool throwError)
        {
            if (XsltFile.Trim() != string.Empty)
            {
                // Get main XML
                var umbracoXml = content.Instance.XmlContent;

                // Create XML document for Macro
                var macroXml = new XmlDocument();
                macroXml.LoadXml("<macro/>");

                foreach (var prop in macro.Model.Properties)
                {
                    addMacroXmlNode(umbracoXml, macroXml, prop.Key, prop.Type, prop.Value);
                }

                if (HttpContext.Current.Request.QueryString["umbDebug"] != null && GlobalSettings.DebugMode)
                {
                    return
                        new LiteralControl("<div style=\"border: 2px solid green; padding: 5px;\"><b>Debug from " +
                                           macro.Name +
                                           "</b><br/><p>" + HttpContext.Current.Server.HtmlEncode(macroXml.OuterXml) +
                                           "</p></div>");
                }

                try
                {
                    var xsltFile = getXslt(XsltFile);

                    try
                    {
                        var result = CreateControlsFromText(GetXsltTransformResult(macroXml, xsltFile));

                        TraceInfo("umbracoMacro", "After performing transformation");

                        return result;
                    }
                    catch (Exception e)
                    {
                        Exceptions.Add(e);
                        LogHelper.WarnWithException<macro>("Error parsing XSLT file", e);
                        // inner exception code by Daniel Lindstr?m from SBBS.se
                        Exception ie = e;
                        while (ie != null)
                        {
                            TraceWarn("umbracoMacro InnerException", ie.Message, ie);
                            ie = ie.InnerException;
                        }

                        var macroErrorEventArgs = new MacroErrorEventArgs { Name = Model.Name, Alias = Model.Alias, ItemKey = Model.Xslt, Exception = e, Behaviour = UmbracoSettings.MacroErrorBehaviour };
                        var macroControl = GetControlForErrorBehavior("Error parsing XSLT file: \\xslt\\" + XsltFile, macroErrorEventArgs);
                        //if it is null, then we are supposed to throw the (original) exception
                        // see: http://issues.umbraco.org/issue/U4-497 at the end
                        if (macroControl == null && throwError)
                        {
                            throw;
                        }
                        return macroControl;
                    }
                }
                catch (Exception e)
                {
                    Exceptions.Add(e);
                    LogHelper.WarnWithException<macro>("Error loading XSLT " + Model.Xslt, true, e);

                    // Invoke any error handlers for this macro
                    var macroErrorEventArgs = new MacroErrorEventArgs { Name = Model.Name, Alias = Model.Alias, ItemKey = Model.Xslt, Exception = e, Behaviour = UmbracoSettings.MacroErrorBehaviour };
                    var macroControl = GetControlForErrorBehavior("Error reading XSLT file: \\xslt\\" + XsltFile, macroErrorEventArgs);
                    //if it is null, then we are supposed to throw the (original) exception
                    // see: http://issues.umbraco.org/issue/U4-497 at the end
                    if (macroControl == null && throwError)
                    {
                        throw;
                    }
                    return macroControl;
                }
            }

            TraceWarn("macro", "Xslt is empty");
            return new LiteralControl(string.Empty);
        }
Пример #12
0
        public Control loadMacroXSLT(macro macro, MacroModel model, Hashtable pageElements)
        {
            if (XsltFile.Trim() != string.Empty)
            {
                // Get main XML
                XmlDocument umbracoXML = content.Instance.XmlContent;

                // Create XML document for Macro
                var macroXML = new XmlDocument();
                macroXML.LoadXml("<macro/>");

                foreach (MacroPropertyModel prop in macro.Model.Properties)
                {
                    addMacroXmlNode(umbracoXML, macroXML, prop.Key, prop.Type,
                                    prop.Value);
                }

                if (HttpContext.Current.Request.QueryString["umbDebug"] != null && GlobalSettings.DebugMode)
                {
                    return
                        new LiteralControl("<div style=\"border: 2px solid green; padding: 5px;\"><b>Debug from " +
                                           macro.Name +
                                           "</b><br/><p>" + UmbracoContext.Current.Server.HtmlEncode(macroXML.OuterXml) +
                                           "</p></div>");
                }
                else
                {
                    try
                    {
                        XslCompiledTransform xsltFile = getXslt(XsltFile);

                        try
                        {
                            Control result = CreateControlsFromText(GetXsltTransformResult(macroXML, xsltFile));

                            UmbracoContext.Current.Trace.Write("umbracoMacro", "After performing transformation");

                            return result;
                        }
                        catch (Exception e)
                        {
                            Exceptions.Add(e);

                            // inner exception code by Daniel Lindstr?m from SBBS.se
                            Exception ie = e;
                            while (ie != null)
                            {
                                UmbracoContext.Current.Trace.Warn("umbracoMacro InnerException", ie.Message, ie);
                                ie = ie.InnerException;
                            }
                            return new LiteralControl("Error parsing XSLT file: \\xslt\\" + XsltFile);
                        }
                    }
                    catch (Exception e)
                    {
                        Exceptions.Add(e);
                        UmbracoContext.Current.Trace.Warn("umbracoMacro", "Error loading XSLT " + Model.Xslt, e);
                        return new LiteralControl("Error reading XSLT file: \\xslt\\" + XsltFile);
                    }
                }
            }
            else
            {
                UmbracoContext.Current.Trace.Warn("macro", "Xslt is empty");
                return new LiteralControl(string.Empty);
            }
        }