public override bool Execute()
        {
            /*TaskEventArgs taskEvent;
             * taskEvent = new TaskEventArgs(BuildEventCategory.Custom,
             *  BuildEventImportance.High, "Important Message",
             *  "SimpleTask");*/
            ;

            Log.LogError("messageResource1", "1", "2", "3");
            Log.LogError("messageResource2");
            Log.LogError(BuildEngine.ProjectFileOfTaskNode);

            var outputFile = Path.Combine(this.TargetDir, this.TargetFileName);

            Log.LogError(outputFile);

            RazorEngine razorEngine = new RazorEngine();

            var ass  = Assembly.LoadFile(outputFile);
            var ass1 = typeof(PrecompiledTemplate).Assembly;

            Log.LogError(ass1.Location);
            Assembly.Load(ass1.GetName());

            //ass.GetCustomAttributes<PrecompiledTemplate>();


            var template = razorEngine.Compile <RazorEngineCorePageModel>("");

            return(true);
        }
        public string RenderHtmlTemplate <T>(ReportViewModel <T> reportViewModel, string type = "DEFAULT")
        {
            string path = null;

            if (type == "DEFAULT")
            {
                path = string.Format("{0}\\templates\\default-report.cshtml", Directory.GetCurrentDirectory());
            }
            else
            {
                path = string.Format("{0}\\templates\\single-order-report.cshtml", Directory.GetCurrentDirectory());
            }
            string       razorHtml   = System.Text.Encoding.UTF8.GetString(File.ReadAllBytes(path));
            IRazorEngine razorEngine = new RazorEngine();
            IRazorEngineCompiledTemplate template = razorEngine.Compile(razorHtml, builder =>
            {
                builder.AddAssemblyReference(typeof(Utility));
                builder.AddAssemblyReference(typeof(Stat));
                builder.AddAssemblyReference(typeof(ReportViewModel <T>));
                builder.AddAssemblyReference(typeof(System.DateTime));
            });
            string generatedHtml = template.Run(reportViewModel);

            return(generatedHtml);
        }
        public void TestCompileAndRun_Linq()
        {
            RazorEngine razorEngine = new RazorEngine();
            IRazorEngineCompiledTemplate <TestTemplate2> template = razorEngine.Compile <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   = template.Run(instance =>
            {
                instance.Initialize(new TestModel
                {
                    Numbers = new[] { 2, 1, 3 }
                });
            });

            Assert.AreEqual(expected, actual);
        }
        protected virtual RazorEngineCompiledTemplate GetCompiledTemplate(ITemplateProvider templateProvider, TemplateData data)
        {
            string template    = templateProvider.ProvideTemplate(data.Language);
            var    razorEngine = new RazorEngine();

            return(razorEngine.Compile(template));
        }
        public void TestCompileAndRun_DynamicModel_Lists()
        {
            RazorEngine razorEngine = new RazorEngine();

            var model = new
            {
                Items = new[]
                {
                    new
                    {
                        Key = "K1"
                    },
                    new
                    {
                        Key = "K2"
                    }
                }
            };

            var template = razorEngine.Compile(@"
@foreach (var item in Model.Items)
{
<div>@item.Key</div>
}
");

            string actual   = template.Run(model);
            string expected = @"
<div>K1</div>
<div>K2</div>
";

            Assert.AreEqual(expected, actual);
        }
Beispiel #6
0
        public void TestCompileAndRun_DynamicModelLinq()
        {
            RazorEngine razorEngine = new RazorEngine();
            IRazorEngineCompiledTemplate template = razorEngine.Compile(
                @"
@foreach (var item in ((IEnumerable<object>)Model.Numbers).OrderByDescending(x => x))
{
    <p>@item</p>
}
");
            string expected = @"
    <p>3</p>
    <p>2</p>
    <p>1</p>
";
            string actual   = template.Run(new
            {
                Numbers = new List <object>()
                {
                    2, 1, 3
                }
            });

            Assert.AreEqual(expected, actual);
        }
Beispiel #7
0
        public void TestCompileAndRun_DynamicModel_Dictionary1()
        {
            RazorEngine razorEngine = new RazorEngine();

            var model = new
            {
                Dictionary = new Dictionary <string, object>()
                {
                    { "K1", "V1" },
                    { "K2", "V2" },
                }
            };

            var template = razorEngine.Compile(@"
@foreach (var key in Model.Dictionary.Keys)
{
<div>@key</div>
}
<div>@Model.Dictionary[""K1""]</div>
<div>@Model.Dictionary[""K2""]</div>
");

            string actual   = template.Run(model);
            string expected = @"
<div>K1</div>
<div>K2</div>
<div>V1</div>
<div>V2</div>
";

            Assert.AreEqual(expected, actual);
        }
Beispiel #8
0
        public void TestCompileAndRun_DynamicModel_Dictionary2()
        {
            RazorEngine razorEngine = new RazorEngine();

            var model = new
            {
                Dictionary = new Dictionary <string, object>()
                {
                    { "K1", new { x = 1 } },
                    { "K2", new { x = 2 } },
                }
            };

            var template = razorEngine.Compile(@"
<div>@Model.Dictionary[""K1""].x</div>
<div>@Model.Dictionary[""K2""].x</div>
");

            string actual   = template.Run(model);
            string expected = @"
<div>1</div>
<div>2</div>
";

            Assert.AreEqual(expected, actual);
        }
Beispiel #9
0
        private static string AddLayoutToPage(ApplicationDbContext context, RenderedTemplate renderedTemplate, List <string> assemblies, Page page)
        {
            IncludeRazorEngine engine      = new IncludeRazorEngine(assemblies);
            RazorEngine        razorEngine = new RazorEngine();

            RazorEngineCompiledTemplate <LayoutTemplateBase> compiledLayout =
                razorEngine.Compile <LayoutTemplateBase>(context.Layouts.Find(renderedTemplate.Layout).Contents,
                                                         engine.GetOptionsBuilder);

            string renderCss = page.CssContents;
            string renderJs  = page.JsContents;

            foreach (var component in renderedTemplate.ComponentDependencies.Distinct().Select(componentDependency =>
                                                                                               context.Components.Find(componentDependency)))
            {
                renderCss += "\n" + component.CssContents;
                renderJs  += "\n" + component.JsContents;
            }

            return(engine.RenderLayout(compiledLayout, new
            {
                RenderBody = renderedTemplate.HtmlContents,
                RenderCss = renderCss,
                // InnerJsContents already has a \n at the beginning of it
                RenderJs = renderJs + renderedTemplate.InnerJsContents,
                ViewData = renderedTemplate.ViewData
            }));
        }
Beispiel #10
0
        private static string RenderPage(ApplicationDbContext context,
                                         Dictionary <string, RazorEngineCompiledTemplate <IncludeTemplateBase> > compiledIncludes, List <string> assemblies, Page page)
        {
            IncludeRazorEngine engine      = new IncludeRazorEngine(assemblies);
            RazorEngine        razorEngine = new RazorEngine();

            RazorEngineCompiledTemplate <IncludeTemplateBase> compiledTemplate =
                razorEngine.Compile <IncludeTemplateBase>(page.HtmlContents, engine.GetOptionsBuilder);

            RenderedTemplate renderedTemplate = engine.Render(compiledTemplate, compiledIncludes, new { });

            // Remove any inline script elements and store them separately
            List <string> inlineScripts = new List <string>();
            XmlDocument   doc           = new XmlDocument();

            // Wrap the page in a PageContainer so that including text outside of any element doesn't throw an error
            doc.AppendChild(doc.CreateElement("PageContainer"));
            doc.GetElementsByTagName("PageContainer")[0].InnerXml = renderedTemplate.HtmlContents;
            while (doc.GetElementsByTagName("script").Count > 0)
            {
                var node = doc.GetElementsByTagName("script")[0];
                inlineScripts.Add(node.InnerText);
                node.ParentNode.RemoveChild(node);
            }

            renderedTemplate.HtmlContents    = doc.GetElementsByTagName("PageContainer")[0].InnerXml;
            renderedTemplate.InnerJsContents =
                inlineScripts.Aggregate(string.Empty, (current, script) => current + "\n" + script);

            return(renderedTemplate.Layout is null ? renderedTemplate.HtmlContents : AddLayoutToPage(context, renderedTemplate, assemblies, page));
        }
        public void TestCompileAndRun_TestFunction()
        {
            RazorEngine razorEngine = new RazorEngine();

            var template = razorEngine.Compile(@"
@<area>
    @{ RecursionTest(3); }
</area>

@{

void RecursionTest(int level)
{
	if (level <= 0)
	{
		return;
	}
		
    <div>LEVEL: @level</div>
	@{ RecursionTest(level - 1); }
}

}");

            string actual   = template.Run();
            string expected = @"
<area>
    <div>LEVEL: 3</div>
    <div>LEVEL: 2</div>
    <div>LEVEL: 1</div>
</area>
";

            Assert.AreEqual(expected.Trim(), actual.Trim());
        }
Beispiel #12
0
        public void Write(IEnumerable <IRow> rows)
        {
            var l = new Cfg.Net.Loggers.MemoryLogger();

            _output.Debug(() => $"Loading template {_output.Connection.Template}");
            var template = _templateReader.Read(_output.Connection.Template, new Dictionary <string, string>(), l);

            template = Regex.Replace(template, "^@model .+$", string.Empty, RegexOptions.Multiline);

            if (l.Errors().Any())
            {
                foreach (var error in l.Errors())
                {
                    _output.Error(error);
                }
            }
            else
            {
                var engine = new RazorEngine();
                IRazorEngineCompiledTemplate <RazorEngineTemplateBase <RazorModel> > compiledTemplate;

                try {
                    compiledTemplate = engine.Compile <RazorEngineTemplateBase <RazorModel> >(template, builder => {
                        builder.AddAssemblyReference(typeof(Configuration.Process));
                        builder.AddAssemblyReference(typeof(Cfg.Net.CfgNode));
                        builder.AddAssemblyReferenceByName("System.Collections");
                    });
                    // doesn't appear to be a way to stream output yet (in this library), so will just write to string and then file
                    var output = compiledTemplate.Run(instance => {
                        instance.Model = new RazorModel()
                        {
                            Process = _output.Process,
                            Entity  = _output.Entity,
                            Rows    = rows
                        };
                    });
                    File.WriteAllText(_output.Connection.File, output);
                } catch (RazorEngineCompilationException ex) {
                    foreach (var error in ex.Errors)
                    {
                        var line = error.Location.GetLineSpan();
                        _output.Error($"C# error on line {line.StartLinePosition.Line}, column {line.StartLinePosition.Character}.");
                        _output.Error(error.GetMessage());
                    }
                    _output.Error(ex.Message.Replace("{", "{{").Replace("}", "}}"));
                    Utility.CodeToError(_output, template);
                } catch (System.AggregateException ex) {
                    _output.Error(ex.Message.Replace("{", "{{").Replace("}", "}}"));
                    foreach (var error in ex.InnerExceptions)
                    {
                        _output.Error(error.Message.Replace("{", "{{").Replace("}", "}}"));
                    }
                    Utility.CodeToError(_output, template);
                }

                // the template must set Model.Entity.Inserts
            }
        }
Beispiel #13
0
        public Dictionary <string, RazorEngineCompiledTemplate <IncludeTemplateBase> > GetCompiledIncludes(
            IDictionary <string, string> includes)
        {
            RazorEngine razorEngine = new RazorEngine();

            return(includes.ToDictionary(
                       k => k.Key,
                       v => razorEngine.Compile <IncludeTemplateBase>(v.Value, GetOptionsBuilder)));
        }
Beispiel #14
0
        private IRazorEngineCompiledTemplate <RazorEngineTemplateBase <T> > LoadTemplate()
        {
            return(_Engine.Compile <RazorEngineTemplateBase <T> >(TemplateProvider.GetResourceAsString(), (builder) =>
            {
                builder.AddAssemblyReference(Assembly.GetCallingAssembly());
                builder.AddAssemblyReference(Assembly.GetExecutingAssembly());

                builder.AddUsing("GenHTTP.Modules.Razor");
            }));
        }
        public void TestCompileAndRun_NullModel()
        {
            RazorEngine razorEngine = new RazorEngine();

            var template = razorEngine.Compile("Name: @Model");

            string actual = template.Run(null);

            Assert.AreEqual("Name: ", actual);
        }
Beispiel #16
0
        public static void Init()
        {
            var          baseDir     = AppDomain.CurrentDomain.BaseDirectory;
            string       templateDir = Path.Combine(baseDir, "CodeGenerator/Templates");
            var          files       = Directory.GetFiles(templateDir, "*", SearchOption.AllDirectories);
            IRazorEngine razorEngine = new RazorEngine();

            foreach (var item in files)
            {
                IRazorEngineCompiledTemplate template = razorEngine.Compile(File.ReadAllText(item));
                TemplateCache.TryAdd(Path.GetFileNameWithoutExtension(item), template);
            }
            var filePages = Directory.GetFiles(Path.Combine(baseDir, "CodeGenerator/Pages"), "*", SearchOption.AllDirectories);

            foreach (var item in filePages)
            {
                IRazorEngineCompiledTemplate template = razorEngine.Compile(File.ReadAllText(item));
                PagetemplateCache.TryAdd(Path.GetFileNameWithoutExtension(item), template);
            }
        }
        public void TestSettingTemplateNamespaceT()
        {
            RazorEngine razorEngine = new RazorEngine();

            var initialTemplate = razorEngine.Compile <TestTemplate2>("@{ var message = \"OK\"; }@message",
                                                                      builder => { builder.Options.TemplateNamespace = "Test.Namespace"; });

            var result = initialTemplate.Run(a => { });

            Assert.AreEqual("OK", result);
        }
        public void TestCompileAndRun_HtmlAttribute()
        {
            RazorEngine razorEngine = new RazorEngine();
            IRazorEngineCompiledTemplate template = razorEngine.Compile("<div title=\"@Model.Name\">Hello</div>");

            string actual = template.Run(new
            {
                Name = "Alex"
            });

            Assert.AreEqual("<div title=\"Alex\">Hello</div>", actual);
        }
        public void TestCompileAndRun_HtmlLiteral()
        {
            RazorEngine razorEngine = new RazorEngine();
            IRazorEngineCompiledTemplate template = razorEngine.Compile("<h1>Hello @Model.Name</h1>");

            string actual = template.Run(new
            {
                Name = "Alex"
            });

            Assert.AreEqual("<h1>Hello Alex</h1>", actual);
        }
        public void TestCompileAndRun_DynamicModel_Plain()
        {
            RazorEngine razorEngine = new RazorEngine();
            IRazorEngineCompiledTemplate template = razorEngine.Compile("Hello @Model.Name");

            string actual = template.Run(new
            {
                Name = "Alex"
            });

            Assert.AreEqual("Hello Alex", actual);
        }
        /// <summary>
        /// implementing operate on rows (instead of row) to allow loading of external (file based) templates first
        /// </summary>
        /// <param name="rows"></param>
        /// <returns></returns>
        public override IEnumerable <IRow> Operate(IEnumerable <IRow> rows)
        {
            if (!Run)
            {
                yield break;
            }

            var key = string.Join(':', Context.Process.Id, Context.Entity.Alias, Context.Field.Alias, Context.Operation.Method, Context.Operation.Index);

            if (!_memoryCache.TryGetValue(key, out CachedRazorTransform transform))
            {
                transform = new CachedRazorTransform();

                var fileBasedTemplate = Context.Process.Templates.FirstOrDefault(t => t.Name == Context.Operation.Template);

                if (fileBasedTemplate != null)
                {
                    Context.Operation.Template = fileBasedTemplate.Content;
                }

                var input   = MultipleInput();
                var matches = Context.Entity.GetFieldMatches(Context.Operation.Template);
                transform.Input = input.Union(matches).ToArray();

                var engine = new RazorEngine();

                try {
                    transform.Template = engine.Compile(Context.Operation.Template, builder => {
                        builder.AddUsing("System");
                    });

                    // any changes to content item will invalidate cache
                    _memoryCache.Set(key, transform, _signal.GetToken(Common.GetCacheKey(Context.Process.Id)));
                } catch (RazorEngineCompilationException ex) {
                    foreach (var error in ex.Errors)
                    {
                        var line = error.Location.GetLineSpan();
                        Context.Error($"C# error on line {line.StartLinePosition.Line}, column {line.StartLinePosition.Character}.");
                        Context.Error(error.GetMessage());
                    }
                    Context.Error(ex.Message.Replace("{", "{{").Replace("}", "}}"));
                    Utility.CodeToError(Context, Context.Operation.Template);
                    yield break;
                }
            }

            foreach (var row in rows)
            {
                var output = transform.Template.Run(row.ToFriendlyExpandoObject(transform.Input));
                row[Context.Field] = _convert(output);
                yield return(row);
            }
        }
Beispiel #22
0
        public void TestCompileAndRun_InAttributeVariables2()
        {
            RazorEngine razorEngine = new RazorEngine();
            IRazorEngineCompiledTemplate template = razorEngine.Compile("<img src='@(\"test\")'>");

            string actual = template.Run(new
            {
                Colour = 88
            });

            Assert.AreEqual("<img src='test'>", actual);
        }
        public void TestCompileAndRun_InAttributeVariables()
        {
            RazorEngine razorEngine = new RazorEngine();
            IRazorEngineCompiledTemplate template = razorEngine.Compile("<div class=\"circle\" style=\"background-color: hsla(@Model.Colour, 70%,   80%,1);\">");

            string actual = template.Run(new
            {
                Colour = 88
            });

            Assert.AreEqual("<div class=\"circle\" style=\"background-color: hsla(88, 70%,   80%,1);\">", actual);
        }
        public void TestCompileAndRun_NullNestedObject()
        {
            RazorEngine razorEngine = new RazorEngine();

            var template = razorEngine.Compile("Name: @Model.user");

            string actual = template.Run(new
            {
                user = (object)null
            });

            Assert.AreEqual("Name: ", actual);
        }
        public void TestCompileAndRun_TypedModel1()
        {
            RazorEngine razorEngine = new RazorEngine();
            IRazorEngineCompiledTemplate <TestTemplate1> template = razorEngine.Compile <TestTemplate1>("Hello @A @B @(A + B) @C @Decorator(\"777\")");

            string actual = template.Run(instance =>
            {
                instance.A = 1;
                instance.B = 2;
                instance.C = "Alex";
            });

            Assert.AreEqual("Hello 1 2 3 Alex -=777=-", actual);
        }
Beispiel #26
0
        static void Main(string[] args)
        {
            IRazorEngine razorEngine = new RazorEngine();
            IRazorEngineCompiledTemplate template = razorEngine.Compile("Hello @Model.Name");

            string result = template.Run(new
            {
                Name = "Alexander"
            });

            Console.WriteLine(result);

            string curDir = System.Environment.CurrentDirectory;
            string path   = string.Format("{0}{1}{2}{1}{3}"
                                          , curDir
                                          , System.IO.Path.DirectorySeparatorChar
                                          , "template"
                                          , "SqlSugarEntity.txt");
            string content = File.ReadAllText(path);

            template = razorEngine.Compile(content);
            Console.WriteLine(template.Run(new GenerateConfig()));
        }
Beispiel #27
0
        public void TestSaveToFile()
        {
            RazorEngine razorEngine = new RazorEngine();
            RazorEngineCompiledTemplate initialTemplate = razorEngine.Compile("Hello @Model.Name");

            initialTemplate.SaveToFile("testTemplate.dll");

            RazorEngineCompiledTemplate loadedTemplate = RazorEngineCompiledTemplate.LoadFromFile("testTemplate.dll");

            string initialTemplateResult = initialTemplate.Run(new { Name = "Alex" });
            string loadedTemplateResult  = loadedTemplate.Run(new { Name = "Alex" });

            Assert.AreEqual(initialTemplateResult, loadedTemplateResult);
        }
Beispiel #28
0
        void init(DDLConfig.DBType myDBType)
        {
            if (razorEngines.ContainsKey(myDBType.ToString()))
            {
                return;
            }
            lock (this)
            {
                if (razorEngines.ContainsKey(myDBType.ToString()))
                {
                    return;
                }

                string templateRelatePath = string.Empty;
                switch (myDBType)
                {
                case DDLConfig.DBType.MySql:
                    templateRelatePath = templateMysqlRelatePath;
                    break;

                case DDLConfig.DBType.Oracle:
                    templateRelatePath = templateOracleRelatePath;
                    break;

                default:
                    throw new ArgumentNullException(nameof(myDBType));
                }


                string templatePath = Environment.CurrentDirectory + templateRelatePath;
                logger.Info(templatePath);
                string       templateContent = File.ReadAllText(templatePath);
                IRazorEngine razorEngine     = new RazorEngine();
                razorEngines[myDBType.ToString()] = razorEngine;

                IRazorEngineCompiledTemplate <RazorEngineTemplateBase <DDLTable> > template
                    = razorEngine.Compile <RazorEngineTemplateBase <DDLTable> >(templateContent, builder =>
                {
                    //builder.AddAssemblyReferenceByName("System.Security"); // by name
                    //builder.AddAssemblyReference(typeof(System.IO.File)); // by type
                    //builder.AddAssemblyReference(Assembly.Load("source")); // by reference
                    builder.AddAssemblyReferenceByName("System.Collections");
                });

                templates[myDBType.ToString()] = template;


                //IRazorEngineCompiledTemplate template = razorEngine.Compile(templateContent);// "Hello @Model.Name");
            }
        }
Beispiel #29
0
        internal string BuildHtml <T>(string templateText, T model)
        {
            RazorEngine razorEngine = new RazorEngine();

            // yeah, heavy definition
            var template = razorEngine.Compile <RazorEngineTemplateBase <T> >(templateText);

            string result = template.Run(instance =>
            {
                instance.Model = model;
            });

            return(result);
        }
        public void TestCompileAndRun_TypedModel2()
        {
            RazorEngine razorEngine = new RazorEngine();
            IRazorEngineCompiledTemplate <TestTemplate2> template = razorEngine.Compile <TestTemplate2>("Hello @Model.Decorator(Model.C)");

            string actual = template.Run(instance =>
            {
                instance.Initialize(new TestModel
                {
                    C = "Alex"
                });
            });

            Assert.AreEqual("Hello -=Alex=-", actual);
        }