当前位置: 首页>>代码示例>>C#>>正文


C# RazorTemplateEngine.GenerateCode方法代码示例

本文整理汇总了C#中System.Web.Razor.RazorTemplateEngine.GenerateCode方法的典型用法代码示例。如果您正苦于以下问题:C# RazorTemplateEngine.GenerateCode方法的具体用法?C# RazorTemplateEngine.GenerateCode怎么用?C# RazorTemplateEngine.GenerateCode使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在System.Web.Razor.RazorTemplateEngine的用法示例。


在下文中一共展示了RazorTemplateEngine.GenerateCode方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: GetSyntaxTree

        public override SyntaxTree GetSyntaxTree(string sourcePath, Stream sourceStream)
        {
            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);
                    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);
                }
            }
            catch (Exception ex)
            {
                Compilation.Diagnostics.Add(Diagnostic.Create(Compilation.ViewGenerationFailed, Compilation.AsLocation(sourcePath), ex.ToString()));
                return null;
            }
        }
开发者ID:modulexcite,项目名称:StackExchange.Precompilation,代码行数:35,代码来源:RazorParser.cs

示例2: GetGeneratedCode

		private CodeCompileUnit GetGeneratedCode()
		{
		    try
		    {

                if (this.generatedCode == null)
                {
                    var engine = new RazorTemplateEngine(this.host);
                    GeneratorResults results;
                    using (var reader = this.OpenReader())
                    {
                        results = engine.GenerateCode(reader);
                    }

                    if (!results.Success)
                    {
                        throw new InvalidOperationException(results.ToString());
                    }

                    this.generatedCode = results.GeneratedCode;
                }

                return this.generatedCode;
            }
            catch (Exception ex)
            {
                Log.Error("GetGeneratedCode(): ", ex);
                return null;
            }
		}
开发者ID:grammarware,项目名称:fodder,代码行数:30,代码来源:src_ServiceStack_Razor_CSharpRazorBuildProvider.cs

示例3: GenerateCodeFromRazorTemplate

        private static 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();
        }
开发者ID:jpolvora,项目名称:MvcLib.MyGet,代码行数:27,代码来源:RazorCompiler.cs

示例4: parse

        public static ParsedTemplate parse(string sourceFilename, string cshtmlContent, string effectiveTemplateClassName, Type modelType)
        {
            var csCodeLanguage = new CSharpRazorCodeLanguage();
            var templateHost = new RazorEngineHost(csCodeLanguage, () => new HtmlMarkupParser());

            var concreteBaseClassType = getBaseClassTypeFromModel(modelType);
            templateHost.DefaultBaseClass = concreteBaseClassType.FullName;

            var templateEngine = new RazorTemplateEngine(templateHost);

            var trimmedcshtmlContent = HeaderLines.trim(cshtmlContent);

            GeneratorResults res;
            using (var input = new StringReader(trimmedcshtmlContent))
            {
                res = templateEngine.GenerateCode(input, effectiveTemplateClassName, GeneratedTemplateNamespace, sourceFilename);
            }

            if (!res.Success)
                throw new Exception("Failed to generate code");

            var compileUnit = res.GeneratedCode;
            var fullyQualifiedClassName = GeneratedTemplateNamespace + "." + effectiveTemplateClassName;

            return new ParsedTemplate(fullyQualifiedClassName, compileUnit);
        }
开发者ID:pragmatrix,项目名称:SiteSharper,代码行数:26,代码来源:TemplateParser.cs

示例5: ParseToCode

 public GeneratorResults ParseToCode(string TemplateCode, string defaultnamespace, string defaultclassname, string baseClassFullName)
 {
     GeneratorResults razorResults;
     var host = new RazorEngineHost(new CSharpRazorCodeLanguage());
     host.DefaultBaseClass = baseClassFullName;//typeof(BulaqTemplateForRazorBase).FullName;
     host.DefaultNamespace = defaultnamespace;
     host.DefaultClassName = defaultclassname;
     host.NamespaceImports.Add("System");
     host.NamespaceImports.Add("BulaqCMS.Models");
     host.GeneratedClassContext = new GeneratedClassContext("Execute", "Write", "WriteLiteral");
     var engine = new RazorTemplateEngine(host);
     using (var reader = new StringReader(TemplateCode))
     {
         razorResults = engine.GenerateCode(reader);
         CSharpCodeProvider codeProvider = new CSharpCodeProvider();
         CodeGeneratorOptions options = new CodeGeneratorOptions();
         options.BracingStyle = "C";
         using (StringWriter writer = new StringWriter())
         {
             IndentedTextWriter indentwriter = new IndentedTextWriter(writer, "    ");
             codeProvider.GenerateCodeFromCompileUnit(razorResults.GeneratedCode, indentwriter, options);
             indentwriter.Flush();
             indentwriter.Close();
             LastGeneratedCode = writer.GetStringBuilder().ToString();
             string codePath = AppDomain.CurrentDomain.BaseDirectory.TrimEnd('\\') + "\\code.cs";
             File.WriteAllText(codePath, LastGeneratedCode, Encoding.UTF8);
         }
     }
     return razorResults;
 }
开发者ID:abduwaris,项目名称:BulaqCMS,代码行数:30,代码来源:RazorTemplateParser.cs

示例6: CompileCore

        private async Task<CompilationResult> CompileCore(IFileInfo file)
        {
            var host = new MvcRazorHost();
            var engine = new RazorTemplateEngine(host);
            GeneratorResults results;
            using (TextReader rdr = new StreamReader(file.CreateReadStream()))
            {
                results = engine.GenerateCode(rdr, '_' + Path.GetFileNameWithoutExtension(file.Name), "Asp", file.PhysicalPath ?? file.Name);
            }

            string generatedCode;

            using (var writer = new StringWriter())
            using (var codeProvider = new CSharpCodeProvider())
            {
                codeProvider.GenerateCodeFromCompileUnit(results.GeneratedCode, writer, new CodeGeneratorOptions());
                generatedCode = writer.ToString();
            }

            if (!results.Success) 
            {
                return CompilationResult.Failed(generatedCode, results.ParserErrors.Select(e => new CompilationMessage(e.Message)));
            }

            Directory.CreateDirectory(_tempPath);
            string tempFile = Path.Combine(_tempPath, Path.GetRandomFileName() + ".cs");

            File.WriteAllText(tempFile, generatedCode);

            _tempFileSystem.TryGetFileInfo(tempFile, out file);
            return await _baseCompilationService.Compile(file);
        }
开发者ID:464884492,项目名称:Mvc,代码行数:32,代码来源:RazorCompilationService.cs

示例7: GenerateCode

        public GeneratorResults GenerateCode()
        {
            // Create the engine
            RazorTemplateEngine engine = new RazorTemplateEngine(this);

            // Generate code
            using (Stream stream = File.OpenRead(_fullPath))
            {
                using (StreamReader reader = new StreamReader(stream, Encoding.Default, detectEncodingFromByteOrderMarks: true))
                {
                    return engine.GenerateCode(reader);
                }
            }
        }
开发者ID:ryanhaugh,项目名称:razorblade,代码行数:14,代码来源:RazorHost.cs

示例8: GenerateCode

        public GeneratorResults GenerateCode(RazorTemplate descriptor, string className, RazorEngineHost host)
        {
            var engine = new RazorTemplateEngine(host);
             GeneratorResults results;
             using (var fileStream = new FileStream(descriptor.FilePath, FileMode.Open, FileAccess.Read))
             using (var reader = new StreamReader(fileStream))
             {
                 results = engine.GenerateCode(reader, className, host.DefaultNamespace, descriptor.ViewPath);
             }

             if (!results.Success)
             {
                 throw CreateExceptionFromParserError(results.ParserErrors.Last(), descriptor.Name());
             }
             return results;
        }
开发者ID:kingreatwill,项目名称:fubumvc,代码行数:16,代码来源:RazorTemplateGenerator.cs

示例9: GenerateCode

        private CodeCompileUnit GenerateCode()
        {
            var engine = new RazorTemplateEngine(this._host);
            GeneratorResults results;
            using (TextReader reader = OpenReader())
            {
                results = engine.GenerateCode(reader); //, className: null, rootNamespace: null, sourceFileName: Host.PhysicalPath);
            }

            if (!results.Success)
            {
                throw CreateExceptionFromParserError(results.ParserErrors.Last(), VirtualPath);
            }

            return results.GeneratedCode;
        }
开发者ID:muratbeyaztas,项目名称:Simple.Web,代码行数:16,代码来源:SimpleRazorBuildProvider.cs

示例10: GenerateCode

 private CompilationData GenerateCode(string path)
 {
     var viewDefinition = _viewProvider.GetViewDefinition(path);
     var host = OpenRastaRazorHostFactory.CreateHost(DetermineCodeLanguage(viewDefinition.FileName));
     var engine = new RazorTemplateEngine(host);
     GeneratorResults results;
     using (TextReader reader = viewDefinition.Contents)
     {
         results = engine.GenerateCode(reader, GetClassName(viewDefinition.FileName), host.DefaultNamespace, viewDefinition.FileName);
     }
     if (!results.Success)
     {
         throw CreateExceptionFromParserError(results.ParserErrors.Last(), path);
     }
     return new CompilationData(GetReferencedAssemblies(viewDefinition), results.GeneratedCode);
 }
开发者ID:redbadger,项目名称:openrasta-codecs-razor,代码行数:16,代码来源:StandAloneBuildManager.cs

示例11: Compile

        public Task<CompilationResult> Compile(IFileInfo file)
        {
            string className = MakeClassName(file.Name);
            var engine = new RazorTemplateEngine(new RazorEngineHost(new CSharpRazorCodeLanguage())
            {
                DefaultBaseClass = "Microsoft.AspNet.Razor.Owin.PageBase",
                GeneratedClassContext = new GeneratedClassContext(
                    executeMethodName: "Execute",
                    writeMethodName: "Write",
                    writeLiteralMethodName: "WriteLiteral",
                    writeToMethodName: "WriteTo",
                    writeLiteralToMethodName: "WriteLiteralTo",
                    templateTypeName: "Template",
                    defineSectionMethodName: "DefineSection")
                {
                    ResolveUrlMethodName = "Href"
                }
            });
            engine.Host.NamespaceImports.Add("System");
            engine.Host.NamespaceImports.Add("System.Linq");
            engine.Host.NamespaceImports.Add("System.Collections.Generic");

            GeneratorResults results;
            using (TextReader rdr = new StreamReader(file.CreateReadStream()))
            {
                results = engine.GenerateCode(rdr, className, "RazorCompiled", file.PhysicalPath ?? file.Name);
            }

            var messages = new List<CompilationMessage>();
            if (!results.Success)
            {
                foreach (var error in results.ParserErrors)
                {
                    messages.Add(new CompilationMessage(
                        MessageLevel.Error,
                        error.Message,
                        new FileLocation(file.PhysicalPath ?? file.Name, error.Location.LineIndex, error.Location.CharacterIndex)));
                }
            }

            // Regardless of success or failure, we're going to try and compile
            return Task.FromResult(CompileCSharp("RazorCompiled." + className, file, results.Success, messages, results.GeneratedCode));
        }
开发者ID:Kstal,项目名称:Microsoft.Owin,代码行数:43,代码来源:RazorCompiler.cs

示例12: GenerateAssemblyFromTemplate

        public static Assembly GenerateAssemblyFromTemplate(string template)
        {
            var host = new RazorEngineHost(new CSharpRazorCodeLanguage())
            {
                DefaultNamespace = "Federation.MailService",
                DefaultBaseClass = typeof(MailMessageTemplate).FullName
            };

            var engine = new RazorTemplateEngine(host);

            var generatedCode = engine.GenerateCode(new StringReader(template), "MailMessageRazorTemplate", "Federation.MailService", "MailMessageTemplate.cs");

            var currentAssemblyLocation = typeof(MailMessageTemplate).Assembly.CodeBase.Replace("file:///", string.Empty).Replace("/", "\\");
            var modelsAssemblyLocation = typeof(MailRecord).Assembly.CodeBase.Replace("file:///", string.Empty).Replace("/", "\\");

            List<string> refer = new List<string>
                       {
                           "mscorlib.dll",
                           "system.dll",
                           "system.core.dll",
                           "microsoft.csharp.dll",
                           "system.configuration.dll",
                           "system.data.linq.dll",
                           "system.data.dll",
                           currentAssemblyLocation,
                           modelsAssemblyLocation
                       };
            var codeProvider = new CSharpCodeProvider();
            var compilerParameters = new CompilerParameters(refer.ToArray()) { GenerateInMemory = true, CompilerOptions = "/optimize" };
            var compilerResults = codeProvider.CompileAssemblyFromDom(compilerParameters, generatedCode.GeneratedCode);

            if (compilerResults.Errors.HasErrors)
            {
                var compileExceptionMessage = string.Join("\n", compilerResults.Errors.OfType<CompilerError>().Where(ce => !ce.IsWarning).Select(e => "ERROR in " + e.Line + ": " + e.ErrorText).ToArray());

                throw new InvalidOperationException(compileExceptionMessage);
            }

            return compilerResults.CompiledAssembly;
        }
开发者ID:arbium,项目名称:democratia2,代码行数:40,代码来源:RazorBasedTemplateRenderEngine.cs

示例13: Compile

        public CompilationResults Compile(string template)
        {
            Host.DefaultClassName = "Template";
            Host.DefaultNamespace = "__CompiledTemplates";
            RazorTemplateEngine engine = new RazorTemplateEngine(Host);
            GeneratorResults generatorResults;
            using (TextReader reader = new StringReader(template))
            {
                generatorResults = engine.GenerateCode(reader);
            }

            if (!generatorResults.Success)
            {
                return new CompilationResults(generatorResults, new List<CompilerError>());
            }

            // Compile the code to a temporary assembly
            CodeDomProvider provider = Activator.CreateInstance(_language.CodeDomProviderType) as CodeDomProvider;
            if (provider == null)
            {
                throw new InvalidCastException(String.Format("Unable to convert '{0}' to a CodeDomProvider", _language.CodeDomProviderType.FullName));
            }
            var compilerResults = provider.CompileAssemblyFromDom(new CompilerParameters(new [] { typeof(TemplateBase).Assembly.Location }), generatorResults.GeneratedCode);
            if (compilerResults.Errors.HasErrors)
            {
                return new CompilationResults(generatorResults, compilerResults.Errors.Cast<CompilerError>().ToList());
            }
            var type = compilerResults.CompiledAssembly.GetType("__CompiledTemplates.Template");
            if (type == null)
            {
                throw new MissingMemberException("Unable to find compiled template in assembly");
            }
            TemplateBase compiled = Activator.CreateInstance(type) as TemplateBase;
            if (compiled == null)
            {
                throw new InvalidCastException("Unable to convert template to TemplateBase");
            }
            return new CompilationResults(generatorResults, compiled);
        }
开发者ID:anurse,项目名称:MicroRazorHost,代码行数:39,代码来源:MicroRazorCompiler.cs

示例14: GenerateCodeWithAspNetRazorViewEngine

        public static string GenerateCodeWithAspNetRazorViewEngine(string razorTemplatePath)
        {
            //-- Configure the code-generator
            var host = new MvcWebPageRazorHost("/", razorTemplatePath);

            //-- Parse the template into a CodeDOM graph (see http://msdn.microsoft.com/en-us/library/y2k85ax6(v=vs.110).aspx for an overview of what CodeDOM is)
            var engine = new RazorTemplateEngine(host);
            GeneratorResults results;

            using (var reader = new StringReader(File.ReadAllText(razorTemplatePath)))
            {
                results = engine.GenerateCode(reader);
            }

            //-- Generate C# code from the CodeDOM graph
            var builder = new StringBuilder();
            using (var writer = new StringWriter(builder, CultureInfo.InvariantCulture))
            {
                new CSharpCodeProvider().GenerateCodeFromCompileUnit(results.GeneratedCode, writer, new CodeGeneratorOptions());
                return builder.ToString();
            }
        }
开发者ID:dperlyuk,项目名称:RazorEngineEmails,代码行数:22,代码来源:Program.cs

示例15: GenerateCode

		public string GenerateCode (out CompilerErrorCollection errors)
		{
			errors = new CompilerErrorCollection ();

			// Create the engine
			RazorTemplateEngine engine = new RazorTemplateEngine(this);

			// Generate code
			GeneratorResults results = null;
			try
			{
				Stream stream = File.OpenRead(_fullPath);
				using (var reader = new StreamReader(stream, Encoding.Default, detectEncodingFromByteOrderMarks: true))
				{
					results = engine.GenerateCode(reader, className: DefaultClassName, rootNamespace: DefaultNamespace, sourceFileName: _fullPath);
				}
			} catch (Exception e) {
				errors.Add (new CompilerError (FullPath, 1, 1, null, e.ToString ()));
				//Returning null signifies that generation has failed
				return null;
			}

			// Output errors
			foreach (RazorError error in results.ParserErrors) {
				errors.Add (new CompilerError (FullPath, error.Location.LineIndex + 1, error.Location.CharacterIndex + 1, null, error.Message));
			}

			try
			{
				using (StringWriter writer = new StringWriter()) {
					//Generate the code
					writer.WriteLine("#pragma warning disable 1591");
					_codeDomProvider.GenerateCodeFromCompileUnit(results.GeneratedCode, writer, _codeGeneratorOptions);
					writer.WriteLine("#pragma warning restore 1591");
					return writer.ToString();
				}
			} catch (Exception e) {
				errors.Add (new CompilerError (FullPath, 1, 1, null, e.ToString ()));
				//Returning null signifies that generation has failed
				return null;
			}
		}
开发者ID:RainsSoft,项目名称:playscript-monodevelop,代码行数:42,代码来源:RazorHost.cs


注:本文中的System.Web.Razor.RazorTemplateEngine.GenerateCode方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。