internal static WebPageRazorHost CreateHostFromConfigCore(RazorWebSectionGroup config, string virtualPath, string physicalPath)
        {
            // Use the virtual path to select a host environment for the generated code
            // Do this check here because the App_Code host can't be overridden.

            // Make the path app relative
            virtualPath = EnsureAppRelative(virtualPath);

            WebPageRazorHost host;
            if (virtualPath.StartsWith("~/App_Code", StringComparison.OrdinalIgnoreCase))
            {
                // Under App_Code => It's a Web Code file
                host = new WebCodeRazorHost(virtualPath, physicalPath);
            }
            else
            {
                WebRazorHostFactory factory = null;
                if (config != null && config.Host != null && !String.IsNullOrEmpty(config.Host.FactoryType))
                {
                    Func<WebRazorHostFactory> factoryCreator = _factories.GetOrAdd(config.Host.FactoryType, CreateFactory);
                    Debug.Assert(factoryCreator != null); // CreateFactory should throw if there's an error creating the factory
                    factory = factoryCreator();
                }

                host = (factory ?? new WebRazorHostFactory()).CreateHost(virtualPath, physicalPath);

                if (config != null && config.Pages != null)
                {
                    ApplyConfigurationToHost(config.Pages, host);
                }
            }

            return host;
        }
        public static WebPageRazorHost CreateHostFromConfig(RazorWebSectionGroup config, string virtualPath, string physicalPath)
        {
            if (config == null)
            {
                throw new ArgumentNullException("config");
            }
            if (String.IsNullOrEmpty(virtualPath))
            {
                throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, CommonResources.Argument_Cannot_Be_Null_Or_Empty, "virtualPath"), "virtualPath");
            }

            return CreateHostFromConfigCore(config, virtualPath, physicalPath);
        }
        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 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 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 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"));
        }
        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 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.IsType<WebPageRazorHost>(host);
        }
 public static WebPageRazorHost CreateHostFromConfig(RazorWebSectionGroup config, string virtualPath)
 {
     return CreateHostFromConfig(config, virtualPath, null);
 }
Exemple #10
0
        /// <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);

            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;

            try
            {
                using (TextReader reader = new StringReader(inputFileContent))
                {
                    results = engine.GenerateCode(reader,null,null,InputFilePath);
                }
            }
            catch (Exception e)
            {
                GeneratorError(4, e.ToString(), 1, 1);

                return RazorError;
            }

            // 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 (CodeGeneratorProgress != null)
                {
                    // Report that we are 1/2 done

                    CodeGeneratorProgress.Progress(50, 100);
                }

                using (StringWriter writer = new StringWriter(new StringBuilder()))
                {
                    CodeGeneratorOptions options = new CodeGeneratorOptions
                                                       {
                                                           BlankLinesBetweenMembers = false,
                                                           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("RazorViewCompiler")),
                            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 (CodeGeneratorProgress != null)
                    {
                        //Report that we are done

                        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)
            {
                GeneratorError(4, e.ToString(), 1, 1);

                return RazorError;
            }
        }
        public void CreateHostFromConfigUsesDefaultFactoryIfNoHostSectionFound() {
            // Arrange
            RazorWebSectionGroup config = new RazorWebSectionGroup() { 
                Host = null,
                Pages = null
            };

            // Act
            WebPageRazorHost host = WebRazorHostFactory.CreateHostFromConfig(config, "/Foo/Bar.cshtml", null);

            // Assert
            Assert.IsInstanceOfType(host, typeof(WebPageRazorHost));
        }
 internal static WebPageRazorHost CreateHostFromConfigCore(RazorWebSectionGroup config, string virtualPath) {
     return CreateHostFromConfigCore(config, virtualPath, null);
 }