public void CreateHostFromConfigMergesNamespacesFromConfigToHost() { // Arrange RazorWebSectionGroup config = new RazorWebSectionGroup() { Host = null, Pages = new RazorPagesSection() { Namespaces = new NamespaceCollection() { new NamespaceInfo("System"), new NamespaceInfo("Foo") } } }; WebRazorHostFactory.TypeFactory = name => Assembly.GetExecutingAssembly().GetType(name, throwOnError: false); // Act WebPageRazorHost host = WebRazorHostFactory.CreateHostFromConfig(config, "/Foo/Bar.cshtml", null); // Assert Assert.True(host.NamespaceImports.Contains("System")); Assert.True(host.NamespaceImports.Contains("Foo")); }
public static string ParseRazor(string sourceRazor, string virtualPath, bool throws = false) { try { var extension = VirtualPathUtility.GetExtension(virtualPath); if (extension.IsEmpty() || extension != ".cshtml") { return(string.Empty); } Trace.TraceInformation("Parsing razor... {0}", virtualPath); var host = WebRazorHostFactory.CreateHostFromConfig(virtualPath); string code = GenerateCodeFromRazorString(host, sourceRazor, virtualPath); return(code); } catch (Exception ex) { Trace.TraceInformation("Error:... {0}", ex.Message); if (throws) { throw; } return(ex.Message); } }
public void CreateHostFromConfigIgnoresBaseTypeFromConfigIfPageIsAppStart() { // Arrange RazorWebSectionGroup config = new RazorWebSectionGroup() { Host = null, Pages = new RazorPagesSection() { PageBaseType = "System.Foo.Bar" } }; WebRazorHostFactory.TypeFactory = name => Assembly.GetExecutingAssembly().GetType(name, throwOnError: false); // Act WebPageRazorHost host = WebRazorHostFactory.CreateHostFromConfig( config, "/Foo/_appstart.cshtml", null ); // Assert Assert.Equal(typeof(ApplicationStartPage).FullName, host.DefaultBaseClass); }
public void CreateHostFromConfigUsesFactorySpecifiedInConfig() { // Arrange RazorWebSectionGroup config = new RazorWebSectionGroup() { Host = new HostSection() { FactoryType = typeof(TestFactory).FullName }, Pages = null }; WebRazorHostFactory.TypeFactory = name => Assembly.GetExecutingAssembly().GetType(name, throwOnError: false); // Act WebPageRazorHost host = WebRazorHostFactory.CreateHostFromConfig( config, "/Foo/Bar.cshtml", null ); // Assert Assert.IsType <TestHost>(host); }
public void CreateHostFromConfigAppliesBaseTypeFromConfigToHost() { // Arrange RazorWebSectionGroup config = new RazorWebSectionGroup() { Host = null, Pages = new RazorPagesSection() { PageBaseType = "System.Foo.Bar" } }; WebRazorHostFactory.TypeFactory = name => Assembly.GetExecutingAssembly().GetType(name, throwOnError: false); // Act WebPageRazorHost host = WebRazorHostFactory.CreateHostFromConfig( config, "/Foo/Bar.cshtml", null ); // Assert Assert.Equal("System.Foo.Bar", host.DefaultBaseClass); }
RazorEngineHost CreateRazorHost(string fileName) { var projectFile = project.GetProjectFile(fileName); if (projectFile != null && projectFile.Generator == "RazorTemplatePreprocessor") { var h = MonoDevelop.RazorGenerator.RazorTemplatePreprocessor.CreateHost(fileName); h.DesignTimeMode = true; return(h); } string virtualPath = "~/Views/Default.cshtml"; if (aspProject != null) { virtualPath = aspProject.LocalToVirtualPath(fileName); } WebPageRazorHost host = null; // Try to create host using web.config file var webConfigMap = new WebConfigurationFileMap(); if (aspProject != null) { var vdm = new VirtualDirectoryMapping(aspProject.BaseDirectory.Combine("Views"), true, "web.config"); webConfigMap.VirtualDirectories.Add("/", vdm); } Configuration configuration; try { configuration = WebConfigurationManager.OpenMappedWebConfiguration(webConfigMap, "/"); } catch { configuration = null; } if (configuration != null) { var rws = configuration.GetSectionGroup(RazorWebSectionGroup.GroupName) as RazorWebSectionGroup; if (rws != null) { host = WebRazorHostFactory.CreateHostFromConfig(rws, virtualPath, fileName); host.DesignTimeMode = true; } } if (host == null) { host = new MvcWebPageRazorHost(virtualPath, fileName) { DesignTimeMode = true }; // Add default namespaces from Razor section host.NamespaceImports.Add("System.Web.Mvc"); host.NamespaceImports.Add("System.Web.Mvc.Ajax"); host.NamespaceImports.Add("System.Web.Mvc.Html"); host.NamespaceImports.Add("System.Web.Routing"); } return(host); }
public void CreateHostFromConfigRequiresNonNullVirtualPath() { Assert.ThrowsArgumentNullOrEmptyString(() => WebRazorHostFactory.CreateHostFromConfig(virtualPath: null, physicalPath: "foo"), "virtualPath"); Assert.ThrowsArgumentNullOrEmptyString(() => WebRazorHostFactory.CreateHostFromConfig(config: new RazorWebSectionGroup(), virtualPath: null, physicalPath: "foo"), "virtualPath"); }
public void CreateHostFromConfigRequiresNonEmptyVirtualPath() { ExceptionAssert.ThrowsArgNullOrEmpty(() => WebRazorHostFactory.CreateHostFromConfig(virtualPath: String.Empty, physicalPath: "foo"), "virtualPath"); ExceptionAssert.ThrowsArgNullOrEmpty(() => WebRazorHostFactory.CreateHostFromConfig(config: new RazorWebSectionGroup(), virtualPath: String.Empty, physicalPath: "foo"), "virtualPath"); }
private Type GetTypeFromVirtualPathNoCache(string virtualPath) { // Use the Razor engine to generate source code from the view WebPageRazorHost host = WebRazorHostFactory.CreateHostFromConfig(virtualPath); string code = GenerateCodeFromRazorTemplate(host, virtualPath); // Use Roslyn to compile the code into an assembly Assembly assembly = CompileCodeIntoAssembly(code, virtualPath); return(assembly.GetType(String.Format(CultureInfo.CurrentCulture, "{0}.{1}", host.DefaultNamespace, host.DefaultClassName))); }
public void CreateHostFromConfigRequiresNonNullSectionGroup() { Assert.ThrowsArgumentNull( () => WebRazorHostFactory.CreateHostFromConfig( config: (RazorWebSectionGroup)null, virtualPath: String.Empty, physicalPath: "foo" ), "config" ); }
private Type GetTypeFromVirtualPathNoCache(string virtualPath) { using (DoProfileStep($"{nameof(RoslynRazorViewEngine)}: Compiling {virtualPath}")) { OnCodeGenerationStarted(); var args = new CompilingPathEventArgs(virtualPath, WebRazorHostFactory.CreateHostFromConfig(virtualPath)); OnBeforeCompilePath(args); var host = args.Host; var razorResult = RunRazorGenerator(virtualPath, host); var syntaxTree = GetSyntaxTree(host, razorResult); var assembly = CompileToAssembly(host, syntaxTree); return(assembly.GetType($"{host.DefaultNamespace}.{host.DefaultClassName}")); } }
public void CreateHostFromConfigUsesDefaultFactoryIfNoHostSectionFound() { // Arrange RazorWebSectionGroup config = new RazorWebSectionGroup() { Host = null, Pages = null }; // Act WebPageRazorHost host = WebRazorHostFactory.CreateHostFromConfig(config, "/Foo/Bar.cshtml", null); // Assert Assert.IsType <WebPageRazorHost>(host); }
public override SyntaxTree GetSyntaxTree(string sourcePath, Stream sourceStream, CSharpParseOptions parseOptions) { try { var viewFullPath = sourcePath; var viewVirtualPath = GetRelativeUri(sourcePath, Compilation.CurrentDirectory.FullName); var viewConfig = WebConfigurationManager.OpenMappedWebConfiguration(_configMap, viewVirtualPath); var razorConfig = viewConfig.GetSectionGroup("system.web.webPages.razor") as RazorWebSectionGroup; var host = razorConfig == null ? WebRazorHostFactory.CreateDefaultHost(viewVirtualPath, viewFullPath) : WebRazorHostFactory.CreateHostFromConfig(razorConfig, viewVirtualPath, viewFullPath); using (var rdr = new StreamReader(sourceStream, Compilation.Encoding, detectEncodingFromByteOrderMarks: true)) using (var provider = CodeDomProvider.CreateProvider("csharp")) using (var generatedStream = new MemoryStream()) using (var generatedWriter = new StreamWriter(generatedStream, Compilation.Encoding)) { var engine = new RazorTemplateEngine(host); var razorOut = engine.GenerateCode(rdr, null, null, viewFullPath); // add the CompiledFromFileAttribute to the generated class razorOut.GeneratedCode .Namespaces.OfType <CodeNamespace>().FirstOrDefault()? .Types.OfType <CodeTypeDeclaration>().FirstOrDefault()? .CustomAttributes.Add( new CodeAttributeDeclaration( new CodeTypeReference(typeof(CompiledFromFileAttribute)), new CodeAttributeArgument(new CodePrimitiveExpression(viewFullPath)) )); var codeGenOptions = new CodeGeneratorOptions { VerbatimOrder = true, ElseOnClosing = false, BlankLinesBetweenMembers = false }; provider.GenerateCodeFromCompileUnit(razorOut.GeneratedCode, generatedWriter, codeGenOptions); // rewind generatedWriter.Flush(); generatedStream.Position = 0; return(base.GetSyntaxTree(sourcePath, generatedStream, parseOptions)); } } catch (Exception ex) { Compilation.Diagnostics.Add(Diagnostic.Create(Compilation.ViewGenerationFailed, Compilation.AsLocation(sourcePath), ex.ToString())); return(null); } }
public void CreateHostFromConfigUsesDefaultFactoryIfNullFactoryType() { // Arrange RazorWebSectionGroup config = new RazorWebSectionGroup() { Host = new HostSection() { FactoryType = null }, Pages = null }; // Act WebPageRazorHost host = WebRazorHostFactory.CreateHostFromConfig(config, "/Foo/Bar.cshtml", null); // Assert Assert.IsInstanceOfType(host, typeof(WebPageRazorHost)); }
public void CreateHostFromConfigThrowsInvalidOperationExceptionIfFactoryTypeNotFound() { // Arrange RazorWebSectionGroup config = new RazorWebSectionGroup() { Host = new HostSection() { FactoryType = "Foo" }, Pages = null }; WebRazorHostFactory.TypeFactory = name => Assembly.GetExecutingAssembly().GetType(name, throwOnError: false); // Act Assert.Throws <InvalidOperationException>( () => WebRazorHostFactory.CreateHostFromConfig(config, "/Foo/Bar.cshtml", null), String.Format(RazorWebResources.Could_Not_Locate_FactoryType, "Foo")); }
private async Task BackgroundWorker() { foreach (var loader in _workItems.GetConsumingEnumerable(_cancellationToken)) { if (_cancellationToken.IsCancellationRequested) { loader.Result.SetCanceled(); continue; } try { var originalText = await loader.OriginalLoader.LoadTextAndVersionAsync(_workspace, null, default(CancellationToken)); var viewFullPath = originalText.FilePath; var viewVirtualPath = GetRelativeUri(originalText.FilePath, _compilation.CurrentDirectory.FullName); var viewConfig = WebConfigurationManager.OpenMappedWebConfiguration(_configMap, viewVirtualPath); var host = viewConfig.GetSectionGroup("system.web.webPages.razor") is RazorWebSectionGroup razorConfig ? WebRazorHostFactory.CreateHostFromConfig(razorConfig, viewVirtualPath, viewFullPath) : WebRazorHostFactory.CreateDefaultHost(viewVirtualPath, viewFullPath); // having this as a field would require the ASP.NET MVC dependency even for console apps... RazorWorker worker = RazorWorker; if (_cacheDirectory != null) { worker = CachedRazorWorker; } using (var stream = await worker(host, originalText)) { var generatedText = TextAndVersion.Create( SourceText.From(stream, _compilation.Encoding, _compilation.CscArgs.ChecksumAlgorithm, canBeEmbedded: originalText.Text.CanBeEmbedded, throwIfBinaryDetected: true), originalText.Version, originalText.FilePath); loader.Result.TrySetResult(generatedText); } } catch (Exception ex) { loader.Result.TrySetException(ex); } } }
private static WebPageRazorHost GetRazorWebPageRazorHost(string virtualPath, string physicalPath) { WebPageRazorHost webPageRazorHost = null; try { string physicalDirectory = physicalPath.Substring(0, physicalPath.Length - virtualPath.Length); string text = virtualPath.Replace('\\', '/'); if (!text.StartsWith("/", StringComparison.Ordinal)) { text = "/" + text; } int num = text.LastIndexOf('/'); text = text.Substring(0, (num == 0) ? 1 : num); WebConfigurationFileMap arg_62_0 = new WebConfigurationFileMap(); VirtualDirectoryMapping mapping = new VirtualDirectoryMapping(physicalDirectory, true); arg_62_0.VirtualDirectories.Add("/", mapping); Configuration configuration = WebConfigurationManager.OpenMappedWebConfiguration(arg_62_0, text); if (configuration != null) { RazorWebSectionGroup razorWebSectionGroup = (RazorWebSectionGroup)configuration.GetSectionGroup(RazorWebSectionGroup.GroupName); if (razorWebSectionGroup != null) { webPageRazorHost = WebRazorHostFactory.CreateHostFromConfig(razorWebSectionGroup, virtualPath, physicalPath); } } } catch (Exception) { } if (webPageRazorHost == null) { webPageRazorHost = WebRazorHostFactory.CreateDefaultHost(virtualPath, physicalPath); } return(webPageRazorHost); }
private CodeCompileUnit GenerateCodeByRazor(string inputFileContent) { var projectPath = Path.GetDirectoryName(GetProject().FullName); var projectRelativePath = InputFilePath.Substring(projectPath.Length); var virtualPath = VirtualPathUtility.ToAppRelative("~" + projectRelativePath); var config = WebConfigurationManager.OpenMappedWebConfiguration(new WebConfigurationFileMap { VirtualDirectories = { { "/", new VirtualDirectoryMapping(projectPath, true) } } }, projectRelativePath); var sectGroup = new RazorWebSectionGroup { Host = (HostSection)config.GetSection(HostSection.SectionName) ?? new HostSection { FactoryType = typeof(MvcWebRazorHostFactory).AssemblyQualifiedName }, Pages = (RazorPagesSection)config.GetSection(RazorPagesSection.SectionName) }; var host = projectRelativePath.IndexOf("app_code", StringComparison.InvariantCultureIgnoreCase) >= 0 ? /* Helper file: */ new WebCodeRazorHost(virtualPath, InputFilePath) : /* Regular view: */ WebRazorHostFactory.CreateHostFromConfig(sectGroup, virtualPath, InputFilePath); host.DefaultNamespace = FileNameSpace; host.DefaultDebugCompilation = string.Equals(GetVSProject().Project.ConfigurationManager.ActiveConfiguration.ConfigurationName, "debug", StringComparison.InvariantCultureIgnoreCase); host.DefaultClassName = Path.GetFileNameWithoutExtension(InputFilePath).Replace('.', '_'); var res = new RazorTemplateEngine(host).GenerateCode(new StringReader(inputFileContent), null, null, InputFilePath); foreach (RazorError error in res.ParserErrors) { GeneratorError(4, error.Message, (uint)error.Location.LineIndex + 1, (uint)error.Location.CharacterIndex + 1); } return(res.ParserErrors.Count > 0 ? null : res.GeneratedCode); }
private void WrapCshtmlReader(string sourcePath, TextReader sourceReader, MemoryStream generatedStream) { var viewFullPath = sourcePath; var viewVirtualPath = GetRelativeUri(sourcePath, _compilation.CurrentDirectory.FullName); var viewConfig = WebConfigurationManager.OpenMappedWebConfiguration(_configMap, viewVirtualPath); var razorConfig = viewConfig.GetSectionGroup("system.web.webPages.razor") as RazorWebSectionGroup; var host = razorConfig == null ? WebRazorHostFactory.CreateDefaultHost(viewVirtualPath, viewFullPath) : WebRazorHostFactory.CreateHostFromConfig(razorConfig, viewVirtualPath, viewFullPath); using (var provider = CodeDomProvider.CreateProvider("csharp")) using (var generatedWriter = new StreamWriter(generatedStream, _compilation.Encoding, 1024, leaveOpen: true)) { var engine = new RazorTemplateEngine(host); var razorOut = engine.GenerateCode(sourceReader, null, null, viewFullPath); // add the CompiledFromFileAttribute to the generated class razorOut.GeneratedCode .Namespaces.OfType <CodeNamespace>().FirstOrDefault()? .Types.OfType <CodeTypeDeclaration>().FirstOrDefault()? .CustomAttributes.Add( new CodeAttributeDeclaration( new CodeTypeReference(typeof(CompiledFromFileAttribute)), new CodeAttributeArgument(new CodePrimitiveExpression(viewFullPath)) )); var codeGenOptions = new CodeGeneratorOptions { VerbatimOrder = true, ElseOnClosing = false, BlankLinesBetweenMembers = false }; provider.GenerateCodeFromCompileUnit(razorOut.GeneratedCode, generatedWriter, codeGenOptions); // rewind generatedWriter.Flush(); generatedStream.Position = 0; } }
static RazorEngineHost CreateRazorHost(RazorCSharpParserContext context) { if (context.Project != null) { var projectFile = context.Project.GetProjectFile(context.FileName); if (projectFile != null && projectFile.Generator == "RazorTemplatePreprocessor") { return(new MonoDevelop.AspNet.Razor.Generator.PreprocessedRazorHost(context.FileName) { DesignTimeMode = true, EnableLinePragmas = false, }); } } string virtualPath = "~/Views/Default.cshtml"; if (context.AspProject != null) { virtualPath = context.AspProject.LocalToVirtualPath(context.FileName); } WebPageRazorHost host = null; // Try to create host using web.config file var webConfigMap = new WebConfigurationFileMap(); if (context.AspProject != null) { var vdm = new VirtualDirectoryMapping(context.AspProject.Project.BaseDirectory.Combine("Views"), true, "web.config"); webConfigMap.VirtualDirectories.Add("/", vdm); } Configuration configuration; try { configuration = WebConfigurationManager.OpenMappedWebConfiguration(webConfigMap, "/"); } catch { configuration = null; } if (configuration != null) { //TODO: use our assemblies, not the project's var rws = configuration.GetSectionGroup(RazorWebSectionGroup.GroupName) as RazorWebSectionGroup; if (rws != null) { host = WebRazorHostFactory.CreateHostFromConfig(rws, virtualPath, context.FileName); host.DesignTimeMode = true; } } if (host == null) { host = new MvcWebPageRazorHost(virtualPath, context.FileName) { DesignTimeMode = true }; // Add default namespaces from Razor section host.NamespaceImports.Add("System.Web.Mvc"); host.NamespaceImports.Add("System.Web.Mvc.Ajax"); host.NamespaceImports.Add("System.Web.Mvc.Html"); host.NamespaceImports.Add("System.Web.Routing"); } return(host); }
/// <summary> /// Function that builds the contents of the generated file based on the contents of the input file /// </summary> /// <param name="inputFileContent">Content of the input file</param> /// <returns>Generated file as a byte array</returns> protected override byte[] GenerateCode(string inputFileContent) { var references = GetVSProject().References; //add reference to our buildprovider and virtualpathprovider var buildprovAssembly = typeof(CompiledVirtualPathProvider).Assembly; if (references.Find(buildprovAssembly.GetName().Name) == null) { references.Add(buildprovAssembly.Location); } // Get the root folder of the project var appRoot = Path.GetDirectoryName(GetProject().FullName); // Determine the project-relative path string projectRelativePath = InputFilePath.Substring(appRoot.Length); // Turn it into a virtual path by prepending ~ and fixing it up string virtualPath = VirtualPathUtility.ToAppRelative("~" + projectRelativePath); var vdm = new VirtualDirectoryMapping(appRoot, true); var wcfm = new WebConfigurationFileMap(); wcfm.VirtualDirectories.Add("/", vdm); var config = WebConfigurationManager.OpenMappedWebConfiguration(wcfm, projectRelativePath); //System.Configuration.ConfigurationManager.OpenExeConfiguration(configFile); var sectGroup = new RazorWebSectionGroup { Host = (HostSection)config.GetSection(HostSection.SectionName) ?? new HostSection { FactoryType = typeof(MvcWebRazorHostFactory).AssemblyQualifiedName }, Pages = (RazorPagesSection)config.GetSection(RazorPagesSection.SectionName) }; // Create the same type of Razor host that's used to process Razor files in App_Code var host = IsHelper ? new WebCodeRazorHost(virtualPath, InputFilePath) : WebRazorHostFactory.CreateHostFromConfig(sectGroup, virtualPath, InputFilePath); // Set the namespace to be the same as what's used by default for regular .cs files host.DefaultNamespace = FileNameSpace; host.NamespaceImports.Remove("WebMatrix.Data"); host.NamespaceImports.Remove("WebMatrix.WebData"); var systemWebPages = config.GetSection("system.web/pages") as PagesSection; if (systemWebPages != null) { foreach (NamespaceInfo ns in systemWebPages.Namespaces) { if (!host.NamespaceImports.Contains(ns.Namespace)) { host.NamespaceImports.Add(ns.Namespace); } } } var compilationSection = config.GetSection("system.web/compilation") as CompilationSection; if (compilationSection != null) { foreach (AssemblyInfo assembly in compilationSection.Assemblies) { if (assembly.Assembly != "*" && references.Find(assembly.Assembly) == null) { references.Add(assembly.Assembly); } } } // Create a Razor engine and pass it our host var engine = new RazorTemplateEngine(host); // Generate code GeneratorResults results = null; try { using (TextReader reader = new StringReader(inputFileContent)) { results = engine.GenerateCode(reader, null, null, InputFilePath); } } catch (Exception e) { this.GeneratorError(4, e.ToString(), 1, 1); //Returning null signifies that generation has failed return(null); } // Output errors foreach (RazorError error in results.ParserErrors) { GeneratorError(4, error.Message, (uint)error.Location.LineIndex + 1, (uint)error.Location.CharacterIndex + 1); } CodeDomProvider provider = GetCodeProvider(); try { if (this.CodeGeneratorProgress != null) { //Report that we are 1/2 done this.CodeGeneratorProgress.Progress(50, 100); } using (StringWriter writer = new StringWriter(new StringBuilder())) { CodeGeneratorOptions options = new CodeGeneratorOptions(); options.BlankLinesBetweenMembers = false; options.BracingStyle = "C"; // Add a GeneratedCode attribute to the generated class CodeCompileUnit generatedCode = results.GeneratedCode; var ns = generatedCode.Namespaces[0]; CodeTypeDeclaration generatedType = ns.Types[0]; generatedType.CustomAttributes.Add( new CodeAttributeDeclaration( new CodeTypeReference(typeof(GeneratedCodeAttribute)), new CodeAttributeArgument(new CodePrimitiveExpression("MvcRazorClassGenerator")), new CodeAttributeArgument(new CodePrimitiveExpression("1.0")))); if (!IsHelper) { generatedType.CustomAttributes.Add( new CodeAttributeDeclaration( new CodeTypeReference(typeof(PageVirtualPathAttribute)), new CodeAttributeArgument(new CodePrimitiveExpression(virtualPath)))); } //Generate the code provider.GenerateCodeFromCompileUnit(generatedCode, writer, options); if (this.CodeGeneratorProgress != null) { //Report that we are done this.CodeGeneratorProgress.Progress(100, 100); } writer.Flush(); // Save as UTF8 Encoding enc = Encoding.UTF8; //Get the preamble (byte-order mark) for our encoding byte[] preamble = enc.GetPreamble(); int preambleLength = preamble.Length; //Convert the writer contents to a byte array byte[] body = enc.GetBytes(writer.ToString()); //Prepend the preamble to body (store result in resized preamble array) Array.Resize <byte>(ref preamble, preambleLength + body.Length); Array.Copy(body, 0, preamble, preambleLength, body.Length); //Return the combined byte array return(preamble); } } catch (Exception e) { this.GeneratorError(4, e.ToString(), 1, 1); //Returning null signifies that generation has failed return(null); } }