public SyntaxTreeGenerationBenchmark()
        {
            var current = new DirectoryInfo(AppContext.BaseDirectory);

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

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

            ProjectEngine = RazorProjectEngine.Create(RazorConfiguration.Default, fileSystem, b => RazorExtensions.Register(b));;

            var projectItem = fileSystem.GetItem(Path.Combine(root.FullName, "MSN.cshtml"), FileKinds.Legacy);

            MSN = RazorSourceDocument.ReadFrom(projectItem);

            var directiveFeature = ProjectEngine.EngineFeatures.OfType <IRazorDirectiveFeature>().FirstOrDefault();

            Directives = directiveFeature?.Directives.ToArray() ?? Array.Empty <DirectiveDescriptor>();
        }
    public void MvcViewDocumentClassifierPass_SanitizesClassName()
    {
        // Arrange
        var properties   = new RazorSourceDocumentProperties(filePath: @"x:\Test.cshtml", relativePath: "path.with+invalid-chars");
        var codeDocument = RazorCodeDocument.Create(RazorSourceDocument.Create("@page", properties));

        var projectEngine = CreateProjectEngine();
        var irDocument    = CreateIRDocument(projectEngine, codeDocument);
        var pass          = new MvcViewDocumentClassifierPass
        {
            Engine = projectEngine.Engine
        };

        // Act
        pass.Execute(codeDocument, irDocument);
        var visitor = new Visitor();

        visitor.Visit(irDocument);

        // Assert
        Assert.Equal("path_with_invalid_chars", visitor.Class.ClassName);
    }
예제 #3
0
        public static IList <RazorPageGeneratorResult> MainCore(RazorEngine razorEngine, string targetProjectDirectory)
        {
            var viewDirectories = Directory.EnumerateDirectories(targetProjectDirectory, "Views", SearchOption.AllDirectories);
            var razorProject    = RazorProject.Create(targetProjectDirectory);
            var templateEngine  = new RazorTemplateEngine(razorEngine, razorProject);

            templateEngine.Options.DefaultImports = RazorSourceDocument.Create(@"
@using System
@using System.Threading.Tasks
", fileName: null);

            var fileCount = 0;

            var results = new List <RazorPageGeneratorResult>();

            foreach (var viewDir in viewDirectories)
            {
                Console.WriteLine();
                Console.WriteLine("  Generating code files for views in {0}", viewDir);
                var viewDirPath = viewDir.Substring(targetProjectDirectory.Length).Replace('\\', '/');
                var cshtmlFiles = razorProject.EnumerateItems(viewDirPath);

                if (!cshtmlFiles.Any())
                {
                    Console.WriteLine("  No .cshtml files were found.");
                    continue;
                }

                foreach (var item in cshtmlFiles)
                {
                    Console.WriteLine("    Generating code file for view {0}...", item.FileName);
                    results.Add(GenerateCodeFile(templateEngine, item));
                    Console.WriteLine("      Done!");
                    fileCount++;
                }
            }

            return(results);
        }
    public void MvcViewDocumentClassifierPass_UsesAbsolutePath_IfRelativePathIsNotSet()
    {
        // Arrange
        var properties   = new RazorSourceDocumentProperties(filePath: @"x::\application\Views\Home\Index.cshtml", relativePath: null);
        var codeDocument = RazorCodeDocument.Create(RazorSourceDocument.Create("some-content", properties));

        var projectEngine = CreateProjectEngine();
        var irDocument    = CreateIRDocument(projectEngine, codeDocument);
        var pass          = new MvcViewDocumentClassifierPass
        {
            Engine = projectEngine.Engine
        };

        // Act
        pass.Execute(codeDocument, irDocument);
        var visitor = new Visitor();

        visitor.Visit(irDocument);

        // Assert
        Assert.Equal("x___application_Views_Home_Index", visitor.Class.ClassName);
    }
    public void MvcViewDocumentClassifierPass_UsesRelativePathToGenerateTypeName(string relativePath, string expected)
    {
        // Arrange
        var properties   = new RazorSourceDocumentProperties(filePath: "ignored", relativePath: relativePath);
        var codeDocument = RazorCodeDocument.Create(RazorSourceDocument.Create("some-content", properties));

        var projectEngine = CreateProjectEngine();
        var irDocument    = CreateIRDocument(projectEngine, codeDocument);
        var pass          = new MvcViewDocumentClassifierPass
        {
            Engine = projectEngine.Engine
        };

        // Act
        pass.Execute(codeDocument, irDocument);
        var visitor = new Visitor();

        visitor.Visit(irDocument);

        // Assert
        Assert.Equal(expected, visitor.Class.ClassName);
    }
예제 #6
0
        public void GetCompilationFailedResult_WithMissingReferences()
        {
            // Arrange
            var expected    = "One or more compilation references may be missing. If you're seeing this in a published application, set 'CopyRefAssembliesToPublishDirectory' to true in your project file to ensure files in the refs directory are published.";
            var compilation = CSharpCompilation.Create("Test", options: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));
            var syntaxTree  = CSharpSyntaxTree.ParseText("@class Test { public string Test { get; set; } }");

            compilation = compilation.AddSyntaxTrees(syntaxTree);
            var emitResult = compilation.Emit(new MemoryStream());

            // Act
            var exception = CompilationFailedExceptionFactory.Create(
                RazorCodeDocument.Create(RazorSourceDocument.Create("Test", "Index.cshtml"), Enumerable.Empty <RazorSourceDocument>()),
                syntaxTree.ToString(),
                "Test",
                emitResult.Diagnostics);

            // Assert
            Assert.Collection(
                exception.CompilationFailures,
                failure => Assert.Equal(expected, failure.FailureSummary));
        }
예제 #7
0
    public static CodeRenderingContext CreateDesignTime(
        string newLineString              = null,
        string suppressUniqueIds          = "test",
        RazorSourceDocument source        = null,
        IntermediateNodeWriter nodeWriter = null)
    {
        var codeWriter   = new CodeWriter();
        var documentNode = new DocumentIntermediateNode();
        var options      = RazorCodeGenerationOptions.CreateDesignTimeDefault();

        if (source == null)
        {
            source = TestRazorSourceDocument.Create();
        }

        var codeDocument = RazorCodeDocument.Create(source);

        if (newLineString != null)
        {
            codeDocument.Items[CodeRenderingContext.NewLineString] = newLineString;
        }

        if (suppressUniqueIds != null)
        {
            codeDocument.Items[CodeRenderingContext.SuppressUniqueIds] = suppressUniqueIds;
        }

        if (nodeWriter == null)
        {
            nodeWriter = new DesignTimeNodeWriter();
        }

        var context = new DefaultCodeRenderingContext(codeWriter, nodeWriter, codeDocument, documentNode, options);

        context.Visitor = new RenderChildrenVisitor(context);

        return(context);
    }
        public static string Serialize(RazorCSharpDocument csharpDocument, RazorSourceDocument sourceDocument)
        {
            var builder    = new StringBuilder();
            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];

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

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

                builder.AppendLine();
            }

            return(builder.ToString());
        }
예제 #9
0
        // Internal for testing
        internal void AddHierarchicalImports(string sourceFilePath, List <RazorSourceDocument> imports)
        {
            // We want items in descending order. FindHierarchicalItems returns items in ascending order.
            var importProjectItems = ProjectEngine.FileSystem.FindHierarchicalItems(sourceFilePath, ImportsFileName).Reverse();

            foreach (var importProjectItem in importProjectItems)
            {
                RazorSourceDocument importSourceDocument;

                if (importProjectItem.Exists)
                {
                    importSourceDocument = RazorSourceDocument.ReadFrom(importProjectItem);
                }
                else
                {
                    // File doesn't exist on disk so just add a marker source document as an identifier for "there could be something here".
                    var sourceDocumentProperties = new RazorSourceDocumentProperties(importProjectItem.FilePath, importProjectItem.RelativePhysicalPath);
                    importSourceDocument = RazorSourceDocument.Create(string.Empty, sourceDocumentProperties);
                }

                imports.Add(importSourceDocument);
            }
        }
        private void RunRuntimeTagHelpersTest(IEnumerable <TagHelperDescriptor> descriptors)
        {
            // Arrange
            var projectEngine = CreateProjectEngine(builder =>
            {
                builder.ConfigureDocumentClassifier();

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

                SectionDirective.Register(builder);
            });

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

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

            // Assert
            AssertDocumentNodeMatchesBaseline(codeDocument.GetDocumentIntermediateNode());
            AssertCSharpDocumentMatchesBaseline(codeDocument.GetCSharpDocument());
        }
예제 #11
0
        public void MvcViewDocumentClassifierPass_SetsUpExecuteAsyncMethod()
        {
            // Arrange
            var codeDocument = RazorCodeDocument.Create(RazorSourceDocument.Create("some-content", "Test.cshtml"));

            var projectEngine = CreateProjectEngine();
            var irDocument    = CreateIRDocument(projectEngine, codeDocument);
            var pass          = new MvcViewDocumentClassifierPass
            {
                Engine = projectEngine.Engine
            };

            // Act
            pass.Execute(codeDocument, irDocument);
            var visitor = new Visitor();

            visitor.Visit(irDocument);

            // Assert
            Assert.Equal("ExecuteAsync", visitor.Method.MethodName);
            Assert.Equal("global::System.Threading.Tasks.Task", visitor.Method.ReturnType);
            Assert.Equal(new[] { "public", "async", "override" }, visitor.Method.Modifiers);
        }
        private CompletionList GenerateCompletionList(string documentContent, int queryIndex, TagHelperCompletionProvider componentCompletionProvider)
        {
            var sourceDocument           = RazorSourceDocument.Create(documentContent, RazorSourceDocumentProperties.Default);
            var syntaxTree               = RazorSyntaxTree.Parse(sourceDocument);
            var tagHelperDocumentContext = TagHelperDocumentContext.Create(prefix: string.Empty, DefaultTagHelpers);

            var completionQueryLocation = new SourceSpan(queryIndex, length: 0);
            var razorCompletionItems    = componentCompletionProvider.GetCompletionItems(syntaxTree, tagHelperDocumentContext, completionQueryLocation);
            var completionList          = RazorCompletionEndpoint.CreateLSPCompletionList(
                razorCompletionItems,
                new CompletionListCache(),
                new[] { ExtendedCompletionItemKinds.TagHelper },
                new PlatformAgnosticCompletionCapability()
            {
                VSCompletionList = new VSCompletionListCapability()
                {
                    CommitCharacters = true,
                    Data             = true,
                }
            });

            return(completionList);
        }
예제 #13
0
    public void ProcessDesignTime_WithImportsAndTagHelpers_SetsOnCodeDocument()
    {
        // Arrange
        var projectItem        = new TestRazorProjectItem("Index.cshtml");
        var importItem         = new TestRazorProjectItem("_import.cshtml");
        var expectedImports    = new[] { RazorSourceDocument.ReadFrom(importItem) };
        var expectedTagHelpers = new[]
        {
            TagHelperDescriptorBuilder.Create("TestTagHelper", "TestAssembly").Build(),
            TagHelperDescriptorBuilder.Create("Test2TagHelper", "TestAssembly").Build(),
        };

        var projectEngine = RazorProjectEngine.Create(RazorConfiguration.Default, TestRazorProjectFileSystem.Empty);

        // Act
        var codeDocument = projectEngine.ProcessDesignTime(RazorSourceDocument.ReadFrom(projectItem), "test", expectedImports, expectedTagHelpers);

        // Assert
        var tagHelpers = codeDocument.GetTagHelpers();

        Assert.Same(expectedTagHelpers, tagHelpers);
        Assert.Equal(expectedImports, codeDocument.Imports);
    }
예제 #14
0
        public virtual RazorSyntaxTree Parse(RazorSourceDocument source)
        {
            if (source == null)
            {
                throw new ArgumentNullException(nameof(source));
            }

            var context      = new ParserContext(source, Options);
            var codeParser   = new CSharpCodeParser(Options.Directives, context);
            var markupParser = new HtmlMarkupParser(context);

            codeParser.HtmlParser   = markupParser;
            markupParser.CodeParser = codeParser;

            markupParser.ParseDocument();

            var root = context.Builder.Build();

            // Temporary code while we're still using legacy diagnostics in the SyntaxTree.
            var diagnostics = context.ErrorSink.Errors.Select(error => RazorDiagnostic.Create(error));

            return(RazorSyntaxTree.Create(root, source, diagnostics, Options));
        }
예제 #15
0
        private string Generate(
            Type templateBaseType,
            string template)
        {
            var engine = RazorProjectEngine.Create(
                RazorConfiguration.Default,
                RazorProjectFileSystem.Create(@"."),
                builder =>
            {
                builder.SetNamespace(templateBaseType.Namespace);
                builder.SetBaseType(Regex.Replace(templateBaseType.ToString(), @"`\d+\[", "<").Replace(']', '>'));
            });

            var document = RazorSourceDocument.Create(template, Path.GetRandomFileName());

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

            return(codeDocument.GetCSharpDocument().GeneratedCode);
        }
예제 #16
0
        public void RazorPageDocumentClassifierPass_LogsErrorIfDirectiveNotAtTopOfFile()
        {
            // Arrange
            var sourceSpan = new SourceSpan(
                "Test.cshtml",
                absoluteIndex: 14 + Environment.NewLine.Length * 2,
                lineIndex: 2,
                characterIndex: 0,
                length: 5 + Environment.NewLine.Length);

            var expectedDiagnostic = RazorExtensionsDiagnosticFactory.CreatePageDirective_MustExistAtTheTopOfFile(sourceSpan);
            var content            = @"
@somethingelse
@page
";
            var codeDocument       = RazorCodeDocument.Create(RazorSourceDocument.Create(content, "Test.cshtml"));

            var engine     = CreateRuntimeEngine();
            var irDocument = CreateIRDocument(engine, codeDocument);
            var pass       = new RazorPageDocumentClassifierPass
            {
                Engine = engine
            };

            // Act
            pass.Execute(codeDocument, irDocument);
            var visitor = new Visitor();

            visitor.Visit(irDocument);

            // Assert
            var pageDirectives = irDocument.FindDirectiveReferences(PageDirective.Directive);
            var directive      = Assert.Single(pageDirectives);
            var diagnostic     = Assert.Single(directive.Node.Diagnostics);

            Assert.Equal(expectedDiagnostic, diagnostic);
        }
예제 #17
0
        public override RazorCodeDocument CreateCodeDocument(RazorProjectItem projectItem)
        {
            if (projectItem == null)
            {
                throw new ArgumentNullException($"{nameof(projectItem)} is null!");
            }

            if (!projectItem.Exists)
            {
                throw new InvalidOperationException($"{nameof(projectItem)} doesn't exist!");
            }

            Console.WriteLine();
            Console.WriteLine($"File: {projectItem.FileName}");

            using (var inputStream = projectItem.Read())
            {
                using (var reader = new StreamReader(inputStream))
                {
                    var text = reader.ReadToEnd();

                    var markupStart = text.IndexOf("<!DOCTYPE");
                    var directives  = text.Substring(0, markupStart);
                    var markup      = text.Substring(markupStart);

                    text = directives + Minify(markup);

                    var byteArray           = Encoding.UTF8.GetBytes(text);
                    var minifiedInputStream = new MemoryStream(byteArray);

                    var source  = RazorSourceDocument.ReadFrom(minifiedInputStream, projectItem.PhysicalPath);
                    var imports = GetImports(projectItem);

                    return(RazorCodeDocument.Create(source, imports));
                }
            }
        }
예제 #18
0
        public void MvcViewDocumentClassifierPass_NullFilePath_SetsClass()
        {
            // Arrange
            var properties   = new RazorSourceDocumentProperties(filePath: null, relativePath: null);
            var codeDocument = RazorCodeDocument.Create(RazorSourceDocument.Create("some-content", properties));

            var projectEngine = CreateProjectEngine();
            var irDocument    = CreateIRDocument(projectEngine, codeDocument);
            var pass          = new MvcViewDocumentClassifierPass
            {
                Engine = projectEngine.Engine
            };

            // Act
            pass.Execute(codeDocument, irDocument);
            var visitor = new Visitor();

            visitor.Visit(irDocument);

            // Assert
            Assert.Equal("global::Microsoft.AspNetCore.Mvc.Razor.RazorPage<TModel>", visitor.Class.BaseType);
            Assert.Equal(new[] { "public" }, visitor.Class.Modifiers);
            Assert.Equal("AspNetCore_d9f877a857a7e9928eac04d09a59f25967624155", visitor.Class.ClassName);
        }
예제 #19
0
    protected RazorCodeDocument CreateCodeDocumentCore(
        RazorProjectItem projectItem,
        Action <RazorParserOptionsBuilder> configureParser,
        Action <RazorCodeGenerationOptionsBuilder> configureCodeGeneration)
    {
        if (projectItem == null)
        {
            throw new ArgumentNullException(nameof(projectItem));
        }

        var sourceDocument = RazorSourceDocument.ReadFrom(projectItem);

        var importItems = new List <RazorProjectItem>();
        var features    = ProjectFeatures.OfType <IImportProjectFeature>();

        foreach (var feature in features)
        {
            importItems.AddRange(feature.GetImports(projectItem));
        }

        var importSourceDocuments = GetImportSourceDocuments(importItems);

        return(CreateCodeDocumentCore(sourceDocument, projectItem.FileKind, importSourceDocuments, tagHelpers: null, configureParser, configureCodeGeneration, cssScope: projectItem.CssScope));
    }
예제 #20
0
        public void ComponentDocumentClassifierPass_SetsNamespace()
        {
            // Arrange
            var properties   = new RazorSourceDocumentProperties(filePath: "/MyApp/Test.razor", relativePath: "Test.razor");
            var codeDocument = RazorCodeDocument.Create(RazorSourceDocument.Create("some-content", properties));

            codeDocument.SetFileKind(FileKinds.Component);

            var projectEngine = CreateProjectEngine();
            var irDocument    = CreateIRDocument(projectEngine, codeDocument);
            var pass          = new ComponentDocumentClassifierPass
            {
                Engine = projectEngine.Engine
            };

            // Act
            pass.Execute(codeDocument, irDocument);
            var visitor = new Visitor();

            visitor.Visit(irDocument);

            // Assert
            Assert.Equal("MyApp", visitor.Namespace.Content);
        }
예제 #21
0
        public void RazorPageDocumentClassifierPass_NullFilePath_SetsClass()
        {
            // Arrange
            var properties   = new RazorSourceDocumentProperties(filePath: null, relativePath: null);
            var codeDocument = RazorCodeDocument.Create(RazorSourceDocument.Create("@page", properties));

            var engine     = CreateProjectEngine().Engine;
            var irDocument = CreateIRDocument(engine, codeDocument);
            var pass       = new RazorPageDocumentClassifierPass
            {
                Engine = engine
            };

            // Act
            pass.Execute(codeDocument, irDocument);
            var visitor = new Visitor();

            visitor.Visit(irDocument);

            // Assert
            Assert.Equal("global::Microsoft.AspNetCore.Mvc.RazorPages.Page", visitor.Class.BaseType);
            Assert.Equal(new[] { "public" }, visitor.Class.Modifiers);
            Assert.Equal("AspNetCore_74fbaab062bb228ed1ab09c5ff8d6ed2417320e2", visitor.Class.ClassName);
        }
예제 #22
0
        public void MvcViewDocumentClassifierPass_SetsClass()
        {
            // Arrange
            var properties   = new RazorSourceDocumentProperties(filePath: "ignored", relativePath: "Test.cshtml");
            var codeDocument = RazorCodeDocument.Create(RazorSourceDocument.Create("some-content", properties));

            var projectEngine = CreateProjectEngine();
            var irDocument    = CreateIRDocument(projectEngine, codeDocument);
            var pass          = new MvcViewDocumentClassifierPass
            {
                Engine = projectEngine.Engine
            };

            // Act
            pass.Execute(codeDocument, irDocument);
            var visitor = new Visitor();

            visitor.Visit(irDocument);

            // Assert
            Assert.Equal("global::Microsoft.AspNetCore.Mvc.Razor.RazorPage<TModel>", visitor.Class.BaseType);
            Assert.Equal(new[] { "public" }, visitor.Class.Modifiers);
            Assert.Equal("Test", visitor.Class.ClassName);
        }
예제 #23
0
        public void ComponentDocumentClassifierPass_SanitizesClassName()
        {
            // Arrange
            var properties   = new RazorSourceDocumentProperties(filePath: @"x:\path.with+invalid-chars.razor", relativePath: "path.with+invalid-chars.razor");
            var codeDocument = RazorCodeDocument.Create(RazorSourceDocument.Create("some-content", properties));

            codeDocument.SetFileKind(FileKinds.Component);

            var projectEngine = CreateProjectEngine();
            var irDocument    = CreateIRDocument(projectEngine, codeDocument);
            var pass          = new ComponentDocumentClassifierPass
            {
                Engine = projectEngine.Engine
            };

            // Act
            pass.Execute(codeDocument, irDocument);
            var visitor = new Visitor();

            visitor.Visit(irDocument);

            // Assert
            Assert.Equal("path_with_invalid_chars", visitor.Class.ClassName);
        }
        // Internal for testing.
        internal static RazorSourceDocument GetDefaultImports()
        {
            using (var stream = new MemoryStream())
                using (var writer = new StreamWriter(stream, Encoding.UTF8))
                {
                    writer.WriteLine("@using System");
                    writer.WriteLine("@using System.Collections.Generic");
                    writer.WriteLine("@using System.Linq");
                    writer.WriteLine("@using System.Threading.Tasks");
                    writer.WriteLine("@using Microsoft.AspNetCore.Mvc");
                    writer.WriteLine("@using Microsoft.AspNetCore.Mvc.Rendering");
                    writer.WriteLine("@using Microsoft.AspNetCore.Mvc.ViewFeatures");
                    writer.WriteLine("@inject global::Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper<TModel> Html");
                    writer.WriteLine("@inject global::Microsoft.AspNetCore.Mvc.Rendering.IJsonHelper Json");
                    writer.WriteLine("@inject global::Microsoft.AspNetCore.Mvc.IViewComponentHelper Component");
                    writer.WriteLine("@inject global::Microsoft.AspNetCore.Mvc.IUrlHelper Url");
                    writer.WriteLine("@inject global::Microsoft.AspNetCore.Mvc.ViewFeatures.IModelExpressionProvider ModelExpressionProvider");
                    writer.WriteLine("@addTagHelper Microsoft.AspNetCore.Mvc.Razor.TagHelpers.UrlResolutionTagHelper, Microsoft.AspNetCore.Mvc.Razor");
                    writer.Flush();

                    stream.Position = 0;
                    return(RazorSourceDocument.ReadFrom(stream, fileName: null, encoding: Encoding.UTF8));
                }
        }
예제 #25
0
 public override void Visit(RazorSyntaxTree tree)
 {
     _source = tree.Source;
     Visit(tree.Root);
 }
예제 #26
0
    private RazorCodeDocument CreateDocument(string content)
    {
        var source = RazorSourceDocument.Create(content, "test.cshtml");

        return(RazorCodeDocument.Create(source));
    }
예제 #27
0
 public HtmlParser(RazorSourceDocument source)
 {
     _source = source;
 }
예제 #28
0
        private static RazorSourceDocument Create(string path, string template)
        {
            var stream = new MemoryStream(Encoding.UTF8.GetBytes(template));

            return(RazorSourceDocument.ReadFrom(stream, path));
        }
예제 #29
0
        public void GetCompilationFailedResult_ReturnsCompilationResult_WithGroupedMessages()
        {
            // Arrange
            var viewPath = "Views/Home/Index";
            var generatedCodeFileName = "Generated Code";
            var codeDocument          = RazorCodeDocument.Create(RazorSourceDocument.Create("view-content", viewPath));
            var assemblyName          = "random-assembly-name";

            var diagnostics = new[]
            {
                Diagnostic.Create(
                    GetRoslynDiagnostic("message-1"),
                    Location.Create(
                        viewPath,
                        new TextSpan(10, 5),
                        new LinePositionSpan(new LinePosition(10, 1), new LinePosition(10, 2)))),
                Diagnostic.Create(
                    GetRoslynDiagnostic("message-2"),
                    Location.Create(
                        assemblyName,
                        new TextSpan(1, 6),
                        new LinePositionSpan(new LinePosition(1, 2), new LinePosition(3, 4)))),
                Diagnostic.Create(
                    GetRoslynDiagnostic("message-3"),
                    Location.Create(
                        viewPath,
                        new TextSpan(40, 50),
                        new LinePositionSpan(new LinePosition(30, 5), new LinePosition(40, 12)))),
            };

            // Act
            var compilationResult = CompilationFailedExceptionFactory.Create(
                codeDocument,
                "compilation-content",
                assemblyName,
                diagnostics);

            // Assert
            Assert.Collection(compilationResult.CompilationFailures,
                              failure =>
            {
                Assert.Equal(viewPath, failure.SourceFilePath);
                Assert.Equal("view-content", failure.SourceFileContent);
                Assert.Collection(failure.Messages,
                                  message =>
                {
                    Assert.Equal("message-1", message.Message);
                    Assert.Equal(viewPath, message.SourceFilePath);
                    Assert.Equal(11, message.StartLine);
                    Assert.Equal(2, message.StartColumn);
                    Assert.Equal(11, message.EndLine);
                    Assert.Equal(3, message.EndColumn);
                },
                                  message =>
                {
                    Assert.Equal("message-3", message.Message);
                    Assert.Equal(viewPath, message.SourceFilePath);
                    Assert.Equal(31, message.StartLine);
                    Assert.Equal(6, message.StartColumn);
                    Assert.Equal(41, message.EndLine);
                    Assert.Equal(13, message.EndColumn);
                });
            },
                              failure =>
            {
                Assert.Equal(generatedCodeFileName, failure.SourceFilePath);
                Assert.Equal("compilation-content", failure.SourceFileContent);
                Assert.Collection(failure.Messages,
                                  message =>
                {
                    Assert.Equal("message-2", message.Message);
                    Assert.Equal(assemblyName, message.SourceFilePath);
                    Assert.Equal(2, message.StartLine);
                    Assert.Equal(3, message.StartColumn);
                    Assert.Equal(4, message.EndLine);
                    Assert.Equal(5, message.EndColumn);
                });
            });
        }
예제 #30
0
 public RewriteWalker(RazorSourceDocument source)
 {
     _source = source;
 }