Ejemplo n.º 1
0
        public async Task <TemplateResult> RunTemplateAsync(RazorTemplateBase template, dynamic templateModel)
        {
            string result = String.Empty;

            if (template != null)
            {
                template.Model = templateModel;
                //ToDo: If there are errors executing the code, they are missed here.
                try
                {
                    result = await template.ExecuteTemplate();
                }
                catch (Exception ex)
                {
                    return(new TemplateResult()
                    {
                        GeneratedText = "",
                        ProcessingException = new TemplateProcessingException(new string[] { ex.ToString() }, "")
                    });
                }
            }

            return(new TemplateResult()
            {
                GeneratedText = result,
                ProcessingException = null
            });
        }
Ejemplo n.º 2
0
 public override RazorTemplateBase UseParentLayout(RazorTemplateBase child)
 {
     return(new EnumStringTemplate()
     {
         EnumName = this.EnumName,
         Enums = this.Enums,
         ChildTemplate = child
     });
 }
 public override RazorTemplateBase UseParentLayout(RazorTemplateBase child)
 {
     return(new AstSubclassTemplate()
     {
         ClassName = this.ClassName,
         Superclass = this.Superclass,
         TermName = this.TermName,
         TermMeta = this.TermMeta,
         AllTerms = this.AllTerms,
         ChildTemplate = child
     });
 }
Ejemplo n.º 4
0
        public static void Go()
        {
            var reports = new RazorTemplateBase[] {
                new Report1 {
                    Packages = new Package[] {
                        new Package {
                            Origin = "Cracow", Destination = "Dululu", Cost = 15.0m
                        },
                        new Package {
                            Origin = "Emerald", Destination = "Dingo", Cost = 15.0m
                        },
                        new Package {
                            Origin = "Duaringa", Destination = "Gladstone", Cost = 12.5m
                        },
                        new Package {
                            Origin = "Dingo", Destination = "Dingo", Cost = 16.0m
                        },
                        new Package {
                            Origin = "Dululu", Destination = "Duaringa", Cost = 12.5m
                        },
                        new Package {
                            Origin = "Gladstone", Destination = "Dululu", Cost = 8.5m
                        }
                    }
                },
                new StaticTest1(),
                new CustomPageSetupTest(),
                new TableBackgroundTest(),
                new LeftPaddedTable(),
                new crispin_razor_example(),
                new test_with_bom_report(),
                new RightAlignedNestedTable(),
                new system_dot_web_tests(),
                new Images(),
            };
            var converters = new IReportConverter[] {
                new CsvReportConverter(),
                new HtmlReportConverter(),
                new PdfReportConverter()
            };

            var reportIndex = GetReportIndex(reports);
            var xrpt        = reports[reportIndex - 1].TransformText();

            Console.WriteLine("Generated report:");
            Console.WriteLine(xrpt);
            WriteToFile(xrpt, "xrpt.txt");

            int converterIndex = GetConverterIndex(converters);
            int convertAction  = GetConvertAction();
            var converter      = converters.ToList()[converterIndex - 1];

            if (convertAction == 1)
            {
                var convertedReport = converter.ConvertToString(xrpt);
                Console.WriteLine("Converted report:");
                Console.WriteLine(convertedReport);
                WriteToFile(convertedReport, "conv.txt");
            }
            else if (convertAction == 2 || convertAction == 3)
            {
                var convertedReport = converter.ConvertToBuffer(xrpt, "TEST");
                Console.WriteLine("Converted to buffer.");
                var dest = convertAction == 2 ? "conv.bin" : "conv.pdf";
                WriteToFile(convertedReport, dest);
            }

            Console.WriteLine("Press any key to continue...");
            Console.ReadKey();
        }
Ejemplo n.º 5
0
 public static string Render <T>(RazorTemplateBase template, T model)
 {
     ((dynamic)template).Model = model;
     return(template.TransformText());
 }
Ejemplo n.º 6
0
 public TemplateHelpers(DocTopic topic, RazorTemplateBase template)
 {
     Topic    = topic;
     Project  = Topic?.Project;
     Template = template as RazorTemplateFolderHost <DocTopic>;
 }
Ejemplo n.º 7
0
 public virtual RazorTemplateBase UseParentLayout(RazorTemplateBase child)
 {
     return(null);
 }
 public static string Render <T>(RazorTemplateBase template, T model, GeneratorConfig config)
 {
     ((dynamic)template).Model  = model;
     ((dynamic)template).Config = config;
     return(template.TransformText());
 }
        public void RawRazorTest()
        {
            string generatedNamespace = "__RazorHosting";
            string generatedClassname = "RazorTest";

            Type baseClassType = typeof(RazorTemplateBase);

            // Create an instance of the Razor Engine for a given
            // template type
            RazorEngineHost host = new RazorEngineHost(new CSharpRazorCodeLanguage());

            host.DefaultBaseClass = baseClassType.FullName;

            host.DefaultClassName = generatedClassname;
            host.DefaultNamespace = generatedNamespace;

            host.NamespaceImports.Add("System");
            host.NamespaceImports.Add("System.Text");
            host.NamespaceImports.Add("System.Collections.Generic");
            host.NamespaceImports.Add("System.Linq");
            host.NamespaceImports.Add("System.IO");

            // add the library namespace
            host.NamespaceImports.Add("Westwind.RazorHosting");

            var engine = new RazorTemplateEngine(host);

            // Create and compile Code from the template
            var reader = new StringReader(Templates.BasicTemplateStringWithPersonModel);

            // Generate the template class as CodeDom from reader
            GeneratorResults razorResults = engine.GenerateCode(reader);

            // Create code from the codeDom and compile
            CSharpCodeProvider   codeProvider = new CSharpCodeProvider();
            CodeGeneratorOptions options      = new CodeGeneratorOptions();

            // Capture Code Generated as a string for error info
            // and debugging
            string LastGeneratedCode = null;

            using (StringWriter writer = new StringWriter())
            {
                codeProvider.GenerateCodeFromCompileUnit(razorResults.GeneratedCode, writer, options);
                LastGeneratedCode = writer.ToString();
            }

            CompilerParameters compilerParameters = new CompilerParameters();

            // Always add Standard Assembly References
            compilerParameters.ReferencedAssemblies.Add("System.dll");
            compilerParameters.ReferencedAssemblies.Add("System.Core.dll");
            compilerParameters.ReferencedAssemblies.Add("Microsoft.CSharp.dll");   // dynamic support!
            compilerParameters.ReferencedAssemblies.Add("System.Web.Razor.dll");

            // Must add Razorhosting or whatever assembly holds the template
            // engine can do this automatically but here we have to do manually
            compilerParameters.ReferencedAssemblies.Add("Westwind.RazorHosting.dll");

            // Add this assembly so model can be found
            var razorAssembly = Assembly.GetExecutingAssembly().Location;

            compilerParameters.ReferencedAssemblies.Add(razorAssembly);

            compilerParameters.GenerateInMemory = true;

            CompilerResults compilerResults = codeProvider.CompileAssemblyFromDom(compilerParameters, razorResults.GeneratedCode);

            if (compilerResults.Errors.HasErrors)
            {
                var compileErrors = new StringBuilder();
                foreach (System.CodeDom.Compiler.CompilerError compileError in compilerResults.Errors)
                {
                    compileErrors.Append(String.Format("Line: {0}\t Col: {1}\t Error: {2}", compileError.Line, compileError.Column, compileError.ErrorText));
                }

                Assert.Fail(compileErrors.ToString());
            }

            string name = compilerResults.CompiledAssembly.FullName;

            // Instantiate the template
            Assembly generatedAssembly = compilerResults.CompiledAssembly;

            if (generatedAssembly == null)
            {
                Assert.Fail("Assembly generation failed.");
            }

            // find the generated type to instantiate
            Type type  = null;
            var  types = generatedAssembly.GetTypes() as Type[];

            // there's only 1 per razor assembly
            if (types.Length > 0)
            {
                type = types[0];
            }

            object            inst     = Activator.CreateInstance(type);
            RazorTemplateBase instance = inst as RazorTemplateBase;

            if (instance == null)
            {
                Assert.Fail("Couldn't activate template: " + type.FullName);
                return;
            }

            // Configure the instance
            StringWriter outputWriter = new StringWriter();

            // Template contains a Response object that writes to the writer
            instance.Response.SetTextWriter(outputWriter);

            Person person = new Person()
            {
                Name    = "Rick Strahl",
                Company = "West Wind",
                Entered = DateTime.Now,
                Address = new Address()
                {
                    Street = "50 HoHaia",
                    City   = "Paia"
                }
            };

            // Configure the instance with model and
            // other configuration data
            // instance.Model = person;
            instance.InitializeTemplate(person);

            // Execute the template  and clean up
            instance.Execute();

            // template can set its ResultData property to pass data
            // back to the caller
            dynamic resultData = instance.ResultData;

            instance.Dispose();

            // read the result from the writer passed in
            var result = outputWriter.ToString();

            Console.WriteLine(result);
            Console.WriteLine("\r\nResultData: " + resultData.ToString());
        }