示例#1
0
        public void DocumentProcessed_DoesNothingIfAlreadySynchronized()
        {
            // Arrange
            var router          = new TestRouter();
            var documentVersion = VersionStamp.Default.GetNewerVersion();
            var document        = TestDocumentSnapshot.Create("C:/path/file.cshtml", documentVersion);
            var cache           = new TestDocumentVersionCache(new Dictionary <DocumentSnapshot, long>()
            {
                [document] = 1337,
            });
            var csharpDocument = RazorCSharpDocument.Create("Anything", RazorCodeGenerationOptions.CreateDefault(), Enumerable.Empty <RazorDiagnostic>());

            // Force the state to already be up-to-date
            document.State.HostDocument.GeneratedCodeContainer.SetOutput(document, csharpDocument, documentVersion.GetNewerVersion(), VersionStamp.Default);

            var listener = new UnsynchronizableContentDocumentProcessedListener(Dispatcher, cache, router);

            listener.Initialize(ProjectSnapshotManager);

            // Act
            listener.DocumentProcessed(document);

            // Assert
            Assert.Empty(router.SynchronizedDocuments);
        }
示例#2
0
        public void DocumentProcessed_SynchronizesIfSourceVersionsAreIdenticalButSyncVersionNewer()
        {
            // Arrange
            var router       = new TestRouter();
            var lastVersion  = VersionStamp.Default.GetNewerVersion();
            var lastDocument = TestDocumentSnapshot.Create("C:/path/old.cshtml", lastVersion);
            var document     = TestDocumentSnapshot.Create("C:/path/file.cshtml", lastVersion);
            var cache        = new TestDocumentVersionCache(new Dictionary <DocumentSnapshot, long>()
            {
                [document]     = 1338,
                [lastDocument] = 1337,
            });
            var csharpDocument = RazorCSharpDocument.Create("Anything", RazorCodeGenerationOptions.CreateDefault(), Enumerable.Empty <RazorDiagnostic>());

            // Force the state to already be up-to-date
            document.State.HostDocument.GeneratedCodeContainer.SetOutput(lastDocument, csharpDocument, lastVersion, VersionStamp.Default);

            var listener = new UnsynchronizableContentDocumentProcessedListener(Dispatcher, cache, router);

            listener.Initialize(ProjectSnapshotManager);

            // Act
            listener.DocumentProcessed(document);

            // Assert
            var filePath = Assert.Single(router.SynchronizedDocuments);

            Assert.Equal(document.FilePath, filePath);
        }
示例#3
0
        private static RazorCodeActionContext CreateRazorCodeActionContext(RazorCodeActionParams request, SourceLocation location, string filePath, string text, SourceSpan componentSourceSpan, bool supportsFileCreation = 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);
            });
            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);

            var sourceText = SourceText.From(text);

            var context = new RazorCodeActionContext(request, documentSnapshot, codeDocument, location, sourceText, supportsFileCreation);

            return(context);
        }
示例#4
0
 public OutputItem(
     SourceItem inputItem,
     RazorCSharpDocument cSharpDocument)
 {
     InputItem      = inputItem;
     CSharpDocument = cSharpDocument;
 }
示例#5
0
 public ViewCompilationInfo(
     ViewFileInfo viewFileInfo,
     RazorCSharpDocument cSharpDocument)
 {
     ViewFileInfo   = viewFileInfo;
     CSharpDocument = cSharpDocument;
 }
        public void ReportUnsynchronizableContent_DoesNothingForOlderDocuments()
        {
            // Arrange
            var router       = new TestRouter();
            var lastVersion  = VersionStamp.Default.GetNewerVersion();
            var lastDocument = TestDocumentSnapshot.Create("C:/path/old.cshtml", lastVersion);
            var oldDocument  = TestDocumentSnapshot.Create("C:/path/file.cshtml", VersionStamp.Default);
            var cache        = new TestDocumentVersionCache(new Dictionary <DocumentSnapshot, long>()
            {
                [oldDocument]  = 1337,
                [lastDocument] = 1338,
            });
            var csharpDocument = RazorCSharpDocument.Create("Anything", RazorCodeGenerationOptions.CreateDefault(), Enumerable.Empty <RazorDiagnostic>());

            // Force the state to already be up-to-date
            oldDocument.State.HostDocument.GeneratedCodeContainer.SetOutput(lastDocument, csharpDocument, lastVersion, VersionStamp.Default);

            var backgroundGenerator = new BackgroundDocumentGenerator(Dispatcher, cache, Listeners, router, LoggerFactory);
            var work = new[] { new KeyValuePair <string, DocumentSnapshot>(oldDocument.FilePath, oldDocument) };

            // Act
            backgroundGenerator.ReportUnsynchronizableContent(work);

            // Assert
            Assert.Empty(router.SynchronizedDocuments);
        }
示例#7
0
        public void DocumentProcessed_SynchronizesIfSourceVersionsAreIdenticalButSyncVersionNewer()
        {
            // Arrange
            var lastVersion     = VersionStamp.Default.GetNewerVersion();
            var lastDocument    = TestDocumentSnapshot.Create("C:/path/old.cshtml", lastVersion);
            var document        = TestDocumentSnapshot.Create("C:/path/file.cshtml", lastVersion);
            var csharpPublisher = new Mock <CSharpPublisher>();

            csharpPublisher.Setup(publisher => publisher.Publish(It.IsAny <string>(), It.IsAny <SourceText>(), It.IsAny <long>()))
            .Callback <string, SourceText, long>((filePath, sourceText, hostDocumentVersion) =>
            {
                Assert.Equal(document.FilePath, filePath);
            })
            .Verifiable();
            var cache = new TestDocumentVersionCache(new Dictionary <DocumentSnapshot, long>()
            {
                [document]     = 1338,
                [lastDocument] = 1337,
            });
            var csharpDocument = RazorCSharpDocument.Create("Anything", RazorCodeGenerationOptions.CreateDefault(), Enumerable.Empty <RazorDiagnostic>());

            // Force the state to already be up-to-date
            document.State.HostDocument.GeneratedCodeContainer.SetOutput(lastDocument, csharpDocument, lastVersion, VersionStamp.Default);

            var listener = new UnsynchronizableContentDocumentProcessedListener(Dispatcher, cache, csharpPublisher.Object);

            listener.Initialize(ProjectSnapshotManager);

            // Act
            listener.DocumentProcessed(document);

            // Assert
            csharpPublisher.VerifyAll();
        }
示例#8
0
        public void SetOutput(SourceText source, RazorCodeDocument codeDocument)
        {
            Source = source;
            Output = codeDocument.GetCSharpDocument();

            _textContainer.SetText(SourceText.From(Output.GeneratedCode));
        }
        public void SetOutput_InvokesChangedEvent()
        {
            // Arrange
            using var workspace = TestWorkspace.Create();

            var services     = workspace.Services;
            var hostProject  = new HostProject("C:/project.csproj", RazorConfiguration.Default, "project");
            var projectState = ProjectState.Create(services, hostProject);
            var project      = new DefaultProjectSnapshot(projectState);

            var text           = SourceText.From("...");
            var textAndVersion = TextAndVersion.Create(text, VersionStamp.Default);
            var hostDocument   = new HostDocument("C:/file.cshtml", "C:/file.cshtml");
            var documentState  = new DocumentState(services, hostDocument, text, VersionStamp.Default, () => Task.FromResult(textAndVersion));
            var document       = new DefaultDocumentSnapshot(project, documentState);
            var csharpDocument = RazorCSharpDocument.Create("...", RazorCodeGenerationOptions.CreateDefault(), Enumerable.Empty <RazorDiagnostic>());
            var htmlDocument   = RazorHtmlDocument.Create("...", RazorCodeGenerationOptions.CreateDefault());

            var version       = VersionStamp.Create();
            var container     = new GeneratedDocumentContainer();
            var csharpChanged = false;
            var htmlChanged   = false;

            container.GeneratedCSharpChanged += (o, a) => { csharpChanged = true; };
            container.GeneratedHtmlChanged   += (o, a) => { htmlChanged = true; };

            // Act
            container.SetOutput(document, csharpDocument, htmlDocument, version, version, version);

            // Assert
            Assert.NotNull(container.LatestDocument);
            Assert.True(csharpChanged);
            Assert.True(htmlChanged);
        }
        public void SetOutput(
            DefaultDocumentSnapshot document,
            RazorCSharpDocument outputCSharp,
            RazorHtmlDocument outputHtml,
            VersionStamp inputVersion,
            VersionStamp outputCSharpVersion,
            VersionStamp outputHtmlVersion)
        {
            lock (_setOutputLock)
            {
                if (_inputVersion.HasValue &&
                    _inputVersion != inputVersion &&
                    _inputVersion == _inputVersion.Value.GetNewerVersion(inputVersion))
                {
                    // Latest document is newer than the provided document.
                    return;
                }

                if (!document.TryGetText(out var source))
                {
                    Debug.Fail("The text should have already been evaluated.");
                    return;
                }

                _source              = source;
                _inputVersion        = inputVersion;
                _outputCSharpVersion = outputCSharpVersion;
                _outputHtmlVersion   = outputHtmlVersion;
                _outputCSharp        = outputCSharp;
                _outputHtml          = outputHtml;
                _latestDocument      = document;
                _csharpTextContainer.SetText(SourceText.From(_outputCSharp.GeneratedCode));
                _htmlTextContainer.SetText(SourceText.From(_outputHtml.GeneratedHtml));
            }
        }
示例#11
0
        private static RazorCodeActionContext CreateRazorCodeActionContext(
            CodeActionParams request,
            SourceLocation location,
            string filePath,
            string text,
            SourceSpan componentSourceSpan,
            bool supportsFileCreation      = true,
            bool supportsCodeActionResolve = true)
        {
            var tagHelpers     = Array.Empty <TagHelperDescriptor>();
            var sourceDocument = TestRazorSourceDocument.Create(text, filePath: filePath, relativePath: filePath);
            var projectEngine  = RazorProjectEngine.Create(builder => builder.AddTagHelpers(tagHelpers));
            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);

            return(context);
        }
示例#12
0
        public void SetOutput(RazorCSharpDocument csharpDocument, DefaultDocumentSnapshot document)
        {
            lock (_setOutputLock)
            {
                if (!document.TryGetTextVersion(out var version))
                {
                    Debug.Fail("The text version should have already been evaluated.");
                    return;
                }

                if (_sourceVersion.HasValue && _sourceVersion == SourceVersion.GetNewerVersion(version))
                {
                    // Latest document is newer than the provided document.
                    return;
                }

                if (!document.TryGetText(out var source))
                {
                    Debug.Fail("The text should have already been evaluated.");
                    return;
                }

                _source         = source;
                _sourceVersion  = version;
                _output         = csharpDocument;
                _latestDocument = document;
                _textContainer.SetText(SourceText.From(Output.GeneratedCode));
            }
        }
示例#13
0
 public OutputItem(
     SourceItem viewFileInfo,
     RazorCSharpDocument cSharpDocument)
 {
     ViewFileInfo   = viewFileInfo;
     CSharpDocument = cSharpDocument;
 }
示例#14
0
        public void DocumentProcessed_DoesNothingForOlderDocuments()
        {
            // Arrange
            var generatedDocumentPublisher = new Mock <GeneratedDocumentPublisher>(MockBehavior.Strict);
            var lastVersion  = VersionStamp.Default.GetNewerVersion();
            var lastDocument = TestDocumentSnapshot.Create("C:/path/old.cshtml", lastVersion);
            var oldDocument  = TestDocumentSnapshot.Create("C:/path/file.cshtml", VersionStamp.Default);
            var cache        = new TestDocumentVersionCache(new Dictionary <DocumentSnapshot, int?>()
            {
                [oldDocument]  = 1337,
                [lastDocument] = 1338,
            });
            var csharpDocument = RazorCSharpDocument.Create("Anything", RazorCodeGenerationOptions.CreateDefault(), Enumerable.Empty <RazorDiagnostic>());
            var htmlDocument   = RazorHtmlDocument.Create("Anything", RazorCodeGenerationOptions.CreateDefault());
            var codeDocument   = CreateCodeDocument(csharpDocument, htmlDocument);

            // Force the state to already be up-to-date
            oldDocument.State.HostDocument.GeneratedDocumentContainer.SetOutput(lastDocument, codeDocument, lastVersion, VersionStamp.Default, VersionStamp.Default);

            var listener = new UnsynchronizableContentDocumentProcessedListener(Dispatcher, cache, generatedDocumentPublisher.Object);

            listener.Initialize(ProjectSnapshotManager);

            // Act & Assert
            listener.DocumentProcessed(oldDocument);
        }
示例#15
0
        public async Task <IGeneratedRazorTemplate> GenerateCodeAsync(TkRazorProjectItem projectItem)
        {
            TkDebug.AssertArgumentNull(projectItem, nameof(projectItem), this);

            if (!projectItem.Exists)
            {
                throw new ToolkitException($"Project can not find template with key {projectItem.Key}", this);
            }

            RazorCodeDocument codeDocument = await CreateCodeDocumentAsync(projectItem);

            ProjectEngine.Process(codeDocument);

            RazorCSharpDocument document = codeDocument.GetCSharpDocument();

            if (document.Diagnostics.Count > 0)
            {
                var builder = new StringBuilder();
                builder.AppendLine("Failed to generate Razor template. See \"Diagnostics\" property for more details");

                foreach (RazorDiagnostic d in document.Diagnostics)
                {
                    builder.AppendLine($"- {d.GetMessage()}");
                }

                throw new TemplateGenerationException(builder.ToString(), document.Diagnostics, this);
            }

            return(new GeneratedRazorTemplate(projectItem, document));
        }
示例#16
0
        private CompilationResult GetCompilation(RazorProjectItem projectItem, RazorProjectFileSystem projectFileSystem)
        {
            using (IServiceScope scope = _serviceScopeFactory.CreateScope())
            {
                IServiceProvider serviceProvider = scope.ServiceProvider;

                // See RazorViewCompiler.CompileAndEmit()
                RazorProjectEngine  projectEngine  = serviceProvider.GetRequiredService <RazorProjectEngine>();
                RazorCodeDocument   codeDocument   = projectEngine.Process(projectItem);
                RazorCSharpDocument cSharpDocument = codeDocument.GetCSharpDocument();
                if (cSharpDocument.Diagnostics.Count > 0)
                {
                    throw (Exception)CreateCompilationFailedException.Invoke(
                              null,
                              new object[] { codeDocument, cSharpDocument.Diagnostics });
                }

                // Use the RazorViewCompiler to finish compiling the view for consistency with layouts
                IViewCompilerProvider viewCompilerProvider = serviceProvider.GetRequiredService <IViewCompilerProvider>();
                IViewCompiler         viewCompiler         = viewCompilerProvider.GetCompiler();
                Assembly assembly = (Assembly)CompileAndEmitMethod.Invoke(
                    viewCompiler,
                    new object[] { codeDocument, cSharpDocument.GeneratedCode });

                // Get the runtime item
                RazorCompiledItemLoader compiledItemLoader = new RazorCompiledItemLoader();
                RazorCompiledItem       compiledItem       = compiledItemLoader.LoadItems(assembly).SingleOrDefault();
                return(new CompilationResult(compiledItem));
            }
        }
        private static SyntaxTree GenerateSyntaxTree(RazorProjectItem razorProjectItem, RazorProjectEngine razorProjectEngine)
        {
            RazorCodeDocument   razorCodeDocument   = razorProjectEngine.Process(razorProjectItem);
            RazorCSharpDocument razorCSharpDocument = razorCodeDocument.GetCSharpDocument();

            return(CSharpSyntaxTree.ParseText(razorCSharpDocument.GeneratedCode));
        }
        public void SetOutput_AcceptsSameVersionedDocuments()
        {
            // Arrange
            using var workspace = TestWorkspace.Create();

            var services     = workspace.Services;
            var hostProject  = new HostProject("C:/project.csproj", RazorConfiguration.Default, "project");
            var projectState = ProjectState.Create(services, hostProject);
            var project      = new DefaultProjectSnapshot(projectState);

            var text           = SourceText.From("...");
            var textAndVersion = TextAndVersion.Create(text, VersionStamp.Default);
            var hostDocument   = new HostDocument("C:/file.cshtml", "C:/file.cshtml");
            var documentState  = new DocumentState(services, hostDocument, text, VersionStamp.Default, () => Task.FromResult(textAndVersion));
            var document       = new DefaultDocumentSnapshot(project, documentState);
            var newDocument    = new DefaultDocumentSnapshot(project, documentState);

            var csharpDocument = RazorCSharpDocument.Create("...", RazorCodeGenerationOptions.CreateDefault(), Enumerable.Empty <RazorDiagnostic>());
            var htmlDocument   = RazorHtmlDocument.Create("...", RazorCodeGenerationOptions.CreateDefault());

            var version   = VersionStamp.Create();
            var container = new GeneratedDocumentContainer();

            container.SetOutput(document, csharpDocument, htmlDocument, version, version, version);

            // Act
            container.SetOutput(newDocument, csharpDocument, htmlDocument, version, version, version);

            // Assert
            Assert.Same(newDocument, container.LatestDocument);
        }
        public static string Serialize(RazorCSharpDocument csharpDocument, RazorSourceDocument sourceDocument)
        {
            var builder        = new StringBuilder();
            var sourceFilePath = sourceDocument.FilePath;
            var charBuffer     = new char[sourceDocument.Length];

            sourceDocument.CopyTo(0, charBuffer, 0, sourceDocument.Length);
            var sourceContent = new string(charBuffer);

            for (var i = 0; i < csharpDocument.SourceMappings.Count; i++)
            {
                var sourceMapping = csharpDocument.SourceMappings[i];
                if (!string.Equals(sourceMapping.OriginalSpan.FilePath, sourceFilePath, StringComparison.Ordinal))
                {
                    continue;
                }

                builder.Append("Source Location: ");
                AppendMappingLocation(builder, sourceMapping.OriginalSpan, sourceContent);

                builder.Append("Generated Location: ");
                AppendMappingLocation(builder, sourceMapping.GeneratedSpan, csharpDocument.GeneratedCode);

                builder.AppendLine();
            }

            return(builder.ToString());
        }
示例#20
0
 public RazorCSharp(RazorCSharpDocument cSharp, CSharpCompilationOptions compilationOptions, IList <MetadataReference> references, EmitOptions emitOptions)
 {
     CSharp = cSharp;
     _compilationOptions = compilationOptions;
     _references         = references;
     _emitOptions        = emitOptions;
 }
        public void ReportUnsynchronizableContent_SynchronizesIfSourceVersionsAreIdenticalButSyncVersionNewer()
        {
            // Arrange
            var router       = new TestRouter();
            var lastVersion  = VersionStamp.Default.GetNewerVersion();
            var lastDocument = TestDocumentSnapshot.Create("C:/path/old.cshtml", lastVersion);
            var document     = TestDocumentSnapshot.Create("C:/path/file.cshtml", lastVersion);
            var cache        = new TestDocumentVersionCache(new Dictionary <DocumentSnapshot, long>()
            {
                [document]     = 1338,
                [lastDocument] = 1337,
            });
            var csharpDocument = RazorCSharpDocument.Create("Anything", RazorCodeGenerationOptions.CreateDefault(), Enumerable.Empty <RazorDiagnostic>());

            // Force the state to already be up-to-date
            document.State.HostDocument.GeneratedCodeContainer.SetOutput(csharpDocument, lastDocument);

            var backgroundGenerator = new BackgroundDocumentGenerator(Dispatcher, cache, router, LoggerFactory);
            var work = new[] { new KeyValuePair <string, DocumentSnapshot>(document.FilePath, document) };

            // Act
            backgroundGenerator.ReportUnsynchronizableContent(work);

            // Assert
            var filePath = Assert.Single(router.SynchronizedDocuments);

            Assert.Equal(document.FilePath, filePath);
        }
示例#22
0
        /// <summary>
        /// Parses the template specified by <paramref name="projectItem"/>.
        /// </summary>
        /// <param name="projectItem">The <see cref="RazorLightProjectItem"/>.</param>
        /// <returns>The <see cref="IGeneratedRazorTemplate"/>.</returns>
        public async Task <IGeneratedRazorTemplate> GenerateCodeAsync(RazorLightProjectItem projectItem)
        {
            if (projectItem == null)
            {
                throw new ArgumentNullException(nameof(projectItem));
            }

            if (!projectItem.Exists)
            {
                throw new InvalidOperationException($"{nameof(RazorLightProjectItem)} of type " +
                                                    $"{projectItem.GetType().FullName} with key {projectItem.Key} does not exist.");
            }

            RazorCodeDocument codeDocument = await CreateCodeDocumentAsync(projectItem);

            ProjectEngine.Process(codeDocument);

            RazorCSharpDocument document = codeDocument.GetCSharpDocument();

            if (document.Diagnostics.Count > 0)
            {
                var builder = new StringBuilder();
                builder.AppendLine("Failed to generate Razor template. See \"Diagnostics\" property for more details");

                foreach (RazorDiagnostic d in document.Diagnostics)
                {
                    builder.AppendLine($"- {d.GetMessage()}");
                }

                throw new TemplateGenerationException(builder.ToString(), document.Diagnostics);
            }

            return(new GeneratedRazorTemplate(projectItem, document));
        }
示例#23
0
        private MemoryStream CreateAndCompileToStream(string templateSource, RazorEngineCompilationOptions options)
        {
            templateSource = this.WriteDirectives(templateSource, options);

            RazorProjectEngine engine = RazorProjectEngine.Create(
                RazorConfiguration.Default,
                RazorProjectFileSystem.Create(@"."),
                (builder) =>
            {
                builder.SetNamespace(options.TemplateNamespace);
            });

            string fileName = Path.GetRandomFileName();

            RazorSourceDocument document = RazorSourceDocument.Create(templateSource, fileName);

            RazorCodeDocument codeDocument = engine.Process(
                document,
                null,
                new List <RazorSourceDocument>(),
                new List <TagHelperDescriptor>());

            RazorCSharpDocument razorCSharpDocument = codeDocument.GetCSharpDocument();

            SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(razorCSharpDocument.GeneratedCode);

            CSharpCompilation compilation = CSharpCompilation.Create(
                fileName,
                new[]
            {
                syntaxTree
            },
                options.ReferencedAssemblies
                .Select(ass => MetadataReference.CreateFromFile(ass.Location))
                .Concat(options.MetadataReferences)
                .ToList(),
                new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));

            MemoryStream memoryStream = new MemoryStream();

            EmitResult emitResult = compilation.Emit(memoryStream);

            if (!emitResult.Success)
            {
                List <Diagnostic> errors = emitResult.Diagnostics.ToList();

                RazorEngineCompilationException exception = new RazorEngineCompilationException($"Unable to compile template: {errors.FirstOrDefault()}")
                {
                    Errors        = errors,
                    GeneratedCode = razorCSharpDocument.GeneratedCode
                };

                throw exception;
            }

            memoryStream.Position = 0;

            return(memoryStream);
        }
示例#24
0
        public GeneratedRazorTemplate(TkRazorProjectItem projectItem, RazorCSharpDocument cSharpDocument)
        {
            TkDebug.AssertArgumentNull(projectItem, nameof(projectItem), null);
            TkDebug.AssertArgumentNull(cSharpDocument, nameof(cSharpDocument), null);

            ProjectItem    = projectItem;
            CSharpDocument = cSharpDocument;
        }
示例#25
0
        private static RazorCodeDocument CreateCodeDocument(RazorCSharpDocument csharpDocument, RazorHtmlDocument htmlDocument)
        {
            var codeDocument = TestRazorCodeDocument.CreateEmpty();

            codeDocument.SetCSharpDocument(csharpDocument);
            codeDocument.Items[typeof(RazorHtmlDocument)] = htmlDocument;
            return(codeDocument);
        }
        private static RazorCodeDocument CreateCodeDocument(params RazorDiagnostic[] diagnostics)
        {
            var codeDocument        = TestRazorCodeDocument.CreateEmpty();
            var razorCSharpDocument = RazorCSharpDocument.Create(string.Empty, RazorCodeGenerationOptions.CreateDefault(), diagnostics);

            codeDocument.SetCSharpDocument(razorCSharpDocument);

            return(codeDocument);
        }
示例#27
0
    public static void SetCSharpDocument(this RazorCodeDocument document, RazorCSharpDocument csharp)
    {
        if (document == null)
        {
            throw new ArgumentNullException(nameof(document));
        }

        document.Items[typeof(RazorCSharpDocument)] = csharp;
    }
        protected void AssertCSharpDocumentMatchesBaseline(RazorCSharpDocument cSharpDocument)
        {
            if (FileName == null)
            {
                var message = $"{nameof(AssertCSharpDocumentMatchesBaseline)} should only be called from an integration test ({nameof(FileName)} is null).";
                throw new InvalidOperationException(message);
            }

            var baselineFileName            = Path.ChangeExtension(FileName, ".codegen.cs");
            var baselineDiagnosticsFileName = Path.ChangeExtension(FileName, ".diagnostics.txt");

            if (GenerateBaselines)
            {
                var baselineFullPath = Path.Combine(TestProjectRoot, baselineFileName);
                File.WriteAllText(baselineFullPath, cSharpDocument.GeneratedCode);

                var baselineDiagnosticsFullPath = Path.Combine(TestProjectRoot, baselineDiagnosticsFileName);
                var lines = cSharpDocument.Diagnostics.Select(RazorDiagnosticSerializer.Serialize).ToArray();
                if (lines.Any())
                {
                    File.WriteAllLines(baselineDiagnosticsFullPath, lines);
                }
                else if (File.Exists(baselineDiagnosticsFullPath))
                {
                    File.Delete(baselineDiagnosticsFullPath);
                }

                return;
            }

            var codegenFile = TestFile.Create(baselineFileName, GetType().GetTypeInfo().Assembly);

            if (!codegenFile.Exists())
            {
                throw new XunitException($"The resource {baselineFileName} was not found.");
            }

            var baseline = codegenFile.ReadAllText();

            // Normalize newlines to match those in the baseline.
            var actual = cSharpDocument.GeneratedCode.Replace("\r", "").Replace("\n", "\r\n");

            Assert.Equal(baseline, actual);

            var baselineDiagnostics = string.Empty;
            var diagnosticsFile     = TestFile.Create(baselineDiagnosticsFileName, GetType().GetTypeInfo().Assembly);

            if (diagnosticsFile.Exists())
            {
                baselineDiagnostics = diagnosticsFile.ReadAllText();
            }

            var actualDiagnostics = string.Concat(cSharpDocument.Diagnostics.Select(d => RazorDiagnosticSerializer.Serialize(d) + "\r\n"));

            Assert.Equal(baselineDiagnostics, actualDiagnostics);
        }
示例#29
0
 public void Execute(RazorCodeDocument codeDocument)
 {
     if (Writer != null)
     {
         var intermediateNode       = codeDocument.GetDocumentIntermediateNode();
         RazorCSharpDocument csharp = Writer.WriteDocument(codeDocument, intermediateNode);
         codeDocument.SetCSharpDocument(csharp);
     }
     else
     {
         _inner.Execute(codeDocument);
     }
 }
示例#30
0
        private static RazorCodeDocument CreateCodeDocumentWithCSharpProjection(string razorSource, string projectedCSharpSource, IEnumerable <SourceMapping> sourceMappings)
        {
            var codeDocument   = CreateCodeDocument(razorSource, Array.Empty <TagHelperDescriptor>());
            var csharpDocument = RazorCSharpDocument.Create(
                projectedCSharpSource,
                RazorCodeGenerationOptions.CreateDefault(),
                Enumerable.Empty <RazorDiagnostic>(),
                sourceMappings,
                Enumerable.Empty <LinePragma>());

            codeDocument.SetCSharpDocument(csharpDocument);
            return(codeDocument);
        }