コード例 #1
0
        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());
            }
        }
コード例 #2
0
        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;
        }
コード例 #3
0
        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);
        }
コード例 #4
0
        private void RunDesignTimeTagHelpersTest(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.ProcessDesignTime(projectItem);

            // Assert
            AssertDocumentNodeMatchesBaseline(codeDocument.GetDocumentIntermediateNode());
            AssertCSharpDocumentMatchesBaseline(codeDocument.GetCSharpDocument());
            AssertSourceMappingsMatchBaseline(codeDocument);
        }
コード例 #5
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);
        }
コード例 #6
0
        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());
        }
コード例 #7
0
        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());
            }
        }
コード例 #8
0
        private void RunRuntimeTagHelpersTest(IEnumerable <TagHelperDescriptor> descriptors)
        {
            // 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 = CreateProjectItemFromFile();
            var imports     = GetImports(projectEngine, projectItem);

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

            // Assert
            AssertDocumentNodeMatchesBaseline(codeDocument.GetDocumentIntermediateNode());
            AssertCSharpDocumentMatchesBaseline(codeDocument.GetCSharpDocument());
        }
コード例 #9
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());
        }
コード例 #10
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);
        }
コード例 #11
0
        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);
        }
コード例 #12
0
        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());
        }
コード例 #13
0
        private void RunRuntimeTagHelpersTest(IEnumerable <TagHelperDescriptor> descriptors)
        {
            // Arrange
            var engine = RazorEngine.Create(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 document = CreateCodeDocument();

            // Act
            engine.Process(document);

            // Assert
            AssertDocumentNodeMatchesBaseline(document.GetDocumentIntermediateNode());
            AssertCSharpDocumentMatchesBaseline(document.GetCSharpDocument());
        }
コード例 #14
0
        private void DesignTimeTest()
        {
            // Arrange
            var engine = RazorEngine.CreateDesignTime(builder =>
            {
                builder.ConfigureDocumentClassifier();

                // 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);
        }
コード例 #15
0
ファイル: BlazorRazorEngine.cs プロジェクト: ddobric/Blazor-1
        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];
                });
            });
        }
コード例 #16
0
ファイル: Program.cs プロジェクト: vyaspranjal33/Razor
        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");
                });

                FunctionsDirective.Register(builder);
                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);
        }
コード例 #17
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());
            }
        }
コード例 #18
0
        public static void Register(RazorProjectEngineBuilder builder)
        {
            if (builder == null)
            {
                throw new ArgumentNullException(nameof(builder));
            }

            FunctionsDirective.Register(builder);
            builder.Features.Add(new ComponentDocumentClassifierPass());
        }
コード例 #19
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());
        }
コード例 #20
0
        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[]
コード例 #21
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);
        }
コード例 #22
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();
        }
コード例 #23
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)
コード例 #24
0
        private DocumentIntermediateNode Lower(
            RazorCodeDocument codeDocument,
            Action <RazorProjectEngineBuilder> builder   = null,
            IEnumerable <TagHelperDescriptor> tagHelpers = null,
            bool designTime = false)
        {
            tagHelpers = tagHelpers ?? new TagHelperDescriptor[0];

            Action <RazorProjectEngineBuilder> configureEngine = b =>
            {
                builder?.Invoke(b);

                FunctionsDirective.Register(b);
                SectionDirective.Register(b);
                b.AddTagHelpers(tagHelpers);

                b.Features.Add(new DesignTimeOptionsFeature(designTime));
            };

            var projectEngine = RazorProjectEngine.Create(configureEngine);

            for (var i = 0; i < projectEngine.Phases.Count; i++)
            {
                var phase = projectEngine.Phases[i];
                phase.Execute(codeDocument);

                if (phase is IRazorIntermediateNodeLoweringPhase)
                {
                    break;
                }
            }

            var documentNode = codeDocument.GetDocumentIntermediateNode();

            Assert.NotNull(documentNode);

            return(documentNode);
        }
コード例 #25
0
        private void RunTimeTest()
        {
            // Arrange
            var engine = RazorEngine.Create(builder =>
            {
                builder.Features.Add(new ApiSetsIRTestAdapter());

                // 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());
        }
コード例 #26
0
        private void RunTimeTest()
        {
            // 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.Process(projectItem);

            // Assert
            AssertDocumentNodeMatchesBaseline(codeDocument.GetDocumentIntermediateNode());
            AssertCSharpDocumentMatchesBaseline(codeDocument.GetCSharpDocument());
        }
コード例 #27
0
        private string GetGeneratorResultBak(IEnumerable <string> namespaces, TypeContext context)
        {
#pragma warning disable 612, 618
            var razorCompiledItemAssembly = typeof(RazorCompiledItemAttribute).Assembly;
            //手动加载程序集,防止编译 Razor 类时找不到 DLL
            var razorEngine = RazorEngine.Create(builder =>
            {
                InheritsDirective.Register(builder);
                FunctionsDirective.Register(builder);
                SectionDirective.Register(builder);
                builder
                .SetNamespace(DynamicTemplateNamespace)
                //.SetBaseType("Microsoft.Extensions.RazorViews.BaseView")
                .SetBaseType(BuildTypeName(context.TemplateType, context.ModelType))
                .ConfigureClass((document, @class) =>
                {
                    @class.ClassName = context.ClassName;
                    //if (!str  ing.IsNullOrWhiteSpace(document.Source.FilePath))
                    //{
                    //    @class.ClassName = Path.GetFileNameWithoutExtension(document.Source.FilePath);
                    //}
                    @class.Modifiers.Clear();
                    @class.Modifiers.Add("internal");
                });
                builder.Features.Add(new SuppressChecksumOptionsFeature());
            });

            string importString = @"
@using System
@using System.Threading.Tasks
";
            importString += String.Join("\r\n", namespaces.Select(n => "@using " + n.Trim())) + "\r\n";

            using (var reader = context.TemplateContent.GetTemplateReader())
            {
                string path = null;
                if (string.IsNullOrWhiteSpace(context.TemplateContent.TemplateFile))
                {
                    path = Directory.GetCurrentDirectory();
                }
                else
                {
                    path = Path.GetDirectoryName(context.TemplateContent.TemplateFile);
                }
                var razorProject   = RazorProjectFileSystem.Create(path);
                var templateEngine = new RazorTemplateEngine(razorEngine, razorProject);
                templateEngine.Options.DefaultImports = RazorSourceDocument.Create(importString, fileName: null);
                RazorPageGeneratorResult result;
                if (string.IsNullOrWhiteSpace(context.TemplateContent.TemplateFile))
                {
                    var item    = RazorSourceDocument.Create(context.TemplateContent.Template, string.Empty);
                    var imports = new List <RazorSourceDocument>();
                    imports.Add(templateEngine.Options.DefaultImports);
                    var doc = RazorCodeDocument.Create(item, imports);
                    result = GenerateCodeFile(templateEngine, doc);
                }
                else
                {
                    var item = razorProject.GetItem(context.TemplateContent.TemplateFile);
                    result = GenerateCodeFile(templateEngine, item);
                }
                return(InspectSource(result, context));
            }
        }
コード例 #28
0
        private static Type CreateGeneratorType(Type _)
        {
            var name = typeof(T).FullName;

            var metadataReferences = GetMetadataReferences();

            RazorSourceDocument document;

            using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream($"{name}.razor"))
            {
                if (stream == null)
                {
                    throw new Exception($"Could not find embedded resource {name}.razor");
                }
                using (var reader = new StreamReader(stream))
                {
                    document = RazorSourceDocument.Create(reader.ReadToEnd(), $"{name}.razor");
                }
            }

#pragma warning disable CS0618 //Create and Register are marked as obsolete but there aren't alternative available
            var engine = RazorEngine.Create(b =>
            {
                FunctionsDirective.Register(b);
                InheritsDirective.Register(b);
#pragma warning restore CS0618
            });
            RazorCodeDocument codeDocument = RazorCodeDocument.Create(document);
            engine.Process(codeDocument);
            string code;
            using (var srcFileWriter = new StringWriter())
            {
                code = codeDocument.GetCSharpDocument().GeneratedCode;
            }

            SourceText sourceText = SourceText.From(code, Encoding.UTF8);
            SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(sourceText, CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.Latest));
            CSharpCompilationOptions compilationOptions = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)
                                                          .WithSpecificDiagnosticOptions(new Dictionary <string, ReportDiagnostic> {
                // Binding redirects
                ["CS1701"] = ReportDiagnostic.Suppress,
                ["CS1702"] = ReportDiagnostic.Suppress,
                ["CS1705"] = ReportDiagnostic.Suppress,
                ["CS8019"] = ReportDiagnostic.Suppress
            })
                                                          .WithUsings("System");
            CSharpCompilation compilation = CSharpCompilation.Create(typeof(T).FullName, new List <SyntaxTree> {
                syntaxTree
            }, metadataReferences, compilationOptions);

            Assembly    assembly;
            EmitOptions emitOptions = new EmitOptions(debugInformationFormat: DebugInformationFormat.PortablePdb);
            using (MemoryStream assemblyStream = new MemoryStream())
            {
                using (MemoryStream pdbStream = new MemoryStream())
                {
                    var emitResult = compilation.Emit(
                        assemblyStream,
                        pdbStream,
                        options: emitOptions);

                    if (!emitResult.Success)
                    {
                        throw new Exception("Compilation error: " + string.Join("; ", emitResult.Diagnostics.Select(d => d.ToString())));
                    }

                    assemblyStream.Seek(0, SeekOrigin.Begin);
                    pdbStream.Seek(0, SeekOrigin.Begin);

                    assembly = Assembly.Load(assemblyStream.ToArray(), pdbStream.ToArray());
                }
            }

            var generatorType = assembly.GetTypes().Where(type => type.IsSubclassOf(typeof(T))).Single();
            return(generatorType);
        }
コード例 #29
0
        /// <summary>
        /// Getting the generated code through Microsoft.AspNetCore.Razor.Language
        /// </summary>
        /// <param name="dynamicTemplateNamespace"></param>
        /// <param name="templateSourceCode"></param>
        /// <param name="generatedCSharpClassName"></param>
        /// <param name="classBaseType"></param>
        /// <param name="templateFile"></param>
        /// <returns></returns>
        public static string GetGeneratedCode(string dynamicTemplateNamespace,
                                              string templateSourceCode,
                                              string generatedCSharpClassName,
                                              string classBaseType,
                                              string templateFile = null)
        {
            string systemPath = Directory.GetCurrentDirectory();
            string path       = null;

            if (string.IsNullOrWhiteSpace(templateFile))
            {
                path = systemPath;
            }
            else
            {
                path = Path.GetDirectoryName(templateFile);
            }
            RazorProjectFileSystem fs     = RazorProjectFileSystem.Create(path); // or '.'
            RazorProjectEngine     engine = RazorProjectEngine.Create(RazorConfiguration.Default, fs, (builder) =>
            {
                InheritsDirective.Register(builder);
                FunctionsDirective.Register(builder);
                SectionDirective.Register(builder);
                builder.ConfigureClass((document, @class) =>
                {
                    @class.ClassName = generatedCSharpClassName;
                });
                builder.SetNamespace(dynamicTemplateNamespace); // define a namespace for the Template class
                builder.SetBaseType(classBaseType);
                builder.AddDefaultImports("@using System",
                                          "@using System.Threading.Tasks",
                                          "@using System.Collections.Generic",
                                          "@using System.Linq",
                                          "@using System.Text",
                                          "@using RazorEngine",
                                          "@using RazorEngine.Templating");
            });
            string razorRelativePath;
            string randomRazorFileFullPath = null;

            if (string.IsNullOrEmpty(templateFile))
            {
                razorRelativePath       = Path.GetRandomFileName();
                randomRazorFileFullPath = Path.Combine(systemPath, razorRelativePath);
                File.AppendAllText(randomRazorFileFullPath, templateSourceCode ?? string.Empty, System.Text.Encoding.UTF8);
            }
            else
            {
                razorRelativePath = templateFile;
            }
            RazorProjectItem    item           = fs.GetItem(razorRelativePath);
            RazorCodeDocument   codeDocument   = engine.Process(item);
            RazorCSharpDocument csharpDocument = codeDocument.GetCSharpDocument();

            if (!string.IsNullOrEmpty(randomRazorFileFullPath))
            {
                try
                {
                    File.Delete(randomRazorFileFullPath);
                }
                catch (Exception) { }
            }
            if (csharpDocument.Diagnostics.Any())
            {
                var diagnostics = string.Join(Environment.NewLine, csharpDocument.Diagnostics);
                throw new InvalidOperationException($"One or more parse errors encountered. This will not prevent the generator from continuing: {Environment.NewLine}{diagnostics}.");
            }
            //Manual loading of assemblies to prevent DLLs from being lost when compiling classes
            AppDomain.CurrentDomain.Load(typeof(RazorCompiledItemAttribute).Assembly.FullName);
            //手动加载程序集,防止编译的类时找不到 DLL
            return(csharpDocument.GeneratedCode);
        }
コード例 #30
0
ファイル: RazorTemplating.cs プロジェクト: yputt/Scaffolding
        public async Task <TemplateResult> RunTemplateAsync(string content,
                                                            dynamic templateModel)
        {
            // Don't care about the RazorProject as we already have the content of the .cshtml file
            // and don't need to deal with imports.
            var fileSystem    = RazorProjectFileSystem.Create(Directory.GetCurrentDirectory());
            var projectEngine = RazorProjectEngine.Create(RazorConfiguration.Default, fileSystem, (builder) =>
            {
                FunctionsDirective.Register(builder);
                InheritsDirective.Register(builder);
                SectionDirective.Register(builder);

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

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

            var templateItem     = new TemplateRazorProjectItem(content);
            var codeDocument     = projectEngine.Process(templateItem);
            var generatorResults = codeDocument.GetCSharpDocument();

            if (generatorResults.Diagnostics.Any())
            {
                var messages = generatorResults.Diagnostics.Select(d => d.GetMessage());
                return(new TemplateResult()
                {
                    GeneratedText = string.Empty,
                    ProcessingException = new TemplateProcessingException(messages, generatorResults.GeneratedCode)
                });
            }
            var templateResult = _compilationService.Compile(generatorResults.GeneratedCode);

            if (templateResult.Messages.Any())
            {
                return(new TemplateResult()
                {
                    GeneratedText = string.Empty,
                    ProcessingException = new TemplateProcessingException(templateResult.Messages, generatorResults.GeneratedCode)
                });
            }

            var compiledObject = Activator.CreateInstance(templateResult.CompiledType);

            var result = string.Empty;

            if (compiledObject is RazorTemplateBase razorTemplate)
            {
                razorTemplate.Model = templateModel;
                //ToDo: If there are errors executing the code, they are missed here.
                result = await razorTemplate.ExecuteTemplate();
            }

            return(new TemplateResult()
            {
                GeneratedText = result,
                ProcessingException = null
            });
        }