public void GetIdentifier_ReturnsNull_ForEmptyRelativePath() { // Arrange var sourceDocument = RazorSourceDocument.Create("content", new RazorSourceDocumentProperties("Test.cshtml", string.Empty)); var codeDocument = RazorCodeDocument.Create(sourceDocument); var feature = new DefaultMetadataIdentifierFeature() { Engine = RazorProjectEngine.Create().Engine, }; // Act var result = feature.GetIdentifier(codeDocument, sourceDocument); // Assert Assert.Null(result); }
public RazorProjectEngine Create(RazorConfiguration configuration, RazorProjectFileSystem fileSystem, Action <RazorProjectEngineBuilder> configure) { // Rewrite the assembly name into a full name just like this one, but with the name of the MVC design time assembly. var assemblyName = new AssemblyName(typeof(RazorProjectEngine).Assembly.FullName) { Name = AssemblyName }; var extension = new AssemblyExtension(configuration.ConfigurationName, Assembly.Load(assemblyName)); var initializer = extension.CreateInitializer(); return(RazorProjectEngine.Create(configuration, fileSystem, b => { initializer.Initialize(b); configure?.Invoke(b); })); }
private int ExecuteCore(RazorConfiguration configuration, 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] = Parent.AssemblyReferenceProvider(assemblies[i], default(MetadataReferenceProperties)); } var engine = RazorProjectEngine.Create(configuration, RazorProjectFileSystem.Empty, b => { b.Features.Add(new DefaultMetadataReferenceFeature() { References = metadataReferences }); b.Features.Add(new CompilationTagHelperFeature()); b.Features.Add(new DefaultTagHelperDescriptorProvider()); b.Features.Add(new ComponentTagHelperDescriptorProvider()); }); var feature = engine.Engine.Features.OfType <ITagHelperFeature>().Single(); var tagHelpers = feature.GetDescriptors(); using (var stream = new MemoryStream()) { Serialize(stream, tagHelpers); stream.Position = 0; var newHash = Hash(stream); var existingHash = Hash(outputFilePath); if (!HashesEqual(newHash, existingHash)) { stream.Position = 0; using (var output = File.Open(outputFilePath, FileMode.Create)) { stream.CopyTo(output); } } } return(ExitCodeSuccess); }
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); }
private static RazorCodeDocument CreateCodeDocument(string text) { var projectItem = new TestRazorProjectItem("c:/Test.razor", "c:/Test.razor", "Test.razor") { Content = text }; var projectEngine = RazorProjectEngine.Create(RazorConfiguration.Default, TestRazorProjectFileSystem.Empty, (builder) => { builder.SetRootNamespace("test.Pages"); }); var codeDocument = projectEngine.Process(projectItem); codeDocument.SetFileKind(FileKinds.Component); return(codeDocument); }
public ComponentMarkupBlockPassTest() { Pass = new ComponentMarkupBlockPass(); ProjectEngine = (DefaultRazorProjectEngine)RazorProjectEngine.Create( RazorConfiguration.Default, RazorProjectFileSystem.Create(Environment.CurrentDirectory), b => { if (b.Features.OfType <ComponentMarkupBlockPass>().Any()) { b.Features.Remove(b.Features.OfType <ComponentMarkupBlockPass>().Single()); } }); Engine = ProjectEngine.Engine; Pass.Engine = Engine; }
public RazorProjectEngine CreateRazorProjectEngine(IReadOnlyList <MetadataReference> references) { Console.WriteLine("CreateRazorProjectEngine"); return(RazorProjectEngine.Create(_config, _fileSystem, builder => { builder.SetRootNamespace(DefaultRootNamespace); builder.AddDefaultImports(RazorConstants.DefaultUsings); // Features that use Roslyn are mandatory for components CompilerFeatures.Register(builder); builder.Features.Add(new CompilationTagHelperFeature()); builder.Features.Add(new DefaultMetadataReferenceFeature { References = references }); })); }
private static RazorCodeDocument CreateCodeDocument(string text) { var fileName = "Test.razor"; var filePath = $"c:/{fileName}"; var projectItem = new TestRazorProjectItem(filePath, filePath, fileName) { Content = text }; var projectEngine = RazorProjectEngine.Create(RazorConfiguration.Default, TestRazorProjectFileSystem.Empty, (builder) => { PageDirective.Register(builder); }); var codeDocument = projectEngine.Process(projectItem); codeDocument.SetFileKind(FileKinds.Component); return(codeDocument); }
public void SetCSharpLanguageVersion_ResolvesNonNumericCSharpLangVersions() { // Arrange var csharpLanguageVersion = CSharp.LanguageVersion.Latest; // Act var projectEngine = RazorProjectEngine.Create(builder => { builder.SetCSharpLanguageVersion(csharpLanguageVersion); }); // Assert var feature = projectEngine.EngineFeatures.OfType <ConfigureParserForCSharpVersionFeature>().FirstOrDefault(); Assert.NotNull(feature); Assert.NotEqual(csharpLanguageVersion, feature.CSharpLanguageVersion); }
public BackgroundThread(MainThreadState main, RazorProjectEngine projectEngine, string filePath, string projectDirectory, string fileKind) { // Run on MAIN thread! _main = main; _shutdownToken = _main.CancelToken; _projectEngine = projectEngine; _filePath = filePath; _relativeFilePath = GetNormalizedRelativeFilePath(filePath, projectDirectory); _projectDirectory = projectDirectory; _fileKind = fileKind; _backgroundThread = new Thread(WorkerLoop) { Name = "Razor Background Document Parser" }; SetThreadId(_backgroundThread.ManagedThreadId); }
public void GetIdentifier_SanitizesRelativePath(string relativePath, string expected) { // Arrange var sourceDocument = RazorSourceDocument.Create("content", new RazorSourceDocumentProperties("Test.cshtml", relativePath)); var codeDocument = RazorCodeDocument.Create(sourceDocument); var feature = new DefaultMetadataIdentifierFeature() { Engine = RazorProjectEngine.Create().Engine, }; // Act var result = feature.GetIdentifier(codeDocument, sourceDocument); // Assert Assert.Equal(expected, result); }
public async Task Handle_AddOneUsingToPageDirective() { // Arrange var documentPath = "c:/Test.cshtml"; var documentUri = new Uri(documentPath); var contents = $"@page{Environment.NewLine}@model IndexModel"; var projectItem = new TestRazorProjectItem("c:/Test.cshtml", "c:/Test.cshtml", "Test.cshtml") { Content = contents }; var projectEngine = RazorProjectEngine.Create(RazorConfiguration.Default, TestRazorProjectFileSystem.Empty, (builder) => { PageDirective.Register(builder); ModelDirective.Register(builder); }); var codeDocument = projectEngine.Process(projectItem); codeDocument.SetFileKind(FileKinds.Legacy); var resolver = new AddUsingsCodeActionResolver(LegacyDispatcher, CreateDocumentResolver(documentPath, codeDocument)); var actionParams = new AddUsingsCodeActionParams { Uri = documentUri, Namespace = "System" }; var data = JObject.FromObject(actionParams); // Act var workspaceEdit = await resolver.ResolveAsync(data, default); // Assert Assert.NotNull(workspaceEdit); Assert.NotNull(workspaceEdit.DocumentChanges); Assert.Single(workspaceEdit.DocumentChanges); var documentChanges = workspaceEdit.DocumentChanges.ToArray(); var addUsingsChange = documentChanges[0]; Assert.True(addUsingsChange.IsTextDocumentEdit); var firstEdit = Assert.Single(addUsingsChange.TextDocumentEdit.Edits); Assert.Equal(1, firstEdit.Range.Start.Line); Assert.Equal($"@using System{Environment.NewLine}", firstEdit.NewText); }
public CSharpScriptRazorGenerator(string directoryRoot) { var fileSystem = RazorProjectFileSystem.Create(directoryRoot); var projectEngine = RazorProjectEngine.Create(RazorConfiguration.Default, fileSystem, builder => { // Register directives. SectionDirective.Register(builder); // We replace the default document classifier, because we can't have namespace declaration ins script. var defaultDocumentClassifier = builder.Features .OfType <IRazorDocumentClassifierPass>() .FirstOrDefault(x => x.Order == 1000); builder.Features.Remove(defaultDocumentClassifier); builder.Features.Add(new CSharpScriptDocumentClassifierPass()); }); _projectEngine = projectEngine; }
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); }
public TestRazorViewCompiler( TestFileProvider fileProvider, RazorProjectEngine projectEngine, CSharpCompiler csharpCompiler, IList <CompiledViewDescriptor> precompiledViews, Func <string, CompiledViewDescriptor> compile = null) : base(fileProvider, projectEngine, csharpCompiler, precompiledViews, NullLogger.Instance) { Compile = compile; if (Compile == null) { Compile = path => new CompiledViewDescriptor { RelativePath = path, Item = CreateForView(path), }; } }
public HtmlBlockPassTest() { Pass = new HtmlBlockPass(); Engine = RazorProjectEngine.Create( BlazorExtensionInitializer.DefaultConfiguration, RazorProjectFileSystem.Create(Environment.CurrentDirectory), b => { BlazorExtensionInitializer.Register(b); if (b.Features.OfType <HtmlBlockPass>().Any()) { b.Features.Remove(b.Features.OfType <HtmlBlockPass>().Single()); } }).Engine; Pass.Engine = Engine; }
public void GenerateCodeWithSetNamespace() { // Arrange var fileSystem = new DefaultRazorProjectFileSystem(TestProjectRoot); var razorEngine = RazorProjectEngine.Create(engine => { engine.Features.Add(new SuppressChecksumOptionsFeature()); engine.SetNamespace("MyApp.Razor.Views"); }).Engine; var templateEngine = new RazorTemplateEngine(razorEngine, fileSystem); // Act var cSharpDocument = templateEngine.GenerateCode($"{FileName}.cshtml"); // Assert AssertCSharpDocumentMatchesBaseline(cSharpDocument); }
private OutputItem[] GenerateCode(RazorProjectEngine engine, SourceItem[] inputs) { var outputs = new OutputItem[inputs.Length]; Parallel.For(0, outputs.Length, new ParallelOptions() { MaxDegreeOfParallelism = Debugger.IsAttached ? 1 : 4 }, i => { var inputItem = inputs[i]; var codeDocument = engine.Process(engine.FileSystem.GetItem(inputItem.FilePath)); var csharpDocument = codeDocument.GetCSharpDocument(); outputs[i] = new OutputItem(inputItem, csharpDocument); }); return(outputs); }
public void Execute_AddsSyntaxTree() { // Arrange var phase = new DefaultRazorParsingPhase(); var engine = RazorProjectEngine.CreateEmpty(builder => { builder.Phases.Add(phase); builder.Features.Add(new DefaultRazorParserOptionsFeature(designTime: false, version: RazorLanguageVersion.Latest, fileKind: null)); }); var codeDocument = TestRazorCodeDocument.CreateEmpty(); // Act phase.Execute(codeDocument); // Assert Assert.NotNull(codeDocument.GetSyntaxTree()); }
private static (RazorCodeDocument, DocumentSnapshot) CreateCodeDocumentAndSnapshot(SourceText text, string path, IReadOnlyList <TagHelperDescriptor> tagHelpers = null, string fileKind = default) { fileKind ??= FileKinds.Component; tagHelpers ??= Array.Empty <TagHelperDescriptor>(); var sourceDocument = text.GetRazorSourceDocument(path, path); var projectEngine = RazorProjectEngine.Create(builder => { builder.SetRootNamespace("Test"); }); var codeDocument = projectEngine.ProcessDesignTime(sourceDocument, fileKind, Array.Empty <RazorSourceDocument>(), tagHelpers); var documentSnapshot = new Mock <DocumentSnapshot>(); documentSnapshot.Setup(d => d.GetGeneratedOutputAsync()).Returns(Task.FromResult(codeDocument)); documentSnapshot.Setup(d => d.Project.GetProjectEngine()).Returns(projectEngine); 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); }
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); }
public TestRazorViewCompiler( RazorProjectEngine projectEngine, PublicCSharpCompiler csharpCompiler, IList <CompiledViewDescriptor> precompiledViews, Func <string, CompiledViewDescriptor> compile = null) : base(new Dictionary <string, RazorProjectEngine> { { "default", projectEngine } }, csharpCompiler, precompiledViews, NullLogger.Instance) { Compile = compile; if (Compile == null) { Compile = path => new CompiledViewDescriptor { RelativePath = path, Item = CreateForView(path), }; } }
// Consumed from CodeGen internal static string ToCSharp(string source, Action <RazorProjectEngineBuilder>?configure = null) { // For some reason Razor engine ignores @namespace directive if // the file system is not configured properly. // So to work around it, we "parse" it ourselves. var actualNamespace = TryGetNamespace(source) ?? "MiniRazor.GeneratedTemplates"; var engine = RazorProjectEngine.Create( RazorConfiguration.Default, EmptyRazorProjectFileSystem.Instance, options => { options.SetNamespace(actualNamespace); options.SetBaseType("MiniRazor.TemplateBase<dynamic>"); options.ConfigureClass((_, node) => { node.Modifiers.Clear(); // Internal to allow referencing internal types inside node.Modifiers.Add("internal"); // Partial to allow extension node.Modifiers.Add("partial"); }); configure?.Invoke(options); } ); var sourceDocument = RazorSourceDocument.Create( source, $"MiniRazor_GeneratedTemplate_{Guid.NewGuid()}.cs" ); var codeDocument = engine.Process( sourceDocument, null, Array.Empty <RazorSourceDocument>(), Array.Empty <TagHelperDescriptor>() ); return(codeDocument.GetCSharpDocument().GeneratedCode); }
private static RazorCodeActionContext CreateRazorCodeActionContext( CodeActionParams request, SourceLocation location, string filePath, string text, SourceSpan componentSourceSpan, bool supportsFileCreation = true, bool supportsCodeActionResolve = true) { var shortComponent = TagHelperDescriptorBuilder.Create(ComponentMetadata.Component.TagHelperKind, "Fully.Qualified.Component", "TestAssembly"); shortComponent.TagMatchingRule(rule => rule.TagName = "Component"); var fullyQualifiedComponent = TagHelperDescriptorBuilder.Create(ComponentMetadata.Component.TagHelperKind, "Fully.Qualified.Component", "TestAssembly"); fullyQualifiedComponent.TagMatchingRule(rule => rule.TagName = "Fully.Qualified.Component"); var tagHelpers = new[] { shortComponent.Build(), fullyQualifiedComponent.Build() }; var sourceDocument = TestRazorSourceDocument.Create(text, filePath: filePath, relativePath: filePath); var projectEngine = RazorProjectEngine.Create(builder => { builder.AddTagHelpers(tagHelpers); builder.AddDirective(InjectDirective.Directive); }); var codeDocument = projectEngine.ProcessDesignTime(sourceDocument, FileKinds.Component, Array.Empty <RazorSourceDocument>(), tagHelpers); var cSharpDocument = codeDocument.GetCSharpDocument(); var diagnosticDescriptor = new RazorDiagnosticDescriptor("RZ10012", () => "", RazorDiagnosticSeverity.Error); var diagnostic = RazorDiagnostic.Create(diagnosticDescriptor, componentSourceSpan); var cSharpDocumentWithDiagnostic = RazorCSharpDocument.Create(cSharpDocument.GeneratedCode, cSharpDocument.Options, new[] { diagnostic }); codeDocument.SetCSharpDocument(cSharpDocumentWithDiagnostic); var documentSnapshot = Mock.Of <DocumentSnapshot>(document => document.GetGeneratedOutputAsync() == Task.FromResult(codeDocument) && document.GetTextAsync() == Task.FromResult(codeDocument.GetSourceText()) && document.Project.TagHelpers == tagHelpers, MockBehavior.Strict); var sourceText = SourceText.From(text); var context = new RazorCodeActionContext(request, documentSnapshot, codeDocument, location, sourceText, supportsFileCreation, supportsCodeActionResolve: supportsCodeActionResolve); return(context); }
private DocumentIntermediateNode Lower(RazorCodeDocument codeDocument, RazorProjectEngine projectEngine) { 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); }
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); }
private TestCompiledPageRouteModelProvider CreateProvider( RazorPagesOptions options = null, IList <CompiledViewDescriptor> descriptors = null, VirtualRazorProjectFileSystem fileSystem = null) { options = options ?? new RazorPagesOptions(); fileSystem = fileSystem ?? new VirtualRazorProjectFileSystem(); var projectEngine = RazorProjectEngine.Create(RazorConfiguration.Default, fileSystem); var provider = new TestCompiledPageRouteModelProvider( new ApplicationPartManager(), Options.Create(options), projectEngine, NullLogger <CompiledPageRouteModelProvider> .Instance); provider.Descriptors.AddRange(descriptors ?? Array.Empty <CompiledViewDescriptor>()); return(provider); }
public void Execute_NoOps_IfNamespaceNodeIsMissing() { // Arrange var irDocument = new DocumentIntermediateNode() { Options = RazorCodeGenerationOptions.CreateDefault(), }; var pass = new AssemblyAttributeInjectionPass { Engine = RazorProjectEngine.Create().Engine, }; // Act pass.Execute(TestRazorCodeDocument.CreateEmpty(), irDocument); // Assert Assert.Empty(irDocument.Children); }
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); }
private static DocumentIntermediateNode Lower(RazorCodeDocument codeDocument, RazorProjectEngine projectEngine) { for (var i = 0; i < projectEngine.Phases.Count; i++) { var phase = projectEngine.Phases[i]; phase.Execute(codeDocument); if (phase is IRazorDocumentClassifierPhase) { break; } } var irDocument = codeDocument.GetDocumentIntermediateNode(); Assert.NotNull(irDocument); return(irDocument); }