示例#1
0
        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"));
        }
示例#2
0
        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);
        }
示例#3
0
 public static WebPageRazorHost CreateHostFromConfig(
     RazorWebSectionGroup config,
     string virtualPath
     )
 {
     return(CreateHostFromConfig(config, virtualPath, null));
 }
示例#4
0
        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);
        }
示例#5
0
        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);
        }
        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);
        }
示例#7
0
        public void HostFactoryTypeIsCorrectlyLoadedFromConfig()
        {
            // Act
            RazorWebSectionGroup group = GetRazorGroup();
            HostSection          host  = (HostSection)group.Host;

            // Assert
            Assert.NotNull(host);
            Assert.Equal("System.Web.WebPages.Razor.Test.TestRazorHostFactory, System.Web.WebPages.Razor.Test", host.FactoryType);
        }
示例#8
0
        public void PageBaseTypeIsCorrectlyLoadedFromConfig()
        {
            // Act
            RazorWebSectionGroup group = GetRazorGroup();
            RazorPagesSection    pages = (RazorPagesSection)group.Pages;

            // Assert
            Assert.NotNull(pages);
            Assert.Equal("System.Web.WebPages.Razor.Test.TestPageBase, System.Web.WebPages.Razor.Test", pages.PageBaseType);
        }
示例#9
0
        public void NamespacesAreCorrectlyLoadedFromConfig()
        {
            // Act
            RazorWebSectionGroup group = GetRazorGroup();
            RazorPagesSection    pages = (RazorPagesSection)group.Pages;

            // Assert
            Assert.NotNull(pages);
            Assert.Equal(1, pages.Namespaces.Count);
            Assert.Equal("System.Text.RegularExpressions", pages.Namespaces[0].Namespace);
        }
        public void NamespacesAreCorrectlyLoadedFromConfig()
        {
            // Act
            RazorWebSectionGroup group = GetRazorGroup();
            RazorPagesSection    pages = (RazorPagesSection)group.Pages;

            // Assert
            Assert.NotNull(pages);
            NamespaceInfo namespaceInfo = Assert.IsType <NamespaceInfo>(Assert.Single(pages.Namespaces));

            Assert.Equal("System.Text.RegularExpressions", namespaceInfo.Namespace);
        }
        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));
        }
示例#12
0
        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);
        }
示例#13
0
        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));
        }
示例#14
0
        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 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 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);
        }
示例#17
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);
            //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);
            }
        }