protected override async Task Run() { const int baseButton = 2; while (!Ct.IsCancellationRequested) { if (_lastHealTime.AddSeconds(NoOperationDelay) < DateTime.UtcNow) { await DoHeal(baseButton.ToString()); } var model = MacroModel.GetClientModel(_targetWnd); var hpStr = string.Join(" ", model.Party.Select(m => $"hp:{m.Hp:0}")); var cd = (DateTime.UtcNow - _lastHealTime).TotalSeconds; Status = $"t: {cd:0} " + hpStr; for (int pIndex = 0; pIndex < model.Party.Count; pIndex++) { var m = model.Party[pIndex]; if (m.Hp.HasValue && m.Hp < PercentToHeal) { await DoHeal((baseButton + pIndex).ToString()); break; } } await Task.Delay(200, Ct).ConfigureAwait(false); } }
/// <summary> /// Executes a macro of a given type. /// </summary> private Attempt <MacroContent> ExecuteMacroWithErrorWrapper(MacroModel macro, string msgIn, string msgOut, Func <MacroContent> getMacroContent, Func <string> msgErr) { using (_profilingLogger.DebugDuration <MacroRenderer>(msgIn, msgOut)) { return(ExecuteProfileMacroWithErrorWrapper(macro, msgIn, getMacroContent, msgErr)); } }
public string Execute(MacroModel macro, INode currentPage) { //if this is executing, we need to ensure the folder exists and that the correct web.config exists on that folder too var absolutePath = IOHelper.MapPath(SystemDirectories.MacroScripts); if (!Directory.Exists(absolutePath)) { Directory.CreateDirectory(absolutePath); } if (!File.Exists(Path.Combine(absolutePath, "web.config"))) { using (var writer = File.CreateText(Path.Combine(absolutePath, "web.config"))) { writer.Write(Strings.WebConfig); } } 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; } }
public async Task <IActionResult> FromMacroCalculator([FromBody] MacroModel macros) { _MacroService.macroList.Add(macros); var totalMacros = await _MacroService.startCalculation(); return(Ok(totalMacros)); }
// stores macro content into the cache private async Task AddMacroContentToCacheAsync(MacroModel model, MacroContent macroContent) { IUmbracoContext umbracoContext = _umbracoContextAccessor.GetRequiredUmbracoContext(); // only if cache is enabled if (umbracoContext.InPreviewMode || model.CacheDuration <= 0) { return; } // do not cache if it should cache by member and there's not member if (model.CacheByMember) { IMemberManager?memberManager = _httpContextAccessor.HttpContext?.RequestServices.GetRequiredService <IMemberManager>(); MemberIdentityUser?member = await memberManager?.GetCurrentMemberAsync() !; if (member is null) { return; } } // remember when we cache the content macroContent.Date = DateTime.Now; IAppPolicyCache cache = _appCaches.RuntimeCache; cache.Insert( CacheKeys.MacroContentCacheKey + model.CacheIdentifier, () => macroContent, new TimeSpan(0, 0, model.CacheDuration)); _logger.LogDebug("Macro content saved to cache '{MacroCacheId}'", model.CacheIdentifier); }
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); }
protected override async Task Initialize() { Status = "Select window to watch and click heal"; _targetWnd = await MacroModel.GetClientTarget(Ct); Status = "Ok"; }
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)); }
private static string GetMacroFile(MacroModel model) { if (model.ScriptName != string.Empty) { return(string.Concat(string.Format("/macroScripts/{0}", model.ScriptName))); } return("/" + model.TypeName); }
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)); }
// updates the model properties values according to the attributes private static void UpdateMacroModelProperties(MacroModel model, IDictionary <string, object> macroParams) { foreach (var prop in model.Properties) { var key = prop.Key.ToLowerInvariant(); prop.Value = macroParams != null && macroParams.ContainsKey(key) ? macroParams[key]?.ToString() ?? string.Empty : string.Empty; } }
private async Task <MacroContent> RenderAsync(MacroModel macro, IPublishedContent content) { if (content == null) { throw new ArgumentNullException(nameof(content)); } var macroInfo = $"Render Macro: {macro.Name}, cache: {macro.CacheDuration}"; using (_profilingLogger.DebugDuration <MacroRenderer>(macroInfo, "Rendered Macro.")) { // parse macro parameters ie replace the special [#key], [$key], etc. syntaxes foreach (var prop in macro.Properties) { prop.Value = ParseAttribute(prop.Value); } var cultureName = System.Threading.Thread.CurrentThread.CurrentUICulture.Name; macro.CacheIdentifier = await GetContentCacheIdentifier(macro, content.Id, cultureName); // get the macro from cache if it is there var macroContent = GetMacroContentFromCache(macro); // macroContent.IsEmpty may be true, meaning the macro produces no output, // but still can be cached because its execution did not trigger any error. // so we need to actually render, only if macroContent is null if (macroContent != null) { return(macroContent); } // this will take care of errors // it may throw, if we actually want to throw, so better not // catch anything here and let the exception be thrown var attempt = ExecuteMacroOfType(macro, content); // by convention ExecuteMacroByType must either throw or return a result // just check to avoid internal errors macroContent = attempt.Result; if (macroContent == null) { throw new Exception("Internal error, ExecuteMacroOfType returned no content."); } // add to cache if render is successful // content may be empty but that's not an issue if (attempt.Success) { // write to cache (if appropriate) await AddMacroContentToCacheAsync(macro, macroContent); } return(macroContent); } }
public Control loadMacroXSLT(uWebshopMacro 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 (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 { XslCompiledTransform xsltFile = umbraco.macro.getXslt(XsltFile); try { Control result = CreateControlsFromText(umbraco.macro.GetXsltTransformResult(macroXML, xsltFile)); TraceInfo("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) { TraceWarn("umbracoMacro InnerException", ie.Message, ie); ie = ie.InnerException; } return(new LiteralControl("Error parsing XSLT file: \\xslt\\" + XsltFile)); } } catch (Exception e) { Exceptions.Add(e); return(new LiteralControl("Error reading XSLT file: \\xslt\\" + XsltFile)); } } TraceWarn("macro", "Xslt is empty"); return(new LiteralControl(string.Empty)); }
public PartialViewMacroViewComponent( MacroModel macro, IPublishedContent content, ViewComponentContext viewComponentContext) { _macro = macro; _content = content; // This must be set before Invoke is called else the call to View will end up // using an empty ViewData instance because this hasn't been set yet. ViewComponentContext = viewComponentContext; }
public MacroContent Execute(MacroModel macro, IPublishedContent content) { if (macro == null) { throw new ArgumentNullException(nameof(macro)); } if (content == null) { throw new ArgumentNullException(nameof(content)); } if (string.IsNullOrWhiteSpace(macro.MacroSource)) { throw new ArgumentException("The MacroSource property of the macro object cannot be null or empty"); } HttpContext httpContext = _httpContextAccessor.GetRequiredHttpContext(); RouteData currentRouteData = httpContext.GetRouteData(); // Check if there's proxied ViewData (i.e. returned from a SurfaceController) ProxyViewDataFeature?proxyViewDataFeature = httpContext.Features.Get <ProxyViewDataFeature>(); ViewDataDictionary viewData = proxyViewDataFeature?.ViewData ?? new ViewDataDictionary(_modelMetadataProvider, new ModelStateDictionary()); ITempDataDictionary tempData = proxyViewDataFeature?.TempData ?? _tempDataDictionaryFactory.GetTempData(httpContext); var viewContext = new ViewContext( new ActionContext(httpContext, currentRouteData, new ControllerActionDescriptor()), new FakeView(), viewData, tempData, TextWriter.Null, new HtmlHelperOptions()); var writer = new StringWriter(); var viewComponentContext = new ViewComponentContext( new ViewComponentDescriptor(), new Dictionary <string, object?>(), HtmlEncoder.Default, viewContext, writer); var viewComponent = new PartialViewMacroViewComponent(macro, content, viewComponentContext); viewComponent.Invoke().Execute(viewComponentContext); var output = writer.GetStringBuilder().ToString(); return(new MacroContent { Text = output }); }
///// <summary> ///// Renders a Partial View Macro ///// </summary> ///// <param name="macro"></param> ///// <param name="nodeId"></param> ///// <returns></returns> //internal ScriptingMacroResult LoadPartialViewMacro(MacroModel macro, int nodeId) //{ // var retVal = new ScriptingMacroResult(); // TraceInfo("umbracoMacro", "Rendering Partial View Macro"); // var engine = MacroEngineFactory.GetEngine("Partial View Macro Engine");//PartialViewMacroEngine.EngineName); // var ret = engine.Execute(macro, new Node(nodeId)); // // 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; // } // } // TraceInfo("umbracoMacro", "Rendering Partial View Macro [done]"); // retVal.Result = ret; // return retVal; //} public ScriptingMacroResult LoadMacroScript(MacroModel macro, int currentPageId) { Log.Instance.LogDebug("LoadMacroScript macro.Alias: " + macro.Alias); Log.Instance.LogDebug("LoadMacroScript macro.ScriptCode: " + macro.ScriptCode); Log.Instance.LogDebug("LoadMacroScript macro.ScriptName: " + macro.ScriptName); var retVal = new ScriptingMacroResult(); TraceInfo("umbracoMacro", "Loading IMacroEngine script"); string ret; IMacroEngine engine; if (!string.IsNullOrEmpty(macro.ScriptCode)) { Log.Instance.LogDebug("LoadMacroScript engine.ScriptLanguage: " + macro.ScriptLanguage); engine = MacroEngineFactory.GetByExtension(macro.ScriptLanguage); Log.Instance.LogDebug("LoadMacroScript engine.Name: " + engine.Name); ret = engine.Execute(macro, new Node(currentPageId)); } else { var path = macro.ScriptName; if (!macro.ScriptName.StartsWith("~")) { path = SystemDirectories.MacroScripts.TrimEnd('/') + "/" + macro.ScriptName.TrimStart('/'); } Log.Instance.LogDebug("LoadMacroScript path: " + path); engine = MacroEngineFactory.GetByFilename(path); Log.Instance.LogDebug("LoadMacroScript engine.Name: " + engine.Name); ret = engine.Execute(macro, new Node(currentPageId)); } // 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; } } TraceInfo("umbracoMacro", "Loading IMacroEngine script [done]"); retVal.Result = ret; return(retVal); }
public override void SetMembers(MacroModel macro, INode node) { if (macro == null) { throw new ArgumentNullException("macro"); } if (node == null) { throw new ArgumentNullException("node"); } CurrentModel = new DynamicNode(node); base.SetMembers(macro, node); }
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; } }
public async Task <MacroContent> RenderAsync(string macroAlias, IPublishedContent content, IDictionary <string, object> macroParams) { var m = _appCaches.RuntimeCache.GetCacheItem(CacheKeys.MacroFromAliasCacheKey + macroAlias, () => _macroService.GetByAlias(macroAlias)); if (m == null) { throw new InvalidOperationException("No macro found by alias " + macroAlias); } var macro = new MacroModel(m); UpdateMacroModelProperties(macro, macroParams); return(await RenderAsync(macro, content)); }
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))); }
public string Execute(MacroModel macro, INode currentPage) { try { return(ExecuteRazor(macro, currentPage)); } catch (Exception exception) { HttpContext.Current.Trace.Warn("umbracoMacro", string.Format("Error Loading Razor Script (file: {0}) {1} {2}", macro.Name, exception.Message, exception.StackTrace)); var loading = string.Format("<div style=\"border: 1px solid #990000\">Error loading Razor Script {0}</br/>", macro.ScriptName); if (GlobalSettings.DebugMode) { loading = loading + exception.Message; } loading = loading + "</div>"; return(loading); } }
// gets the macro source file // null if macro is not file-based private FileInfo?GetMacroFile(MacroModel model) { var filename = GetMacroFileName(model); if (filename == null) { return(null); } var mapped = _webHostEnvironment.MapPathContentRoot(filename); var file = new FileInfo(mapped); return(file.Exists ? file : null); }
public virtual void SetMembers(MacroModel macro, INode node) { if (macro == null) { throw new ArgumentNullException("macro"); } if (node == null) { throw new ArgumentNullException("node"); } _macro = macro; ParameterDictionary = new UmbracoParameterDictionary(macro.Properties); CultureDictionary = new UmbracoCultureDictionary(); _node = node; }
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 razorWebPage.Context = contextWrapper; //Inject Macro Model And Parameters if (razorWebPage is IMacroContext) { var razorMacro = (IMacroContext)razorWebPage; razorMacro.SetMembers(macro, currentPage); } }
public override void SetMembers(MacroModel macro, INode node) { if (macro == null) { throw new ArgumentNullException("macro"); } if (node == null) { throw new ArgumentNullException("node"); } var backingItem = new DynamicBackingItem(node); var dynamicNode = new DynamicNode(backingItem); CurrentModel = dynamicNode; base.SetMembers(macro, node); }
public void Macro_Is_File_Based(string macroSource, bool expectedNonNull) { var model = new MacroModel { MacroSource = macroSource }; var filename = MacroRenderer.GetMacroFileName(model); if (expectedNonNull) { Assert.IsNotNull(filename); } else { Assert.IsNull(filename); } }
/// <summary> /// Executes a macro of a given type. /// </summary> private Attempt <MacroContent> ExecuteProfileMacroWithErrorWrapper(MacroModel macro, string msgIn, Func <MacroContent> getMacroContent, Func <string> msgErr) { try { return(Attempt.Succeed(getMacroContent())); } catch (Exception e) { _logger.LogWarning(e, "Failed {MsgIn}", msgIn); var macroErrorEventArgs = new MacroErrorEventArgs { Name = macro.Name, Alias = macro.Alias, MacroSource = macro.MacroSource, Exception = e, Behaviour = _contentSettings.MacroErrors }; switch (macroErrorEventArgs.Behaviour) { case MacroErrorBehaviour.Inline: // do not throw, eat the exception, display the trace error message return(Attempt.Fail(new MacroContent { Text = msgErr() }, e)); case MacroErrorBehaviour.Silent: // do not throw, eat the exception, do not display anything return(Attempt.Fail(new MacroContent { Text = string.Empty }, e)); case MacroErrorBehaviour.Content: // do not throw, eat the exception, display the custom content return(Attempt.Fail(new MacroContent { Text = macroErrorEventArgs.Html ?? string.Empty }, e)); //case MacroErrorBehaviour.Throw: default: // see http://issues.umbraco.org/issue/U4-497 at the end // throw the original exception throw; } } }
/// <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)); } }
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)); }
// gets this macro content cache identifier private async Task <string> GetContentCacheIdentifier(MacroModel model, int pageId, string cultureName) { var id = new StringBuilder(); var alias = model.Alias; id.AppendFormat("{0}-", alias); // always add current culture to the key to allow variants to have different cache results if (!string.IsNullOrEmpty(cultureName)) { // are there any unusual culture formats we'd need to handle? id.AppendFormat("{0}-", cultureName); } if (model.CacheByPage) { id.AppendFormat("{0}-", pageId); } if (model.CacheByMember) { object key = 0; if (_httpContextAccessor.HttpContext?.User.Identity?.IsAuthenticated ?? false) { IMemberManager memberManager = _httpContextAccessor.HttpContext.RequestServices.GetRequiredService <IMemberManager>(); MemberIdentityUser?member = await memberManager.GetCurrentMemberAsync(); if (member is not null) { key = member.Key; } } id.AppendFormat("m{0}-", key); } foreach (var value in model.Properties.Select(x => x.Value)) { id.AppendFormat("{0}-", value?.Length <= 255 ? value : value?.Substring(0, 255)); } return(id.ToString()); }