Beispiel #1
0
        private void RunDesignTimeTagHelpersTest(IEnumerable <TagHelperDescriptor> descriptors)
        {
            // Arrange
            var engine = RazorEngine.CreateDesignTime(builder =>
            {
                builder.Features.Add(new ApiSetsIRTestAdapter());
                builder.AddTagHelpers(descriptors);

                // Some of these tests use templates
                builder.AddTargetExtension(new TemplateTargetExtension());

                FunctionsDirective.Register(builder);
                InheritsDirective.Register(builder);
                SectionDirective.Register(builder);
            });

            var document = CreateCodeDocument();

            // Act
            engine.Process(document);

            // Assert
            AssertDocumentNodeMatchesBaseline(document.GetDocumentIntermediateNode());
            AssertCSharpDocumentMatchesBaseline(document.GetCSharpDocument());
            AssertSourceMappingsMatchBaseline(document);
        }
        public static void Register(RazorProjectEngineBuilder builder)
        {
            if (builder == null)
            {
                throw new ArgumentNullException(nameof(builder));
            }

            FunctionsDirective.Register(builder);
            ImplementsDirective.Register(builder);
            InheritsDirective.Register(builder);
            InjectDirective.Register(builder);
            LayoutDirective.Register(builder);
            PageDirective.Register(builder);

            builder.Features.Remove(builder.Features.OfType <IImportProjectFeature>().Single());
            builder.Features.Add(new BlazorImportProjectFeature());

            var index = builder.Phases.IndexOf(builder.Phases.OfType <IRazorCSharpLoweringPhase>().Single());

            builder.Phases[index] = new BlazorRazorCSharpLoweringPhase();

            builder.Features.Add(new ConfigureBlazorCodeGenerationOptions());

            builder.Features.Add(new ComponentDocumentClassifierPass());
            builder.Features.Add(new ComponentLoweringPass());

            builder.Features.Add(new ComponentTagHelperDescriptorProvider());

            if (builder.Configuration.ConfigurationName == DeclarationConfiguration.ConfigurationName)
            {
                // This is for 'declaration only' processing. We don't want to try and emit any method bodies during
                // the design time build because we can't do it correctly until the set of components is known.
                builder.Features.Add(new EliminateMethodBodyPass());
            }
        }
Beispiel #3
0
        private void RunDesignTimeTagHelpersTest(IEnumerable <TagHelperDescriptor> descriptors)
        {
            // Arrange
            var projectEngine = CreateProjectEngine(builder =>
            {
                builder.ConfigureDocumentClassifier();

                // Some of these tests use templates
                builder.AddTargetExtension(new TemplateTargetExtension());

                InheritsDirective.Register(builder);
                SectionDirective.Register(builder);
            });

            var projectItem = CreateProjectItemFromFile();
            var imports     = GetImports(projectEngine, projectItem);

            // Act
            var codeDocument = projectEngine.ProcessDesignTime(RazorSourceDocument.ReadFrom(projectItem), imports, descriptors.ToList());

            // Assert
            AssertDocumentNodeMatchesBaseline(codeDocument.GetDocumentIntermediateNode());
            AssertCSharpDocumentMatchesBaseline(codeDocument.GetCSharpDocument());
            AssertSourceMappingsMatchBaseline(codeDocument);
        }
 static void Main(string[] args)
 {
     // points to the local path
     var fs = RazorProjectFileSystem.Create(".");
     // customize the default engine a little bit
     var engine = RazorProjectEngine.Create(RazorConfiguration.Default, fs, (builder) =>
     {
         InheritsDirective.Register(builder);
         builder.SetNamespace("MyNamespace");     // define a namespace for the Template class
     });
     // get a razor-templated file. My "hello.txt" template file is defined like this:
     //
     // @inherits RazorTemplate.MyTemplate
     // Hello @Model.Name, welcome to Razor World!
     //
     var item = fs.GetItem("hello.txt");
     // parse and generate C# code, outputs it on the console
     //var cs = te.GenerateCode(item);
     //Console.WriteLine(cs.GeneratedCode);
     var codeDocument = engine.Process(item);
     var cs           = codeDocument.GetCSharpDocument();
     // now, use roslyn, parse the C# code
     var tree = CSharpSyntaxTree.ParseText(cs.GeneratedCode);
     // define the dll
     const string dllName     = "hello";
     var          compilation = CSharpCompilation.Create(dllName, new[] { tree },
                                                         new[]
        public static void Register(RazorProjectEngineBuilder builder)
        {
            if (builder == null)
            {
                throw new ArgumentNullException(nameof(builder));
            }

            InjectDirective.Register(builder);
            ModelDirective.Register(builder);
            NamespaceDirective.Register(builder);
            PageDirective.Register(builder);

            FunctionsDirective.Register(builder);
            InheritsDirective.Register(builder);
            SectionDirective.Register(builder);

            builder.Features.Add(new DefaultTagHelperDescriptorProvider());
            builder.Features.Add(new ViewComponentTagHelperDescriptorProvider());

            builder.AddTargetExtension(new ViewComponentTagHelperTargetExtension());
            builder.AddTargetExtension(new TemplateTargetExtension()
            {
                TemplateTypeName = "global::Microsoft.AspNetCore.Mvc.Razor.HelperResult",
            });

            builder.Features.Add(new ModelExpressionPass());
            builder.Features.Add(new PagesPropertyInjectionPass());
            builder.Features.Add(new ViewComponentTagHelperPass());
            builder.Features.Add(new RazorPageDocumentClassifierPass());
            builder.Features.Add(new MvcViewDocumentClassifierPass());
            builder.Features.Add(new AssemblyAttributeInjectionPass());
            builder.Features.Add(new InstrumentationPass());

            builder.SetImportFeature(new MvcImportProjectFeature());
        }
        public static void Register(IRazorEngineBuilder builder)
        {
            InjectDirective.Register(builder);
            ModelDirective.Register(builder);
            NamespaceDirective.Register(builder);
            PageDirective.Register(builder);

            FunctionsDirective.Register(builder);
            InheritsDirective.Register(builder);
            SectionDirective.Register(builder);

            builder.AddTargetExtension(new TemplateTargetExtension()
            {
                TemplateTypeName = "global::Microsoft.AspNetCore.Mvc.Razor.HelperResult",
            });

            builder.Features.Add(new ModelExpressionPass());
            builder.Features.Add(new PagesPropertyInjectionPass());
            builder.Features.Add(new ViewComponentTagHelperPass());
            builder.Features.Add(new RazorPageDocumentClassifierPass());
            builder.Features.Add(new MvcViewDocumentClassifierPass());
            builder.Features.Add(new AssemblyAttributeInjectionPass());

            if (!builder.DesignTime)
            {
                builder.Features.Add(new InstrumentationPass());
            }
        }
Beispiel #7
0
        public static void Register(RazorProjectEngineBuilder builder)
        {
            if (builder == null)
            {
                throw new ArgumentNullException(nameof(builder));
            }

            InjectDirective.Register(builder);
            ModelDirective.Register(builder);

            InheritsDirective.Register(builder);

            builder.Features.Add(new DefaultTagHelperDescriptorProvider());

            // Register section directive with the 1.x compatible target extension.
            builder.AddDirective(SectionDirective.Directive);
            builder.Features.Add(new SectionDirectivePass());
            builder.AddTargetExtension(new LegacySectionTargetExtension());

            builder.AddTargetExtension(new TemplateTargetExtension()
            {
                TemplateTypeName = "global::Microsoft.AspNetCore.Mvc.Razor.HelperResult",
            });

            builder.Features.Add(new ModelExpressionPass());
            builder.Features.Add(new MvcViewDocumentClassifierPass());

            builder.Features.Add(new MvcImportProjectFeature());

            // The default C# language version for what this Razor configuration supports.
            builder.SetCSharpLanguageVersion(LanguageVersion.CSharp7_3);
        }
        public static RazorEngine CreateInstance(string baseType)
        {
            var configuration      = RazorConfiguration.Default;
            var razorProjectEngine = RazorProjectEngine.Create(configuration,
                                                               new NullRazorProjectFileSystem(), builder =>
            {
                TkInjectDirective.Register(builder);
                TkModelDirective.Register(builder);

                if (!RazorLanguageVersion.TryParse("3.0", out var razorLanguageVersion) ||
                    configuration.LanguageVersion.CompareTo(razorLanguageVersion) < 0)
                {
                    NamespaceDirective.Register(builder);
                    FunctionsDirective.Register(builder);
                    InheritsDirective.Register(builder);
                }
                SectionDirective.Register(builder);

                builder.Features.Add(new ModelExpressionPass());
                builder.Features.Add(new RazorTemplateDocumentClassifierPass(baseType));
                builder.Features.Add(new RazorAssemblyAttributeInjectionPass());
#if NETSTANDARD2_0
                builder.Features.Add(new InstrumentationPass());
#endif
                builder.AddTargetExtension(new TemplateTargetExtension()
                {
                    TemplateTypeName = "global::YJC.Toolkit.Razor.TkRazorHelperResult",
                });

                OverrideRuntimeNodeWriterTemplateTypeNamePhase.Register(builder);
            });

            return(razorProjectEngine.Engine);
        }
        public CSharpScriptRazorGenerator(string directoryRoot)
        {
            var fileSystem    = RazorProjectFileSystem.Create(directoryRoot);
            var projectEngine = RazorProjectEngine.Create(RazorConfiguration.Default, fileSystem, builder =>
            {
                //builder
                //    .SetNamespace("Remove")
                //    .SetBaseType("Microsoft.Extensions.RazorViews.BaseView")
                //    .ConfigureClass((document, @class) =>
                //    {
                //        @class.ClassName = Path.GetFileNameWithoutExtension(document.Source.FilePath);
                //        @class.Modifiers.Clear();
                //        @class.Modifiers.Add("internal");
                //    });

                FunctionsDirective.Register(builder);
                InheritsDirective.Register(builder);
                SectionDirective.Register(builder);

                builder.Features.Remove(builder.Features.OfType <IRazorDocumentClassifierPass>().Single());
                builder.Features.Add(new CSharpScriptDocumentClassifierPass());

                //configure?.Invoke(builder);

//                builder.AddDefaultImports(@"
//@using System
//@using System.Threading.Tasks
//");
            });

            _projectEngine = projectEngine;
        }
        static void Main(string[] args)
        {
            // customize the default engine a little bit
            var engine = RazorEngine.Create(b =>
            {
                InheritsDirective.Register(b);     // make sure the engine understand the @inherits directive in the input templates
                b.SetNamespace("MyNamespace");     // define a namespace for the Template class
                b.Build();
            });
            // points to the local path
            var project = RazorProject.Create(".");
            var te      = new RazorTemplateEngine(engine, project);
            // get a razor-templated file. My "hello.txt" template file is defined like this:
            //
            // @inherits RazorTemplate.MyTemplate
            // Hello @Model.Name, welcome to Razor World!
            //
            var item = project.GetItem("hello.txt");
            // parse and generate C# code, outputs it on the console
            var cs = te.GenerateCode(item);

            Console.WriteLine(cs.GeneratedCode);
            // now, use roslyn, parse the C# code
            var tree = CSharpSyntaxTree.ParseText(cs.GeneratedCode);
            // define the dll
            const string dllName     = "hello";
            var          compilation = CSharpCompilation.Create(dllName, new[] { tree },
                                                                new[]
Beispiel #11
0
        public BlazorRazorEngine()
        {
            _codegenOptions = RazorCodeGenerationOptions.CreateDefault();

            _engine = RazorEngine.Create(configure =>
            {
                FunctionsDirective.Register(configure);
                InheritsDirective.Register(configure);
                InjectDirective.Register(configure);
                TemporaryLayoutPass.Register(configure);
                TemporaryImplementsPass.Register(configure);

                configure.SetBaseType(BlazorComponent.FullTypeName);

                configure.Phases.Remove(
                    configure.Phases.OfType <IRazorCSharpLoweringPhase>().Single());
                configure.Phases.Add(new BlazorLoweringPhase(_codegenOptions));

                configure.ConfigureClass((codeDoc, classNode) =>
                {
                    configure.SetNamespace((string)codeDoc.Items[BlazorCodeDocItems.Namespace]);
                    classNode.ClassName = (string)codeDoc.Items[BlazorCodeDocItems.ClassName];
                });
            });
        }
        public static void Register(RazorProjectEngineBuilder builder)
        {
            if (builder == null)
            {
                throw new ArgumentNullException(nameof(builder));
            }
            //InjectDirective.Register(builder);
            //ModelDirective.Register(builder);
            //NamespaceDirective.Register(builder);

            FunctionsDirective.Register(builder);
            InheritsDirective.Register(builder);
            SectionDirective.Register(builder);

            builder.AddDefaultImports(new string[] {
                "@using System",
                "@using System.Linq",
                "@using System.Threading.Tasks",
                "@Templates"
            });

            //builder.Features.Add(new DefaultTagHelperDescriptorProvider());
            //builder.Features.Add(new ModelExpressionPass());
            //builder.Features.Add(new PagesPropertyInjectionPass());
            //builder.Features.Add(new RazorPageDocumentClassifierPass());
            //builder.Features.Add(new AssemblyAttributeInjectionPass());
            //builder.Features.Add(new InstrumentationPass());
        }
Beispiel #13
0
        public static void Register(IRazorEngineBuilder builder)
        {
            if (builder == null)
            {
                throw new ArgumentNullException(nameof(builder));
            }

            EnsureDesignTime(builder);

            InjectDirective.Register(builder);
            ModelDirective.Register(builder);

            FunctionsDirective.Register(builder);
            InheritsDirective.Register(builder);

            builder.Features.Add(new DefaultTagHelperDescriptorProvider());

            // Register section directive with the 1.x compatible target extension.
            builder.AddDirective(SectionDirective.Directive);
            builder.Features.Add(new SectionDirectivePass());
            builder.AddTargetExtension(new LegacySectionTargetExtension());

            builder.AddTargetExtension(new TemplateTargetExtension()
            {
                TemplateTypeName = "global::Microsoft.AspNetCore.Mvc.Razor.HelperResult",
            });

            builder.Features.Add(new ModelExpressionPass());
            builder.Features.Add(new MvcViewDocumentClassifierPass());
        }
Beispiel #14
0
        private RazorEngine GetRazorEngine()
        {
            var razorEngine = RazorEngine.Create(builder =>
            {
                InjectDirective.Register(builder);
                ModelDirective.Register(builder);
                NamespaceDirective.Register(builder);
                PageDirective.Register(builder);
                FunctionsDirective.Register(builder);
                InheritsDirective.Register(builder);
                SectionDirective.Register(builder);

                ////builder.AddTargetExtension(new TemplateTargetExtension()
                ////{
                ////    TemplateTypeName = "global::Microsoft.AspNetCore.Mvc.Razor.HelperResult",
                ////});

                ////builder.Features.Add(new SuppressChecksumOptionsFeature());
                builder.Features.Add(new ModelExpressionPass());
                builder.Features.Add(new PagesPropertyInjectionPass());
                builder.Features.Add(new ViewComponentTagHelperPass());
                builder.Features.Add(new RazorPageDocumentClassifierPass());
                builder.Features.Add(new MvcViewDocumentClassifierPass2(RuntimeTemplatesNamespace, BaseViewName));
                builder.Features.Add(new AssemblyAttributeInjectionPass2());

                if (!builder.DesignTime)
                {
                    //builder.Features.Add(new InstrumentationPass());
                }
            });

            return(razorEngine);
        }
        static RazorTemplateEngine BuildRazorTemplateEngine(RazorProjectFileSystem fileSystem)
        {
            var razorConfiguration = Microsoft.AspNetCore.Razor.Language.RazorConfiguration.Default;
            var razorProjectEngine = RazorProjectEngine.Create(razorConfiguration, fileSystem, builder =>
            {
                FunctionsDirective.Register(builder);
                InheritsDirective.Register(builder);
                SectionDirective.Register(builder);

                var metadataReferences = AppDomain.CurrentDomain.GetAssemblies()
                                         .Where(a => !a.IsDynamic)
                                         .Select(a => MetadataReference.CreateFromFile(a.Location))
                                         .ToArray();

                builder.Features.Add(new DefaultMetadataReferenceFeature {
                    References = metadataReferences
                });
                builder.Features.Add(new CompilationTagHelperFeature());
                builder.Features.Add(new DefaultTagHelperDescriptorProvider());
                //builder.Features.Add(new ViewComponentTagHelperDescriptorProvider());
                builder.Features.Add(new DocumentClassifierPass());
                //builder.Features.Add(new ViewComponentTagHelperPass());
            });

            var templateEngine = new RazorTemplateEngine(razorProjectEngine.Engine, fileSystem);

            return(templateEngine);
        }
        private void RunRuntimeTagHelpersTest(IEnumerable <TagHelperDescriptor> descriptors)
        {
            // Arrange
            var projectEngine = CreateProjectEngine(builder =>
            {
                builder.ConfigureDocumentClassifier();
                builder.AddTagHelpers(descriptors);

                // Some of these tests use templates
                builder.AddTargetExtension(new TemplateTargetExtension());

                FunctionsDirective.Register(builder);
                InheritsDirective.Register(builder);
                SectionDirective.Register(builder);
            });

            var projectItem = CreateProjectItem();

            // Act
            var codeDocument = projectEngine.Process(projectItem);

            // Assert
            AssertDocumentNodeMatchesBaseline(codeDocument.GetDocumentIntermediateNode());
            AssertCSharpDocumentMatchesBaseline(codeDocument.GetCSharpDocument());
        }
        private void DesignTimeTest()
        {
            // Arrange
            var projectEngine = CreateProjectEngine(builder =>
            {
                builder.ConfigureDocumentClassifier();

                // Some of these tests use templates
                builder.AddTargetExtension(new TemplateTargetExtension());

                FunctionsDirective.Register(builder);
                InheritsDirective.Register(builder);
                SectionDirective.Register(builder);
            });

            var projectItem = CreateProjectItem();

            // Act
            var codeDocument = projectEngine.ProcessDesignTime(projectItem);

            // Assert
            AssertDocumentNodeMatchesBaseline(codeDocument.GetDocumentIntermediateNode());
            AssertCSharpDocumentMatchesBaseline(codeDocument.GetCSharpDocument());
            AssertSourceMappingsMatchBaseline(codeDocument);
        }
Beispiel #18
0
        private static string GetTemplateSourceCode <T>(string templatePath, string content)
        {
            // customize the default engine a little bit
            var engine = RazorEngine.Create(engineBuilder =>
            {
                InheritsDirective.Register(engineBuilder);
                engineBuilder.SetNamespace("MyNamespace");
                engineBuilder.Build();
            });

            // points to the local path
            var project = RazorProject.Create(".");
            var te      = new RazorTemplateEngine(engine, project);

            // get a razor-templated file. My "hello.txt" template file is defined like this:
            //
            // @inherits RazorTemplate.MyTemplate
            // Hello @Model.Name, welcome to Razor World!
            //
            StringBuilder builder = new StringBuilder();

            builder.AppendLine(String.Format("@inherits Developpez.MagazineTool.TemplateManager.Template<{0}>", typeof(T).FullName));
            builder.Append(content);
            RazorSourceDocument sourceDocument = RazorSourceDocument.Create(builder.ToString(), templatePath);
            RazorCodeDocument   codeDocument   = RazorCodeDocument.Create(sourceDocument);

            // parse and generate C# code, outputs it on the console

            //var cs = te.GenerateCode(item);
            var cs = te.GenerateCode(codeDocument);

            return(cs.GeneratedCode);
        }
Beispiel #19
0
        public static RazorProjectEngine CreateProjectEngine(string rootNamespace, string targetProjectDirectory, Action <RazorProjectEngineBuilder> configure = null)
        {
            var fileSystem    = RazorProjectFileSystem.Create(targetProjectDirectory);
            var projectEngine = RazorProjectEngine.Create(RazorConfiguration.Default, fileSystem, builder =>
            {
                builder
                .SetNamespace(rootNamespace)
                .SetBaseType("Microsoft.Extensions.RazorViews.BaseView")
                .ConfigureClass((document, @class) =>
                {
                    @class.ClassName = Path.GetFileNameWithoutExtension(document.Source.FilePath);
                    @class.Modifiers.Clear();
                    @class.Modifiers.Add("internal");
                });

                InheritsDirective.Register(builder);
                SectionDirective.Register(builder);

                builder.Features.Add(new SuppressChecksumOptionsFeature());
                builder.Features.Add(new SuppressMetadataAttributesFeature());

                if (configure != null)
                {
                    configure(builder);
                }

                builder.AddDefaultImports(@"
@using System
@using System.Threading.Tasks
");
            });

            return(projectEngine);
        }
Beispiel #20
0
        /// <summary>
        /// Registers the Blazor extension.
        /// </summary>
        /// <param name="builder">The <see cref="RazorProjectEngineBuilder"/>.</param>
        public static void Register(RazorProjectEngineBuilder builder)
        {
            if (builder == null)
            {
                throw new ArgumentNullException(nameof(builder));
            }

            FunctionsDirective.Register(builder);
            ImplementsDirective.Register(builder);
            InheritsDirective.Register(builder);
            InjectDirective.Register(builder);
            LayoutDirective.Register(builder);
            PageDirective.Register(builder);
            TypeParamDirective.Register(builder);

            builder.Features.Remove(builder.Features.OfType <IImportProjectFeature>().Single());
            builder.Features.Add(new BlazorImportProjectFeature());

            var index = builder.Phases.IndexOf(builder.Phases.OfType <IRazorCSharpLoweringPhase>().Single());

            builder.Phases[index] = new BlazorRazorCSharpLoweringPhase();

            builder.Features.Add(new ConfigureBlazorCodeGenerationOptions());

            builder.AddTargetExtension(new BlazorTemplateTargetExtension());

            var isDeclarationOnlyCompile = builder.Configuration.ConfigurationName == DeclarationConfiguration.ConfigurationName;

            // Blazor-specific passes, in order.
            if (!isDeclarationOnlyCompile)
            {
                // There's no benefit in this optimization during the declaration-only compile
                builder.Features.Add(new TrimWhitespacePass());
            }
            builder.Features.Add(new ComponentDocumentClassifierPass());
            builder.Features.Add(new ComponentDocumentRewritePass());
            builder.Features.Add(new ScriptTagPass());
            builder.Features.Add(new ComplexAttributeContentPass());
            builder.Features.Add(new ComponentLoweringPass());
            builder.Features.Add(new EventHandlerLoweringPass());
            builder.Features.Add(new RefLoweringPass());
            builder.Features.Add(new BindLoweringPass());
            builder.Features.Add(new TemplateDiagnosticPass());
            builder.Features.Add(new GenericComponentPass());
            builder.Features.Add(new ChildContentDiagnosticPass());
            builder.Features.Add(new HtmlBlockPass());

            builder.Features.Add(new ComponentTagHelperDescriptorProvider());
            builder.Features.Add(new BindTagHelperDescriptorProvider());
            builder.Features.Add(new EventHandlerTagHelperDescriptorProvider());
            builder.Features.Add(new RefTagHelperDescriptorProvider());

            if (isDeclarationOnlyCompile)
            {
                // This is for 'declaration only' processing. We don't want to try and emit any method bodies during
                // the design time build because we can't do it correctly until the set of components is known.
                builder.Features.Add(new EliminateMethodBodyPass());
            }
        }
        static void Main(string[] args)
        {
            // points to the local path
            var fs = RazorProjectFileSystem.Create(".");
            // customize the default engine a little bit
            var engine = RazorProjectEngine.Create(RazorConfiguration.Default, fs, (builder) =>
            {
                InheritsDirective.Register(builder);
                builder.SetNamespace("MyNamespace");     // define a namespace for the Template class
            });
            // get a razor-templated file. My "hello.txt" template file is defined like this:
            //
            // @inherits RazorTemplate.MyTemplate
            // Hello @Model.Name, welcome to Razor World!
            //
            var item = fs.GetItem("hello.txt");
            // parse and generate C# code, outputs it on the console
            //var cs = te.GenerateCode(item);
            //Console.WriteLine(cs.GeneratedCode);
            var codeDocument = engine.Process(item);
            var cs           = codeDocument.GetCSharpDocument();
            // now, use roslyn, parse the C# code
            var tree = CSharpSyntaxTree.ParseText(cs.GeneratedCode);
            // define the dll
            const string dllName     = "hello";
            var          compilation = CSharpCompilation.Create(dllName, new[] { tree },
                                                                new[]
            {
                MetadataReference.CreateFromFile(typeof(object).Assembly.Location),                     // include corlib
                MetadataReference.CreateFromFile(typeof(RazorCompiledItemAttribute).Assembly.Location), // include Microsoft.AspNetCore.Razor.Runtime
                MetadataReference.CreateFromFile(Assembly.GetExecutingAssembly().Location),             // this file (that contains the MyTemplate base class)
                // for some reason on .NET core, I need to add this... this is not needed with .NET framework
                MetadataReference.CreateFromFile(Path.Combine(Path.GetDirectoryName(typeof(object).Assembly.Location), "System.Runtime.dll")),
                // as found out by @Isantipov, for some other reason on .NET Core for Mac and Linux, we need to add this... this is not needed with .NET framework
                MetadataReference.CreateFromFile(Path.Combine(Path.GetDirectoryName(typeof(object).Assembly.Location), "netstandard.dll"))
            },
                                                                new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)); // we want a dll
            // compile the dll
            string path   = Path.Combine(Path.GetFullPath("."), dllName + ".dll");
            var    result = compilation.Emit(path);

            if (!result.Success)
            {
                Console.WriteLine(string.Join(Environment.NewLine, result.Diagnostics));
                return;
            }
            // load the built dll
            Console.WriteLine(path);
            var asm = Assembly.LoadFile(path);
            // the generated type is defined in our custom namespace, as we asked. "Template" is the type name that razor uses by default.
            var template = (MyTemplate)Activator.CreateInstance(asm.GetType("MyNamespace.Template"));

            // run the code.
            // should display "Hello Killroy, welcome to Razor World!"
            template.ExecuteAsync().Wait();
        }
        private RazorEngine CreateDesignTimeEngine()
        {
            return(RazorEngine.CreateDesignTime(b =>
            {
                // Notice we're not registering the ModelDirective.Pass here so we can run it on demand.
                b.AddDirective(ModelDirective.Directive);

                // There's some special interaction with the inherits directive
                InheritsDirective.Register(b);
            }));
        }
        static void Main(string[] args)
        {
            // customize the default engine a little bit
            var engine = RazorEngine.Create(b =>
            {
                InheritsDirective.Register(b);     // make sure the engine understand the @inherits directive in the input templates
                b.SetNamespace("MyNamespace");     // define a namespace for the Template class
                b.Build();
            });
            // points to the local path
            var project = RazorProject.Create(".");
            var te      = new RazorTemplateEngine(engine, project);
            // get a file. My file is defined like this:
            //
            // @inherits RazorTemplate.MyTemplate
            // Hello @Model.Name, welcome to Razor World!
            //
            var item = project.GetItem("hello.txt");
            // parse and generate C# code, outputs it on the console
            var cs = te.GenerateCode(item);

            Console.WriteLine(cs.GeneratedCode);
            // now, use roslyn, parse the C# code
            var tree = CSharpSyntaxTree.ParseText(cs.GeneratedCode);
            // define the dll
            const string dllName     = "hello";
            var          compilation = CSharpCompilation.Create(dllName, new[] { tree },
                                                                new[]
            {
                MetadataReference.CreateFromFile(typeof(object).Assembly.Location),         // include corlib
                MetadataReference.CreateFromFile(Assembly.GetExecutingAssembly().Location), // this file (that contains the MyTemplate base class)
                // for some reason on .NET core, I need to add this... this is not needed with .NET framework
                MetadataReference.CreateFromFile(Path.Combine(Path.GetDirectoryName(typeof(object).Assembly.Location), "System.Runtime.dll")),
            },
                                                                new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)); // we want a dll
            // compile the dll
            string path   = Path.Combine(Path.GetFullPath("."), dllName + ".dll");
            var    result = compilation.Emit(path);

            if (!result.Success)
            {
                Console.WriteLine(string.Join(Environment.NewLine, result.Diagnostics));
                return;
            }
            // load the built DLL
            Console.WriteLine(path);
            var asm = Assembly.LoadFile(path);
            // the generated type is defined in our custom namespace, as we asked. "Template" is the type name that razor uses by default.
            var template = (MyTemplate)Activator.CreateInstance(asm.GetType("MyNamespace.Template"));

            // run the code.
            // should display "Hello Killroy, welcome to Razor World!"
            template.ExecuteAsync().Wait();
        }
        private RazorEngine CreateEngineCore(bool designTime = false)
        {
            return(CreateProjectEngine(b =>
            {
                // Notice we're not registering the ModelDirective.Pass here so we can run it on demand.
                b.AddDirective(ModelDirective.Directive);

                // There's some special interaction with the inherits directive
                InheritsDirective.Register(b);

                b.Features.Add(new DesignTimeOptionsFeature(designTime));
            }).Engine);
        }
Beispiel #25
0
        public static RazorProjectEngine Create(
            RazorConfiguration configuration,
            RazorProjectFileSystem fileSystem,
            Action <RazorProjectEngineBuilder> configure)
        {
            if (fileSystem == null)
            {
                throw new ArgumentNullException(nameof(fileSystem));
            }

            if (configuration == null)
            {
                throw new ArgumentNullException(nameof(configuration));
            }

            var builder = new DefaultRazorProjectEngineBuilder(configuration, fileSystem);

            // The intialization order is somewhat important.
            //
            // Defaults -> Extensions -> Additional customization
            //
            // This allows extensions to rely on default features, and customizations to override choices made by
            // extensions.
            AddDefaultPhases(builder.Phases);
            AddDefaultFeatures(builder.Features);

            if (configuration.LanguageVersion.CompareTo(RazorLanguageVersion.Version_5_0) >= 0)
            {
                builder.Features.Add(new ViewCssScopePass());
            }

            if (configuration.LanguageVersion.CompareTo(RazorLanguageVersion.Version_3_0) >= 0)
            {
                FunctionsDirective.Register(builder);
                ImplementsDirective.Register(builder);
                InheritsDirective.Register(builder);
                NamespaceDirective.Register(builder);
                AttributeDirective.Register(builder);

                AddComponentFeatures(builder, configuration.LanguageVersion);
            }

            LoadExtensions(builder, configuration.Extensions);

            configure?.Invoke(builder);

            return(builder.Build());
        }
        private static RazorProjectFileSystem InitialiseTemplateProject(string dynamicAssemblyNamespace, out RazorProjectEngine razorProjectEngine)
        {
            // points to the local path
            RazorProjectFileSystem razorProjectFileSystem = RazorProjectFileSystem.Create(".");

            // customize the default engine a little bit
            razorProjectEngine = RazorProjectEngine.Create(RazorConfiguration.Default, razorProjectFileSystem, (builder) =>
            {
                InheritsDirective.Register(builder);

                // define a namespace for the Template class
                builder.SetNamespace(dynamicAssemblyNamespace);
            });

            return(razorProjectFileSystem);
        }
        private void _Init(string templateNamespace, string typeName, string basePath)
        {
            if (string.IsNullOrWhiteSpace(templateNamespace))
            {
                throw new ArgumentNullException(nameof(templateNamespace), "Cannot be null or empty.");
            }

            if (string.IsNullOrWhiteSpace(typeName))
            {
                throw new ArgumentNullException(nameof(typeName), "Cannot be null or empty.");
            }

            // customize the default engine a little bit
            var engine = RazorEngine.Create(b =>
            {
                InheritsDirective.Register(b);     // make sure the engine understand the @inherits directive in the input templates
                FunctionsDirective.Register(b);    // make sure the engine understand the @function directive in the input templates
                SectionDirective.Register(b);      // make sure the engine understand the @section directive in the input templates
                b.SetNamespace(templateNamespace); // define a namespace for the Template class
                b.Build();
            });

            var project        = RazorProject.Create(HostingEnvironment.ContentRootPath);
            var templateEngine = new RazorTemplateEngine(engine, project);

            // get a razor-templated file. My "hello.txt" template file is defined like this:
            //
            // @inherits RazorTemplate.MyTemplate
            // Hello @Model.Name, welcome to Razor World!
            //

            var fileInfo = _FindView(typeName, basePath, out var filepath);

            // ... parse and generate C# code ...
            var codeDoc = RazorCSharpDocument.Create();
            var cs      = templateEngine.GenerateCode(codeDoc);

            // ... use roslyn to parse the C# code ...
            //
            var tree = CSharpSyntaxTree.ParseText(cs.GeneratedCode);

            // ... name the assembly ...
            //
            string dllName = templateNamespace + "." + typeName;

            var compilation = CSharpCompilation.Create(dllName, new[] { tree },
                                                       new[]
Beispiel #28
0
        static RazorProjectEngine CreateProjectEngine(string rootNamespace, string projectDirectory)
        {
            var fileSystem    = RazorProjectFileSystem.Create(projectDirectory);
            var projectEngine = RazorProjectEngine.Create(RazorConfiguration.Default, fileSystem, builder => {
                builder
                .SetNamespace(rootNamespace)
                .ConfigureClass((document, @class) => {
                    @class.ClassName = Path.GetFileNameWithoutExtension(document.Source.FilePath);
                });

                FunctionsDirective.Register(builder);
                InheritsDirective.Register(builder);
                SectionDirective.Register(builder);
            });

            return(projectEngine);
        }
Beispiel #29
0
        public DaoGenerator()
        {
            logger = this.CreateLogger();

            engine = RazorEngine.Create(builder =>
            {
                FunctionsDirective.Register(builder);
                InheritsDirective.Register(builder);
                SectionDirective.Register(builder);
                builder.Features.Add(new SqlDocumentClassifierPassBase());
            });

            assembly     = GetType().Assembly;
            assemblyName = Path.GetRandomFileName();
            types        = new List <Type>();
            syntaxTrees  = new List <SyntaxTree>();
            Extractor    = new Extractor();
        }
Beispiel #30
0
        public Task Run(string[] args)
        {
            string targetProjectDirectory = AppContext.BaseDirectory;
            string rootNamespace          = System.IO.Path.GetFileNameWithoutExtension(System.IO.Path.GetTempFileName()).ToLowerInvariant();

            RazorProjectFileSystem fileSystem    = RazorProjectFileSystem.Create(targetProjectDirectory);
            RazorProjectEngine     projectEngine = RazorProjectEngine.Create(RazorConfiguration.Default, fileSystem, builder =>
            {
                builder
                .SetNamespace(rootNamespace)
                .SetBaseType("Microsoft.Extensions.RazorViews.BaseView")
                .ConfigureClass((document, @class) =>
                {
                    @class.ClassName = Path.GetFileNameWithoutExtension(document.Source.FilePath);
                    @class.Modifiers.Clear();
                    @class.Modifiers.Add("internal");
                });

                FunctionsDirective.Register(builder);
                InheritsDirective.Register(builder);
                SectionDirective.Register(builder);

                //builder.Features.Add()
                //builder.Features.Add(new SuppressChecksumOptionsFeature());
                //builder.Features.Add(new SuppressMetadataAttributesFeature());

                // configure is always null
                //if (configure != null)
                //{
                //    configure(builder);
                //}

                builder.AddDefaultImports(@"
@using System
@using System.Threading.Tasks");
            });

            return(Task.Run(() => {
                Console.WriteLine("Do nothing");
            }));
        } // public void Run(string[] args)