本文整理汇总了C#中System.CodeDom.Compiler.CodeDomProvider.GenerateCodeFromCompileUnit方法的典型用法代码示例。如果您正苦于以下问题:C# CodeDomProvider.GenerateCodeFromCompileUnit方法的具体用法?C# CodeDomProvider.GenerateCodeFromCompileUnit怎么用?C# CodeDomProvider.GenerateCodeFromCompileUnit使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.CodeDom.Compiler.CodeDomProvider
的用法示例。
在下文中一共展示了CodeDomProvider.GenerateCodeFromCompileUnit方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: GenerateString
public static string GenerateString(this CodeCompileUnit self, CodeDomProvider provider)
{
StringBuilder b = new StringBuilder();
using (TextWriter writer = new StringWriter(b))
{
provider.GenerateCodeFromCompileUnit(self, writer, new CodeGeneratorOptions());
}
return b.ToString();
}
示例2: GetCode
public string GetCode(CodeDomProvider codeProdiver, CodeGeneratorOptions generatorOptions)
{
using (var codeStream = new StringWriter())
using (var indentedWriter = new IndentedTextWriter(codeStream, " "))
{
codeProdiver.GenerateCodeFromCompileUnit(_compileUnit, indentedWriter, generatorOptions);
return codeStream.ToString();
}
}
示例3: GenerateSource
internal string GenerateSource(CodeDomProvider codeProvider)
{
StringBuilder sb = new StringBuilder();
TextWriter tWriter = new IndentedTextWriter(new StringWriter(sb));
CodeCompileUnit ccu = GenerateCode();
codeProvider.GenerateCodeFromCompileUnit(ccu, tWriter, new CodeGeneratorOptions());
codeProvider.Dispose();
tWriter.Close();
return sb.ToString();
}
示例4: CodeUnitToLanguage
/// <summary>
/// Convert the abstract representation of the code to functional code given a code provider.
/// </summary>
/// <param name="codeProvider">The code provider.</param>
/// <returns>The code as a string.</returns>
protected string CodeUnitToLanguage(CodeDomProvider codeProvider)
{
var stringBuilder = new StringBuilder();
var stringWriter = new StringWriter(stringBuilder);
var writer = new IndentedTextWriter(stringWriter, TAB_CHARACTER);
codeProvider.GenerateCodeFromCompileUnit(_codeCompileUnit, writer, new CodeGeneratorOptions
{
BlankLinesBetweenMembers = true,
VerbatimOrder = false,
BracingStyle = "C"
});
string output = stringBuilder.ToString().Replace(" { get; set; };\r\n", " { get; set; }\r\n");
return output;
}
示例5: GenerateProjectCode
public static void GenerateProjectCode (string file, CodeDomProvider provider, GenerationOptions options, ProjectBackend[] projects)
{
CodeGenerationResult res = GenerateProjectCode (options, projects);
string basePath = Path.GetDirectoryName (file);
foreach (SteticCompilationUnit unit in res.Units) {
string fname;
if (unit.Name.Length == 0)
fname = file;
else
fname = Path.Combine (basePath, unit.Name);
StreamWriter fileStream = new StreamWriter (fname);
try {
provider.GenerateCodeFromCompileUnit (unit, fileStream, new CodeGeneratorOptions ());
} finally {
fileStream.Close ();
}
}
}
示例6: Run
void Run (string [] args)
{
co.ProcessArgs (args);
if (co.RemainingArguments.Length == 0)
co.DoHelp ();
if (!co.NoLogo)
co.ShowBanner ();
CodeCompileUnit ccu = new CodeCompileUnit ();
CodeNamespace cns = new CodeNamespace (co.Namespace);
ccu.Namespaces.Add (cns);
generator = new ServiceContractGenerator (ccu);
generator.Options = GetGenerationOption ();
code_provider = GetCodeProvider ();
// For now only assemblyPath is supported.
foreach (string arg in co.RemainingArguments) {
FileInfo fi = new FileInfo (arg);
if (!fi.Exists)
throw new ArgumentException (String.Format ("File {0} not found.", fi.Name));
switch (fi.Extension) {
case ".exe":
case ".dll":
GenerateContractType (fi.FullName);
break;
default:
throw new NotSupportedException ("Not supported file extension: " + fi.Extension);
}
}
if (cns.Types.Count == 0) {
Console.Error.WriteLine ("Argument assemblies have no types.");
Environment.Exit (1);
}
using (TextWriter w = File.CreateText (GetOutputFilename ())) {
code_provider.GenerateCodeFromCompileUnit (ccu, w, null);
}
}
示例7: GenerateCode
// generate code to save on disk
public void GenerateCode(CodeDomProvider provider, CodeCompileUnit compileUnit, string fileName)
{
// Build the source file name with the appropriate
// language extension.
String sourceFile;
if (provider.FileExtension[0] == '.')
{
sourceFile = fileName + provider.FileExtension;
}
else
{
sourceFile = fileName + "." + provider.FileExtension;
}
// Create an IndentedTextWriter, constructed with
// a StreamWriter to the source file.
IndentedTextWriter tw = new IndentedTextWriter(new StreamWriter(sourceFile, true), " ");
// Generate source code using the code generator.
provider.GenerateCodeFromCompileUnit(compileUnit, tw, new CodeGeneratorOptions());
// Close the output file.
tw.Close();
}
示例8: CreateProxyCode
private static string CreateProxyCode(CodeDomProvider codeDomProvider, CodeCompileUnit codeCompileUnit)
{
string proxyCode;
using (StringWriter writer = new StringWriter())
{
CodeGeneratorOptions codeGenOptions = new CodeGeneratorOptions();
codeGenOptions.BracingStyle = "C";
codeDomProvider.GenerateCodeFromCompileUnit(codeCompileUnit, writer, codeGenOptions);
writer.Flush();
proxyCode = writer.ToString();
}
return proxyCode;
}
示例9: Run
/// <summary>
/// This overrides the CodeDomTest Run method that does verification
/// on the tree provided in the BuildTree method you provide.
/// </summary>
/// <param name="provider">Provider to test.</param>
/// <returns>True if the tree builds, compiles, searches and passes
/// assembly verification. False if any of these fails.</returns>
public override bool Run (CodeDomProvider provider) {
bool fail = false;
// build the tree
LogMessageIndent ();
LogMessage ("- Generating tree.");
CodeCompileUnit cu = new CodeCompileUnit ();
LogMessageIndent ();
BuildTree (provider, cu);
LogMessageUnindent ();
// validate tree using 'experimental' subset tester
// but only if the test believes its in the subset
if ((TestType & TestTypes.Subset) != 0) {
SubsetConformance subsConf = new SubsetConformance ();
LogMessage ("- Checking tree subset conformance.");
if (!subsConf.ValidateCodeCompileUnit (cu))
LogMessage ("Failed subset tester: {0}",
subsConf.ToString ());
}
// realize source
StringWriter sw = new StringWriter (CultureInfo.InvariantCulture);
#if WHIDBEY
provider.GenerateCodeFromCompileUnit (cu, sw, GetGeneratorOptions (provider));
#else
ICodeGenerator generator = provider.CreateGenerator ();
generator.GenerateCodeFromCompileUnit (cu, sw, GetGeneratorOptions (provider));
#endif
// only continue if the source could be realized into a string.
if (!fail) {
string source = sw.ToString ();
if (saveSourceFileName.Length > 0) {
LogMessage ("- Saving source into '" + saveSourceFileName + "'");
// save this source to a file
DumpStringToFile (source, saveSourceFileName);
}
// log the source code
//LogMessage (source);
// search the source if the test case asks us to
if (ShouldSearch) {
LogMessageIndent ();
Search (provider, source);
LogMessageUnindent ();
}
// continue only if the test case wants to compile or verify
if (ShouldCompile || ShouldVerify) {
// ask the test case which compiler parameters it would like to use
CompilerParameters parms = GetCompilerParameters (provider);
#if FSHARP
// If the generated code has entrypoint, then F# requires us to generate EXE
bool hasEntryPoint = false;
foreach(CodeNamespace ns in cu.Namespaces)
foreach (CodeTypeDeclaration ty in ns.Types)
foreach(CodeTypeMember mem in ty.Members)
if (mem is CodeEntryPointMethod) { hasEntryPoint = true; }
// If the output file name is specified then it should be EXE
if (hasEntryPoint && parms.GenerateExecutable == false)
{
parms.GenerateExecutable = true;
if (saveAssemblyFileName.ToLower().EndsWith(".dll"))
saveAssemblyFileName = saveAssemblyFileName.Substring(0, saveAssemblyFileName.Length - 4) + ".exe";
}
#endif
// add the appropriate compiler parameters if the user asked us
// to save assemblies to file
if (saveAssemblyFileName.Length > 0) {
parms.OutputAssembly = saveAssemblyFileName;
LogMessage ("- Compiling to '" + saveAssemblyFileName + "'.");
}
// always generate in memory for verification purposes
parms.GenerateInMemory = true;
// compile!
#if WHIDBEY
CompilerResults results = provider.CompileAssemblyFromDom (parms, cu);
#else
ICodeCompiler compiler = provider.CreateCompiler ();
CompilerResults results = compiler.CompileAssemblyFromDom (parms, cu);
#endif
if (results.NativeCompilerReturnValue != 0) {
//.........这里部分代码省略.........
示例10: SourceFromCcu
/////////////////////////////////////////////////////////////////////////////
private static string SourceFromCcu( CodeDomProvider codeProvider, CodeCompileUnit ccu, bool removeLineHidden )
{
// ******
CodeGeneratorOptions options = new CodeGeneratorOptions();
// ******
using( var writer = new StringWriter() ) {
codeProvider.GenerateCodeFromCompileUnit( ccu, writer, options );
string source = writer.ToString();
return removeLineHidden ? RemoveLineHidden(source) : source;
}
}
示例11: GenerateCode
protected virtual void GenerateCode(CodeCompileUnit unit, CodeDomProvider provider,
CodeGenerationResults content, string itemPath)
{
CodeCompileUnit cloneUnit = CloneUnit(unit);
foreach (CodeNamespace ns in unit.Namespaces)
{
cloneUnit.Namespaces.Clear();
cloneUnit.Namespaces.Add(CloneNamespace(ns));
foreach (CodeTypeDeclaration codeType in ns.Types)
{
string file = Path.Combine(Path.GetDirectoryName(itemPath),
Path.ChangeExtension(codeType.Name, Path.GetExtension(itemPath)));
if (!content.ContainsFile(file))
{
cloneUnit.Namespaces[0].Types.Clear();
cloneUnit.Namespaces[0].Types.Add(codeType);
using (StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture))
{
provider.GenerateCodeFromCompileUnit(cloneUnit, stringWriter, new CodeGeneratorOptions());
content.Add(file, stringWriter.ToString());
}
}
}
}
}
示例12: GenerateFiles
internal static string[] GenerateFiles(CodeDomProvider codeDomProvider, CompilerParameters parameters, CodeCompileUnit[] ccus)
{
CodeGeneratorOptions options = new CodeGeneratorOptions();
options.BracingStyle = "C";
string[] filenames = new string[ccus.Length];
for (int i = 0; i < ccus.Length; i++)
{
ResolveReferencedAssemblies(parameters, ccus[i]);
filenames[i] = parameters.TempFiles.AddExtension(i + codeDomProvider.FileExtension);
Stream temp = new FileStream(filenames[i], FileMode.Create, FileAccess.Write, FileShare.Read);
try
{
using (StreamWriter sw = new StreamWriter(temp, Encoding.UTF8))
{
codeDomProvider.GenerateCodeFromCompileUnit(ccus[i], sw, options);
sw.Flush();
}
}
finally
{
temp.Close();
}
}
return filenames;
}
示例13: GetClassFromCcu
private string GetClassFromCcu(CodeDomProvider provider, CodeCompileUnit ccu)
{
CodeGeneratorOptions options = new CodeGeneratorOptions();
using (StringWriter tw = new StringWriter(CultureInfo.InvariantCulture))
{
provider.GenerateCodeFromCompileUnit(ccu, tw, options);
return tw.ToString();
}
}
示例14: GenerateProjectCode
public CodeGenerationResult GenerateProjectCode (string file, string namespaceName, CodeDomProvider provider, GenerationOptions options, params Project[] projects)
{
ArrayList files = new ArrayList ();
CodeGenerationResult res = GenerateProjectCode (options, projects);
string basePath = Path.GetDirectoryName (file);
string ext = Path.GetExtension (file);
foreach (SteticCompilationUnit unit in res.Units) {
string fname;
if (unit.Name.Length == 0)
fname = file;
else
fname = Path.Combine (basePath, unit.Name) + ext;
files.Add (fname);
unit.Name = fname;
StreamWriter fileStream = new StreamWriter (fname);
try {
provider.GenerateCodeFromCompileUnit (unit, fileStream, new CodeGeneratorOptions ());
} finally {
fileStream.Close ();
}
}
return res;
}
示例15: GenerateFile
//.........这里部分代码省略.........
if (root_class == null) {
File.WriteAllText (out_file, "");
return result;
}
bool is_application = root.LocalName == "Application";
string root_ns;
string root_type;
string root_asm;
ParseXmlns (root_class.Value, out root_type, out root_ns, out root_asm);
Hashtable names_and_types = GetNamesAndTypes (root, nsmgr);
// Hashtable keys_and_types = GetKeysAndTypes (root, nsmgr);
CodeCompileUnit ccu = new CodeCompileUnit ();
CodeNamespace decl_ns = new CodeNamespace (root_ns);
ccu.Namespaces.Add (decl_ns);
decl_ns.Imports.Add (new CodeNamespaceImport ("System"));
decl_ns.Imports.Add (new CodeNamespaceImport ("System.Windows"));
decl_ns.Imports.Add (new CodeNamespaceImport ("System.Windows.Controls"));
decl_ns.Imports.Add (new CodeNamespaceImport ("System.Windows.Documents"));
decl_ns.Imports.Add (new CodeNamespaceImport ("System.Windows.Input"));
decl_ns.Imports.Add (new CodeNamespaceImport ("System.Windows.Media"));
decl_ns.Imports.Add (new CodeNamespaceImport ("System.Windows.Media.Animation"));
decl_ns.Imports.Add (new CodeNamespaceImport ("System.Windows.Shapes"));
decl_ns.Imports.Add (new CodeNamespaceImport ("System.Windows.Controls.Primitives"));
CodeTypeDeclaration decl_type = new CodeTypeDeclaration (root_type);
decl_type.IsPartial = true;
decl_ns.Types.Add (decl_type);
CodeMemberMethod initcomp = new CodeMemberMethod ();
initcomp.Name = "InitializeComponent";
decl_type.Members.Add (initcomp);
if (sl2) {
CodeMemberField field = new CodeMemberField ();
field.Name = "_contentLoaded";
field.Type = new CodeTypeReference (typeof (bool));
decl_type.Members.Add (field);
CodeConditionStatement is_content_loaded = new CodeConditionStatement (new CodeVariableReferenceExpression ("_contentLoaded"),
new CodeStatement [] { new CodeMethodReturnStatement () });
initcomp.Statements.Add (is_content_loaded);
CodeAssignStatement set_content_loaded = new CodeAssignStatement (new CodeVariableReferenceExpression ("_contentLoaded"),
new CodePrimitiveExpression (true));
initcomp.Statements.Add (set_content_loaded);
string component_path = String.Format ("/{0};component/{1}", app_name, xaml_path_in_project);
CodeMethodInvokeExpression load_component = new CodeMethodInvokeExpression (
new CodeTypeReferenceExpression ("System.Windows.Application"), "LoadComponent",
new CodeExpression [] { new CodeThisReferenceExpression (),
new CodeObjectCreateExpression (new CodeTypeReference ("System.Uri"), new CodeExpression [] {
new CodePrimitiveExpression (component_path),
new CodeFieldReferenceExpression (new CodeTypeReferenceExpression ("System.UriKind"), "Relative") })
});
initcomp.Statements.Add (load_component);
}
if (!is_application) {
foreach (DictionaryEntry entry in names_and_types) {
string name = (string) entry.Key;
CodeTypeReference type = (CodeTypeReference) entry.Value;
CodeMemberField field = new CodeMemberField ();
if (sl2)
field.Attributes = MemberAttributes.Assembly;
field.Name = name;
field.Type = type;
decl_type.Members.Add (field);
CodeMethodInvokeExpression find_invoke = new CodeMethodInvokeExpression (
new CodeThisReferenceExpression(), "FindName",
new CodeExpression[] { new CodePrimitiveExpression (name) } );
CodeCastExpression cast = new CodeCastExpression (type, find_invoke);
CodeAssignStatement assign = new CodeAssignStatement (
new CodeVariableReferenceExpression (name), cast);
initcomp.Statements.Add (assign);
}
}
using (StreamWriter writer = new StreamWriter (out_file)) {
provider.GenerateCodeFromCompileUnit (ccu, writer, new CodeGeneratorOptions ());
}
return result;
}