本文整理汇总了C#中Microsoft.CSharp.CSharpCodeProvider.GenerateCodeFromCompileUnit方法的典型用法代码示例。如果您正苦于以下问题:C# Microsoft.CSharp.CSharpCodeProvider.GenerateCodeFromCompileUnit方法的具体用法?C# Microsoft.CSharp.CSharpCodeProvider.GenerateCodeFromCompileUnit怎么用?C# Microsoft.CSharp.CSharpCodeProvider.GenerateCodeFromCompileUnit使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Microsoft.CSharp.CSharpCodeProvider
的用法示例。
在下文中一共展示了Microsoft.CSharp.CSharpCodeProvider.GenerateCodeFromCompileUnit方法的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Create
/// <summary>
/// Writes the code to string in the specific language
/// and returns the string
/// </summary>
public static string Create(Language language, string expression, RegexOptions options)
{
CodeCompileUnit unit = Create(expression, options);
System.Text.StringBuilder builder = new System.Text.StringBuilder();
using (System.IO.StringWriter stringWriter = new System.IO.StringWriter(builder))
{
System.CodeDom.Compiler.ICodeGenerator generator;
switch (language)
{
case Language.CSharp:
System.CodeDom.Compiler.CodeGeneratorOptions genOptions = new System.CodeDom.Compiler.CodeGeneratorOptions();
genOptions.BracingStyle = "C";
generator = new Microsoft.CSharp.CSharpCodeProvider().CreateGenerator();
generator.GenerateCodeFromCompileUnit(unit, stringWriter, genOptions);
break;
case Language.VisualBasic:
generator = new Microsoft.VisualBasic.VBCodeProvider().CreateGenerator();
generator.GenerateCodeFromCompileUnit(unit, stringWriter, null);
break;
}
return builder.ToString();
}
}
示例2: ParseForm
CodeCompileUnit ParseForm()
{
ParseInformation parseInfo = ParserService.ParseFile(this.Generator.ViewContent.DesignerCodeFile.FileName, this.Generator.ViewContent.DesignerCodeFileContent, false);
Module module = ParseFormAsModule();
#if DEBUG
Console.WriteLine(module.ToCodeString());
#endif
CodeDomVisitor visitor = new CodeDomVisitor(parseInfo.MostRecentCompilationUnit.ProjectContent);
module.Accept(visitor);
#if DEBUG
// output generated CodeDOM to the console :
ICSharpCode.NRefactory.Visitors.CodeDomVerboseOutputGenerator outputGenerator = new ICSharpCode.NRefactory.Visitors.CodeDomVerboseOutputGenerator();
outputGenerator.GenerateCodeFromMember(visitor.OutputCompileUnit.Namespaces[0].Types[0], Console.Out, null);
CodeDomProvider cSharpProvider = new Microsoft.CSharp.CSharpCodeProvider();
cSharpProvider.GenerateCodeFromCompileUnit(visitor.OutputCompileUnit, Console.Out, null);
#endif
return visitor.OutputCompileUnit;
}
示例3: SaveAssembly
private void SaveAssembly(string Path)
{
//Create a new object of the global CodeCompileUnit class.
myassembly = new CodeCompileUnit();
//Add the namespace to the assembly.
myassembly.Namespaces.Add(mynamespace);
//Add the following compiler parameters. (The references to the //standard .net dll(s) and framework library).
CompilerParameters comparam = new CompilerParameters(new string[] { "mscorlib.dll" });
comparam.ReferencedAssemblies.Add("System.dll");
comparam.ReferencedAssemblies.Add("System.Core.dll");
comparam.ReferencedAssemblies.Add("System.Data.dll");
comparam.ReferencedAssemblies.Add("System.Data.DataSetExtensions.dll");
comparam.ReferencedAssemblies.Add("System.Xml.dll");
comparam.ReferencedAssemblies.Add("System.Xml.Linq.dll");
comparam.ReferencedAssemblies.Add("System.Core.dll");
//comparam.ReferencedAssemblies.Add("System.Collections.Generic.dll");
comparam.ReferencedAssemblies.Add("Driver.dll");
comparam.ReferencedAssemblies.Add("SupportLibrary.dll");
comparam.ReferencedAssemblies.Add("log4net.dll");
//Indicates Whether the compiler has to generate the output in //memory
comparam.GenerateInMemory = false;
//Indicates whether the output is an executable.
comparam.GenerateExecutable = true;
//provide the name of the class which contains the Main Entry //point method
comparam.MainClass = "mynamespace.myclass";
//provide the path where the generated assembly would be placed
comparam.OutputAssembly = @Path;
//Create an instance of the c# compiler and pass the assembly to //compile
Microsoft.CSharp.CSharpCodeProvider ccp = new Microsoft.CSharp.CSharpCodeProvider();
//Build to cs file
CodeGeneratorOptions options = new CodeGeneratorOptions();
options.BracingStyle = "C";
using (StreamWriter sourceWriter = new StreamWriter( @"release.cs"))
{
ccp.GenerateCodeFromCompileUnit(
myassembly, sourceWriter, options);
}
ICodeCompiler icc = ccp.CreateCompiler();
////The CompileAssemblyFromDom would either return the list of
////compile time errors (if any), or would create the
////assembly in the respective path in case of successful //compilation
CompilerResults compres = icc.CompileAssemblyFromDom(comparam, myassembly);
if (compres == null || compres.Errors.Count > 0)
{
for (int i = 0; i < compres.Errors.Count; i++)
{
//Console.WriteLine(compres.Errors[i]);
MessageShow.Writelog("CCodeGenerator.cs::", compres.Errors[i].ToString());
}
}
}
示例4: Main
//.........这里部分代码省略.........
switch (para_ptr_count)
{
case 0:
goto normal_final_para_type;
case 1:
if (!is_out)
{
if (para_native_type == "interface")
final_para += para_type + " ";
else if (para_type == "void")
final_para += para_native_type + " ";
else
Console.WriteLine("[warning] {0}/{1}* with [In] attr in {2}:{3}",
para_type, para_native_type,
interface_name, func_name);
goto after_normal_final_para_type;
}
else
{
final_para += "out ";
goto normal_final_para_type;
}
case 2:
if (is_out)
{
if (para_native_type == "interface")
{
final_para += string.Format("out {0} ", para_type);
goto after_normal_final_para_type;
}
else if (para_type == "void")
{
final_para += string.Format("out {0} ", para_native_type);
goto after_normal_final_para_type;
}
}
Console.WriteLine("[warning] {0}/{1}** in {2}:{3}",
para_type, para_native_type,
interface_name, func_name);
goto after_normal_final_para_type;
default:
break;
}
normal_final_para_type:
if (para_native_type == "interface" || para_native_type == "enum")
final_para += para_type + " ";
else
final_para += para_native_type + " ";
after_normal_final_para_type:
final_para += para_name;
//Console.WriteLine(final_para);
func_paras += final_para + ", ";
}
}
if (!string.IsNullOrEmpty(func_paras))
func_paras = func_paras.Substring(0, func_paras.Length - 2);
w.WriteLine("\t[PreserveSig]\n\t{0} {1} ({2});", func_type, func_name, func_paras);
}
w.WriteLine("}}", interface_name);
}
w.WriteLine("#endregion");
Console.WriteLine("Total {0} interface processed.", r.Count);
#endregion
w.WriteLine("}");
w.Close();
#if USE_DOM
Microsoft.CSharp.CSharpCodeProvider code_provider = new Microsoft.CSharp.CSharpCodeProvider();
CodeGeneratorOptions code_opts = new CodeGeneratorOptions();
code_opts.BlankLinesBetweenMembers = false;
code_opts.VerbatimOrder = true;
code_opts.BracingStyle = "C";
code_provider.GenerateCodeFromCompileUnit(code_root, code_writer, code_opts);
code_writer.Close();
#endif
}
catch (Exception e)
{
Console.WriteLine(e);
return;
}
#if AUTO_DUMP_OUTPUT
Console.WriteLine("\nDumping output file: {0}\n", out_filename);
StreamReader o = new StreamReader(out_filename);
while (!o.EndOfStream)
{
Console.WriteLine(o.ReadLine());
}
o.Close();
#endif
}
示例5: Generate
//.........这里部分代码省略.........
//generate Equality code
ClassHelper.GenerateEqualityCode(vertexClass);
//add input type to namespace
targetNamespace.Types.Add(vertexClass);
}
}
//add constant buffer classes
CodeTypeDeclaration[] cBufferClasses = ClassHelper.GenerateConstantBufferClasses(reader.GetConsttantBuffers());
targetNamespace.Types.AddRange(cBufferClasses);
//add samplers to the shaderclass
//add directX objects
//add the correct Shader class
string shaderName = "NULL";
switch (reader.TypePrefix)
{
case "vs":
{
shaderName = "vertexShader";
targetClass.Members.Add(new CodeMemberField(vertexShaderRef, shaderName));
break;
}
case "ps":
{
shaderName = "pixelShader";
targetClass.Members.Add(new CodeMemberField(pixelShaderRef, shaderName));
break;
}
case "ds":
{
shaderName = "domainShader";
targetClass.Members.Add(new CodeMemberField(domainShaderRef, shaderName));
break;
}
case "hs":
{
shaderName = "hullShader";
targetClass.Members.Add(new CodeMemberField(hullShaderRef, shaderName));
break;
}
case "gs":
{
shaderName = "geometryShader";
targetClass.Members.Add(new CodeMemberField(geometryShaderRef, shaderName));
break;
}
}
if (shaderName != "NULL")
{
ClassHelper.AddDisposalOfMember(disposeMethod, shaderName);
}
else throw new Exception("unrecognized Shader prefix. check the shader profile in the reader code");
foreach (CodeTypeDeclaration cbuffer in cBufferClasses)
{
string bufferName = cbuffer.Name.ToLower() + "Buffer";
targetClass.Members.Add(new CodeMemberField(bufferRef, bufferName));
ClassHelper.AddDisposalOfMember(disposeMethod, bufferName);
}
//add buffer assignment methods
//add others
//add dispose method
targetClass.Members.Add(disposeMethod);
//wrap up /////////////////////////////////////////////////////////////////////////////////////////////////////
targetNamespace.Types.Add(targetClass);
targetUnit.Namespaces.Add(targetNamespace);
using (Microsoft.CSharp.CSharpCodeProvider codeProvider = new Microsoft.CSharp.CSharpCodeProvider())
{
CodeGeneratorOptions options = new CodeGeneratorOptions();
options.BracingStyle = "C";
using (StreamWriter sourceWriter = new StreamWriter(outputfilename))
{
codeProvider.GenerateCodeFromCompileUnit(
targetUnit, sourceWriter, options);
}
}
}
示例6: GenerateCode
private static void GenerateCode(Options options)
{
var packageTransform = new NMF.Models.Meta.Meta2ClassesTransformation();
var stopWatch = new Stopwatch();
packageTransform.ForceGeneration = options.Force;
packageTransform.CreateOperations = options.Operations;
packageTransform.DefaultNamespace = options.OverallNamespace;
var metaPackage = LoadPackageFromFiles(options.InputFiles, options.OverallNamespace);
var model = metaPackage.Model;
if (model == null)
{
model = new Model();
model.RootElements.Add(metaPackage);
}
model.ModelUri = metaPackage.Uri;
if (options.NMeta != null)
{
using (var fs = File.OpenWrite(options.NMeta))
{
MetaRepository.Instance.Serializer.Serialize(model, fs);
}
}
stopWatch.Start();
var compileUnit = TransformationEngine.Transform<INamespace, CodeCompileUnit>(metaPackage,
options.Parallel
? (ITransformationEngineContext)new ParallelTransformationContext(packageTransform)
: new TransformationContext(packageTransform));
stopWatch.Stop();
Console.WriteLine("Operation took {0}ms", stopWatch.Elapsed.TotalMilliseconds);
CodeDomProvider generator = null;
switch (options.Language)
{
case SupportedLanguage.CS:
generator = new Microsoft.CSharp.CSharpCodeProvider();
break;
case SupportedLanguage.VB:
generator = new Microsoft.VisualBasic.VBCodeProvider();
break;
case SupportedLanguage.FS:
generator = new Microsoft.FSharp.Compiler.CodeDom.FSharpCodeProvider();
break;
case SupportedLanguage.CPP:
generator = new Microsoft.VisualC.CppCodeProvider();
break;
case SupportedLanguage.JS:
generator = new Microsoft.JScript.JScriptCodeProvider();
break;
default:
Console.WriteLine("Unknown language detected. Falling back to default C#");
generator = new Microsoft.CSharp.CSharpCodeProvider();
break;
}
var genOptions = new System.CodeDom.Compiler.CodeGeneratorOptions()
{
BlankLinesBetweenMembers = true,
VerbatimOrder = false,
ElseOnClosing = false,
BracingStyle = "C",
IndentString = " "
};
if (options.UseFolders)
{
foreach (var file in MetaFacade.SplitCompileUnit(compileUnit))
{
var fileInfo = new FileInfo(Path.Combine(options.OutputFile, file.Key) + "." + generator.FileExtension);
CheckDirectoryExists(fileInfo.Directory);
using (var fs = fileInfo.Create())
{
using (var sw = new StreamWriter(fs))
{
generator.GenerateCodeFromCompileUnit(file.Value, sw, genOptions);
}
}
}
}
else
{
using (var sw = new StreamWriter(options.OutputFile))
{
generator.GenerateCodeFromCompileUnit(compileUnit, sw, genOptions);
}
}
Console.WriteLine("Code generated successfully!");
}
示例7: GenerateAssembly
public static byte[] GenerateAssembly(string namespaceName, string className, params CodeMemberMethod[] methods)
{
CodeCompileUnit unit = new CodeCompileUnit();
CodeNamespace space = new CodeNamespace(namespaceName);
CodeTypeDeclaration type = new CodeTypeDeclaration(className);
type.Attributes = MemberAttributes.Static | MemberAttributes.Public;
type.TypeAttributes = System.Reflection.TypeAttributes.Public | System.Reflection.TypeAttributes.Sealed;
type.Members.AddRange(methods);
space.Types.Add(type);
unit.Namespaces.Add(space);
Microsoft.CSharp.CSharpCodeProvider provider = new Microsoft.CSharp.CSharpCodeProvider();
System.CodeDom.Compiler.CompilerParameters options = new System.CodeDom.Compiler.CompilerParameters();
options.IncludeDebugInformation = false;
options.GenerateExecutable = false;
options.ReferencedAssemblies.Add(typeof(int).Assembly.Location);
options.ReferencedAssemblies.Add(typeof(Vector2).Assembly.Location);
System.CodeDom.Compiler.CompilerResults results = provider.CompileAssemblyFromDom(options,unit);
System.CodeDom.Compiler.CodeGeneratorOptions ops = new System.CodeDom.Compiler.CodeGeneratorOptions();
ops.IndentString = "\t";
ops.VerbatimOrder = true;
ops.BracingStyle = "C";
StringWriter text = new StringWriter();
provider.GenerateCodeFromCompileUnit(unit, text, ops);
string code = text.ToString();
if (results.Errors.HasErrors)
{
string errors = "";
foreach (System.CodeDom.Compiler.CompilerError error in results.Errors)
{
errors += error.ToString() + Environment.NewLine;
}
throw new InvalidOperationException(errors);
}
byte[] data = File.ReadAllBytes(results.PathToAssembly);
File.Delete(results.PathToAssembly);
return data;
}
示例8: Generate
public void Generate(IEnumerable<string> files)
{
var schemas = files.Select(f => XmlSchema.Read(XmlReader.Create(f, new XmlReaderSettings { DtdProcessing = DtdProcessing.Ignore }), (s, e) =>
{
Trace.TraceError(e.Message);
}));
foreach (var s in schemas)
{
Set.Add(s);
}
Set.Compile();
BuildModel();
var namespaces = GenerateCode();
var provider = new Microsoft.CSharp.CSharpCodeProvider();
foreach (var ns in namespaces)
{
var compileUnit = new CodeCompileUnit();
compileUnit.Namespaces.Add(ns);
var title = ((AssemblyTitleAttribute)Attribute.GetCustomAttribute(Assembly.GetExecutingAssembly(),
typeof(AssemblyTitleAttribute))).Title;
var version = Assembly.GetExecutingAssembly().GetName().Version.ToString();
ns.Comments.Add(new CodeCommentStatement(string.Format("This code was generated by {0} version {1}.", title, version)));
using (StringWriter sw = new StringWriter())
{
provider.GenerateCodeFromCompileUnit(compileUnit, sw, new CodeGeneratorOptions { VerbatimOrder = true, BracingStyle = "C" });
var s = sw.ToString().Replace("};", "}"); // remove ';' at end of automatic properties
var path = Path.Combine(OutputFolder, ns.Name + ".cs");
if (Log != null) Log(path);
File.WriteAllText(path, s);
}
}
}
示例9: OutputGeneratedCode
private static void OutputGeneratedCode(CodeCompileUnit compileUnit)
{
Microsoft.CSharp.CSharpCodeProvider codeProvider = new Microsoft.CSharp.CSharpCodeProvider();
using (MemoryStream stream = new MemoryStream())
using (TextWriter textWriter = new StreamWriter(stream))
{
codeProvider.GenerateCodeFromCompileUnit(compileUnit, textWriter, new System.CodeDom.Compiler.CodeGeneratorOptions());
textWriter.Flush();
stream.Seek(0, SeekOrigin.Begin);
using (StreamReader reader = new StreamReader(stream))
{
string output = reader.ReadToEnd();
//Trace.WriteLine(output);
}
}
}
示例10: Emit
// Emit byte code for the expression tree owned by this root.
// Accepts the compiler parameters that were given to PieCodeProvider
// since it will be needed for the CSharpCodeProvider.
public CompilerResults Emit(CompilerParameters compilerParams, Root root)
{
// Emit the code compile unit, the top of the codedom tree.
// This method will cal emit method for all child expressions
// until all expressions have had byte code emitted.
var codeCompileUnit = RootEmitter.Emit(root);
// Create the C# compiler.
var csProvider = new Microsoft.CSharp.CSharpCodeProvider();
CodeGeneratorOptions options = new CodeGeneratorOptions();
options.BracingStyle = "C";
// Compile the codedom tree into an assembly
var sw = new StringWriter();
csProvider.GenerateCodeFromCompileUnit(codeCompileUnit, sw, options);
// Display the C# code for debugging purposes.
string ccode = sw.GetStringBuilder().ToString();
Console.WriteLine(ccode);
// Get the results of the compilation: the assembly and error list
CompilerResults results = csProvider.CompileAssemblyFromSource(compilerParams, ccode);
// Store all C# compiler errors, so that they can be included with Pie compiler errors..
foreach (CompilerError e in root.CompilerErrors)
results.Errors.Add(e);
root.CompilerErrors.Clear();
return results;
}
示例11: Main3
static void Main3()
{
CodeMemberMethod Calc = new CodeMemberMethod()
{
Name = "Calc",
Attributes = MemberAttributes.Public | MemberAttributes.Static
};
Calc.Parameters.Add(new CodeParameterDeclarationExpression(typeof(int), "x"));
Calc.Statements.Add(
new CodeConditionStatement(
new CodeBinaryOperatorExpression(
new CodeArgumentReferenceExpression("x"), CodeBinaryOperatorType.LessThanOrEqual,
new CodeSnippetExpression("1")
),
new CodeMethodReturnStatement(new CodeSnippetExpression("1"))
)
);
Calc.Statements.Add(
new CodeMethodReturnStatement(
new CodeBinaryOperatorExpression(
new CodeMethodInvokeExpression(null, "Calc",
new CodeBinaryOperatorExpression(
new CodeArgumentReferenceExpression("x"), CodeBinaryOperatorType.Subtract,
new CodeSnippetExpression("1")
)
), CodeBinaryOperatorType.Add,
new CodeMethodInvokeExpression(null, "Calc",
new CodeBinaryOperatorExpression(
new CodeArgumentReferenceExpression("x"), CodeBinaryOperatorType.Subtract,
new CodeSnippetExpression("2")
)
)
)
)
);
CodeTypeDeclaration Fibonacci = new CodeTypeDeclaration();
Fibonacci.Members.Add(Calc);
CodeNamespace ns = new CodeNamespace("TestNS");
ns.Types.Add(Fibonacci);
CodeCompileUnit unit = new CodeCompileUnit();
unit.Namespaces.Add(ns);
using (TextWriter tw = new IndentedTextWriter(Console.Out))
{
using (CodeDomProvider codeProvider = new Microsoft.CSharp.CSharpCodeProvider())
{
codeProvider.GenerateCodeFromCompileUnit(unit, tw, new CodeGeneratorOptions());
}
}
}
示例12: GenerateCode
//.........这里部分代码省略.........
}
}
var metaPackage = LoadPackageFromFiles(options.InputFiles, options.OverallNamespace, mappings);
if (options.Uri != null)
{
Uri uri;
if (Uri.TryCreate(options.Uri, UriKind.Absolute, out uri))
{
metaPackage.Uri = uri;
}
else
{
Console.Error.WriteLine("The provided string {0} could not be parsed as an absolute URI.", options.Uri);
}
}
if (metaPackage.Uri == null)
{
Console.Error.WriteLine("Warning: There is no base Uri for the provided metamodels. Some features of the generated code will be disabled.");
}
var model = metaPackage.Model;
if (model == null)
{
model = new Model();
model.RootElements.Add(metaPackage);
}
model.ModelUri = metaPackage.Uri;
if (options.NMeta != null)
{
using (var fs = File.Create(options.NMeta))
{
MetaRepository.Instance.Serializer.Serialize(model, fs);
}
}
stopWatch.Start();
var compileUnit = TransformationEngine.Transform<INamespace, CodeCompileUnit>(metaPackage,
options.Parallel
? (ITransformationEngineContext)new ParallelTransformationContext(packageTransform)
: new TransformationContext(packageTransform));
stopWatch.Stop();
Console.WriteLine("Operation took {0}ms", stopWatch.Elapsed.TotalMilliseconds);
CodeDomProvider generator = null;
switch (options.Language)
{
case SupportedLanguage.CS:
generator = new Microsoft.CSharp.CSharpCodeProvider();
break;
case SupportedLanguage.VB:
generator = new Microsoft.VisualBasic.VBCodeProvider();
break;
case SupportedLanguage.CPP:
generator = new Microsoft.VisualC.CppCodeProvider();
break;
case SupportedLanguage.JS:
generator = new Microsoft.JScript.JScriptCodeProvider();
break;
default:
Console.WriteLine("Unknown language detected. Falling back to default C#");
generator = new Microsoft.CSharp.CSharpCodeProvider();
break;
}
var genOptions = new System.CodeDom.Compiler.CodeGeneratorOptions()
{
BlankLinesBetweenMembers = true,
VerbatimOrder = false,
ElseOnClosing = false,
BracingStyle = "C",
IndentString = " "
};
if (options.UseFolders)
{
foreach (var file in MetaFacade.SplitCompileUnit(compileUnit))
{
var fileInfo = new FileInfo(Path.Combine(options.OutputFile, file.Key) + "." + generator.FileExtension);
CheckDirectoryExists(fileInfo.Directory);
using (var fs = fileInfo.Create())
{
using (var sw = new StreamWriter(fs))
{
generator.GenerateCodeFromCompileUnit(file.Value, sw, genOptions);
}
}
}
}
else
{
using (var sw = new StreamWriter(options.OutputFile))
{
generator.GenerateCodeFromCompileUnit(compileUnit, sw, genOptions);
}
}
Console.WriteLine("Code generated successfully!");
}
示例13: writeSource
private static void writeSource(string outputFile, CodeCompileUnit cu)
{
Microsoft.CSharp.CSharpCodeProvider csp = new Microsoft.CSharp.CSharpCodeProvider();
CodeGeneratorOptions options = new CodeGeneratorOptions();
options.BracingStyle = "C";
options.BlankLinesBetweenMembers = false;
using (StreamWriter writer = new StreamWriter(outputFile, false))
{
csp.GenerateCodeFromCompileUnit(cu, writer, options);
}
}