Пример #1
0
        private byte[] GenerateFromHost()
        {
            var projectDirectory    = Path.GetDirectoryName(GetProject().FullName);
            var projectRelativePath = InputFilePath.Substring(projectDirectory.Length);

            using (var hostManager = new HostManager(projectDirectory))
            {
                var host = hostManager.CreateHost(InputFilePath, projectRelativePath, GetCodeProvider());
                host.DefaultNamespace = FileNameSpace;
                host.Error           += (o, eventArgs) =>
                {
                    GeneratorError(0, eventArgs.ErrorMessage, eventArgs.LineNumber, eventArgs.ColumnNumber);
                };
                host.Progress += (o, eventArgs) =>
                {
                    if (CodeGeneratorProgress != null)
                    {
                        CodeGeneratorProgress.Progress(eventArgs.Completed, eventArgs.Total);
                    }
                };

                var content = host.GenerateCode();
                return(ConvertToBytes(content));
            }
        }
Пример #2
0
        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);
        }
Пример #3
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);
            }
        }