public void HtmlWithConditionalAttribute() { // Arrange var engine = RazorEngine.Create(); var document = CreateCodeDocument(); // Act engine.Process(document); // Assert AssertDocumentNodeMatchesBaseline(document.GetDocumentIntermediateNode()); }
public async Task Return_Empty_Imports_ForTextSource_ProjectItem() { //Assign var generator = new RazorSourceGenerator(RazorEngine.Create(), new EmbeddedRazorProject(typeof(Root))); //Act var projectItem = new TextSourceRazorProjectItem("key", "some content"); IEnumerable <RazorSourceDocument> result = await generator.GetImportsAsync(projectItem); //Assert Assert.NotNull(result); Assert.Empty(result); }
public void Ensure_Namespaces_Are_Passed() { var namespaces = new HashSet <string> { "System.Diagnostics", "System.CodeDom" }; var generator = new RazorSourceGenerator(RazorEngine.Create(), new EmbeddedRazorProject(typeof(Root)), namespaces); Assert.NotNull(generator.Namespaces); Assert.Equal(generator.Namespaces, namespaces); }
public void HelloWorld() { // Arrange var engine = RazorEngine.Create(); var document = CreateCodeDocument(); // Act engine.Process(document); // Assert AssertDocumentNodeMatchesBaseline(document.GetDocumentIntermediateNode()); }
public void GetCompilationFailedResult_ReadsContentFromImports() { // Arrange var viewPath = "/Views/Home/Index.cshtml"; var importsPath = "/Views/_MyImports.cshtml"; var fileContent = "@ "; var importsContent = "@(abc"; var fileSystem = new VirtualRazorProjectFileSystem(); fileSystem.Add(new TestRazorProjectItem(viewPath, fileContent)); fileSystem.Add(new TestRazorProjectItem("/Views/_MyImports.cshtml", importsContent)); var razorEngine = RazorEngine.Create(); var templateEngine = new MvcRazorTemplateEngine(razorEngine, fileSystem) { Options = { ImportsFileName = "_MyImports.cshtml", } }; var codeDocument = templateEngine.CreateCodeDocument(viewPath); // Act var csharpDocument = templateEngine.GenerateCode(codeDocument); var compilationResult = CompilationFailedExceptionFactory.Create(codeDocument, csharpDocument.Diagnostics); // Assert Assert.Collection( compilationResult.CompilationFailures, failure => { Assert.Equal(viewPath, failure.SourceFilePath); Assert.Collection(failure.Messages, message => { Assert.Equal(@"A space or line break was encountered after the ""@"" character. Only valid identifiers, keywords, comments, ""("" and ""{"" are valid at the start of a code block and they must occur immediately following ""@"" with no space in between.", message.Message); }); }, failure => { Assert.Equal(importsPath, failure.SourceFilePath); Assert.Collection(failure.Messages, message => { Assert.Equal(@"The explicit expression block is missing a closing "")"" character. Make sure you have a matching "")"" character for all the ""("" characters within this block, and that none of the "")"" characters are being interpreted as markup.", message.Message); }); }); }
public void BuildEngine_CallProcess() { // Arrange var engine = RazorEngine.Create(); var document = RazorCodeDocument.Create(TestRazorSourceDocument.Create()); // Act engine.Process(document); // Assert Assert.NotNull(document.GetSyntaxTree()); Assert.NotNull(document.GetDocumentIntermediateNode()); }
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); }
public void Execute_NoOps_IfNamespaceNodeIsMissing() { // Arrange var irDocument = new DocumentIntermediateNode(); var pass = new AssemblyAttributeInjectionPass { Engine = RazorEngine.Create(), }; // Act pass.Execute(TestRazorCodeDocument.CreateEmpty(), irDocument); // Assert Assert.Empty(irDocument.Children); }
public void DefaultImports_Created_On_Constructor() { var generator = new RazorSourceGenerator( RazorEngine.Create(), new EmbeddedRazorProject(typeof(RazorSourceGeneratorTest))); var defaultImports = generator.GetDefaultImportLines().ToList(); Assert.NotEmpty(defaultImports); Assert.Contains(defaultImports, i => i == "@using System"); Assert.Contains(defaultImports, i => i == "@using System.Threading.Tasks"); Assert.Contains(defaultImports, i => i == "@using System.Collections.Generic"); Assert.Contains(defaultImports, i => i == "@using System.Linq"); }
public void CustomDirective() { // Arrange var engine = RazorEngine.Create(b => { b.AddDirective(DirectiveDescriptor.CreateDirective("test", DirectiveKind.SingleLine)); }); var document = CreateCodeDocument(); // Act engine.Process(document); // Assert AssertDocumentNodeMatchesBaseline(document.GetDocumentIntermediateNode()); }
public void GenerateCodeWithDefaults() { // Arrange var project = new FileSystemRazorProject(TestProjectRoot); var razorEngine = RazorEngine.Create(engine => { engine.Features.Add(new SuppressChecksumOptionsFeature()); }); var templateEngine = new RazorTemplateEngine(razorEngine, project); // Act var cSharpDocument = templateEngine.GenerateCode($"{FileName}.cshtml"); // Assert AssertCSharpDocumentMatchesBaseline(cSharpDocument); }
private void _Init(string templateNamespace, string typeName, string basePath) { if (string.IsNullOrWhiteSpace(templateNamespace)) { throw new ArgumentNullException(nameof(templateNamespace), "Cannot be null or empty."); } if (string.IsNullOrWhiteSpace(typeName)) { throw new ArgumentNullException(nameof(typeName), "Cannot be null or empty."); } // customize the default engine a little bit var engine = RazorEngine.Create(b => { InheritsDirective.Register(b); // make sure the engine understand the @inherits directive in the input templates FunctionsDirective.Register(b); // make sure the engine understand the @function directive in the input templates SectionDirective.Register(b); // make sure the engine understand the @section directive in the input templates b.SetNamespace(templateNamespace); // define a namespace for the Template class b.Build(); }); var project = RazorProject.Create(HostingEnvironment.ContentRootPath); var templateEngine = new RazorTemplateEngine(engine, project); // get a razor-templated file. My "hello.txt" template file is defined like this: // // @inherits RazorTemplate.MyTemplate // Hello @Model.Name, welcome to Razor World! // var fileInfo = _FindView(typeName, basePath, out var filepath); // ... parse and generate C# code ... var codeDoc = RazorCSharpDocument.Create(); var cs = templateEngine.GenerateCode(codeDoc); // ... use roslyn to parse the C# code ... // var tree = CSharpSyntaxTree.ParseText(cs.GeneratedCode); // ... name the assembly ... // string dllName = templateNamespace + "." + typeName; var compilation = CSharpCompilation.Create(dllName, new[] { tree }, new[]
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 = RazorEngine.Create(), }; // Act var result = feature.GetIdentifier(codeDocument, sourceDocument); // Assert Assert.Null(result); }
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 = RazorEngine.Create(), }; // Act var result = feature.GetIdentifier(codeDocument, sourceDocument); // Assert Assert.Equal(expected, result); }
public void Setup() { var razorProject = RazorProject.Create(AppDomain.CurrentDomain.BaseDirectory); var razorEngine = RazorEngine.Create(b => { b.SetNamespace("Some.Namespace"); b.SetBaseType(typeof(MinimalistRazorTemplate).FullName); }); var razorTemplateEngine = new RazorTemplateEngine(razorEngine, razorProject); var references = AppDomain.CurrentDomain.GetAssemblies() .Where(a => !a.IsDynamic) .Select(a => MetadataReference.CreateFromFile(a.Location)) .ToList(); var emitOptions = new EmitOptions(debugInformationFormat: We.SupportFullPdb() ? DebugInformationFormat.Pdb : DebugInformationFormat.PortablePdb); _renderer = new RazorViewCompiler(razorTemplateEngine, references, emitOptions); }
public void GetDefaultImports_IncludesDefaultTagHelpers() { // Arrange var mvcRazorTemplateEngine = new MvcRazorTemplateEngine( RazorEngine.Create(), new TestRazorProjectFileSystem()); // Act var imports = mvcRazorTemplateEngine.Options.DefaultImports; // Assert var importContent = GetContent(imports) .Split(new[] { Environment.NewLine }, StringSplitOptions.None) .Where(line => line.StartsWith("@addTagHelper")); Assert.Contains("@addTagHelper Microsoft.AspNetCore.Mvc.Razor.TagHelpers.UrlResolutionTagHelper, Microsoft.AspNetCore.Mvc.Razor", importContent); }
public void Execute_NoOps_ForDesignTime() { // Arrange var irDocument = new DocumentIntermediateNode { DocumentKind = MvcViewDocumentClassifierPass.MvcViewDocumentKind, Options = RazorCodeGenerationOptions.CreateDesignTimeDefault(), }; var builder = IntermediateNodeBuilder.Create(irDocument); var @namespace = new NamespaceDeclarationIntermediateNode { Content = "SomeNamespace", Annotations = { [CommonAnnotations.PrimaryNamespace] = CommonAnnotations.PrimaryNamespace }, }; builder.Push(@namespace); var @class = new ClassDeclarationIntermediateNode { ClassName = "SomeName", Annotations = { [CommonAnnotations.PrimaryClass] = CommonAnnotations.PrimaryClass, }, }; builder.Add(@class); var pass = new AssemblyAttributeInjectionPass { Engine = RazorEngine.Create(), }; var source = TestRazorSourceDocument.Create("test", new RazorSourceDocumentProperties(filePath: null, relativePath: "/Views/Index.cshtml")); var document = RazorCodeDocument.Create(source); // Act pass.Execute(document, irDocument); // Assert Assert.Collection( irDocument.Children, node => Assert.Same(@namespace, node)); }
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 }); })); }
public void GenerateCodeWithSetNamespace() { // Arrange var fileSystem = new DefaultRazorProjectFileSystem(TestProjectRoot); var razorEngine = RazorEngine.Create(engine => { engine.Features.Add(new SuppressChecksumOptionsFeature()); engine.SetNamespace("MyApp.Razor.Views"); }); var templateEngine = new RazorTemplateEngine(razorEngine, fileSystem); // Act var cSharpDocument = templateEngine.GenerateCode($"{FileName}.cshtml"); // Assert AssertCSharpDocumentMatchesBaseline(cSharpDocument); }
public void GetChangeToken_WatchesAllCshtmlFilesUnderFileSystemRoot() { // Arrange var fileProvider = new Mock <IFileProvider>(); var accessor = Mock.Of <IRazorViewEngineFileProviderAccessor>(a => a.FileProvider == fileProvider.Object); var templateEngine = new RazorTemplateEngine( RazorEngine.Create(), new FileProviderRazorProject(accessor)); var options = Options.Create(new RazorPagesOptions()); var changeProvider = new PageActionDescriptorChangeProvider(templateEngine, accessor, options); // Act var changeToken = changeProvider.GetChangeToken(); // Assert fileProvider.Verify(f => f.Watch("/Pages/**/*.cshtml")); }
public DaoGenerator() { logger = this.CreateLogger(); engine = RazorEngine.Create(builder => { FunctionsDirective.Register(builder); InheritsDirective.Register(builder); SectionDirective.Register(builder); builder.Features.Add(new SqlDocumentClassifierPassBase()); }); assembly = GetType().Assembly; assemblyName = Path.GetRandomFileName(); types = new List <Type>(); syntaxTrees = new List <SyntaxTree>(); Extractor = new Extractor(); }
protected override RazorPageGeneratorResult Generate(string rootNamespace, string targetPath, Type modelType) { var baseTypeName = "KiraNet.GutsMvc.View.RazorPageViewBase"; if (modelType != null) { baseTypeName = $"{baseTypeName}<{TypeHelper.GetCSharpTypeName(modelType)}>"; } var className = String.Empty; var razorEngine = RazorEngine.Create(builder => { builder .SetNamespace(rootNamespace) .SetBaseType(baseTypeName) .ConfigureClass((document, @class) => { @class.ClassName = className = Path.GetFileNameWithoutExtension(document.Source.FilePath) + DateTime.Now.Ticks; @class.Modifiers.Clear(); @class.Modifiers.Add("internal"); }); builder.Features.Add(new SuppressChecksumOptionsFeature()); }); var razorProject = RazorProject.Create(ViewPath.Path); var templateEngine = new RazorTemplateEngine(razorEngine, razorProject); templateEngine.Options.DefaultImports = RazorSourceDocument.Create(@" @using System @using System.Threading.Tasks @using System.Collections.Generic @using System.Collections ", fileName: null); //templateEngine.Options.DefaultImports = RazorSourceDocument.Create("", null); var cshtmlFile = razorProject.GetItem(targetPath); var razorResult = GenerateCodeFile(templateEngine, cshtmlFile); razorResult.ClassName = className; return(razorResult); }
public void GenerateCodeWithBaseType() { // Arrange var filePath = Path.Combine(TestProjectRoot, $"{FileName}.cshtml"); var content = File.ReadAllText(filePath); var projectItem = new TestRazorProjectItem($"{FileName}.cshtml", "") { Content = content, }; var project = new TestRazorProject(new[] { projectItem }); var razorEngine = RazorEngine.Create(engine => engine.SetBaseType("MyBaseType")); var templateEngine = new RazorTemplateEngine(razorEngine, project); // Act var cSharpDocument = templateEngine.GenerateCode(projectItem.FilePath); // Assert AssertCSharpDocumentMatchesBaseline(cSharpDocument); }
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 projectSystem = new FileProviderRazorProject(accessor, hostingEnvironment); var templateEngine = new RazorTemplateEngine(RazorEngine.Create(), projectSystem) { Options = { ImportsFileName = "_ViewImports.cshtml", } }; var viewCompiler = new TestRazorViewCompiler( fileProvider, templateEngine, new CSharpCompiler(referenceManager, hostingEnvironment), compilationCallback, precompiledViews); return(viewCompiler); }
public void CSharpDocument_Runtime_PreservesParserErrors() { // Arrange var engine = RazorEngine.Create(); var document = RazorCodeDocument.Create(TestRazorSourceDocument.Create("@!!!", fileName: "test.cshtml")); var expected = RazorDiagnosticFactory.CreateParsing_UnexpectedCharacterAtStartOfCodeBlock( new SourceSpan(new SourceLocation("test.cshtml", 1, 0, 1), contentLength: 1), "!"); // Act engine.Process(document); // Assert var csharpDocument = document.GetCSharpDocument(); var error = Assert.Single(csharpDocument.Diagnostics); Assert.Equal(expected, error); }
public void SimpleTagHelpers() { // Arrange var descriptors = new[] { CreateTagHelperDescriptor( tagName: "input", typeName: "InputTagHelper", assemblyName: "TestAssembly") }; var engine = RazorEngine.Create(builder => builder.AddTagHelpers(descriptors)); var document = CreateCodeDocument(); // Act engine.Process(document); // Assert AssertDocumentNodeMatchesBaseline(document.GetDocumentIntermediateNode()); }
public BlazorRazorEngine() { _codegenOptions = RazorCodeGenerationOptions.CreateDefault(); _engine = RazorEngine.Create(configure => { FunctionsDirective.Register(configure); configure.SetBaseType(typeof(BlazorComponent).FullName); configure.Phases.Remove( configure.Phases.OfType <IRazorCSharpLoweringPhase>().Single()); configure.Phases.Add(new BlazorLoweringPhase(_codegenOptions)); configure.ConfigureClass((codeDoc, classNode) => { configure.SetNamespace((string)codeDoc.Items[BlazorCodeDocItems.Namespace]); classNode.ClassName = (string)codeDoc.Items[BlazorCodeDocItems.ClassName]; }); }); }
public void CSharpDocument_Runtime_PreservesParserErrors() { // Arrange var engine = RazorEngine.Create(); var document = RazorCodeDocument.Create(TestRazorSourceDocument.Create("@!!!", fileName: "test.cshtml")); var expected = RazorDiagnostic.Create(new RazorError( LegacyResources.FormatParseError_Unexpected_Character_At_Start_Of_CodeBlock_CS("!"), new SourceLocation("test.cshtml", 1, 0, 1), length: 1)); // Act engine.Process(document); // Assert var csharpDocument = document.GetCSharpDocument(); var error = Assert.Single(csharpDocument.Diagnostics); Assert.Equal(expected, error); }
public void GetChangeToken_WatchesAllCshtmlFilesUnderSpecifiedRootDirectory(string rootDirectory) { // Arrange var fileProvider = new Mock <IFileProvider>(); var accessor = Mock.Of <IRazorViewEngineFileProviderAccessor>(a => a.FileProvider == fileProvider.Object); var templateEngine = new RazorTemplateEngine( RazorEngine.Create(), new FileProviderRazorProject(accessor)); var options = Options.Create(new RazorPagesOptions()); options.Value.RootDirectory = rootDirectory; var changeProvider = new PageActionDescriptorChangeProvider(templateEngine, accessor, options); // Act var changeToken = changeProvider.GetChangeToken(); // Assert fileProvider.Verify(f => f.Watch("/pages-base-dir/**/*.cshtml")); }
public void Execute_NoOps_IfClassNameIsEmpty() { // Arrange var irDocument = new DocumentIntermediateNode() { Options = RazorCodeGenerationOptions.CreateDefault(), }; var builder = IntermediateNodeBuilder.Create(irDocument); var @namespace = new NamespaceDeclarationIntermediateNode { Content = "SomeNamespace", Annotations = { [CommonAnnotations.PrimaryNamespace] = CommonAnnotations.PrimaryNamespace, }, }; builder.Push(@namespace); var @class = new ClassDeclarationIntermediateNode { Annotations = { [CommonAnnotations.PrimaryClass] = CommonAnnotations.PrimaryClass, }, }; builder.Add(@class); var pass = new AssemblyAttributeInjectionPass { Engine = RazorEngine.Create(), }; // Act pass.Execute(TestRazorCodeDocument.CreateEmpty(), irDocument); // Assert Assert.Collection(irDocument.Children, node => Assert.Same(@namespace, node)); }