private static string GenerateCodeFromRazorString(WebPageRazorHost host, string razorString, string virtualPath) { // Create Razor engine and use it to generate a CodeCompileUnit var engine = new RazorTemplateEngine(host); GeneratorResults results = null; using (StringReader reader = new StringReader(razorString)) { results = engine.GenerateCode(reader, className: null, rootNamespace: null, sourceFileName: host.PhysicalPath); } if (!results.Success) { throw CreateExceptionFromParserError(results.ParserErrors.Last(), virtualPath); } // Use CodeDom to generate source code from the CodeCompileUnit using (var codeDomProvider = new CSharpCodeProvider()) { using (var srcFileWriter = new StringWriter()) { codeDomProvider.GenerateCodeFromCompileUnit(results.GeneratedCode, srcFileWriter, new CodeGeneratorOptions()); return(srcFileWriter.ToString()); } } }
public void BuildProviderFiresEventToAlterHostBeforeBuildingPath() { // Arrange WebPageRazorHost expected = new TestHost("~/Foo/Boz.cshtml", @"C:\Foo\Boz.cshtml"); WebPageRazorHost expectedBefore = new WebPageRazorHost("~/Foo/Baz.cshtml", @"C:\Foo\Baz.cshtml"); RazorBuildProvider provider = CreateBuildProvider("foo"); typeof(BuildProvider).GetField("_virtualPath", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(provider, CreateVirtualPath("/Samples/Foo/Baz.cshtml")); Mock.Get(provider).Setup(p => p.GetHostFromConfig()).Returns(expectedBefore); bool called = false; EventHandler <CompilingPathEventArgs> handler = (sender, args) => { Assert.Equal("/Samples/Foo/Baz.cshtml", args.VirtualPath); Assert.Same(expectedBefore, args.Host); args.Host = expected; called = true; }; RazorBuildProvider.CompilingPath += handler; try { // Act CodeCompileUnit ccu = provider.GeneratedCode; // Assert Assert.Equal("Test", ccu.Namespaces[0].Name); Assert.Same(expected, provider.Host); Assert.True(called); } finally { RazorBuildProvider.CompilingPath -= handler; } }
public void PostProcessGeneratedCodeAddsApplicationInstanceProperty() { const string expectedPropertyCode = @" protected Foo.Bar ApplicationInstance { get { return ((Foo.Bar)(Context.ApplicationInstance)); } } "; // Arrange CodeCompileUnit generatedCode = new CodeCompileUnit(); CodeNamespace generatedNamespace = new CodeNamespace(); CodeTypeDeclaration generatedClass = new CodeTypeDeclaration(); CodeMemberMethod executeMethod = new CodeMemberMethod(); WebPageRazorHost host = new WebPageRazorHost("Foo.cshtml") { GlobalAsaxTypeName = "Foo.Bar" }; // Act host.PostProcessGeneratedCode(generatedCode, generatedNamespace, generatedClass, executeMethod); // Assert CodeMemberProperty property = generatedClass.Members[0] as CodeMemberProperty; Assert.IsNotNull(property); CSharpCodeProvider provider = new CSharpCodeProvider(); StringBuilder builder = new StringBuilder(); using(StringWriter writer = new StringWriter(builder)) { provider.GenerateCodeFromMember(property, writer, new CodeDom.Compiler.CodeGeneratorOptions()); } Assert.AreEqual(expectedPropertyCode, builder.ToString()); }
private string GenerateCodeFromRazorTemplate(WebPageRazorHost host, string virtualPath) { // Create Razor engine and use it to generate a CodeCompileUnit var engine = new RazorTemplateEngine(host); GeneratorResults results = null; VirtualFile file = HostingEnvironment.VirtualPathProvider.GetFile(virtualPath); using (var stream = file.Open()) { using (TextReader reader = new StreamReader(stream)) { results = engine.GenerateCode(reader, className: null, rootNamespace: null, sourceFileName: host.PhysicalPath); } } if (!results.Success) { throw CreateExceptionFromParserError(results.ParserErrors.Last(), virtualPath); } // Use CodeDom to generate source code from the CodeCompileUnit var codeDomProvider = new CSharpCodeProvider(); var srcFileWriter = new StringWriter(); codeDomProvider.GenerateCodeFromCompileUnit(results.GeneratedCode, srcFileWriter, new CodeGeneratorOptions()); return(srcFileWriter.ToString()); }
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); }
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); }
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 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); }
private static Assembly CompileToAssembly(WebPageRazorHost host, SyntaxTree syntaxTree) { var compilation = CSharpCompilation.Create( "RoslynRazor", // Note: using a fixed assembly name, which doesn't matter as long as we don't expect cross references of generated assemblies new[] { syntaxTree }, BuildManager.GetReferencedAssemblies().OfType <Assembly>().Select(ResolveReference), new CSharpCompilationOptions( outputKind: OutputKind.DynamicallyLinkedLibrary, assemblyIdentityComparer: DesktopAssemblyIdentityComparer.Default, optimizationLevel: host.DefaultDebugCompilation ? OptimizationLevel.Debug : OptimizationLevel.Release)); using (var dllStream = new MemoryStream()) using (var pdbStream = new MemoryStream()) { EmitResult emitResult = compilation.Emit(dllStream, pdbStream); if (!emitResult.Success) { Diagnostic diagnostic = emitResult.Diagnostics.First(x => x.Severity == DiagnosticSeverity.Error); string message = diagnostic.ToString(); LinePosition linePosition = diagnostic.Location.GetMappedLineSpan().StartLinePosition; throw new HttpParseException(message, null, host.VirtualPath, null, linePosition.Line + 1); } return(Assembly.Load(dllStream.GetBuffer(), pdbStream.GetBuffer())); } }
public static void Initialize() { WebPageRazorHost.AddGlobalImport("MvcSiteMapProvider.Web.Html"); WebPageRazorHost.AddGlobalImport("MvcSiteMapProvider.Web.Html.Models"); var settings = new ConfigurationSettings(); if (settings.EnableSiteMapFile) { var validator = new SiteMapXmlValidator(); validator.ValidateXml(HostingEnvironment.MapPath(settings.SiteMapFileName)); } if (DependencyResolver.Current.GetType().FullName.Equals("System.Web.Mvc.DependencyResolver+DefaultDependencyResolver")) { var currentFactory = ControllerBuilder.Current.GetControllerFactory(); ControllerBuilder.Current.SetControllerFactory( new ControllerFactoryDecorator(currentFactory, settings)); } else { var currentResolver = DependencyResolver.Current; DependencyResolver.SetResolver(new DependencyResolverDecorator(currentResolver, settings)); } var siteMapLoaderContainer = new CustomSiteMapLoaderContainer(settings); SiteMaps.Loader = siteMapLoaderContainer.ResolveSiteMapLoader(); if (settings.EnableSitemapsXml) { XmlSiteMapController.RegisterRoutes(RouteTable.Routes); } }
public static void Start() { // Even though ASP.NET will only call each PreAppStart once, we sometimes internally call one PreAppStart from // another PreAppStart to ensure that things get initialized in the right order. ASP.NET does not guarantee the // order so we have to guard against multiple calls. // All Start calls are made on same thread, so no lock needed here. if (_startWasCalled) { return; } _startWasCalled = true; // Summary of Simple Membership startup behavior: // 1. If the appSetting enabledSimpleMembership is present and equal to "false", NEITHER SimpleMembership NOR AutoFormsAuth are activated // 2. If the appSetting is true, a non-boolean string or not present, BOTH may be activated // a. SimpleMembership ONLY replaces the AspNetSqlMemberhipProvider, but it does replace it even if it isn't the default. This // means that anything accessing this provider by name will get Simple Membership, but if this provider is no longer the default // then SimpleMembership does not affect the default // b. SimpleMembership delegates to the previous default provider UNLESS WebSecurity.InitializeDatabaseConnection is called. // Initialize membership provider WebSecurity.PreAppStartInit(); // Initialize Forms Authentication default configuration SetUpFormsAuthentication(); // Wire up WebMatrix.Data's Database object to the ASP.NET Web Pages resource tracker Database.ConnectionOpened += OnConnectionOpened; // Auto import the WebMatrix.Data and WebMatrix.WebData namespaces to all apps that are executing. WebPageRazorHost.AddGlobalImport("WebMatrix.Data"); WebPageRazorHost.AddGlobalImport("WebMatrix.WebData"); }
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 void CreateHostFromConfigUsesDefaultFactoryIfNoRazorWebSectionGroupFound() { // Act WebPageRazorHost host = WebRazorHostFactory.CreateHostFromConfigCore(null, "/Foo/Bar.cshtml", null); // Assert Assert.IsType <WebPageRazorHost>(host); }
/// <summary> /// Register global namepace imports for this assembly /// </summary> public static void Start() { WebPageRazorHost.AddGlobalImport("DotNetOpenAuth.AspNet"); WebPageRazorHost.AddGlobalImport("Microsoft.Web.WebPages.OAuth"); // Disable the "calls home" feature of DNOA DotNetOpenAuth.Reporting.Enabled = false; }
public void CreateHostFromConfigReturnsWebCodeHostIfVirtualPathStartsWithAppCode() { // Act WebPageRazorHost host = WebRazorHostFactory.CreateHostFromConfigCore(null, "~/App_Code/Bar.cshtml", null); // Assert Assert.IsType <WebCodeRazorHost>(host); }
private static Assembly CompileToAssembly(WebPageRazorHost host, SyntaxTree syntaxTree, ICollection <ICompileModule> compilationModules) { var strArgs = new List <string>(); strArgs.Add("/target:library"); strArgs.Add(host.DefaultDebugCompilation ? "/o-" : "/o+"); strArgs.Add(host.DefaultDebugCompilation ? "/debug+" : "/debug-"); var cscArgs = CSharpCommandLineParser.Default.Parse(strArgs, null, null); var compilation = CSharpCompilation.Create( "RoslynRazor", // Note: using a fixed assembly name, which doesn't matter as long as we don't expect cross references of generated assemblies new[] { syntaxTree }, BuildManager.GetReferencedAssemblies().OfType <Assembly>().Select(ResolveReference), cscArgs.CompilationOptions.WithAssemblyIdentityComparer(DesktopAssemblyIdentityComparer.Default)); compilation = Hacks.MakeValueTuplesWorkWhenRunningOn47RuntimeAndTargetingNet45Plus(compilation); var diagnostics = new List <Diagnostic>(); var context = new CompileContext(compilationModules); context.Before(new BeforeCompileContext { Arguments = cscArgs, Compilation = compilation, Diagnostics = diagnostics, }); compilation = context.BeforeCompileContext.Compilation; using (var dllStream = new MemoryStream()) using (var pdbStream = new MemoryStream()) { EmitResult emitResult = compilation.Emit(dllStream, pdbStream); diagnostics.AddRange(emitResult.Diagnostics); if (!emitResult.Success) { Diagnostic diagnostic = diagnostics.First(x => x.Severity == DiagnosticSeverity.Error); string message = diagnostic.ToString(); LinePosition linePosition = diagnostic.Location.GetMappedLineSpan().StartLinePosition; throw new HttpParseException(message, null, host.VirtualPath, null, linePosition.Line + 1); } context.After(new AfterCompileContext { Arguments = context.BeforeCompileContext.Arguments, AssemblyStream = dllStream, Compilation = compilation, Diagnostics = diagnostics, SymbolStream = pdbStream, XmlDocStream = null, }); return(Assembly.Load(dllStream.GetBuffer(), pdbStream.GetBuffer())); } }
public void ConstructorWithVirtualPathUsesItToDetermineBaseClassClassNameAndLanguage() { // Act WebPageRazorHost host = new WebPageRazorHost("~/Foo/Bar.cshtml"); // Assert Assert.AreEqual("_Page_Foo_Bar_cshtml", host.DefaultClassName); Assert.AreEqual("System.Web.WebPages.WebPage", host.DefaultBaseClass); Assert.IsInstanceOfType(host.CodeLanguage, typeof(CSharpRazorCodeLanguage)); Assert.IsFalse(host.StaticHelpers); }
public override WebPageRazorHost CreateHost(string virtualPath, string physicalPath) { WebPageRazorHost host = base.CreateHost(virtualPath, physicalPath); if ((host.IsSpecialPage) || (host.DesignTimeMode)) { return(host); } return(new MinifyHtmlMvcWebPageRazorHost(host, _minifier, virtualPath, physicalPath)); }
public void CreateHost_DoesNotChangePageStartFileHost() { // Arrange MvcWebRazorHostFactory factory = new MvcWebRazorHostFactory(); // Act WebPageRazorHost result = factory.CreateHost("_pagestart.cshtml", null); // Assert Assert.IsNotType <MvcWebPageRazorHost>(result); }
public override WebPageRazorHost CreateHost(string virtualPath, string physicalPath) { WebPageRazorHost host = base.CreateHost(virtualPath, physicalPath); if (host.IsSpecialPage || host.DesignTimeMode) { return(host); } return(new HtmlOptimizerMvc4WebPageRazorHost(virtualPath, physicalPath)); }
public void GeneratedCodeThrowsHttpParseExceptionForLastParserError() { // Arrange WebPageRazorHost host = new WebPageRazorHost("~/Foo/Baz.cshtml", @"C:\Foo\Baz.cshtml"); RazorBuildProvider provider = CreateBuildProvider("foo @{ if( baz"); provider.Host = host; // Act Assert.Throws <HttpParseException>(() => { CodeCompileUnit ccu = provider.GeneratedCode; }); }
/// <summary> /// Creates the host. /// </summary> /// <param name="virtualPath">The virtual path</param> /// <param name="physicalPath">The physical path</param> /// <returns></returns> public override WebPageRazorHost CreateHost(string virtualPath, string physicalPath) { if (DisableMinify) { return(base.CreateHost(virtualPath, physicalPath)); } WebPageRazorHost host = base.CreateHost(virtualPath, physicalPath); return(!host.IsSpecialPage ? new RazorMinificationHost(virtualPath, physicalPath) : host); }
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 CreateHost_ReplacesRegularHostWithMvcSpecificOne() { // Arrange MvcWebRazorHostFactory factory = new MvcWebRazorHostFactory(); // Act WebPageRazorHost result = factory.CreateHost("foo.cshtml", null); // Assert Assert.IsType <MvcWebPageRazorHost>(result); }
public void CreateHost_DoesNotChangeAppStartFileHost() { // Arrange MvcWebRazorHostFactory factory = new MvcWebRazorHostFactory(); // Act WebPageRazorHost result = factory.CreateHost("_appstart.cshtml", null); // Assert Assert.IsNotInstanceOfType(result, typeof(MvcWebPageRazorHost)); }
public ShimRazorEditorParserImpl(string virtualPath, string physicalPath) { WebPageRazorHost razorWebPageRazorHost = ShimRazorEditorParserImpl.GetRazorWebPageRazorHost(virtualPath, physicalPath); HtmlSettings.Changed += OnSettingsChanged; razorWebPageRazorHost.DesignTimeMode = true; OnSettingsChanged(razorWebPageRazorHost); _codeDomProviderType = razorWebPageRazorHost.CodeLanguage.CodeDomProviderType; RazorEditorParser = new RazorEditorParser(razorWebPageRazorHost, physicalPath); RazorEditorParser.DocumentParseComplete += OnDocumentParseComplete; }
public override WebPageRazorHost CreateHost(string virtualPath, string physicalPath) { WebPageRazorHost host = base.CreateHost(virtualPath, physicalPath); if (!host.IsSpecialPage) { return(new MvcWebPageRazorHost(virtualPath, physicalPath)); } return(host); }
public void CodeCompilerTypeReturnsTypeFromCodeLanguage() { // Arrange WebPageRazorHost host = new WebPageRazorHost("~/Foo/Bar.vbhtml", @"C:\Foo\Bar.vbhtml"); RazorBuildProvider provider = CreateBuildProvider("foo @bar baz"); provider.Host = host; // Act CompilerType type = provider.CodeCompilerType; // Assert Assert.AreEqual(typeof(VBCodeProvider), type.CodeDomProviderType); }
public void CodeGenerationStartedTest() { // Arrange WebPageRazorHost host = new WebPageRazorHost("~/Foo/Baz.cshtml", @"C:\Foo\Baz.cshtml"); RazorBuildProvider provider = CreateBuildProvider("foo @bar baz"); provider.Host = host; // Expected original base dependencies var baseDependencies = new ArrayList(); baseDependencies.Add("/Samples/Foo/Baz.cshtml"); // Expected list of dependencies after GenerateCode is called var dependencies = new ArrayList(); dependencies.Add(baseDependencies[0]); dependencies.Add("/Samples/Foo/Foo.cshtml"); // Set up the event handler provider.CodeGenerationStartedInternal += (sender, e) => { var bp = sender as RazorBuildProvider; bp.AddVirtualPathDependency("/Samples/Foo/Foo.cshtml"); }; // Set up the base dependency MockAssemblyBuilder builder = new MockAssemblyBuilder(); typeof(BuildProvider) .GetField("_virtualPath", BindingFlags.NonPublic | BindingFlags.Instance) .SetValue(provider, CreateVirtualPath("/Samples/Foo/Baz.cshtml")); // Test that VirtualPathDependencies returns the original dependency before GenerateCode is called Assert.True( baseDependencies .OfType <string>() .SequenceEqual(provider.VirtualPathDependencies.OfType <string>()) ); // Act provider.GenerateCodeCore(builder); // Assert Assert.NotNull(provider.AssemblyBuilderInternal); Assert.Equal(builder, provider.AssemblyBuilderInternal); Assert.True( dependencies .OfType <string>() .SequenceEqual(provider.VirtualPathDependencies.OfType <string>()) ); Assert.Equal("/Samples/Foo/Baz.cshtml", provider.VirtualPath); }
public void CodeCompilerTypeSetsDebugFlagInFullTrust() { // Arrange WebPageRazorHost host = new WebPageRazorHost("~/Foo/Bar.vbhtml", @"C:\Foo\Bar.vbhtml"); RazorBuildProvider provider = CreateBuildProvider("foo @bar baz"); provider.Host = host; // Act CompilerType type = provider.CodeCompilerType; // Assert Assert.IsTrue(type.CompilerParameters.IncludeDebugInformation); }
public void StartTest() { AppDomainUtils.RunInSeparateAppDomain(() => { // Act AppDomainUtils.SetPreAppStartStage(); PreApplicationStartCode.Start(); // Assert var imports = WebPageRazorHost.GetGlobalImports(); Assert.IsTrue(imports.Any(ns => ns.Equals("Microsoft.Web.Helpers"))); }); }
public static void Compose() { #if !MVC2 // Register global namespaces with Razor so we don't have to import them in Web.config WebPageRazorHost.AddGlobalImport("MvcSiteMapProvider.Web.Html"); WebPageRazorHost.AddGlobalImport("MvcSiteMapProvider.Web.Html.Models"); #endif // Get the configuration settings var settings = new ConfigurationSettings(); // If the config specifies to use an external DI container, skip the internal container. if (!settings.UseExternalDIContainer) { if (settings.EnableSiteMapFile) { // Validate the Xml File. var validator = new SiteMapXmlValidator(); validator.ValidateXml(HostingEnvironment.MapPath(settings.SiteMapFileName)); } #if !MVC2 // If not using a custom DependencyResolver, we prefer to use IControllerFactory if (DependencyResolver.Current.GetType().FullName.Equals("System.Web.Mvc.DependencyResolver+DefaultDependencyResolver")) { #endif // Setup the Controller Factory with a decorator that can resolve the internal controllers var currentFactory = ControllerBuilder.Current.GetControllerFactory(); ControllerBuilder.Current.SetControllerFactory( new ControllerFactoryDecorator(currentFactory, settings)); #if !MVC2 } else { // If using a custom IDependencyResolver, decorate it with our IDependencyResolver so we can resolve // our internal controller. var currentResolver = DependencyResolver.Current; DependencyResolver.SetResolver(new DependencyResolverDecorator(currentResolver, settings)); } #endif // Set the static loader instance var siteMapLoaderContainer = new SiteMapLoaderContainer(settings); SiteMaps.Loader = siteMapLoaderContainer.ResolveSiteMapLoader(); if (settings.EnableSitemapsXml) { // Register the route for SiteMaps XML XmlSiteMapController.RegisterRoutes(RouteTable.Routes); } } }
public void GetGeneratedTypeUsesNameAndNamespaceFromHostToExtractType() { // Arrange WebPageRazorHost host = new WebPageRazorHost("~/Foo/Test.cshtml", @"C:\Foo\Test.cshtml"); RazorBuildProvider provider = new RazorBuildProvider() { Host = host }; CompilerResults results = new CompilerResults(new TempFileCollection()); results.CompiledAssembly = typeof(ASP._Page_Foo_Test_cshtml).Assembly; // Act Type typ = provider.GetGeneratedType(results); // Assert Assert.AreEqual(typeof(ASP._Page_Foo_Test_cshtml), typ); }
public void CodeCompilerTypeSetsDebugFlagInFullTrust() { // Arrange WebPageRazorHost host = new WebPageRazorHost("~/Foo/Baz.cshtml", @"C:\Foo\Baz.cshtml"); RazorBuildProvider provider = CreateBuildProvider("foo @bar baz"); provider.Host = host; // Act CompilerType type = provider.CodeCompilerType; // Assert Assert.True(type.CompilerParameters.IncludeDebugInformation); }
public void PostProcessGeneratedCodeAddsGlobalImports() { // Arrange WebPageRazorHost.AddGlobalImport("Foo.Bar"); CodeCompileUnit generatedCode = new CodeCompileUnit(); CodeNamespace generatedNamespace = new CodeNamespace(); CodeTypeDeclaration generatedClass = new CodeTypeDeclaration(); CodeMemberMethod executeMethod = new CodeMemberMethod(); WebPageRazorHost host = new WebPageRazorHost("Foo.cshtml"); // Act host.PostProcessGeneratedCode(generatedCode, generatedNamespace, generatedClass, executeMethod); // Assert Assert.IsTrue(generatedNamespace.Imports.OfType<CodeNamespaceImport>().Any(import => String.Equals("Foo.Bar", import.Namespace))); }
public void GenerateCodeCoreAddsGeneratedCodeToAssemblyBuilder() { // Arrange WebPageRazorHost host = new WebPageRazorHost("~/Foo/Bar.vbhtml", @"C:\Foo\Bar.vbhtml"); RazorBuildProvider provider = new RazorBuildProvider(); CodeCompileUnit ccu = new CodeCompileUnit(); MockAssemblyBuilder asmBuilder = new MockAssemblyBuilder(); provider.Host = host; provider.GeneratedCode = ccu; // Act provider.GenerateCodeCore(asmBuilder); // Assert Assert.AreSame(provider, asmBuilder.BuildProvider); Assert.AreSame(ccu, asmBuilder.CompileUnit); Assert.AreEqual("ASP._Page_Foo_Bar_vbhtml", asmBuilder.LastTypeFactoryGenerated); }
public void PostProcessGeneratedCodeAddsGlobalImports() { // Arrange WebPageRazorHost.AddGlobalImport("Foo.Bar"); WebPageRazorHost host = new WebPageRazorHost("Foo.cshtml"); CodeGeneratorContext context = CodeGeneratorContext.Create( host, () => new CSharpCodeWriter(), "TestClass", "TestNs", "TestFile.cshtml", shouldGenerateLinePragmas: true); // Act host.PostProcessGeneratedCode(context); // Assert Assert.True(context.Namespace.Imports.OfType<CodeNamespaceImport>().Any(import => String.Equals("Foo.Bar", import.Namespace))); }
public void PostProcessGeneratedCodeAddsApplicationInstanceProperty() { const string expectedPropertyCode = @" protected Foo.Bar ApplicationInstance { get { return ((Foo.Bar)(Context.ApplicationInstance)); } } "; // Arrange WebPageRazorHost host = new WebPageRazorHost("Foo.cshtml") { GlobalAsaxTypeName = "Foo.Bar" }; CodeGeneratorContext context = CodeGeneratorContext.Create( host, () => new CSharpCodeWriter(), "TestClass", "TestNs", "TestFile.cshtml", shouldGenerateLinePragmas: true); // Act host.PostProcessGeneratedCode(context); // Assert CodeMemberProperty property = context.GeneratedClass.Members[0] as CodeMemberProperty; Assert.NotNull(property); CSharpCodeProvider provider = new CSharpCodeProvider(); StringBuilder builder = new StringBuilder(); using (StringWriter writer = new StringWriter(builder)) { provider.GenerateCodeFromMember(property, writer, new CodeGeneratorOptions()); } Assert.Equal(expectedPropertyCode, builder.ToString()); }
public void BuildProviderFiresEventToAlterHostBeforeBuildingPath() { // Arrange WebPageRazorHost expected = new TestHost("~/Foo/Boz.cshtml", @"C:\Foo\Boz.cshtml"); WebPageRazorHost expectedBefore = new WebPageRazorHost("~/Foo/Baz.cshtml", @"C:\Foo\Baz.cshtml"); RazorBuildProvider provider = CreateBuildProvider("foo"); typeof(BuildProvider).GetField("_virtualPath", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(provider, CreateVirtualPath("/Samples/Foo/Baz.cshtml")); Mock.Get(provider).Setup(p => p.GetHostFromConfig()).Returns(expectedBefore); bool called = false; EventHandler<CompilingPathEventArgs> handler = (sender, args) => { Assert.Equal("/Samples/Foo/Baz.cshtml", args.VirtualPath); Assert.Same(expectedBefore, args.Host); args.Host = expected; called = true; }; RazorBuildProvider.CompilingPath += handler; try { // Act CodeCompileUnit ccu = provider.GeneratedCode; // Assert Assert.Equal("Test", ccu.Namespaces[0].Name); Assert.Same(expected, provider.Host); Assert.True(called); } finally { RazorBuildProvider.CompilingPath -= handler; } }
public void GeneratedCodeThrowsHttpParseExceptionForLastParserError() { // Arrange WebPageRazorHost host = new WebPageRazorHost("~/Foo/Baz.cshtml", @"C:\Foo\Baz.cshtml"); RazorBuildProvider provider = CreateBuildProvider("foo @{ if( baz"); provider.Host = host; // Act Assert.Throws<HttpParseException>(() => { CodeCompileUnit ccu = provider.GeneratedCode; }); }
public void AfterGeneratedCodeEventGetsExecutedAtCorrectTime() { // Arrange WebPageRazorHost host = new WebPageRazorHost("~/Foo/Baz.cshtml", @"C:\Foo\Baz.cshtml"); RazorBuildProvider provider = CreateBuildProvider("foo @bar baz"); provider.Host = host; provider.CodeGenerationCompletedInternal += (sender, e) => { Assert.Equal("~/Foo/Baz.cshtml", e.VirtualPath); e.GeneratedCode.Namespaces.Add(new CodeNamespace("DummyNamespace")); }; // Act CodeCompileUnit generated = provider.GeneratedCode; // Assert Assert.NotNull(generated.Namespaces .OfType<CodeNamespace>() .SingleOrDefault(ns => String.Equals(ns.Name, "DummyNamespace"))); }
public void CodeGenerationStartedTest() { // Arrange WebPageRazorHost host = new WebPageRazorHost("~/Foo/Baz.cshtml", @"C:\Foo\Baz.cshtml"); RazorBuildProvider provider = CreateBuildProvider("foo @bar baz"); provider.Host = host; // Expected original base dependencies var baseDependencies = new ArrayList(); baseDependencies.Add("/Samples/Foo/Baz.cshtml"); // Expected list of dependencies after GenerateCode is called var dependencies = new ArrayList(); dependencies.Add(baseDependencies[0]); dependencies.Add("/Samples/Foo/Foo.cshtml"); // Set up the event handler provider.CodeGenerationStartedInternal += (sender, e) => { var bp = sender as RazorBuildProvider; bp.AddVirtualPathDependency("/Samples/Foo/Foo.cshtml"); }; // Set up the base dependency MockAssemblyBuilder builder = new MockAssemblyBuilder(); typeof(BuildProvider).GetField("_virtualPath", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(provider, CreateVirtualPath("/Samples/Foo/Baz.cshtml")); // Test that VirtualPathDependencies returns the original dependency before GenerateCode is called Assert.True(baseDependencies.OfType<string>().SequenceEqual(provider.VirtualPathDependencies.OfType<string>())); // Act provider.GenerateCodeCore(builder); // Assert Assert.NotNull(provider.AssemblyBuilderInternal); Assert.Equal(builder, provider.AssemblyBuilderInternal); Assert.True(dependencies.OfType<string>().SequenceEqual(provider.VirtualPathDependencies.OfType<string>())); Assert.Equal("/Samples/Foo/Baz.cshtml", provider.VirtualPath); }
public CompilingPathEventArgs(string virtualPath, WebPageRazorHost host) { VirtualPath = virtualPath; Host = host; }