예제 #1
0
 public void Macro_Is_File_Based(string macroType, bool expectedResult)
 {
     var mType = Enum<MacroTypes>.Parse(macroType);
     var model = new MacroModel("Test", "test", "", "", "", "", 0, false, false);
     model.MacroType = mType; //force the type
     Assert.AreEqual(expectedResult, macro.MacroIsFileBased(model));
 }
예제 #2
0
 public virtual string Execute(MacroModel macro, INode currentPage) {
     var fileEnding = macro.ScriptName.Substring(macro.ScriptName.LastIndexOf('.')).Trim('.');
     var mse = MacroScriptEngine.LoadEngineByFileExtension(fileEnding);
     var vars = new SortedDictionary<string, object> {
                        {"currentPage", new DynamicNode(currentPage)}
                    };
     foreach (var prop in macro.Properties) {
         vars.Add(prop.Key, prop.Value);
     }
     mse.ScriptVariables = vars;
     return mse.ExecuteFile(IOHelper.MapPath(SystemDirectories.MacroScripts + "/" + macro.ScriptName));
 }
예제 #3
0
        public void SetUserControlProperty(string val, string macroPropName, Type convertTo)
        {
            var ctrl = new UserControlTest();
            var macroModel = new MacroModel("test", "test", "", "~/usercontrols/menu.ascx", "", "", 0, false, false);
            macroModel.Properties.Add(new MacroPropertyModel(macroPropName, val));

            macro.UpdateControlProperties(ctrl, macroModel);

            var ctrlType = ctrl.GetType();
            var prop = ctrlType.GetProperty(macroPropName);
            var converted = val.TryConvertTo(convertTo);

            Assert.IsTrue(converted.Success);
            Assert.NotNull(prop);
            Assert.AreEqual(converted.Result, prop.GetValue(ctrl));
        }
예제 #4
0
        public static string Render(string razorScript = "", string macroScriptFileName = "", int nodeId = 0, IDictionary<string, string> macroParameters = null)
        {
            var macroEngine = new RazorMacroEngine();
            var macro = new MacroModel();

            macro.ScriptCode = razorScript;
            macro.ScriptLanguage = "cshtml";
            macro.ScriptName = macroScriptFileName;

            var node = new umbraco.NodeFactory.Node(nodeId);

            if(macroParameters != null) {
            foreach(var param in macroParameters) {
                macro.Properties.Add(new MacroPropertyModel(param.Key, param.Value));
            }
            }
            return macroEngine.Execute(macro, new umbraco.NodeFactory.Node(nodeId));
        }
예제 #5
0
        public static void InjectContext(WebPage razorWebPage, MacroModel macro, INode currentPage) {
            var context = HttpContext.Current;
            var contextWrapper = new HttpContextWrapper(context);

            //inject http context - for request response
            HttpContext.Current.Trace.Write("umbracoMacro", string.Format("Loading Macro Script Context (file: {0})", macro.Name));
            razorWebPage.Context = contextWrapper;
            HttpContext.Current.Trace.Write("umbracoMacro", string.Format("Done Loading Macro Script Context (file: {0})", macro.Name));

            //Inject Macro Model And Parameters
            if (razorWebPage is IMacroContext) {
                HttpContext.Current.Trace.Write("umbracoMacro", string.Format("Boxing Macro Script MacroContext (file: {0})", macro.Name));
                var razorMacro = (IMacroContext)razorWebPage;
                HttpContext.Current.Trace.Write("umbracoMacro", string.Format("Done Boxing Macro Script MacroContext (file: {0})", macro.Name));

                HttpContext.Current.Trace.Write("umbracoMacro", string.Format("Loading Macro Script Model (file: {0})", macro.Name));
                razorMacro.SetMembers(macro, currentPage);
                HttpContext.Current.Trace.Write("umbracoMacro", string.Format("Done Loading Macro Script Model (file: {0})", macro.Name));
            }
        }
        public string Execute(MacroModel macro, INode currentPage)
        {
            var fileLocation = string.Empty;

            if (!string.IsNullOrEmpty(macro.ScriptName))
            {
                fileLocation = macro.ScriptName;
            }
            else if (!string.IsNullOrEmpty(macro.ScriptCode))
            {
                var code = macro.ScriptCode.Trim();
                var md5 = library.md5(code);
                var filename = string.Concat("inline-", md5, ".php");

                fileLocation = this.CreateTemporaryFile(code, filename, true);
            }

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

            var builder = new StringBuilder();

            using (var writer = new StringWriter(builder))
            {
                var contents = File.ReadAllText(IOHelper.MapPath(fileLocation));

                var context = ScriptContext.CurrentContext;
                context.Output = writer;

                Operators.SetVariable(context, null, "model", PhpSafeType(currentPage));

                PhpEval(context, Parse(contents));
            }

            return builder.ToString();
        }
예제 #7
0
 /// <summary>
 /// Determine if macro can be cached as string
 /// </summary>
 /// <param name="model"></param>
 /// <returns></returns>
 /// <remarks>
 /// Scripts and XSLT can be generated as strings, but not controls as page events wouldn't be hit (such as Page_Load, etc)
 /// </remarks>
 internal static bool CacheMacroAsString(MacroModel model)
 {
     switch (model.MacroType)
     {
         case MacroTypes.XSLT:            
         case MacroTypes.Python:
         case MacroTypes.Script:
         case MacroTypes.PartialView:
             return true;
         case MacroTypes.UserControl:
         case MacroTypes.CustomControl:
         case MacroTypes.Unknown:
         default:
             return false;
     }
 }
예제 #8
0
 internal static string GetMacroFile(MacroModel model)
 {
     switch (model.MacroType)
     {
         case MacroTypes.XSLT:
             return string.Concat("~/xslt/", model.Xslt);                
         case MacroTypes.Python:
         case MacroTypes.Script:
             return string.Concat("~/macroScripts/", model.ScriptName);
         case MacroTypes.PartialView:
             return model.ScriptName; //partial views are saved with the full virtual path
         case MacroTypes.UserControl:
             return model.TypeName; //user controls saved with the full virtual path
         case MacroTypes.CustomControl:                
         case MacroTypes.Unknown:
         default:
             return "/" + model.TypeName;
     }
 }
예제 #9
0
 internal static bool MacroIsFileBased(MacroModel model)
 {
     return model.MacroType != MacroTypes.CustomControl && model.MacroType != MacroTypes.Unknown;
 }
예제 #10
0
        public string ExecuteRazor(MacroModel macro, INode currentPage) {
            var context = HttpContext.Current;
            var contextWrapper = new HttpContextWrapper(context);

            string fileLocation = null;
            if (!string.IsNullOrEmpty(macro.ScriptName)) {
                //Razor Is Already Contained In A File
                if (macro.ScriptName.StartsWith("~"))
                    fileLocation = macro.ScriptName;
                else
                    fileLocation = SystemDirectories.MacroScripts + "/" + macro.ScriptName;
            } else if (!string.IsNullOrEmpty(macro.ScriptCode) && !string.IsNullOrEmpty(macro.ScriptLanguage)) {
                //Inline Razor Syntax
                fileLocation = CreateInlineRazorFile(macro.ScriptCode, macro.ScriptLanguage);
            }

            if (string.IsNullOrEmpty(fileLocation))
                return String.Empty; //No File Location

            var razorWebPage = CompileAndInstantiate(fileLocation);

            HttpContext.Current.Trace.Write("umbracoMacro", string.Format("Loading Macro Script Context (file: {0})", macro.Name));
            InjectContext(razorWebPage, macro, currentPage);
            HttpContext.Current.Trace.Write("umbracoMacro", string.Format("Done Loading Macro Script Context (file: {0})", macro.Name));

            //Output Razor To String
            var output = new StringWriter();
            HttpContext.Current.Trace.Write("umbracoMacro", string.Format("Executing Macro Script (file: {0})", macro.Name));
            razorWebPage.ExecutePageHierarchy(new WebPageContext(contextWrapper, razorWebPage, null), output);
            HttpContext.Current.Trace.Write("umbracoMacro", string.Format("Done Executing Macro Script (file: {0})", macro.Name));
            return output.ToString();
        }
예제 #11
0
        /// <summary>
        /// check that the file has not recently changed
        /// </summary>
        /// <param name="model"></param>
        /// <param name="dateAddedKey"></param>
        /// <param name="macroFile"></param>
        /// <returns></returns>
        /// <remarks>
        /// The only reason this is necessary is because a developer might update a file associated with the 
        /// macro, we need to ensure if that is the case that the cache not be used and it is refreshed.
        /// </remarks>
        internal static bool MacroNeedsToBeClearedFromCache(MacroModel model, string dateAddedKey, FileInfo macroFile)
        {
            if (MacroIsFileBased(model))
            {
                var cacheResult = ApplicationContext.Current.ApplicationCache.GetCacheItem<DateTime?>(dateAddedKey);

                if (cacheResult != null)
                {
                    var dateMacroAdded = cacheResult;

                    if (macroFile.LastWriteTime.CompareTo(dateMacroAdded) == 1)
                    {
                        TraceInfo("renderMacro", string.Format("Macro needs to be removed from cache due to file change '{0}'.", model.CacheIdentifier));
                        return true;
                    }
                }
            }

            return false;
        }
 public PartialViewMacroController(UmbracoContext umbracoContext, MacroModel macro, INode currentPage)
 {
     _umbracoContext = umbracoContext;
     _macro = macro;
     _currentPage = currentPage;
 }
예제 #13
0
 public void Get_Macro_File(string xslt, string scriptFile, string scriptType, string scriptAssembly, string expectedResult)
 {
     var model = new MacroModel("Test", "test", scriptAssembly, scriptType, xslt, scriptFile, 0, false, false);
     var file = macro.GetMacroFile(model);
     Assert.AreEqual(expectedResult, file);
 }
예제 #14
0
        /// <summary>
        /// Loads a custom or webcontrol using reflection into the macro object
        /// </summary>
        /// <param name="fileName">The assembly to load from</param>
        /// <param name="controlName">Name of the control</param>
        /// <returns></returns>
        public Control loadControl(string fileName, string controlName, MacroModel model, Hashtable pageElements)
        {
            Type type;
            Assembly asm;
            try
            {
                string currentAss = IOHelper.MapPath(string.Format("{0}/{1}.dll", SystemDirectories.Bin, fileName));

                if (!File.Exists(currentAss))
                    return new LiteralControl("Unable to load user control because is does not exist: " + fileName);
                asm = Assembly.LoadFrom(currentAss);
                
				TraceInfo("umbracoMacro", "Assembly file " + currentAss + " LOADED!!");
            }
            catch
            {
                throw new ArgumentException(string.Format("ASSEMBLY NOT LOADED PATH: {0} NOT FOUND!!",
                                                          IOHelper.MapPath(SystemDirectories.Bin + "/" + fileName +
                                                                           ".dll")));
            }

	        TraceInfo("umbracoMacro", string.Format("Assembly Loaded from ({0}.dll)", fileName));
            type = asm.GetType(controlName);
            if (type == null)
                return new LiteralControl(string.Format("Unable to get type {0} from assembly {1}",
                                                        controlName, asm.FullName));

            var control = Activator.CreateInstance(type) as Control;
            if (control == null)
                return new LiteralControl(string.Format("Unable to create control {0} from assembly {1}",
                                                        controlName, asm.FullName));

            AddCurrentNodeToControl(control, type);

            // Properties
            UpdateControlProperties(type, control, model);
            return control;
        }
예제 #15
0
 public void Can_Cache_As_String(string macroType, bool expectedResult)
 {
     var mType = Enum<MacroTypes>.Parse(macroType);
     var model = new MacroModel("Test", "test", "", "", "", "", 0, false, false);
     model.MacroType = mType; //force the type
     Assert.AreEqual(expectedResult, macro.CacheMacroAsString(model));
 }
예제 #16
0
 /// <summary>
 /// Loads a custom or webcontrol using reflection into the macro object
 /// </summary>
 /// <param name="fileName">The assembly to load from</param>
 /// <param name="controlName">Name of the control</param>
 /// <returns></returns>
 public Control loadControl(string fileName, string controlName, MacroModel model)
 {
     return loadControl(fileName, controlName, model, null);
 }
예제 #17
0
 public macro(string alias)
 {
     Macro m = Macro.GetByAlias(alias);
     Model = new MacroModel(m);  
 }
예제 #18
0
        public DLRMacroResult loadMacroDLR(MacroModel macro)
        {
            var retVal = new DLRMacroResult();
            var ret = new LiteralControl();
            IMacroEngine engine = null;
            if (!String.IsNullOrEmpty(macro.ScriptCode))
            {
                engine = MacroEngineFactory.GetByExtension(macro.ScriptLanguage);
                ret.Text = engine.Execute(
                    macro,
                    Node.GetCurrent());
            }
            else
            {
                string path = IOHelper.MapPath(SystemDirectories.MacroScripts + "/" + macro.ScriptName);
                engine = MacroEngineFactory.GetByFilename(path);
                ret.Text = engine.Execute(macro, Node.GetCurrent());
            }

            // if the macro engine supports success reporting and executing failed, then return an empty control so it's not cached
            if (engine is IMacroEngineResultStatus)
            {
                var result = engine as IMacroEngineResultStatus;
                if (!result.Success)
                {
                    retVal.ResultException = result.ResultException;
                }
            }
            retVal.Control = ret;
            return retVal;
        }
예제 #19
0
 /// <summary>
 /// Creates a macro object
 /// </summary>
 /// <param name="id">Specify the macro-id which should be loaded (from table macro)</param>
 public macro(int id)
 {
     Macro m = Macro.GetById(id);
     Model = new MacroModel(m);
 }
예제 #20
0
		/// <summary>
		/// Renders a Partial View Macro
		/// </summary>
		/// <param name="macro"></param>
		/// <returns></returns>
		internal ScriptingMacroResult LoadPartialViewMacro(MacroModel macro)
		{
			var retVal = new ScriptingMacroResult();
			IMacroEngine engine = null;
			
			engine = MacroEngineFactory.GetEngine(PartialViewMacroEngine.EngineName);
			var ret = engine.Execute(macro, Node.GetCurrent());

			// if the macro engine supports success reporting and executing failed, then return an empty control so it's not cached
			if (engine is IMacroEngineResultStatus)
			{
				var result = engine as IMacroEngineResultStatus;
				if (!result.Success)
				{
					retVal.ResultException = result.ResultException;
				}
			}
			retVal.Result = ret;
			return retVal;
		}
예제 #21
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;
                }
            }            
        }
예제 #22
0
        /// <summary>
        /// Loads an usercontrol using reflection into the macro object
        /// </summary>
        /// <param name="fileName">Filename of the usercontrol - ie. ~wulff.ascx</param>
        /// <param name="attributes">The attributes.</param>
        /// <param name="pageElements">The page elements.</param>
        /// <returns></returns>
        public Control loadUserControl(string fileName, MacroModel model, Hashtable pageElements)
        {
            Debug.Assert(!string.IsNullOrEmpty(fileName), "fileName cannot be empty");
            Debug.Assert(model.Properties != null, "attributes cannot be null");
            Debug.Assert(pageElements != null, "pageElements cannot be null");
            try
            {
                string userControlPath = @"~/" + fileName;

                if (!File.Exists(IOHelper.MapPath(userControlPath)))
                    return new LiteralControl(string.Format("UserControl {0} does not exist.", fileName));

                var oControl = (UserControl)new UserControl().LoadControl(userControlPath);

                int slashIndex = fileName.LastIndexOf("/") + 1;
                if (slashIndex < 0)
                    slashIndex = 0;

                if (!String.IsNullOrEmpty(model.MacroControlIdentifier))
                    oControl.ID = model.MacroControlIdentifier;
                else
                    oControl.ID =
                        string.Format("{0}_{1}", fileName.Substring(slashIndex, fileName.IndexOf(".ascx") - slashIndex),
                                      StateHelper.GetContextValue<int>(macrosAddedKey));

                TraceInfo(loadUserControlKey, string.Format("Usercontrol added with id '{0}'", oControl.ID));

                Type type = oControl.GetType();
                if (type == null)
                {
                    TraceWarn(loadUserControlKey, "Unable to retrieve control type: " + fileName);
                    return oControl;
                }

                AddCurrentNodeToControl(oControl, type);

                foreach (string propertyAlias in properties.Keys)
                {
                    PropertyInfo prop = type.GetProperty(propertyAlias);
                    if (prop == null)
                    {
                        TraceWarn(loadUserControlKey, "Unable to retrieve type from propertyAlias: " + propertyAlias);
                        continue;
                    }

                    MacroPropertyModel propModel = model.Properties.Find(m => m.Key == propertyAlias.ToLower());
                    // zb-00037 #29875 : values have already been parsed + no need to parse ""
                    object propValue = propModel != null && prop != null ? propModel.Value : null;

                    if (propValue == null)
                        continue;

                    // Special case for types of webControls.unit
                    try
                    {
                        if (prop.PropertyType == typeof(Unit))
                            propValue = Unit.Parse(propValue.ToString());
                        else
                        {
                            try
                            {
                                object o = propertyDefinitions[propertyAlias];
                                if (o == null)
                                    continue;
                                var st = (TypeCode)Enum.Parse(typeof(TypeCode), o.ToString(), true);

                                // Special case for booleans
                                if (prop.PropertyType == typeof(bool))
                                {
                                    bool parseResult;
                                    if (
                                        Boolean.TryParse(
                                            propValue.ToString().Replace("1", "true").Replace("0", "false"),
                                            out parseResult))
                                        propValue = parseResult;
                                    else
                                        propValue = false;
                                }
                                else
                                    propValue = Convert.ChangeType(propValue, st);

                                Trace.Write("macro.loadControlProperties",
                                            string.Format("Property added '{0}' with value '{1}'", propertyAlias,
                                                          propValue));
                            }
                            catch (Exception PropException)
                            {
                                HttpContext.Current.Trace.Warn("macro.loadControlProperties",
                                                               string.Format(
                                                                   "Error adding property '{0}' with value '{1}'",
                                                                   propertyAlias, propValue), PropException);
                            }
                        }

                        prop.SetValue(oControl, Convert.ChangeType(propValue, prop.PropertyType), null);
                    }
                    catch (Exception propException)
                    {
                        HttpContext.Current.Trace.Warn("macro.loadControlProperties",
                                                       string.Format(
                                                           "Error adding property '{0}' with value '{1}', maybe it doesn't exists or maybe casing is wrong!",
                                                           propertyAlias, propValue), propException);
                    }
                }
                return oControl;
            }
            catch (Exception e)
            {
                HttpContext.Current.Trace.Warn("macro", string.Format("Error creating usercontrol ({0})", fileName), e);
                return new LiteralControl(
                    string.Format(
                        "<div style=\"color: black; padding: 3px; border: 2px solid red\"><b style=\"color:red\">Error creating control ({0}).</b><br/> Maybe file doesn't exists or the usercontrol has a cache directive, which is not allowed! See the tracestack for more information!</div>",
                        fileName));
            }
        }
예제 #23
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);
 }
예제 #24
0
 /// <summary>
 /// Creates an empty macro object.
 /// </summary>
 public macro()
 {
     Model = new MacroModel();
 }
예제 #25
0
        public string Execute(MacroModel macro, INode currentPage)
        {
            if (macro == null) throw new ArgumentNullException("macro");
            if (currentPage == null) throw new ArgumentNullException("currentPage");
			if (macro.ScriptName.IsNullOrWhiteSpace()) throw new ArgumentException("The ScriptName property of the macro object cannot be null or empty");
		
            if (!macro.ScriptName.StartsWith(SystemDirectories.MvcViews + "/MacroPartials/")
                && (!Regex.IsMatch(macro.ScriptName, "~/App_Plugins/.+?/Views/MacroPartials", RegexOptions.Compiled)))
            {
                throw new InvalidOperationException("Cannot render the Partial View Macro with file: " + macro.ScriptName + ". All Partial View Macros must exist in the " + SystemDirectories.MvcViews + "/MacroPartials/ folder");
            }

            var http = _getHttpContext();
            var umbCtx = _getUmbracoContext();
            var routeVals = new RouteData();
            routeVals.Values.Add("controller", "PartialViewMacro");
            routeVals.Values.Add("action", "Index");
            routeVals.DataTokens.Add("umbraco-context", umbCtx); //required for UmbracoViewPage

			//lets render this controller as a child action if we are currently executing using MVC 
			//(otherwise don't do this since we're using webforms)
			var mvcHandler = http.CurrentHandler as MvcHandler;
			var viewContext = new ViewContext {ViewData = new ViewDataDictionary()};;
			if (mvcHandler != null)
			{
				//try and extract the current view context from the route values, this would be set in the UmbracoViewPage.
				if (mvcHandler.RequestContext.RouteData.DataTokens.ContainsKey(Constants.DataTokenCurrentViewContext))
				{
					viewContext = (ViewContext) mvcHandler.RequestContext.RouteData.DataTokens[Constants.DataTokenCurrentViewContext];
				}
				routeVals.DataTokens.Add("ParentActionViewContext", viewContext);
			}

            var request = new RequestContext(http, routeVals);
            string output;
            using (var controller = new PartialViewMacroController(umbCtx, macro, currentPage))
            {
				//bubble up the model state from the main view context to our custom controller.
				//when merging we'll create a new dictionary, otherwise you might run into an enumeration error
				// caused from ModelStateDictionary
				controller.ModelState.Merge(new ModelStateDictionary(viewContext.ViewData.ModelState));
				controller.ControllerContext = new ControllerContext(request, controller);
				//call the action to render
                var result = controller.Index();
				output = controller.RenderViewResultAsString(result);
            }

            return output;
        }
예제 #26
0
        string GetCacheIdentifier(MacroModel model, Hashtable pageElements, int pageId)
        {
            var id = new StringBuilder();

            var alias = string.IsNullOrEmpty(model.ScriptCode) ? model.Alias : Macro.GenerateCacheKeyFromCode(model.ScriptCode);
            id.AppendFormat("{0}-", alias);

            if (CacheByPage)
            {
                id.AppendFormat("{0}-", pageId);
            }

            if (CacheByPersonalization)
            {
                var currentMember = Member.GetCurrentMember();
                id.AppendFormat("m{0}-", currentMember == null ? 0 : currentMember.Id);
            }

            foreach (var prop in model.Properties)
            {
                var propValue = prop.Value;
                id.AppendFormat("{0}-", propValue.Length <= 255 ? propValue : propValue.Substring(0, 255));
            }

            return id.ToString();
        }
예제 #27
0
        private static void UpdateControlProperties(Type type, Control control, MacroModel model)
        {
            foreach (MacroPropertyModel mp in model.Properties)
            {
                PropertyInfo prop = type.GetProperty(mp.Key);
                if (prop == null)
                {					
					TraceWarn("macro", string.Format("control property '{0}' doesn't exist or aren't accessible (public)", mp.Key));
                    continue;
                }

                object propValue = mp.Value;
                bool propValueSet = false;
                // Special case for types of webControls.unit
                if (prop.PropertyType == typeof(Unit))
                {
                    propValue = Unit.Parse(propValue.ToString());
                    propValueSet = true;
                }
                else
                {
                    try
                    {
                        if (mp.CLRType == null)
                            continue;
                        var st = (TypeCode)Enum.Parse(typeof(TypeCode), mp.CLRType, true);

                        // Special case for booleans
                        if (prop.PropertyType == typeof(bool))
                        {
                            bool parseResult;
                            if (
                                Boolean.TryParse(
                                    propValue.ToString().Replace("1", "true").Replace("0", "false"),
                                    out parseResult))
                                propValue = parseResult;
                            else
                                propValue = false;
                            propValueSet = true;

                        }
                        else
                        {
                            string sPropValue = string.Format("{0}", propValue);
                            Type propType = prop.PropertyType;
                            if (!string.IsNullOrWhiteSpace(sPropValue))
                            {
                                try
                                {
                                    propValue = Convert.ChangeType(propValue, st);
                                    propValueSet = true;
                                }
                                catch (FormatException)
                                {
                                    propValue = Convert.ChangeType(propValue, propType);
                                    propValueSet = true;
                                }
                            }
                            /* NH 06-01-2012: Remove the lines below as they would only get activated if the values are empty
                        else
                        {
                            if (propType != null)
                            {
                                if (propType.IsValueType)
                                {
                                    propValue = Activator.CreateInstance(propType);
                                }
                                else
                                {
                                    propValue = null;
                                }
                            }
                        }*/
                        }

						if (GlobalSettings.DebugMode)
							TraceInfo("macro.loadControlProperties",
							          string.Format("Property added '{0}' with value '{1}'",
							                        mp.Key,
							                        propValue));
                    }
                    catch (Exception PropException)
                    {
						LogHelper.WarnWithException<macro>(string.Format(
										  "Error adding property '{0}' with value '{1}'",
										  mp.Key, propValue), PropException);

						if (GlobalSettings.DebugMode)
						{
							TraceWarn("macro.loadControlProperties",
							          string.Format(
								          "Error adding property '{0}' with value '{1}'",
								          mp.Key, propValue), PropException);
						}
                    }
                }

                // NH 06-01-2012: Only set value if it has content
                if (propValueSet)
                {
                    //GE 06-05-2012: Handle Nullable<T> properties
                    if (prop.PropertyType.IsGenericType && prop.PropertyType.Name == "Nullable`1")
                    {
                        Type underlyingType = Nullable.GetUnderlyingType(prop.PropertyType);
                        if (underlyingType != null)
                        {
                            object safeValue = null;
                            if (propValue != null)
                            {
                                if (!(underlyingType == typeof(Guid)))
                                {
                                    prop.SetValue(control, Convert.ChangeType(propValue, underlyingType), null);
                                }
                                else
                                {
                                    Guid g = Guid.Empty;
                                    if (Guid.TryParse(string.Format("{0}", propValue), out g))
                                    {
                                        prop.SetValue(control, g, null);
                                    }
                                }
                            }
                            else
                            {
                                prop.SetValue(control, safeValue, null);
                            }
                        }
                    }
                    else
                    {
                        //GE 06-05-2012: Handle Guid properties as Convert.ChangeType throws on string->Guid
                        if (!(prop.PropertyType == typeof(Guid)))
                        {
                            prop.SetValue(control, Convert.ChangeType(propValue, prop.PropertyType), null);
                        }
                        else
                        {
                            Guid g = Guid.Empty;
                            if (Guid.TryParse(string.Format("{0}", propValue), out g))
                            {
                                prop.SetValue(control, g, null);
                            }
                        }
                    }
                }
            }
        }
예제 #28
0
 public string Execute(MacroModel macro, INode currentPage) {
     try
     {
         Success = true;
         return ExecuteRazor(macro, currentPage);
     } catch (Exception exception)
     {
         Success = false;
         ResultException = exception;
         HttpContext.Current.Trace.Warn("umbracoMacro", string.Format("Error Loading Razor Script (file: {0}) {1} {2}", macro.Name, exception.Message, exception.StackTrace));
         throw;
     }
 }
예제 #29
0
        [TestCase(5, false)] //the cache DateTime will be newer than the file date
        public void Macro_Needs_Removing_Based_On_Macro_File(int minutesToNow, bool expectedResult)
        {
            var now = DateTime.Now;
            ApplicationContext.Current.ApplicationCache.InsertCacheItem(
                "TestDate",
                CacheItemPriority.NotRemovable,
                new TimeSpan(0, 0, 60),
                () => now.AddMinutes(minutesToNow)); //add a datetime value of 'now' with the minutes offset

            //now we need to update a file's date to 'now' to compare
            var path = Path.Combine(TestHelpers.TestHelper.CurrentAssemblyDirectory, "temp.txt");
            File.CreateText(path).Close();

            //needs to be file based (i.e. xslt)
            var model = new MacroModel("Test", "test", "", "", "test.xslt", "", 0, false, false);

            Assert.AreEqual(expectedResult, macro.MacroNeedsToBeClearedFromCache(model, "TestDate", new FileInfo(path)));
        }
예제 #30
0
	    /// <summary>
	    /// Loads an usercontrol using reflection into the macro object
	    /// </summary>
	    /// <param name="fileName">Filename of the usercontrol - ie. ~wulff.ascx</param>
	    /// <param name="model"> </param>
	    /// <param name="pageElements">The page elements.</param>
	    /// <returns></returns>
	    public Control loadUserControl(string fileName, MacroModel model, Hashtable pageElements)
        {
			Mandate.ParameterNotNullOrEmpty(fileName, "fileName");
	        Mandate.ParameterNotNull(model, "model");

            try
            {
                string userControlPath = IOHelper.FindFile(fileName);

                if (!File.Exists(IOHelper.MapPath(userControlPath)))
                    throw new UmbracoException(string.Format("UserControl {0} does not exist.", fileName));

                var oControl = (UserControl)new UserControl().LoadControl(userControlPath);

                int slashIndex = fileName.LastIndexOf("/") + 1;
                if (slashIndex < 0)
                    slashIndex = 0;

                if (!String.IsNullOrEmpty(model.MacroControlIdentifier))
                    oControl.ID = model.MacroControlIdentifier;
                else
                    oControl.ID =
                        string.Format("{0}_{1}", fileName.Substring(slashIndex, fileName.IndexOf(".ascx") - slashIndex),
                                      StateHelper.GetContextValue<int>(MacrosAddedKey));

                TraceInfo(LoadUserControlKey, string.Format("Usercontrol added with id '{0}'", oControl.ID));

                Type type = oControl.GetType();

	            AddCurrentNodeToControl(oControl, type);
                UpdateControlProperties(type, oControl, model);
                return oControl;
            }
            catch (Exception e)
            {
				LogHelper.WarnWithException<macro>(string.Format("Error creating usercontrol ({0})", fileName), true, e);
                throw;
            }
        }