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


C# CSharpCodeProvider.GenerateCodeFromCompileUnit方法代码示例

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


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

示例1: GenerateHelper

		private void GenerateHelper()
		{
			using (GenParamsForm gpf = new GenParamsForm())
			{
				gpf.Namespace = _rootCategory.Name;
				if (gpf.ShowDialog(this) == DialogResult.OK)
				{
					CodeCompileUnit ccu = HelperGenerator.Generate(_rootCategory,
						gpf.Namespace, gpf.IsInternal);
					CSharpCodeProvider cscp = new CSharpCodeProvider();
					CodeGeneratorOptions cgo = new CodeGeneratorOptions();
					cgo.BracingStyle = "C";
					using (StreamWriter sw = new StreamWriter(
							Path.Combine(_directory, _rootCategory.TreeName + ".cs")))
						cscp.GenerateCodeFromCompileUnit(ccu, sw, cgo);
					if (gpf.ShowResult)
						using (ShowResultForm srf = new ShowResultForm())
						using (StringWriter strW = new StringWriter())
						{
							cscp.GenerateCodeFromCompileUnit(ccu, strW, cgo);
							srf.Result = strW.ToString();
							srf.ShowDialog(this);
						}
				}
			}
		}
开发者ID:rsdn,项目名称:janus,代码行数:26,代码来源:MainForm.cs

示例2: CreateOutput

        public override string CreateOutput()
        {
            RemoveComments = Generators.Any(p => !p.AlwaysRegenerate);

            Namespace = new CodeNamespace(NamespaceName);
            Unit = new CodeCompileUnit();
            Unit.Namespaces.Add(Namespace);
      
            foreach (var codeGenerator in Generators.Where(p=>p.IsValid()))
            {
               // UnityEngine.Debug.Log(codeGenerator.GetType().Name + " is generating");
                codeGenerator.Initialize(this);
            }
            var provider = new CSharpCodeProvider();

            var sb = new StringBuilder();
            var tw1 = new IndentedTextWriter(new StringWriter(sb), "    ");
            provider.GenerateCodeFromCompileUnit(Unit, tw1, new CodeGeneratorOptions());
            tw1.Close();
            if (RemoveComments)
            {
                var removedLines = sb.ToString().Split(new string[] { Environment.NewLine }, StringSplitOptions.None).Skip(10).ToArray();
                return string.Join(Environment.NewLine, removedLines);
            }
            return sb.ToString();
        }
开发者ID:InvertGames,项目名称:uFrame.Editor,代码行数:26,代码来源:CodeFileGenerator.cs

示例3: 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

示例4: Compile

        internal static TemplateCompilationResult Compile(Type templateType, string templateBody, IEnumerable<string> namespaces, string tempDirectory)
        {
            LoadRuntimeBinder();

            string className;
            var compileUnit = GetCodeCompileUnit(templateType, namespaces, templateBody, out className);

            string sourceCode;
            var codeProvider = new CSharpCodeProvider();
            var builder = new StringBuilder();

            using (var writer = new StringWriter(builder, CultureInfo.InvariantCulture))
            {
                codeProvider.GenerateCodeFromCompileUnit(compileUnit, writer, new CodeGeneratorOptions());
                sourceCode = builder.ToString();
            }

            var parameters = CreateComplilerParameters(tempDirectory);
            var compileResult = codeProvider.CompileAssemblyFromDom(parameters, compileUnit);
            if (compileResult.Errors != null && compileResult.Errors.Count > 0)
                throw new TemplateCompilationException(compileResult.Errors, sourceCode, templateBody);

            var fullClassName = TEMPLATES_NAMESPACE + "." + className;

            return new TemplateCompilationResult
            {
                Type = compileResult.CompiledAssembly.GetType(fullClassName),
                SourceCode = sourceCode
            };
        }
开发者ID:TDaelman,项目名称:RazorTemplates,代码行数:30,代码来源:TemplateCompiler.cs

示例5: Main

        static void Main(string[] args)
        {
            CodeCompileUnit compileUnit = new CodeCompileUnit();
            CodeNamespace myNamespace = new CodeNamespace("MyNamespace");
            myNamespace.Imports.Add(new CodeNamespaceImport("System"));
            CodeTypeDeclaration myClass = new CodeTypeDeclaration("MyClass");
            CodeEntryPointMethod start = new CodeEntryPointMethod();
            CodeMethodInvokeExpression cs1 = new CodeMethodInvokeExpression(new CodeTypeReferenceExpression("Console"), "WriteLine", new CodePrimitiveExpression("Hello World"));
            compileUnit.Namespaces.Add(myNamespace);
            myNamespace.Types.Add(myClass);
            myClass.Members.Add(start);
            start.Statements.Add(cs1);

            CSharpCodeProvider provider = new CSharpCodeProvider();

            using(StreamWriter sw = new StreamWriter("HelloWorld.cs", false))
            {
                IndentedTextWriter tw = new IndentedTextWriter(sw, " ");
                provider.GenerateCodeFromCompileUnit(compileUnit, tw, new CodeGeneratorOptions());
                tw.Close();
            }

            Console.WriteLine("HelloWorld.cs generated in .../bin/Debug or .../bin/Release project folders.");

            Console.Write("Press a key to exit");
            Console.ReadKey();
        }
开发者ID:jbijoux,项目名称:Exam70_483,代码行数:27,代码来源:Program.cs

示例6: GenerateCode

        public void GenerateCode(State rootState, TextWriter output, string namespaceName, UsingList usings, string[] genericArguments)
        {
            _syntaxTypes.Clear();

            var code = new CodeCompileUnit();
            var ns = new CodeNamespace(namespaceName);
            code.Namespaces.Add(ns);
            ns.Imports.Add(new CodeNamespaceImport("System"));

            foreach (var u in usings)
            {
                ns.Imports.Add(new CodeNamespaceImport(u.Namespace));
            }

            GenerateCode(t => ns.Types.Add(t), rootState, new HashSet<string>(), genericArguments);

            ns.Types.Add(new CodeTypeDeclaration(_syntaxEnd)
            {
                Attributes = MemberAttributes.Public,
                TypeAttributes = TypeAttributes.Interface | TypeAttributes.Public,
                IsPartial = true,
            });

            var codeProvider = new CSharpCodeProvider();
            codeProvider.GenerateCodeFromCompileUnit(code, output, new CodeGeneratorOptions
            {
                BracingStyle = "C",
                IndentString = "\t",
            });
        }
开发者ID:aaubry,项目名称:FluentOMatic,代码行数:30,代码来源:CodeGenerator.cs

示例7: GenerateCSharpTo

 /// <summary>
 /// Generates CSharp text from a compile unit and writes it to a text writer with the given options.
 /// </summary>
 /// <param name="compileUnit">The compile unit to generate text from.</param>
 /// <param name="writer">The text writer to write to.</param>
 /// <param name="options">The generation options.</param>
 public static void GenerateCSharpTo(this CodeCompileUnit compileUnit, TextWriter writer, CodeGeneratorOptions options)
 {
     using (var provider = new CSharpCodeProvider())
     {
         provider.GenerateCodeFromCompileUnit(compileUnit, writer, options);
     }
 }
开发者ID:DzmitrySo,项目名称:mc,代码行数:13,代码来源:CodeDomGenerator.cs

示例8: Run

        public void Run()
        {
            var compileUnit = new CodeCompileUnit();
            var myNamespace = new CodeNamespace("MyNamespace");
            myNamespace.Imports.Add(new CodeNamespaceImport("System"));
            var myClass = new CodeTypeDeclaration("MyClass");
            var start = new CodeEntryPointMethod();
            var cs1 = new CodeMethodInvokeExpression(
                new CodeTypeReferenceExpression("Console"),
                "WriteLine", new CodePrimitiveExpression("Hello World!"));

            compileUnit.Namespaces.Add(myNamespace);
            myNamespace.Types.Add(myClass);
            myClass.Members.Add(start);
            start.Statements.Add(cs1);

            var provider = new CSharpCodeProvider();

            using (var sw = new StreamWriter("HelloWorld.cs", false))
            {
                var tw = new IndentedTextWriter(sw, "    ");
                provider.GenerateCodeFromCompileUnit(compileUnit, tw,
                    new CodeGeneratorOptions());
                tw.Close();
            }
        }
开发者ID:rrsc,项目名称:ProgrammingInCSharp,代码行数:26,代码来源:GeneratingASourceFileFromCodeCompileUnit.cs

示例9: GenerateCSharpCode

        public static String GenerateCSharpCode(CodeCompileUnit compileunit)
        {
            // Generate the code with the C# code provider.
            CSharpCodeProvider provider = new CSharpCodeProvider();

            // Build the output file name.
            String sourceFile;
            if (provider.FileExtension[0] == '.')
            {
                sourceFile = "HelloWorld" + provider.FileExtension;
            }
            else
            {
                sourceFile = "HelloWorld." + provider.FileExtension;
            }

            // Create a TextWriter to a StreamWriter to the output file.
            IndentedTextWriter tw = new IndentedTextWriter(
                    new StreamWriter(sourceFile, false), "    ");

            // Generate source code using the code provider.
            provider.GenerateCodeFromCompileUnit(compileunit, tw,
                    new CodeGeneratorOptions());

            // Close the output file.
            tw.Close();

            return sourceFile;
        }
开发者ID:nyet,项目名称:nyet,代码行数:29,代码来源:Program.cs

示例10: ParseAndCompileTemplate

        /// <summary>
        /// This method Parses and compiles the source code into an Assembly and returns it
        /// </summary>
        /// <param name="baseClassType">The Type of the Base class the generated class descends from</param>
        /// <param name="namespaceOfGeneratedClass">The Namespace of the generated class</param>
        /// <param name="generatedClassName">The Class Name of the generated class</param>
        /// <param name="sourceCodeReader">A Text reader that is a warpper around the "Template" that is to be parsed and compiled</param>
        /// <returns>An instance of a generated assembly that contains the generated class</returns>
        public Assembly ParseAndCompileTemplate(Type baseClassType, string namespaceOfGeneratedClass, string generatedClassName, TextReader sourceCodeReader)
        {
            RazorTemplateEngine engine = InitializeRazorEngine(baseClassType, namespaceOfGeneratedClass, generatedClassName);
            GeneratorResults razorResults = engine.GenerateCode(sourceCodeReader);

            CSharpCodeProvider codeProvider = new CSharpCodeProvider();
            CodeGeneratorOptions options = new CodeGeneratorOptions();

            string generatedCode = null;
            using (StringWriter writer = new StringWriter())
            {
                codeProvider.GenerateCodeFromCompileUnit(razorResults.GeneratedCode, writer, options);
                generatedCode = writer.GetStringBuilder().ToString();
            }

            var outputAssemblyName = Path.GetTempPath() + Guid.NewGuid().ToString("N") + ".dll";
            CompilerParameters compilerParameters = new CompilerParameters(new string[]{}, outputAssemblyName);
            compilerParameters.ReferencedAssemblies.Add("System.dll");
            compilerParameters.ReferencedAssemblies.Add("System.Core.dll");
            compilerParameters.ReferencedAssemblies.Add(Assembly.GetExecutingAssembly().CodeBase.Substring(8));
            compilerParameters.GenerateInMemory = false;

            CompilerResults compilerResults = codeProvider.CompileAssemblyFromDom(compilerParameters, razorResults.GeneratedCode);
            if (compilerResults.Errors.Count > 0)
            {
                var compileErrors = new StringBuilder();
                foreach (System.CodeDom.Compiler.CompilerError compileError in compilerResults.Errors)
                    compileErrors.Append(String.Format("Line: {0}\t Col: {1}\t Error: {2}\r\n", compileError.Line, compileError.Column, compileError.ErrorText));

                throw new Exception(compileErrors.ToString() + generatedCode);
            }

            return compilerResults.CompiledAssembly;
        }
开发者ID:jhosm,项目名称:BlissInSoftware.Sandcastle,代码行数:42,代码来源:RazorEngineHostWrapper.cs

示例11: 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

示例12: 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

示例13: DeclToString

        private static string DeclToString(CodeCompileUnit decl)
        {
            var provider = new CSharpCodeProvider();
            var opts = new CodeGeneratorOptions { IndentString = "    ", BracingStyle = "C" };

            var writer = new StringWriter();
            provider.GenerateCodeFromCompileUnit(decl, writer, opts);
            return writer.GetStringBuilder().ToString();
        }
开发者ID:xinmyname,项目名称:Castle.MonoRail3,代码行数:9,代码来源:CodeGenTests.cs

示例14: Main

        public static void Main()
        {
            CSharpCodeProvider cs = new CSharpCodeProvider();

            CodeGenerator cg = new CodeGenerator();
            using (StreamWriter sw=new StreamWriter("HelloWorld.cs",false))
            {
                IndentedTextWriter tw = new IndentedTextWriter(sw, "      ");
                cs.GenerateCodeFromCompileUnit(cg.GetCompierUnit(), tw, new CodeGeneratorOptions());
                tw.Close();
            }
        }
开发者ID:vijaychandar1989,项目名称:70-483_Samples,代码行数:12,代码来源:CodeGeneratorCS.cs

示例15: Generate

        public string Generate(GenerationOptions options)
        {
            var compileUnit = this.GenerateUnit(options);

            var provider = new CSharpCodeProvider();
            using (var sw = new StringWriter())
            {
                provider.GenerateCodeFromCompileUnit(compileUnit, sw, new CodeGeneratorOptions {});
                string codeText = sw.GetStringBuilder().ToString();
                return SugarUp(codeText.Substring(codeText.IndexOf("using", System.StringComparison.Ordinal)));
            }
        }
开发者ID:chwilliamson,项目名称:ServiceStackGen,代码行数:12,代码来源:ServiceStackWrapperGenerator.cs


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