コード例 #1
0
        private static TestRazorViewCompiler GetViewCompiler(
            TestFileProvider fileProvider = null,
            PublicRazorReferenceManager referenceManager    = null,
            IList <CompiledViewDescriptor> precompiledViews = null,
            PublicCSharpCompiler csharpCompiler             = null)
        {
            fileProvider = fileProvider ?? new TestFileProvider();
            var options = Options.Create(new MvcRazorRuntimeCompilationOptions {
                FileProviders = { fileProvider }
            });
            var compilationFileProvider = new PublicRuntimeCompilationFileProvider(options);


            referenceManager = referenceManager ?? CreateReferenceManager();
            precompiledViews = precompiledViews ?? Array.Empty <CompiledViewDescriptor>();

            var hostingEnvironment = Mock.Of <IWebHostEnvironment>(e => e.ContentRootPath == "BasePath");
            var fileSystem         = new PublicFileProviderRazorProjectFileSystem(compilationFileProvider);
            var projectEngine      = RazorProjectEngine.Create(RazorConfiguration.Default, fileSystem, builder => {
                RazorExtensions.Register(builder);
            });

            csharpCompiler = csharpCompiler ?? new PublicCSharpCompiler(referenceManager, hostingEnvironment);

            return(new TestRazorViewCompiler(
                       projectEngine,
                       csharpCompiler,
                       precompiledViews));
        }
 public override RazorProjectEngine Create(RazorConfiguration configuration, RazorProjectFileSystem fileSystem, Action <RazorProjectEngineBuilder> configure)
 {
     return(RazorProjectEngine.Create(configuration, fileSystem, b =>
     {
         RazorExtensions.Register(b);
     }));
 }
コード例 #3
0
        private static RazorProjectEngine GetDeclarationProjectEngine(
            SourceGeneratorProjectItem item,
            IEnumerable <SourceGeneratorProjectItem> imports,
            RazorSourceGenerationOptions razorSourceGeneratorOptions)
        {
            var fileSystem = new VirtualRazorProjectFileSystem();

            fileSystem.Add(item);
            foreach (var import in imports)
            {
                fileSystem.Add(import);
            }

            var discoveryProjectEngine = RazorProjectEngine.Create(razorSourceGeneratorOptions.Configuration, fileSystem, b =>
            {
                b.Features.Add(new DefaultTypeNameFeature());
                b.Features.Add(new ConfigureRazorCodeGenerationOptions(options =>
                {
                    options.SuppressPrimaryMethodBody = true;
                    options.SuppressChecksum          = true;
                }));

                b.SetRootNamespace(razorSourceGeneratorOptions.RootNamespace);

                CompilerFeatures.Register(b);
                RazorExtensions.Register(b);

                b.SetCSharpLanguageVersion(razorSourceGeneratorOptions.CSharpLanguageVersion);
            });

            return(discoveryProjectEngine);
        }
コード例 #4
0
        protected override async Task <UpgradeStepInitializeResult> InitializeImplAsync(IUpgradeContext context, CancellationToken token)
        {
            if (context is null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            _razorEngine = RazorProjectEngine.Create(RazorConfiguration.Default, GetRazorFileSystem(context.CurrentProject.Required()), builder =>
            {
                // Add useful "MVC View-isms" like _ViewImports support, page models, etc.
                // https://github.com/dotnet/aspnetcore/blob/main/src/Razor/Microsoft.AspNetCore.Mvc.Razor.Extensions/src/RazorExtensions.cs
                RazorExtensions.Register(builder);
            });

            // Process all Razor documents initially
            // SubSteps can call ProcessRazorDocuments with specific files that have changed later to re-process specific documents
            ProcessRazorDocuments(null);

            foreach (var step in SubSteps)
            {
                await step.InitializeAsync(context, token).ConfigureAwait(false);
            }

            var incompleteSubSteps = SubSteps.Count(s => !s.IsDone);

            return(incompleteSubSteps == 0
                ? new UpgradeStepInitializeResult(UpgradeStepStatus.Complete, "No Razor updaters need applied", BuildBreakRisk.None)
                : new UpgradeStepInitializeResult(UpgradeStepStatus.Incomplete, $"{incompleteSubSteps} Razor updaters need applied", SubSteps.Where(s => !s.IsDone).Max(s => s.Risk)));
        }
コード例 #5
0
        private static RazorTemplateEngineFactoryService CreateTemplateEngineFactory(
            string path = TestLinePragmaFileName,
            IEnumerable <TagHelperDescriptor> tagHelpers = null)
        {
            var engine = RazorEngine.CreateDesignTime(builder =>
            {
                RazorExtensions.Register(builder);

                if (tagHelpers != null)
                {
                    builder.AddTagHelpers(tagHelpers);
                }
            });

            // GetImports on RazorTemplateEngine will at least check that the item exists, so we need to pretend
            // that it does.
            var items = new List <RazorProjectItem>();

            items.Add(new TestRazorProjectItem(path));

            var project = new TestRazorProject(items);

            var templateEngine = new RazorTemplateEngine(engine, project);

            templateEngine.Options.DefaultImports = RazorSourceDocument.Create("@addTagHelper *, Test", "_TestImports.cshtml");

            var templateEngineFactory = Mock.Of <RazorTemplateEngineFactoryService>(
                service => service.Create(It.IsAny <string>(), It.IsAny <Action <IRazorEngineBuilder> >()) == templateEngine);

            return(templateEngineFactory);
        }
コード例 #6
0
ファイル: RazorSourceGenerator.cs プロジェクト: anynny9/sdk
        public void Execute(GeneratorExecutionContext context)
        {
            var razorContext = RazorSourceGenerationContext.Create(context);

            if (razorContext is null ||
                (razorContext.RazorFiles.Count == 0 && razorContext.CshtmlFiles.Count == 0))
            {
                return;
            }

            HandleDebugSwitch(razorContext.WaitForDebugger);

            var tagHelpers = ResolveTagHelperDescriptors(context, razorContext);

            var projectEngine = RazorProjectEngine.Create(razorContext.Configuration, razorContext.FileSystem, b =>
            {
                b.Features.Add(new DefaultTypeNameFeature());
                b.SetRootNamespace(razorContext.RootNamespace);

                b.Features.Add(new StaticTagHelperFeature {
                    TagHelpers = tagHelpers,
                });
                b.Features.Add(new DefaultTagHelperDescriptorProvider());

                CompilerFeatures.Register(b);
                RazorExtensions.Register(b);

                b.SetCSharpLanguageVersion(((CSharpParseOptions)context.ParseOptions).LanguageVersion);
            });

            CodeGenerateRazorComponents(context, razorContext, projectEngine);
            GenerateViews(context, razorContext, projectEngine);
        }
コード例 #7
0
        private static RazorTemplateEngine CreateTemplateEngine(
            string path = "C:\\This\\Path\\Is\\Just\\For\\Line\\Pragmas.cshtml",
            IEnumerable <TagHelperDescriptor> tagHelpers = null)
        {
            var engine = RazorEngine.CreateDesignTime(builder =>
            {
                RazorExtensions.Register(builder);

                if (tagHelpers != null)
                {
                    builder.AddTagHelpers(tagHelpers);
                }
            });

            // GetImports on RazorTemplateEngine will at least check that the item exists, so we need to pretend
            // that it does.
            var items = new List <RazorProjectItem>();

            items.Add(new TestRazorProjectItem(path));

            var project = new TestRazorProject(items);

            var templateEngine = new RazorTemplateEngine(engine, project);

            templateEngine.Options.DefaultImports = RazorSourceDocument.Create("@addTagHelper *, Test", "_TestImports.cshtml");
            return(templateEngine);
        }
コード例 #8
0
        public RazorTagHelperParsingBenchmark()
        {
            var current = new DirectoryInfo(AppContext.BaseDirectory);

            while (current != null && !File.Exists(Path.Combine(current.FullName, "taghelpers.json")))
            {
                current = current.Parent;
            }

            var root = current;

            var tagHelpers       = ReadTagHelpers(Path.Combine(root.FullName, "taghelpers.json"));
            var tagHelperFeature = new StaticTagHelperFeature(tagHelpers);

            var blazorServerTagHelpersFilePath = Path.Combine(root.FullName, "BlazorServerTagHelpers.razor");

            var fileSystem = RazorProjectFileSystem.Create(root.FullName);

            ProjectEngine = RazorProjectEngine.Create(RazorConfiguration.Default, fileSystem,
                                                      b =>
            {
                RazorExtensions.Register(b);
                b.Features.Add(tagHelperFeature);
            });
            BlazorServerTagHelpersDemoFile = fileSystem.GetItem(Path.Combine(blazorServerTagHelpersFilePath), FileKinds.Component);

            ComponentDirectiveVisitor = new ComponentDirectiveVisitor(blazorServerTagHelpersFilePath, tagHelpers, currentNamespace: null);
            var codeDocument = ProjectEngine.ProcessDesignTime(BlazorServerTagHelpersDemoFile);

            SyntaxTree = codeDocument.GetSyntaxTree();
        }
        private static RazorProjectEngineFactoryService CreateTemplateEngineFactory(
            string path = TestLinePragmaFileName,
            IEnumerable <TagHelperDescriptor> tagHelpers = null)
        {
            var fileSystem    = new TestRazorProjectFileSystem();
            var projectEngine = RazorProjectEngine.Create(RazorConfiguration.Default, fileSystem, builder =>
            {
                RazorExtensions.Register(builder);

                builder.AddDefaultImports(new TestRazorProjectItem("_TestImports.cshtml")
                {
                    Content = "@addTagHelper *, Test"
                });

                if (tagHelpers != null)
                {
                    builder.AddTagHelpers(tagHelpers);
                }
            });

            var projectEngineFactoryService = Mock.Of <RazorProjectEngineFactoryService>(
                service => service.Create(It.IsAny <string>(), It.IsAny <Action <RazorProjectEngineBuilder> >()) == projectEngine);

            return(projectEngineFactoryService);
        }
コード例 #10
0
        // Internal for testing.
        internal static void AddRazorViewEngineServices(IServiceCollection services)
        {
            services.TryAddSingleton <CSharpCompiler>();
            services.TryAddSingleton <RazorReferenceManager, DefaultRazorReferenceManager>();

            services.TryAddEnumerable(
                ServiceDescriptor.Transient <IConfigureOptions <MvcViewOptions>, MvcRazorMvcViewOptionsSetup>());

            services.TryAddEnumerable(
                ServiceDescriptor.Transient <IConfigureOptions <RazorViewEngineOptions>, RazorViewEngineOptionsSetup>());

            services.TryAddSingleton <
                IRazorViewEngineFileProviderAccessor,
                DefaultRazorViewEngineFileProviderAccessor>();

            services.TryAddSingleton <IRazorViewEngine, RazorViewEngine>();
            services.TryAddSingleton <IViewCompilerProvider, RazorViewCompilerProvider>();

            // In the default scenario the following services are singleton by virtue of being initialized as part of
            // creating the singleton RazorViewEngine instance.
            services.TryAddTransient <IRazorPageFactoryProvider, DefaultRazorPageFactoryProvider>();

            //
            // Razor compilation infrastructure
            //
            services.TryAddSingleton <RazorProject, FileProviderRazorProject>();
            services.TryAddSingleton <RazorTemplateEngine, MvcRazorTemplateEngine>();
            services.TryAddSingleton <LazyMetadataReferenceFeature>();

            services.TryAddSingleton(s =>
            {
                return(RazorEngine.Create(b =>
                {
                    RazorExtensions.Register(b);

                    // Roslyn + TagHelpers infrastructure
                    var metadataReferenceFeature = s.GetRequiredService <LazyMetadataReferenceFeature>();
                    b.Features.Add(metadataReferenceFeature);
                    b.Features.Add(new Microsoft.CodeAnalysis.Razor.CompilationTagHelperFeature());

                    // TagHelperDescriptorProviders (actually do tag helper discovery)
                    b.Features.Add(new Microsoft.CodeAnalysis.Razor.DefaultTagHelperDescriptorProvider());
                    b.Features.Add(new ViewComponentTagHelperDescriptorProvider());
                }));
            });

            // This caches Razor page activation details that are valid for the lifetime of the application.
            services.TryAddSingleton <IRazorPageActivator, RazorPageActivator>();

            // Only want one ITagHelperActivator so it can cache Type activation information. Types won't conflict.
            services.TryAddSingleton <ITagHelperActivator, DefaultTagHelperActivator>();
            services.TryAddSingleton <ITagHelperFactory, DefaultTagHelperFactory>();

            // TagHelperComponents manager
            services.TryAddScoped <ITagHelperComponentManager, TagHelperComponentManager>();

            // Consumed by the Cache tag helper to cache results across the lifetime of the application.
            services.TryAddSingleton <IMemoryCache, MemoryCache>();
        }
コード例 #11
0
        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) =>
            {
                RazorExtensions.Register(builder);

                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 razorTemplate  = compiledObject as RazorTemplateBase;

            string result = String.Empty;

            if (razorTemplate != null)
            {
                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
            });
        }
コード例 #12
0
        private static (RazorCodeDocument, DocumentSnapshot) CreateCodeDocumentAndSnapshot(SourceText text, string path, IReadOnlyList <TagHelperDescriptor>?tagHelpers = null, string?fileKind = default, bool allowDiagnostics = false)
        {
            fileKind ??= FileKinds.Component;
            tagHelpers ??= Array.Empty <TagHelperDescriptor>();
            if (fileKind == FileKinds.Component)
            {
                tagHelpers = tagHelpers.Concat(s_defaultComponents).ToArray();
            }

            var sourceDocument = text.GetRazorSourceDocument(path, path);

            // Yes I know "BlazorServer_31 is weird, but thats what is in the taghelpers.json file
            const string DefaultImports = @"
@using BlazorServer_31
@using BlazorServer_31.Pages
@using BlazorServer_31.Shared
@using Microsoft.AspNetCore.Components
@using Microsoft.AspNetCore.Components.Authorization
@using Microsoft.AspNetCore.Components.Routing
@using Microsoft.AspNetCore.Components.Web
";

            var importsPath       = new Uri("file:///path/to/_Imports.razor").AbsolutePath;
            var importsSourceText = SourceText.From(DefaultImports);
            var importsDocument   = importsSourceText.GetRazorSourceDocument(importsPath, importsPath);
            var importsSnapshot   = new Mock <DocumentSnapshot>(MockBehavior.Strict);

            importsSnapshot.Setup(d => d.GetTextAsync()).Returns(Task.FromResult(importsSourceText));
            importsSnapshot.Setup(d => d.FilePath).Returns(importsPath);
            importsSnapshot.Setup(d => d.TargetPath).Returns(importsPath);

            var projectEngine = RazorProjectEngine.Create(builder =>
            {
                builder.SetRootNamespace("Test");
                builder.Features.Add(new DefaultTypeNameFeature());
                RazorExtensions.Register(builder);
            });
            var codeDocument = projectEngine.ProcessDesignTime(sourceDocument, fileKind, new[] { importsDocument }, tagHelpers);

            if (!allowDiagnostics)
            {
                Assert.False(codeDocument.GetCSharpDocument().Diagnostics.Any(), "Error creating document:" + Environment.NewLine + string.Join(Environment.NewLine, codeDocument.GetCSharpDocument().Diagnostics));
            }

            var documentSnapshot = new Mock <DocumentSnapshot>(MockBehavior.Strict);

            documentSnapshot.Setup(d => d.GetGeneratedOutputAsync()).Returns(Task.FromResult(codeDocument));
            documentSnapshot.Setup(d => d.GetImports()).Returns(new[] { importsSnapshot.Object });
            documentSnapshot.Setup(d => d.Project.GetProjectEngine()).Returns(projectEngine);
            documentSnapshot.Setup(d => d.FilePath).Returns(path);
            documentSnapshot.Setup(d => d.TargetPath).Returns(path);
            documentSnapshot.Setup(d => d.Project.TagHelpers).Returns(tagHelpers);
            documentSnapshot.Setup(d => d.FileKind).Returns(fileKind);

            return(codeDocument, documentSnapshot.Object);
        }
コード例 #13
0
        public void Execute(GeneratorExecutionContext context)
        {
            var _razorContext = new RazorSourceGenerationContext(context);

            if (_razorContext is null)
            {
                context.ReportDiagnostic(Diagnostic.Create(RazorDiagnostics.InvalidRazorContextComputedDescriptor, Location.None));
                return;
            }

            if (_razorContext.RazorFiles.Count == 0 && _razorContext.CshtmlFiles.Count == 0)
            {
                return;
            }

            if (_razorContext.SuppressRazorSourceGenerator)
            {
                return;
            }

            HandleDebugSwitch(_razorContext.WaitForDebugger);

            var tagHelpers = ResolveTagHelperDescriptors(context, _razorContext);

            AssertOrFailFast(tagHelpers.Count == 0, "No tag helpers resolved.");

            var projectEngine = RazorProjectEngine.Create(_razorContext.Configuration, _razorContext.FileSystem, b =>
            {
                b.Features.Add(new DefaultTypeNameFeature());
                b.SetRootNamespace(_razorContext.RootNamespace);

                b.Features.Add(new ConfigureRazorCodeGenerationOptions(options =>
                {
                    options.SuppressMetadataSourceChecksumAttributes = !_razorContext.GenerateMetadataSourceChecksumAttributes;
                }));

                b.Features.Add(new StaticTagHelperFeature {
                    TagHelpers = tagHelpers,
                });
                b.Features.Add(new DefaultTagHelperDescriptorProvider());

                CompilerFeatures.Register(b);
                RazorExtensions.Register(b);

                b.SetCSharpLanguageVersion(((CSharpParseOptions)context.ParseOptions).LanguageVersion);
            });

            if (_razorContext.CshtmlFiles.Count != 0)
            {
                context.AddSource($"{context.Compilation.AssemblyName}.UnifiedAssembly.Info.g.cs", ProvideApplicationPartFactoryAttributeSourceText);
            }

            RazorGenerateForSourceTexts(_razorContext.CshtmlFiles, context, projectEngine);
            RazorGenerateForSourceTexts(_razorContext.RazorFiles, context, projectEngine);
        }
コード例 #14
0
        // Internal for testing.
        internal static void AddServices(IServiceCollection services)
        {
            services.TryAddEnumerable(
                ServiceDescriptor.Transient <IConfigureOptions <MvcRazorRuntimeCompilationOptions>, MvcRazorRuntimeCompilationOptionsSetup>());

            var compilerProvider = services.FirstOrDefault(f =>
                                                           f.ServiceType == typeof(IViewCompilerProvider) &&
                                                           f.ImplementationType?.Assembly == typeof(IViewCompilerProvider).Assembly &&
                                                           f.ImplementationType.FullName == "Microsoft.AspNetCore.Mvc.Razor.Compilation.DefaultViewCompilerProvider");

            if (compilerProvider != null)
            {
                // Replace the default implementation of IViewCompilerProvider
                services.Remove(compilerProvider);
            }

            services.TryAddSingleton <IViewCompilerProvider, RuntimeViewCompilerProvider>();

            services.TryAddSingleton <RuntimeCompilationFileProvider>();
            services.TryAddSingleton <RazorReferenceManager>();
            services.TryAddSingleton <CSharpCompiler>();

            services.TryAddSingleton <RazorProjectFileSystem, FileProviderRazorProjectFileSystem>();
            services.TryAddSingleton(s =>
            {
                var fileSystem     = s.GetRequiredService <RazorProjectFileSystem>();
                var csharpCompiler = s.GetRequiredService <CSharpCompiler>();
                var projectEngine  = RazorProjectEngine.Create(RazorConfiguration.Default, fileSystem, builder =>
                {
                    RazorExtensions.Register(builder);

                    // Roslyn + TagHelpers infrastructure
                    var referenceManager = s.GetRequiredService <RazorReferenceManager>();
                    builder.Features.Add(new LazyMetadataReferenceFeature(referenceManager));
                    builder.Features.Add(new CompilationTagHelperFeature());

                    // TagHelperDescriptorProviders (actually do tag helper discovery)
                    builder.Features.Add(new DefaultTagHelperDescriptorProvider());
                    builder.Features.Add(new ViewComponentTagHelperDescriptorProvider());
                    builder.SetCSharpLanguageVersion(csharpCompiler.ParseOptions.LanguageVersion);
                });

                return(projectEngine);
            });

            //
            // Razor Pages
            //
            services.TryAddEnumerable(
                ServiceDescriptor.Singleton <IPageRouteModelProvider, RazorProjectPageRouteModelProvider>());

            services.TryAddEnumerable(
                ServiceDescriptor.Singleton <IActionDescriptorChangeProvider, PageActionDescriptorChangeProvider>());
        }
コード例 #15
0
        protected RazorEngine CreateRuntimeEngine(CSharpCompilation compilation)
        {
            var references = compilation.References.Concat(new[] { compilation.ToMetadataReference() });

            return(RazorEngine.Create(b =>
            {
                RazorExtensions.Register(b);

                b.Features.Add(GetMetadataReferenceFeature(references));
                b.Features.Add(new CompilationTagHelperFeature());
            }));
        }
コード例 #16
0
        private int ExecuteCore(
            string projectDirectory,
            string tagHelperManifest,
            List <string> sources,
            List <string> outputs,
            List <string> relativePaths)
        {
            tagHelperManifest = Path.Combine(projectDirectory, tagHelperManifest);

            var tagHelpers = GetTagHelpers(tagHelperManifest);

            var engine = RazorEngine.Create(b =>
            {
                RazorExtensions.Register(b);

                b.Features.Add(new StaticTagHelperFeature()
                {
                    TagHelpers = tagHelpers,
                });
            });


            var inputItems       = GetInputItems(projectDirectory, sources, outputs, relativePaths);
            var compositeProject = new CompositeRazorProjectFileSystem(
                new[]
            {
                GetVirtualRazorProjectSystem(inputItems),
                RazorProjectFileSystem.Create(projectDirectory),
            });

            var templateEngine = new MvcRazorTemplateEngine(engine, compositeProject);

            var results = GenerateCode(templateEngine, inputItems);

            var success = true;

            foreach (var result in results)
            {
                if (result.CSharpDocument.Diagnostics.Count > 0)
                {
                    success = false;
                    foreach (var error in result.CSharpDocument.Diagnostics)
                    {
                        Console.Error.WriteLine(error.ToString());
                    }
                }

                var outputFilePath = result.InputItem.OutputPath;
                File.WriteAllText(outputFilePath, result.CSharpDocument.GeneratedCode);
            }

            return(success ? 0 : -1);
        }
コード例 #17
0
ファイル: DiscoverCommand.cs プロジェクト: agametov/Razor
        private int ExecuteCore(string projectDirectory, string outputFilePath, string[] assemblies)
        {
            outputFilePath = Path.Combine(projectDirectory, outputFilePath);

            var metadataReferences = new MetadataReference[assemblies.Length];

            for (var i = 0; i < assemblies.Length; i++)
            {
                metadataReferences[i] = MetadataReference.CreateFromFile(assemblies[i]);
            }

            var engine = RazorEngine.Create((b) =>
            {
                RazorExtensions.Register(b);

                b.Features.Add(new DefaultMetadataReferenceFeature()
                {
                    References = metadataReferences
                });
                b.Features.Add(new CompilationTagHelperFeature());

                // TagHelperDescriptorProviders (actually do tag helper discovery)
                b.Features.Add(new DefaultTagHelperDescriptorProvider());
                b.Features.Add(new ViewComponentTagHelperDescriptorProvider());
            });

            var feature    = engine.Features.OfType <ITagHelperFeature>().Single();
            var tagHelpers = feature.GetDescriptors();

            using (var stream = new MemoryStream())
            {
                Serialize(stream, tagHelpers);

                stream.Position = 0L;

                var newHash      = Hash(stream);
                var existingHash = Hash(outputFilePath);

                if (!HashesEqual(newHash, existingHash))
                {
                    stream.Position = 0;
                    using (var output = File.OpenWrite(outputFilePath))
                    {
                        stream.CopyTo(output);
                    }
                }
            }

            return(0);
        }
コード例 #18
0
        protected RazorProjectEngine CreateEngine(CSharpCompilation compilation)
        {
            var references = compilation.References.Concat(new[] { compilation.ToMetadataReference() });

            return(CreateProjectEngine(b =>
            {
                RazorExtensions.Register(b);

                var existingImportFeature = b.Features.OfType <IImportProjectFeature>().Single();
                b.SetImportFeature(new NormalizedDefaultImportFeature(existingImportFeature));

                b.Features.Add(GetMetadataReferenceFeature(references));
                b.Features.Add(new CompilationTagHelperFeature());
            }));
        }
コード例 #19
0
    public override void Initialize(RazorProjectEngineBuilder builder)
    {
        if (builder == null)
        {
            throw new ArgumentNullException(nameof(builder));
        }

        if (builder.Configuration.ConfigurationName == "MVC-1.0")
        {
            RazorExtensions.Register(builder);
        }
        else if (builder.Configuration.ConfigurationName == "MVC-1.1")
        {
            RazorExtensions.Register(builder);
            RazorExtensions.RegisterViewComponentTagHelpers(builder);
        }
    }
コード例 #20
0
        protected RazorEngine CreateRuntimeEngine(IEnumerable <MetadataReference> references)
        {
            return(RazorEngine.Create(b =>
            {
                RazorExtensions.Register(b);

                b.Features.Add(GetMetadataReferenceFeature(references));
                b.Features.Add(new CompilationTagHelperFeature());
                b.Features.Add(new DefaultTagHelperDescriptorProvider()
                {
                    DesignTime = true
                });
                b.Features.Add(new ViewComponentTagHelperDescriptorProvider()
                {
                    ForceEnabled = true
                });
            }));
        }
コード例 #21
0
        private static RazorProjectEngine GetDiscoveryProjectEngine(
            IReadOnlyList <MetadataReference> references,
            StaticCompilationTagHelperFeature tagHelperFeature)
        {
            var discoveryProjectEngine = RazorProjectEngine.Create(RazorConfiguration.Default, new VirtualRazorProjectFileSystem(), b =>
            {
                b.Features.Add(new DefaultMetadataReferenceFeature {
                    References = references
                });
                b.Features.Add(tagHelperFeature);
                b.Features.Add(new DefaultTagHelperDescriptorProvider());

                CompilerFeatures.Register(b);
                RazorExtensions.Register(b);
            });

            return(discoveryProjectEngine);
        }
コード例 #22
0
        private static RazorProjectEngine CreateProjectEngine(
            IEnumerable <TagHelperDescriptor> tagHelpers = null)
        {
            var fileSystem    = new TestRazorProjectFileSystem();
            var projectEngine = RazorProjectEngine.Create(RazorConfiguration.Default, fileSystem, builder =>
            {
                RazorExtensions.Register(builder);

                builder.AddDefaultImports("@addTagHelper *, Test");

                if (tagHelpers != null)
                {
                    builder.AddTagHelpers(tagHelpers);
                }
            });

            return(projectEngine);
        }
コード例 #23
0
        private static RazorProjectEngine GetEngine()
        {
            var options = Options.Create(new MvcRazorRuntimeCompilationOptions {
                FileProviders = { new TestFileProvider() }
            });
            var compilationFileProvider = new PublicRuntimeCompilationFileProvider(options);


            var referenceManager = CreateReferenceManager();
            var precompiledViews = Array.Empty <CompiledViewDescriptor>();

            var hostingEnvironment = Mock.Of <IWebHostEnvironment>(e => e.ContentRootPath == "BasePath");
            var fileSystem         = new PublicFileProviderRazorProjectFileSystem(compilationFileProvider);
            var projectEngine      = RazorProjectEngine.Create(RazorConfiguration.Default, fileSystem, builder => {
                RazorExtensions.Register(builder);
            });

            return(projectEngine);
        }
コード例 #24
0
        private static RazorProjectEngine CreateProjectEngine(
            string path = "C:\\This\\Path\\Is\\Just\\For\\Line\\Pragmas.cshtml",
            IEnumerable <TagHelperDescriptor> tagHelpers = null)
        {
            var fileSystem    = new TestRazorProjectFileSystem();
            var projectEngine = RazorProjectEngine.Create(RazorConfiguration.Default, fileSystem, builder =>
            {
                RazorExtensions.Register(builder);

                builder.AddDefaultImports("@addTagHelper *, Test");

                if (tagHelpers != null)
                {
                    builder.AddTagHelpers(tagHelpers);
                }
            });

            return(projectEngine);
        }
        public override RazorTemplateEngine Create(string projectPath, Action <IRazorEngineBuilder> configure)
        {
            if (projectPath == null)
            {
                throw new ArgumentNullException(nameof(projectPath));
            }

            var engine = RazorEngine.CreateDesignTime(b =>
            {
                configure?.Invoke(b);

                // For now we're hardcoded to use MVC's extensibility.
                RazorExtensions.Register(b);
            });

            var templateEngine = new MvcRazorTemplateEngine(engine, RazorProject.Create(projectPath));

            templateEngine.Options.ImportsFileName = "_ViewImports.cshtml";
            return(templateEngine);
        }
コード例 #26
0
        private static RazorProjectEngine GetEngine(PublicCSharpCompiler csharpCompiler,
                                                    PublicRazorReferenceManager referenceManager,
                                                    PublicFileProviderRazorProjectFileSystem projectFileSystem,
                                                    string assemblyName)
        {
            var engineConfig = RazorConfiguration.Create(RazorLanguageVersion.Latest, assemblyName, Array.Empty <RazorExtension>());

            return(RazorProjectEngine.Create(engineConfig, projectFileSystem, builder => {
                RazorExtensions.Register(builder);

                // Roslyn + TagHelpers infrastructure
                builder.Features.Add(new PublicLazyMetadataReferenceFeature(referenceManager));
                builder.Features.Add(new CompilationTagHelperFeature());

                // TagHelperDescriptorProviders (actually do tag helper discovery)
                builder.Features.Add(new DefaultTagHelperDescriptorProvider());
                builder.Features.Add(new ViewComponentTagHelperDescriptorProvider());
                builder.SetCSharpLanguageVersion(csharpCompiler.ParseOptions.LanguageVersion);
            }));
        }
コード例 #27
0
        private static TestRazorViewCompiler GetViewCompiler(
            TestFileProvider fileProvider = null,
            Action <RoslynCompilationContext> compilationCallback = null,
#pragma warning disable CS0618 // Type or member is obsolete
            RazorReferenceManager referenceManager = null,
#pragma warning restore CS0618 // Type or member is obsolete
            IList <CompiledViewDescriptor> precompiledViews = null,
            CSharpCompiler csharpCompiler = null)
        {
            fileProvider = fileProvider ?? new TestFileProvider();
            var accessor = Mock.Of <IRazorViewEngineFileProviderAccessor>(a => a.FileProvider == fileProvider);

            compilationCallback = compilationCallback ?? (_ => { });
            var options = Options.Create(new RazorViewEngineOptions());

            if (referenceManager == null)
            {
                referenceManager = CreateReferenceManager(options);
            }

            precompiledViews = precompiledViews ?? Array.Empty <CompiledViewDescriptor>();

            var hostingEnvironment = Mock.Of <IHostingEnvironment>(e => e.ContentRootPath == "BasePath");
            var fileSystem         = new FileProviderRazorProjectFileSystem(accessor, hostingEnvironment);
            var projectEngine      = RazorProjectEngine.Create(RazorConfiguration.Default, fileSystem, builder =>
            {
                RazorExtensions.Register(builder);
            });

            csharpCompiler = csharpCompiler ?? new CSharpCompiler(referenceManager, hostingEnvironment);

            var viewCompiler = new TestRazorViewCompiler(
                fileProvider,
                projectEngine,
                csharpCompiler,
                compilationCallback,
                precompiledViews);

            return(viewCompiler);
        }
コード例 #28
0
        private RazorProjectEngineFactoryService GetProjectEngineFactoryService()
        {
            var projectManager = new Mock <ProjectSnapshotManager>();

            projectManager.Setup(p => p.Projects).Returns(Array.Empty <ProjectSnapshot>());

            var projectEngineFactory = new Mock <IFallbackProjectEngineFactory>();

            projectEngineFactory.Setup(s => s.Create(It.IsAny <RazorConfiguration>(), It.IsAny <RazorProjectFileSystem>(), It.IsAny <Action <RazorProjectEngineBuilder> >()))
            .Returns <RazorConfiguration, RazorProjectFileSystem, Action <RazorProjectEngineBuilder> >(
                (c, fs, b) => RazorProjectEngine.Create(
                    RazorConfiguration.Default,
                    fs,
                    builder => RazorExtensions.Register(builder)));

            var service = new DefaultProjectEngineFactoryService(
                projectManager.Object,
                projectEngineFactory.Object,
                new Lazy <IProjectEngineFactory, ICustomProjectEngineFactoryMetadata> [0]);

            return(service);
        }
コード例 #29
0
        private static ProjectSnapshotProjectEngineFactory CreateProjectEngineFactory(
            string path = TestLinePragmaFileName,
            IEnumerable <TagHelperDescriptor> tagHelpers = null)
        {
            var fileSystem    = new TestRazorProjectFileSystem();
            var projectEngine = RazorProjectEngine.Create(RazorConfiguration.Default, fileSystem, builder =>
            {
                RazorExtensions.Register(builder);

                builder.AddDefaultImports("@addTagHelper *, Test");

                if (tagHelpers != null)
                {
                    builder.AddTagHelpers(tagHelpers);
                }
            });

            return(new TestProjectSnapshotProjectEngineFactory()
            {
                Engine = projectEngine,
            });
        }
コード例 #30
0
        private static TestRazorViewCompiler GetViewCompiler(
            TestFileProvider fileProvider = null,
            Action <RoslynCompilationContext> compilationCallback = null,
            RazorReferenceManager referenceManager          = null,
            IList <CompiledViewDescriptor> precompiledViews = null)
        {
            fileProvider = fileProvider ?? new TestFileProvider();
            var accessor = Mock.Of <IRazorViewEngineFileProviderAccessor>(a => a.FileProvider == fileProvider);

            compilationCallback = compilationCallback ?? (_ => { });
            var options = Options.Create(new RazorViewEngineOptions());

            if (referenceManager == null)
            {
                var applicationPartManager = new ApplicationPartManager();
                var assembly = typeof(RazorViewCompilerTest).Assembly;
                applicationPartManager.ApplicationParts.Add(new AssemblyPart(assembly));
                applicationPartManager.FeatureProviders.Add(new MetadataReferenceFeatureProvider());

                referenceManager = new DefaultRazorReferenceManager(applicationPartManager, options);
            }

            precompiledViews = precompiledViews ?? Array.Empty <CompiledViewDescriptor>();

            var hostingEnvironment = Mock.Of <IHostingEnvironment>(e => e.ContentRootPath == "BasePath");
            var fileSystem         = new FileProviderRazorProjectFileSystem(accessor, hostingEnvironment);
            var projectEngine      = RazorProjectEngine.Create(RazorConfiguration.Default, fileSystem, builder =>
            {
                RazorExtensions.Register(builder);
            });
            var viewCompiler = new TestRazorViewCompiler(
                fileProvider,
                projectEngine,
                new CSharpCompiler(referenceManager, hostingEnvironment),
                compilationCallback,
                precompiledViews);

            return(viewCompiler);
        }