本文整理汇总了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);
}
}
}
}
示例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();
}
示例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);
}
示例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
};
}
示例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();
}
示例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",
});
}
示例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);
}
}
示例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();
}
}
示例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;
}
示例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;
}
示例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;
}
示例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();
}
示例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();
}
示例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();
}
}
示例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)));
}
}