public async Task TestCompileAndRun_DynamicModel_ListsAsync() { RazorEngine razorEngine = new RazorEngine(); var model = new { Items = new[] { new { Key = "K1" }, new { Key = "K2" } } }; var template = await razorEngine.CompileAsync(@" @foreach (var item in Model.Items) { <div>@item.Key</div> } "); string actual = await template.RunAsync(model); string expected = @" <div>K1</div> <div>K2</div> "; Assert.AreEqual(expected, actual); }
public async Task TestCompileAndRun_LinqAsync() { RazorEngine razorEngine = new RazorEngine(); IRazorEngineCompiledTemplate <TestTemplate2> template = await razorEngine.CompileAsync <TestTemplate2>( @" @foreach (var item in Model.Numbers.OrderByDescending(x => x)) { <p>@item</p> } "); string expected = @" <p>3</p> <p>2</p> <p>1</p> "; string actual = await template.RunAsync(instance => { instance.Initialize(new TestModel { Numbers = new[] { 2, 1, 3 } }); }); Assert.AreEqual(expected, actual); }
public async Task TestCompileAndRun_MetadataReference() { string greetingClass = @" namespace TestAssembly { public static class Greeting { public static string GetGreeting(string name) { return ""Hello, "" + name + ""!""; } } } "; // This needs to be done in the builder to have access to all of the assemblies added through // the various AddAssemblyReference options CSharpCompilation compilation = CSharpCompilation.Create( "TestAssembly", new[] { CSharpSyntaxTree.ParseText(greetingClass) }, GetMetadataReferences(), new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary) ); MemoryStream memoryStream = new MemoryStream(); EmitResult emitResult = compilation.Emit(memoryStream); if (!emitResult.Success) { Assert.Fail("Unable to compile test assembly"); } memoryStream.Position = 0; // Add an assembly resolver so the assembly can be found AppDomain.CurrentDomain.AssemblyResolve += (sender, eventArgs) => new AssemblyName(eventArgs.Name ?? string.Empty).Name == "TestAssembly" ? Assembly.Load(memoryStream.ToArray()) : null; RazorEngine razorEngine = new RazorEngine(); IRazorEngineCompiledTemplate template = await razorEngine.CompileAsync(@" @using TestAssembly <p>@Greeting.GetGreeting(""Name"")</p> ", builder => { builder.AddMetadataReference(MetadataReference.CreateFromStream(memoryStream)); }); string expected = @" <p>Hello, Name!</p> "; string actual = await template.RunAsync(); Assert.AreEqual(expected, actual); }
public async Task TestCompileAndRun_NullModelAsync() { RazorEngine razorEngine = new RazorEngine(); var template = await razorEngine.CompileAsync("Name: @Model"); string actual = await template.RunAsync(null); Assert.AreEqual("Name: ", actual); }
public async Task TestCompileAndRun_DynamicModel_PlainAsync() { RazorEngine razorEngine = new RazorEngine(); IRazorEngineCompiledTemplate template = await razorEngine.CompileAsync("Hello @Model.Name"); string actual = await template.RunAsync(new { Name = "Alex" }); Assert.AreEqual("Hello Alex", actual); }
public async Task TestCompileAndRun_HtmlAttributeAsync() { RazorEngine razorEngine = new RazorEngine(); IRazorEngineCompiledTemplate template = await razorEngine.CompileAsync("<div title=\"@Model.Name\">Hello</div>"); string actual = await template.RunAsync(new { Name = "Alex" }); Assert.AreEqual("<div title=\"Alex\">Hello</div>", actual); }
public async Task TestCompileAndRun_HtmlLiteralAsync() { RazorEngine razorEngine = new RazorEngine(); IRazorEngineCompiledTemplate template = await razorEngine.CompileAsync("<h1>Hello @Model.Name</h1>"); string actual = await template.RunAsync(new { Name = "Alex" }); Assert.AreEqual("<h1>Hello Alex</h1>", actual); }
public async Task TestCompileAndRun_InAttributeVariablesAsync() { RazorEngine razorEngine = new RazorEngine(); IRazorEngineCompiledTemplate template = await razorEngine.CompileAsync("<div class=\"circle\" style=\"background-color: hsla(@Model.Colour, 70%, 80%,1);\">"); string actual = await template.RunAsync(new { Colour = 88 }); Assert.AreEqual("<div class=\"circle\" style=\"background-color: hsla(88, 70%, 80%,1);\">", actual); }
public async Task TestCompileAndRun_NullNestedObjectAsync() { RazorEngine razorEngine = new RazorEngine(); var template = await razorEngine.CompileAsync("Name: @Model.user"); string actual = await template.RunAsync(new { user = (object)null }); Assert.AreEqual("Name: ", actual); }
public async Task TestCompileAndRun_TypedModel1Async() { RazorEngine razorEngine = new RazorEngine(); IRazorEngineCompiledTemplate <TestTemplate1> template = await razorEngine.CompileAsync <TestTemplate1>("Hello @A @B @(A + B) @C @Decorator(\"777\")"); string actual = await template.RunAsync(instance => { instance.A = 1; instance.B = 2; instance.C = "Alex"; }); Assert.AreEqual("Hello 1 2 3 Alex -=777=-", actual); }
public async Task TestCompileAndRun_TypedModel2Async() { RazorEngine razorEngine = new RazorEngine(); IRazorEngineCompiledTemplate <TestTemplate2> template = await razorEngine.CompileAsync <TestTemplate2>("Hello @Model.Decorator(Model.C)"); string actual = await template.RunAsync(instance => { instance.Initialize(new TestModel { C = "Alex" }); }); Assert.AreEqual("Hello -=Alex=-", actual); }
public async Task TestSaveToFileAsync() { RazorEngine razorEngine = new RazorEngine(); IRazorEngineCompiledTemplate initialTemplate = await razorEngine.CompileAsync("Hello @Model.Name"); await initialTemplate.SaveToFileAsync("testTemplate.dll"); IRazorEngineCompiledTemplate loadedTemplate = await RazorEngineCompiledTemplate.LoadFromFileAsync("testTemplate.dll"); string initialTemplateResult = await initialTemplate.RunAsync(new { Name = "Alex" }); string loadedTemplateResult = await loadedTemplate.RunAsync(new { Name = "Alex" }); Assert.AreEqual(initialTemplateResult, loadedTemplateResult); }
public async Task TestSaveToStreamAsync() { RazorEngine razorEngine = new RazorEngine(); IRazorEngineCompiledTemplate initialTemplate = await razorEngine.CompileAsync("Hello @Model.Name"); MemoryStream memoryStream = new MemoryStream(); await initialTemplate.SaveToStreamAsync(memoryStream); memoryStream.Position = 0; IRazorEngineCompiledTemplate loadedTemplate = await RazorEngineCompiledTemplate.LoadFromStreamAsync(memoryStream); string initialTemplateResult = await initialTemplate.RunAsync(new { Name = "Alex" }); string loadedTemplateResult = await loadedTemplate.RunAsync(new { Name = "Alex" }); Assert.AreEqual(initialTemplateResult, loadedTemplateResult); }
public async Task TestCompileAndRun_DynamicModel_NestedAsync() { RazorEngine razorEngine = new RazorEngine(); var model = new { Name = "Alex", Membership = new { Level = "Gold" } }; var template = await razorEngine.CompileAsync("Name: @Model.Name, Membership: @Model.Membership.Level"); string actual = await template.RunAsync(model); Assert.AreEqual("Name: Alex, Membership: Gold", actual); }
/// <summary> /// 构建配置程序集中所有类型 /// </summary> /// <param name="path"></param> /// <returns></returns> async Task <string> BuildClass(string path) { if (_options.Assemblies == null || !_options.Assemblies.Any()) { return("未配置程序集"); } IRazorEngine razorEngine = new RazorEngine(); string template = GetResourceTemplate("class.cshtml"); IRazorEngineCompiledTemplate <RazorEngineTemplateBase <List <ClassModel> > > compile = await razorEngine.CompileAsync <RazorEngineTemplateBase <List <ClassModel> > >(template); string html = compile.Run(modelBuilder => { List <ClassModel> models = new List <ClassModel>(); foreach (var assembly in _options.Assemblies) { var types = assembly.ExportedTypes.Where(x => !x.IsValueType); // 公开类型,且非值类型 models.Add(new ClassModel { Path = path, AssemblyName = assembly.GetName().Name, TypeCount = types.Count(), Types = types.ToArray() }); } modelBuilder.Model = models; }); return(html); }
/// <summary> /// 构建代码信息 /// </summary> /// <param name="assembly"></param> /// <param name="type"></param> /// <returns></returns> async Task <string> BuildInfo(Assembly assembly, Type type) { IRazorEngine razorEngine = new RazorEngine(); string template = GetResourceTemplate("info.cshtml"); IRazorEngineCompiledTemplate <RazorEngineTemplateBase <CodeInfoModel> > compile = await razorEngine.CompileAsync <RazorEngineTemplateBase <CodeInfoModel> >(template); string html = compile.Run(modelBuilder => { CodeInfoModel model = new CodeInfoModel(); PropertyInfo[] properties = type.GetProperties().Where(x => x.CanWrite).ToArray(); // 当前类型公开定义的可写属性数组 model.AssemblyName = assembly.GetName().Name; model.ClassName = type.Name; model.Namespace = type.Namespace; model.PropertyNames = properties.Select(x => x.Name).ToArray(); try { model.Json = JsonSerializer.Serialize(Activator.CreateInstance(type)); } catch { // ignore /*****忽略json序列化失败*****/ } modelBuilder.Model = model; }); return(html); }
static async Task Main(string[] args) { RazorEngine razorEngine = new RazorEngine(); //Warm up CSharpCompilation, ensure fairness when doing a Stopwatch comparison var mocktemplate = await razorEngine.CompileAsync <RazorEngineCorePageModel>(""); var runs = 10; var compileResults = TimeSpan.Zero; var precompileResults = TimeSpan.Zero; for (int i = 0; i < runs; i++) { var sw = new Stopwatch(); sw.Start(); var template = await razorEngine.CompileAsync <RazorEngineCorePageModel>(SampleApp.Content.SampleContent); var model = new { Name = "Alexander", Attribute = "<encode me>", Items = new List <string>() { "item 1", "item 2" } }; await template.RunAsync(model : model); sw.Stop(); compileResults = compileResults.Add(sw.Elapsed); Console.WriteLine($"Compile :: {sw.Elapsed}"); sw.Restart(); var resourceTemplate = await PrecompiledTemplate.LoadAsync("sample"); await resourceTemplate.RunAsync(model : model); sw.Stop(); precompileResults = precompileResults.Add(sw.Elapsed); Console.WriteLine($"Precompile :: {sw.Elapsed}"); } Console.WriteLine($"Results of {runs} runs |"); Console.WriteLine($"\tCompile | total: {compileResults}; average: {TimeSpan.FromMilliseconds(compileResults.TotalMilliseconds / runs)}"); Console.WriteLine($"\tPrecompile | total: {precompileResults}; average: {TimeSpan.FromMilliseconds(precompileResults.TotalMilliseconds / runs)}"); Console.ReadKey(); }
public Task TestCompileAsync() { RazorEngine razorEngine = new RazorEngine(); return(razorEngine.CompileAsync("Hello @Model.Name")); }