private string Render(params object[] args) { try { // Converts the incoming object arguments to proper TemplateArguments TemplateArguments arguments = new TemplateArguments(args); string pageTemplate = _templateMgr.Render("views\\user\\" + MethodName + ".haml", arguments); arguments.Clear(); arguments.Add("text", pageTemplate); return(_templateMgr.Render("views\\layouts\\application.haml", arguments)); } catch (FileNotFoundException err) { throw new NotFoundException("Failed to find template. Details: " + err.Message, err); } catch (InvalidOperationException err) { throw new InternalServerException("Failed to render template. Details: " + err.Message, err); } catch (TemplateException err) { throw new InternalServerException("Failed to compile template. Details: " + err.Message, err); } catch (ArgumentException err) { throw new InternalServerException("Failed to render templates", err); } }
public void TestDuplicate() { _arguments = new TemplateArguments("Test", 1); Assert.Throws(typeof(ArgumentException), delegate { _arguments.Add("Test", 2); }); }
public void TestCodeGenerated() { ParseAndGenerate(@"<html><% if (a == 'a') { %>Hello<% } %></html>"); TemplateArguments args = new TemplateArguments("a", 'b'); ITinyTemplate template = _compiler.Compile(args, _sb.ToString(), "nun"); Assert.Equal("<html></html>\r\n", template.Invoke(args, null)); Assert.Equal("<html>Hello</html>\r\n", template.Invoke(new TemplateArguments("a", 'a'), null)); }
public void TestEchoGenerated() { ParseAndGenerate(@"<html name=""<%= name %>"">"); TemplateArguments args = new TemplateArguments("name", "jonas"); ITinyTemplate template = _compiler.Compile(args, _sb.ToString(), "nun"); string result = template.Invoke(args, null); Assert.Equal("<html name=\"jonas\">\r\n", result); }
public async Task <PreviewResult> PreviewById(string id, PrintingPreviewTemplate template, PrintEntityByIdArguments args, CancellationToken cancellation) { await Initialize(cancellation); var collection = template.Collection; var defId = template.DefinitionId; // (1) The Template Plan var nameP = new TemplatePlanLeaf(template.DownloadName, TemplateLanguage.Text); var bodyP = new TemplatePlanLeaf(template.Body, TemplateLanguage.Html); var printoutP = new TemplatePlanTuple(nameP, bodyP); TemplatePlan plan; if (string.IsNullOrWhiteSpace(template.Context)) { plan = printoutP; } else { plan = new TemplatePlanDefine("$", template.Context, printoutP); } var contextQuery = BaseUtil.EntityPreloadedQuery(id, args, collection, defId); plan = new TemplatePlanDefineQuery("$", contextQuery, plan); // (2) Functions + Variables var globalFunctions = new Dictionary <string, EvaluationFunction>(); var localFunctions = new Dictionary <string, EvaluationFunction>(); var globalVariables = new Dictionary <string, EvaluationVariable>(); var localVariables = BaseUtil.EntityLocalVariables(id, args, collection, defId); await FactBehavior.SetPrintingFunctions(localFunctions, globalFunctions, cancellation); await FactBehavior.SetPrintingVariables(localVariables, globalVariables, cancellation); // (3) Culture var culture = GetCulture(args, await _behavior.Settings(cancellation)); // (4) Generate output var genArgs = new TemplateArguments( customGlobalFunctions: globalFunctions, customGlobalVariables: globalVariables, customLocalFunctions: localFunctions, customLocalVariables: localVariables, culture: culture); await _templateService.GenerateFromPlan(plan : plan, args : genArgs, cancellation : cancellation); var downloadName = AppendExtension(nameP.Outputs[0], template); var body = bodyP.Outputs[0]; // Return as a file return(new PreviewResult(body, downloadName)); }
public virtual ActionResult Template([FromQuery] TemplateArguments args) { try { var abstractFile = GetImportTemplate(); return(ToFileResult(abstractFile, args.Format)); } catch (Exception ex) { _logger.LogError($"Error: {ex.Message} {ex.StackTrace}"); return(BadRequest(ex.Message)); } }
/// <summary> /// Merge arguments array and Arguments property. /// </summary> /// <param name="args">Arguments array to merge</param> /// <returns>arguments/parameters that can be used in the template.</returns> /// <remarks>Will add Request/Response/Session arguments</remarks> private TemplateArguments MergeArguments(object[] args) { // Create a new argument holder TemplateArguments arguments = new TemplateArguments(); arguments.Add("Request", Request, typeof(IHttpRequest)); arguments.Add("Response", Response); arguments.Add("Session", Session); arguments.Add("Controller", this, typeof(ViewController)); arguments.Update(_arguments); arguments.Update(new TemplateArguments(args)); return(arguments); }
private async Task <(string body, string fileName)> PrintImpl(AbstractPrintingTemplate template, PrintArguments args, CancellationToken cancellation) { // (1) The templates var nameP = new TemplatePlanLeaf(template.DownloadName, TemplateLanguage.Text); var bodyP = new TemplatePlanLeaf(template.Body, TemplateLanguage.Html); TemplatePlan plan = new TemplatePlanTuple(nameP, bodyP); if (!string.IsNullOrWhiteSpace(template.Context)) { plan = new TemplatePlanDefine("$", template.Context, plan); } // (2) Functions + Variables var globalFunctions = new Dictionary <string, EvaluationFunction>(); var localFunctions = new Dictionary <string, EvaluationFunction>(); var globalVariables = new Dictionary <string, EvaluationVariable>(); var localVariables = BaseUtil.CustomLocalVariables(args, template.Parameters?.Select(e => e.Key)); await FactBehavior.SetPrintingFunctions(localFunctions, globalFunctions, cancellation); await FactBehavior.SetPrintingVariables(localVariables, globalVariables, cancellation); // (3) Generate output CultureInfo culture = GetCulture(args.Culture); var genArgs = new TemplateArguments(globalFunctions, globalVariables, localFunctions, localVariables, culture: culture); await _templateService.GenerateFromPlan(plan : plan, args : genArgs, cancellation : cancellation); var downloadName = nameP.Outputs[0]; var body = bodyP.Outputs[0]; // Use a default download name if none is provided if (string.IsNullOrWhiteSpace(downloadName)) { downloadName = "File.html"; } if (!downloadName.ToLower().EndsWith(".html")) { downloadName += ".html"; } // Return as a file return(new(body, downloadName)); }
/// <summary> /// Render a template. /// </summary> /// <remarks>Merges the Arguments property with the <c>args</c> parameter and pass those to the template.</remarks> /// <param name="controller">controller name are used as a folder name when looking for the template.</param> /// <param name="method">method are used as filename when looking for the template.</param> /// <param name="args">arguments that should be passed to the template.</param> /// <returns></returns> protected string RenderTemplate(string controller, string method, params object[] args) { try { TemplateArguments args2 = MergeArguments(args); _arguments.Clear(); string result = _templateMgr.Render(controller + "\\" + method + ".*", args2); _errors.Clear(); return(result); } catch (FileNotFoundException err) { throw new NotFoundException("Failed to find template. Details: " + err.Message, err); } catch (InvalidOperationException err) { throw new InternalServerException("Failed to render template. Details: " + err.Message, err); } catch (Fadd.CompilerException err) { throw new TemplateException("Could not compile template '" + controller + "/" + method + "/'", err); } catch (CodeGeneratorException err) { #if DEBUG string error = "Line: " + err.LineNumber + "<br />\r\n" + err.ToString().Replace("\r\n", "<br />\r\n"); throw new InternalServerException(error, err); #else throw new InternalServerException("Failed to compile template.", err); #endif } catch (ArgumentException err) { #if DEBUG throw new InternalServerException( "Failed to render template, reason: " + err.ToString().Replace("\r\n", "<br />\r\n"), err); #else throw new InternalServerException("Failed to render templates", err); #endif } }
public string Execute <T>(Template template, T arguments, out object result) { var code = Run(template); result = null; object executionResult = null; var globals = new TemplateArguments <T>(arguments); var output = ConsoleHelper.CaptureConsoleOutput(() => { var options = ScriptOptions.Default.WithReferences( typeof(System.Console).Assembly, typeof(ConsoleHelper).Assembly ); CSharpScript.EvaluateAsync(code, options, globals) .ContinueWith(s => executionResult = s.Result).Wait(); }); result = executionResult; return(globals.Output.ToString()); }
public void TestNullStringSubmitted() { Assert.Throws(typeof(ArgumentNullException), delegate { _arguments = new TemplateArguments(null, 1); }); }
/// <summary> /// Returns a template-generated text file that is evaluated based on the given <paramref name="templateId"/>. /// The text generation will implicitly contain a variable $ that evaluates to the results of the dynamic query specified in <paramref name="args"/>. /// </summary> public async Task <FileResult> PrintDynamic(int templateId, PrintDynamicArguments args, CancellationToken cancellation) { await Initialize(cancellation); // (1) Preloaded Query var collection = typeof(TEntity).Name; var defId = DefinitionId; // (2) Functions + Variables var globalFunctions = new Dictionary <string, EvaluationFunction>(); var localFunctions = new Dictionary <string, EvaluationFunction>(); var globalVariables = new Dictionary <string, EvaluationVariable>(); var localVariables = new Dictionary <string, EvaluationVariable> { ["$Source"] = new EvaluationVariable($"{collection}/{defId}"), ["$Type"] = new EvaluationVariable(args.Type), ["$Select"] = new EvaluationVariable(args.Select), ["$OrderBy"] = new EvaluationVariable(args.OrderBy), ["$Filter"] = new EvaluationVariable(args.Filter), ["$Having"] = new EvaluationVariable(args.Having), ["$Top"] = new EvaluationVariable(args.Top), ["$Skip"] = new EvaluationVariable(args.Skip) }; await FactBehavior.SetPrintingFunctions(localFunctions, globalFunctions, cancellation); await FactBehavior.SetPrintingVariables(localVariables, globalVariables, cancellation); // (2) The templates var template = await FactBehavior.GetPrintingTemplate(templateId, cancellation); var nameP = new TemplatePlanLeaf(template.DownloadName, TemplateLanguage.Text); var bodyP = new TemplatePlanLeaf(template.Body, TemplateLanguage.Html); var printoutP = new TemplatePlanTuple(nameP, bodyP); TemplatePlan plan; if (string.IsNullOrWhiteSpace(template.Context)) { IReadOnlyList <DynamicRow> data; if (args.Type == "Fact") { var result = await GetFact(new FactArguments { Select = args.Select, Filter = args.Filter, OrderBy = args.OrderBy, Top = args.Top, Skip = args.Skip, CountEntities = false, }, cancellation); data = result?.Data; } else if (args.Type == "Aggregate") { var result = await GetAggregate(new GetAggregateArguments { Select = args.Select, Filter = args.Filter, Having = args.Having, OrderBy = args.OrderBy, Top = args.Top, }, cancellation); data = result?.Data; } else { throw new ServiceException($"Unknown Type '{args.Type}'."); } localVariables.Add("$", new EvaluationVariable(data)); plan = printoutP; } else { plan = new TemplatePlanDefine("$", template.Context, printoutP); } // (4) Culture CultureInfo culture = GetCulture(args.Culture); // Generate the output var genArgs = new TemplateArguments(globalFunctions, globalVariables, localFunctions, localVariables, culture); await _templateService.GenerateFromPlan(plan, genArgs, cancellation); var downloadName = nameP.Outputs[0]; var body = bodyP.Outputs[0]; // Change the body to bytes var bodyBytes = Encoding.UTF8.GetBytes(body); // Use a default download name if none is provided if (string.IsNullOrWhiteSpace(downloadName)) { var meta = await GetMetadata(cancellation); downloadName = meta.PluralDisplay(); } if (!downloadName.ToLower().EndsWith(".html")) { downloadName += ".html"; } // Return as a file return(new FileResult(bodyBytes, downloadName)); }
/// <summary> /// Returns a template-generated text file that is evaluated based on the given <paramref name="templateId"/>. /// The text generation will implicitly contain a variable $ that evaluates to the results of the query specified in <paramref name="args"/>. /// </summary> public async Task <FileResult> PrintEntities(int templateId, PrintEntitiesArguments <TKey> args, CancellationToken cancellation) { await Initialize(cancellation); var collection = typeof(TEntity).Name; var defId = DefinitionId; // (1) The Template Plan var template = await FactBehavior.GetPrintingTemplate(templateId, cancellation); var nameP = new TemplatePlanLeaf(template.DownloadName, TemplateLanguage.Text); var bodyP = new TemplatePlanLeaf(template.Body, TemplateLanguage.Html); var printoutP = new TemplatePlanTuple(nameP, bodyP); TemplatePlan plan; if (string.IsNullOrWhiteSpace(template.Context)) { plan = printoutP; } else { plan = new TemplatePlanDefine("$", template.Context, printoutP); } QueryInfo contextQuery = BaseUtil.EntitiesPreloadedQuery(args, collection, defId); plan = new TemplatePlanDefineQuery("$", contextQuery, plan); // (2) Functions + Variables var globalFunctions = new Dictionary <string, EvaluationFunction>(); var localFunctions = new Dictionary <string, EvaluationFunction>(); var globalVariables = new Dictionary <string, EvaluationVariable>(); var localVariables = BaseUtil.EntitiesLocalVariables(args, collection, defId); await FactBehavior.SetPrintingFunctions(localFunctions, globalFunctions, cancellation); await FactBehavior.SetPrintingVariables(localVariables, globalVariables, cancellation); // (3) Generate the output CultureInfo culture = GetCulture(args.Culture); var genArgs = new TemplateArguments(globalFunctions, globalVariables, localFunctions, localVariables, culture); await _templateService.GenerateFromPlan(plan : plan, args : genArgs, cancellation : cancellation); var downloadName = nameP.Outputs[0]; var body = bodyP.Outputs[0]; // Change the body to bytes var bodyBytes = Encoding.UTF8.GetBytes(body); // Use a default download name if none is provided if (string.IsNullOrWhiteSpace(downloadName)) { var meta = await GetMetadata(cancellation); var titlePlural = meta.PluralDisplay(); if (args.I != null && args.I.Count > 0) { downloadName = $"{titlePlural} ({args.I.Count})"; } else { int from = args.Skip + 1; int to = Math.Max(from, args.Skip + args.Top); downloadName = $"{titlePlural} {from}-{to}"; } } if (!downloadName.ToLower().EndsWith(".html")) { downloadName += ".html"; } // Return as a file return(new FileResult(bodyBytes, downloadName)); }
public void TestNoTypeSubmittedTo() { Assert.Throws(typeof(ArgumentNullException), delegate { _arguments = new TemplateArguments("User", null); }); }
public void TestNonExisting() { _arguments = new TemplateArguments(); Assert.Throws(typeof(ArgumentException), delegate { _arguments.Update("Test", 2); }); }
public void TestNullObject() { _arguments = new TemplateArguments(); Assert.Throws(typeof(ArgumentNullException), delegate { _arguments.Add("Test", null); }); }
/// <summary> /// Returns a template-generated text file that is evaluated based on the given <paramref name="templateId"/>. /// The text generation will implicitly contain a variable $ that evaluates to the entity whose id matches <paramref name="id"/>. /// </summary> public async Task <(byte[] FileBytes, string FileName)> PrintEntity(TKey id, int templateId, PrintEntityByIdArguments args, CancellationToken cancellation) { await Initialize(cancellation); // (1) Collection & DefId var collection = typeof(TEntity).Name; var defId = DefinitionId; // (2) The Template Plan var template = await FactBehavior.GetPrintingTemplate(templateId, cancellation); var nameP = new TemplatePlanLeaf(template.DownloadName, TemplateLanguage.Text); var bodyP = new TemplatePlanLeaf(template.Body, TemplateLanguage.Html); var printoutP = new TemplatePlanTuple(nameP, bodyP); TemplatePlan plan; if (string.IsNullOrWhiteSpace(template.Context)) { plan = printoutP; } else { plan = new TemplatePlanDefine("$", template.Context, printoutP); } QueryInfo contextQuery = BaseUtil.EntityPreloadedQuery(id, args, collection, defId); plan = new TemplatePlanDefineQuery("$", contextQuery, plan); // (3) Functions + Variables var globalFunctions = new Dictionary <string, EvaluationFunction>(); var localFunctions = new Dictionary <string, EvaluationFunction>(); var globalVariables = new Dictionary <string, EvaluationVariable>(); var localVariables = BaseUtil.EntityLocalVariables(id, args, collection, defId); await FactBehavior.SetPrintingFunctions(localFunctions, globalFunctions, cancellation); await FactBehavior.SetPrintingVariables(localVariables, globalVariables, cancellation); // (4) Generate the output CultureInfo culture = GetCulture(args.Culture); var genArgs = new TemplateArguments(globalFunctions, globalVariables, localFunctions, localVariables, culture); await _templateService.GenerateFromPlan(plan, genArgs, cancellation); var downloadName = nameP.Outputs[0]; var body = bodyP.Outputs[0]; // Change the body to bytes var bodyBytes = Encoding.UTF8.GetBytes(body); // Do some sanitization of the downloadName if (string.IsNullOrWhiteSpace(downloadName)) { downloadName = id.ToString(); } if (!downloadName.ToLower().EndsWith(".html")) { downloadName += ".html"; } // Return as a file return(bodyBytes, downloadName); }
public void TestWrongTypeSubmitted() { _arguments = new TemplateArguments(); Assert.Throws(typeof(ArgumentException), delegate { _arguments.Add("TestString", 4, typeof(float)); }); }