本文整理汇总了C#中Microsoft.CSharp.CSharpCodeProvider.CreateCompiler方法的典型用法代码示例。如果您正苦于以下问题:C# Microsoft.CSharp.CSharpCodeProvider.CreateCompiler方法的具体用法?C# Microsoft.CSharp.CSharpCodeProvider.CreateCompiler怎么用?C# Microsoft.CSharp.CSharpCodeProvider.CreateCompiler使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Microsoft.CSharp.CSharpCodeProvider
的用法示例。
在下文中一共展示了Microsoft.CSharp.CSharpCodeProvider.CreateCompiler方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Compile
internal Assembly Compile() {
CodeDomProvider codeProvider = new Microsoft.CSharp.CSharpCodeProvider();
ICodeCompiler compiler = codeProvider.CreateCompiler();
CompilerParameters options = new CompilerParameters(Imports);
options.WarningLevel = 1;
options.TreatWarningsAsErrors = true;
options.CompilerOptions = "/nowarn:183,184,602,612,626,672,679,1030,1200,1201,1202,1203,1522,1570,1574,1580,1581,1584,1589,1590,1592,1596,1598,1607,2002,2014,2023,3012,5000";
if (CompModSwitches.KeepTempFiles.Enabled) {
options.GenerateInMemory = false;
options.IncludeDebugInformation = true;
options.TempFiles = new TempFileCollection();
options.TempFiles.KeepFiles = true;
}
else {
options.GenerateInMemory = true;
}
PermissionSet perms = new PermissionSet(PermissionState.Unrestricted);
perms.AddPermission(FileIOPermission);
perms.AddPermission(new EnvironmentPermission(PermissionState.Unrestricted));
perms.Assert();
CompilerResults results = null;
Assembly assembly = null;
try {
results = compiler.CompileAssemblyFromSource(options, writer.ToString());
assembly = results.CompiledAssembly;
}
finally {
CodeAccessPermission.RevertAssert();
}
if (results.Errors.HasErrors) {
StringWriter stringWriter = new StringWriter();
stringWriter.WriteLine(Res.GetString(Res.XmlCompilerError, results.NativeCompilerReturnValue.ToString()));
foreach (CompilerError e in results.Errors) {
// clear filename. This makes ToString() print just error number and message.
e.FileName = "";
stringWriter.WriteLine(e.ToString());
}
System.Diagnostics.Debug.WriteLine(stringWriter.ToString());
throw new InvalidOperationException(stringWriter.ToString());
}
// somehow we got here without generating an assembly
if (assembly == null) throw new InvalidOperationException(Res.GetString(Res.XmlInternalError));
return assembly;
}
示例2: InvokeWebservice
//public void SendMail(string mailTo, string mailSubject, string content)
//{
// object[] methodParams = new object[4];
// methodParams[0] = new object();
// methodParams[1] = new object();
// methodParams[2] = new object();
// methodParams[3] = new object();
// methodParams[0] = mailTo;
// methodParams[1] = true;
// methodParams[2] = mailSubject;
// methodParams[3] = content;
// InvokeWebservice(ConfigData.MailURL, "Achievo.MMIP.CommonWebService", "EMail", "SendByAdmin", methodParams);
//}
/// 根据指定的信息,调用远程WebService方法
/// </summary>
/// <param name="url">WebService的http形式的地址</param>
/// <param name="namespace">欲调用的WebService的命名空间</param>
/// <param name="classname">欲调用的WebService的类名(不包括命名空间前缀)</param>
/// <param name="methodname">欲调用的WebService的方法名</param>
/// <param name="args">参数列表</param>
/// <returns>WebService的执行结果</returns>
/// <remarks>
/// 如果调用失败,将会抛出Exception。请调用的时候,适当截获异常。
/// 异常信息可能会发生在两个地方:
/// 1、动态构造WebService的时候,CompileAssembly失败。
/// 2、WebService本身执行失败。
/// </remarks>
/// <example>
/// <code>
/// object obj = InvokeWebservice("http://localhost/GSP_WorkflowWebservice/common.asmx",
/// "Genersoft.Platform.Service.Workflow",
/// "Common",
/// "GetToolType",
/// new object[]{"1"});
/// </code>
/// </example>
public object InvokeWebservice(string url, string @namespace, string classname,
string methodname, object[] args)
{
try
{
System.Net.WebClient wc = new System.Net.WebClient();
System.IO.Stream stream = wc.OpenRead(url + "?WSDL");
System.Web.Services.Description.ServiceDescription sd = System.Web.Services.Description.ServiceDescription.Read(stream);
System.Web.Services.Description.ServiceDescriptionImporter sdi = new System.Web.Services.Description.ServiceDescriptionImporter();
sdi.AddServiceDescription(sd, "", "");
System.CodeDom.CodeNamespace cn = new System.CodeDom.CodeNamespace(@namespace);
System.CodeDom.CodeCompileUnit ccu = new System.CodeDom.CodeCompileUnit();
ccu.Namespaces.Add(cn);
sdi.Import(cn, ccu);
Microsoft.CSharp.CSharpCodeProvider csc = new Microsoft.CSharp.CSharpCodeProvider();
System.CodeDom.Compiler.ICodeCompiler icc = csc.CreateCompiler();
System.CodeDom.Compiler.CompilerParameters cplist = new System.CodeDom.Compiler.CompilerParameters();
cplist.GenerateExecutable = false;
cplist.GenerateInMemory = true;
cplist.ReferencedAssemblies.Add("System.dll");
cplist.ReferencedAssemblies.Add("System.XML.dll");
cplist.ReferencedAssemblies.Add("System.Web.Services.dll");
cplist.ReferencedAssemblies.Add("System.Data.dll");
System.CodeDom.Compiler.CompilerResults cr = icc.CompileAssemblyFromDom(cplist, ccu);
if (true == cr.Errors.HasErrors)
{
System.Text.StringBuilder sb = new System.Text.StringBuilder();
foreach (System.CodeDom.Compiler.CompilerError ce in cr.Errors)
{
sb.Append(ce.ToString());
sb.Append(System.Environment.NewLine);
}
throw new Exception(sb.ToString());
}
System.Reflection.Assembly assembly = cr.CompiledAssembly;
Type t = assembly.GetType(@namespace + "." + classname, true, true);
object obj = Activator.CreateInstance(t);
System.Reflection.MethodInfo mi = t.GetMethod(methodname);
return mi.Invoke(obj, args);
}
catch (Exception ex)
{
throw new Exception(ex.InnerException.Message, new Exception(ex.InnerException.StackTrace));
}
}
示例3: TestCompiler
public TestCompiler( string[] assemblyNames, string outputName )
{
Microsoft.CSharp.CSharpCodeProvider provider = new Microsoft.CSharp.CSharpCodeProvider();
this.compiler = provider.CreateCompiler();
this.options = new CompilerParameters();
if ( assemblyNames != null && assemblyNames.Length > 0 )
options.ReferencedAssemblies.AddRange( assemblyNames );
if ( outputName != null )
options.OutputAssembly = outputName;
options.IncludeDebugInformation = false;
options.TempFiles = new TempFileCollection( ".", false );
options.GenerateInMemory = false;
}
示例4: Compile
protected virtual CompilerResults Compile(string code, Type[] types)
{
Microsoft.CSharp.CSharpCodeProvider provider = new Microsoft.CSharp.CSharpCodeProvider ();
ICodeCompiler compiler = provider.CreateCompiler ();
ArrayList assemblies = new ArrayList ();
assemblies.Add ("System.dll");
foreach (Type type in types)
{
assemblies.Add (type.Assembly.Location);
}
string[] assemblyNames = (string[]) assemblies.ToArray (typeof (string));
CompilerParameters options = new CompilerParameters (assemblyNames);
options.GenerateInMemory = true;
CompilerResults results = compiler.CompileAssemblyFromSource (options, code);
return results;
}
示例5: GetAssemblyWithCustomVersionTableMetaData
/// <summary>
/// Creates an assembly by dynamically compiling TestVersionTableMetaData.cs
/// </summary>
/// <returns></returns>
private Assembly GetAssemblyWithCustomVersionTableMetaData()
{
CodeDomProvider provider = new Microsoft.CSharp.CSharpCodeProvider();
ICodeCompiler compiler = provider.CreateCompiler();
CompilerParameters parms = new CompilerParameters();
// Configure parameters
parms.GenerateExecutable = false;
parms.GenerateInMemory = true;
parms.IncludeDebugInformation = false;
parms.ReferencedAssemblies.Add("System.dll");
parms.ReferencedAssemblies.Add("FluentMigrator.dll");
CompilerResults results = compiler.CompileAssemblyFromFile(parms, "..\\..\\Unit\\TestVersionTableMetaData.cs");
Assert.AreEqual(0, results.Errors.Count);
return results.CompiledAssembly;
}
示例6: GetImplementation
public MDynamicSupport GetImplementation()
{
// TODO: Adds a cache for generated assemblies...
CodeNamespace ns = BuildMDynamicSupportCodeDom();
Microsoft.CSharp.CSharpCodeProvider cp = new Microsoft.CSharp.CSharpCodeProvider();
cp.CreateGenerator().GenerateCodeFromNamespace( ns, Console.Out, null );
CodeCompileUnit unit = new CodeCompileUnit();
unit.Namespaces.Add( ns );
String[] assembliesName = GetRequiredAssemblies();
CompilerParameters parameters = new CompilerParameters(assembliesName);
parameters.GenerateExecutable = false;
parameters.GenerateInMemory = true;
CompilerResults result =
cp.CreateCompiler().CompileAssemblyFromDom(parameters, unit);
if (result.Errors.HasErrors)
{
throw new CompilationException(result.Errors);
}
Type dynamicType =
result.CompiledAssembly.GetType(
"Castle.ManagementExtensions.Generated.DynamicImplementation", true, true);
Object inst = Activator.CreateInstance(
dynamicType,
new object[] { info, instance } );
return (MDynamicSupport) inst;
}
示例7: GenerateExecutableAssembly
private Assembly GenerateExecutableAssembly(PrologCompilerParameters compilerParameters, ArrayList instructions)
{
CodeCompileUnit compileUnit = new CodeCompileUnit();
// Declare namespace, default is Prolog.Assembly
CodeNamespace plNamespace = new CodeNamespace("Prolog.Assembly");
plNamespace.Imports.Add(new CodeNamespaceImport("System"));
plNamespace.Imports.Add(new CodeNamespaceImport("System.Collections"));
plNamespace.Imports.Add(new CodeNamespaceImport("Axiom.Runtime"));
compileUnit.Namespaces.Add(plNamespace);
// Declare class type
CodeTypeDeclaration classType = new CodeTypeDeclaration("PrologApp");
plNamespace.Types.Add(classType);
classType.TypeAttributes = TypeAttributes.Public;
// Declare private members
CodeMemberField machineField = new CodeMemberField(new CodeTypeReference("AbstractMachineState"), "machine");
CodeMemberField moreField = new CodeMemberField(new CodeTypeReference("System.Boolean"), "_more");
classType.Members.Add(machineField);
classType.Members.Add(moreField);
// Generate constructor method
CodeConstructor cons = new CodeConstructor();
cons.Attributes = MemberAttributes.Public;
cons.Statements.Add(new CodeSnippetExpression("Init()"));
classType.Members.Add(cons);
// Generate Init() method
GenerateInitMethod(classType, instructions);
// Generate main method
CodeEntryPointMethod mainMethod = new CodeEntryPointMethod();
mainMethod.Name = "Main";
mainMethod.Attributes = MemberAttributes.Static | MemberAttributes.Public;
mainMethod.Statements.Add(new CodeSnippetStatement("PrologApp app = new PrologApp();"));
mainMethod.Statements.Add(new CodeSnippetStatement("app.Run();"));
classType.Members.Add(mainMethod);
CodeMemberMethod runMethod = new CodeMemberMethod();
runMethod.Name = "Run";
runMethod.Attributes = MemberAttributes.Public;
runMethod.Statements.Add(new CodeSnippetStatement("machine.Call(\"main\");"));
classType.Members.Add(runMethod);
// Compile the file into a DLL
CompilerParameters compparams = new CompilerParameters(new string[] { "mscorlib.dll", "Axiom.Runtime.dll" });
compparams.GenerateInMemory = false;
compparams.GenerateExecutable = true;
compparams.OutputAssembly = compilerParameters.OutputAssembly;
compparams.TempFiles.KeepFiles = true;
Microsoft.CSharp.CSharpCodeProvider csharp = new Microsoft.CSharp.CSharpCodeProvider();
ICodeCompiler cscompiler = csharp.CreateCompiler();
CompilerResults compresult = cscompiler.CompileAssemblyFromDom(compparams, compileUnit);
if (compresult.Errors.Count > 0)
{
foreach (CompilerError err in compresult.Errors)
{
Console.WriteLine(err);
}
return null;
}
return compresult.CompiledAssembly;
}
示例8: GenerateDllAssembly
private Assembly GenerateDllAssembly(PrologCompilerParameters compilerParameters, ArrayList instructions, PrologCodeUnit unit)
{
CodeCompileUnit compileUnit = new CodeCompileUnit();
// Declare namespace, default is Prolog.Assembly
CodeNamespace plNamespace = new CodeNamespace("Prolog.Assembly");
plNamespace.Imports.Add(new CodeNamespaceImport("System"));
plNamespace.Imports.Add(new CodeNamespaceImport("System.Collections"));
plNamespace.Imports.Add(new CodeNamespaceImport("Axiom.Runtime"));
compileUnit.Namespaces.Add(plNamespace);
// Declare class type
CodeTypeDeclaration classType = new CodeTypeDeclaration(unit.Class);
plNamespace.Types.Add(classType);
classType.TypeAttributes = TypeAttributes.Public;
// Declare private members
CodeMemberField machineField = new CodeMemberField(new CodeTypeReference("AbstractMachineState"), "machine");
CodeMemberField moreField = new CodeMemberField(new CodeTypeReference("System.Boolean"), "_more");
classType.Members.Add(machineField);
classType.Members.Add(moreField);
// Generate constructor method
CodeConstructor cons = new CodeConstructor();
cons.Attributes = MemberAttributes.Public;
cons.Statements.Add(new CodeSnippetExpression("Init()"));
classType.Members.Add(cons);
// Generate the 'More' property
CodeMemberProperty moreProperty = new CodeMemberProperty();
moreProperty.Attributes = MemberAttributes.Public;
moreProperty.Name = "More";
moreProperty.HasGet = true;
moreProperty.HasSet = false;
moreProperty.Type = new CodeTypeReference("System.Boolean");
string getStmt1 = "if (machine.Program.CurrentInstruction() == null || machine.Program.CurrentInstruction().Name().Equals(\"stop\")) { _more = false; } ";
string getStmt2 = "return !(machine.Program.CurrentInstruction() == null || machine.Program.CurrentInstruction().Name().Equals(\"stop\"));";
moreProperty.GetStatements.Add(new CodeSnippetStatement(getStmt1));
moreProperty.GetStatements.Add(new CodeSnippetStatement(getStmt2));
classType.Members.Add(moreProperty);
// Generate Redo() method
CodeMemberMethod redoMethod = new CodeMemberMethod();
redoMethod.Name = "Redo";
redoMethod.Statements.Add(new CodeSnippetStatement("machine.Backtrack();"));
redoMethod.Statements.Add(new CodeSnippetStatement("_more = true;"));
redoMethod.Attributes = MemberAttributes.Public;
classType.Members.Add(redoMethod);
// Generate Init() method
GenerateInitMethod(classType, instructions);
// Generate method signatures
GenerateMethodSignatures(classType, instructions);
// Compile the file into a DLL
CompilerParameters compparams = new CompilerParameters(new string[] { "mscorlib.dll", "Axiom.Runtime.dll" });
compparams.GenerateInMemory = false;
compparams.OutputAssembly = compilerParameters.OutputAssembly;
compparams.TempFiles.KeepFiles = true;
Microsoft.CSharp.CSharpCodeProvider csharp = new Microsoft.CSharp.CSharpCodeProvider();
ICodeCompiler cscompiler = csharp.CreateCompiler();
CompilerResults compresult = cscompiler.CompileAssemblyFromDom(compparams, compileUnit);
if (compresult.Errors.Count > 0)
{
foreach(CompilerError err in compresult.Errors)
{
Console.WriteLine(err);
}
return null;
}
return compresult.CompiledAssembly;
}
示例9: 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());
}
}
}
示例10: Compile
private static Assembly Compile(string[] files)
{
errors = new List<System.CodeDom.Compiler.CompilerError>();
Microsoft.CSharp.CSharpCodeProvider provider;
Dictionary<string, string> param = new Dictionary<string, string>();
param.Add("CompilerVersion", "v4.0");
provider = new Microsoft.CSharp.CSharpCodeProvider(param);
System.CodeDom.Compiler.CompilerParameters options = new System.CodeDom.Compiler.CompilerParameters();
options.GenerateInMemory = true;
options.TreatWarningsAsErrors = false;
options.IncludeDebugInformation = true;
List<string> refs = new List<string>();
Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
for (int i = 0; i < assemblies.Length; i++) {
if (!assemblies[i].FullName.Contains("System.") && !assemblies[i].FullName.Contains("Microsoft.")) {
refs.Add(System.IO.Path.GetFileName(assemblies[i].Location));
//refs.Add(assemblies[i].Location);
}
}
refs.Add("System.dll");
refs.Add("System.Data.dll");
refs.Add("System.Drawing.dll");
refs.Add("System.Xml.dll");
refs.Add("System.Windows.Forms.dll");
//refs.Add("DatabaseConnector.dll");
refs.Add("System.Core.dll");
refs.Add("MySql.Data.dll");
refs.Add("DataManager.dll");
refs.Add("Server.RDungeons.dll");
refs.Add(System.Windows.Forms.Application.ExecutablePath);
options.ReferencedAssemblies.AddRange(refs.ToArray());
System.CodeDom.Compiler.ICodeCompiler compiler = provider.CreateCompiler();
System.CodeDom.Compiler.CompilerResults results = compiler.CompileAssemblyFromFileBatch(options, files);
foreach (System.CodeDom.Compiler.CompilerError err in results.Errors) {
errors.Add(err);
}
if (results.Errors.Count == 0) {
return results.CompiledAssembly;
} else {
return null;
}
}
示例11: Compile
CompilerResults Compile(MigrationContext context, CodeCompileUnit dom)
{
CompilerParameters parameters = new CompilerParameters();
parameters.GenerateInMemory = true;
parameters.ReferencedAssemblies.Add(GetType().Assembly.Location);
parameters.ReferencedAssemblies.Add(context.TargetAssembly.Location);
if (_references.Length > 0)
{
foreach (string reference in _references.Split(';'))
{
string assemblyName = reference.Trim();
parameters.ReferencedAssemblies.Add(Assembly.Load(assemblyName).Location);
}
}
CodeDomProvider provider = new Microsoft.CSharp.CSharpCodeProvider();
ICodeCompiler compiler = provider.CreateCompiler();
return compiler.CompileAssemblyFromDom(parameters, dom);
}
示例12: Execute
private string Execute(ITemplateGeneratorHost host, string relativePath, string templateFile, string outFileName)
{
Type compiledType = null;
if (!_compiledAssemblies.Contains(templateFile))
{
string guid = Guid.NewGuid().ToString("N");
string generatorClassName = "Template" + guid;
string import = @"using System;
using System.Collections;
";
foreach (DictionaryEntry entry in _currentTemplateContext.Imports)
{
TagAttributes tagAttributes = entry.Value as TagAttributes;
import += "using " + tagAttributes["Namespace"].ToString() + ";\r\n";
}
string prefix = @"
namespace FluorineFx.CodeGenerator
{
public class " + generatorClassName + @" : Template
{
public " + generatorClassName + @"(TemplateEngine templateEngine, ITemplateGeneratorHost host, TemplateContext templateContext) : base(templateEngine, host, templateContext)
{
}
public void RunTemplate()
{";
string suffix = @"
}
}
}";
string code = import + prefix + _codeBuilder.ToString() + suffix;
if (_templateEngineSettings.Trace)
{
host.AddFile(relativePath, outFileName + ".trace.cs", code);
}
CodeDomProvider provider = null;
//Microsoft.CSharp.CSharpCodeProvider provider = new Microsoft.CSharp.CSharpCodeProvider();
//Microsoft.VisualBasic.VBCodeProvider provider = new Microsoft.VisualBasic.VBCodeProvider();
provider = new Microsoft.CSharp.CSharpCodeProvider();
#if (NET_1_1)
ICodeCompiler compiler = provider.CreateCompiler();
#endif
CompilerParameters options = new CompilerParameters();
options.GenerateInMemory = true;
options.GenerateExecutable = false;
foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies())
{
//options.ReferencedAssemblies.Add(Path.GetFileName(assembly.Location));
options.ReferencedAssemblies.Add(assembly.Location);
}
Uri uri = new Uri(Assembly.GetExecutingAssembly().CodeBase);
string libPath = Path.GetDirectoryName(uri.LocalPath);
options.CompilerOptions = "/lib:\"" + libPath + "\"";
if (AppDomain.CurrentDomain.BaseDirectory != null)
options.CompilerOptions += " /lib:\"" + Path.GetDirectoryName(AppDomain.CurrentDomain.BaseDirectory) + "\"";
if (AppDomain.CurrentDomain.DynamicDirectory != null)
options.CompilerOptions += " /lib:\"" + Path.GetDirectoryName(AppDomain.CurrentDomain.DynamicDirectory) + "\"";
foreach (DictionaryEntry entry in _currentTemplateContext.Assemblies)
{
TagAttributes tagAttributes = entry.Value as TagAttributes;
bool referenced = false;
foreach (string referencedAssembly in options.ReferencedAssemblies)
{
string assembly = Path.GetFileName(referencedAssembly);
if (assembly.ToLower() == tagAttributes["Name"].ToString().ToLower())
{
referenced = true;
break;
}
}
if (!referenced)
options.ReferencedAssemblies.Add(tagAttributes["Name"].ToString());
}
//log.Debug("Compiling code");
//log.Debug(code);
/*
string output = Path.Combine(Path.GetTempPath(), generatorClassName + ".cs");
using (StreamWriter sw = File.CreateText(output))
{
sw.Write(code);
}
*/
#if (NET_1_1)
CompilerResults results = compiler.CompileAssemblyFromSource(options, code);
#else
CompilerResults results = provider.CompileAssemblyFromSource(options, code);
//CompilerResults results = provider.CompileAssemblyFromFile(options, output);
#endif
if (results.Errors.Count != 0)
//.........这里部分代码省略.........
示例13: initDimensional
private void initDimensional(string expression)
{
Microsoft.CSharp.CSharpCodeProvider cp = new Microsoft.CSharp.CSharpCodeProvider();
System.CodeDom.Compiler.ICodeCompiler ic = cp.CreateCompiler();
System.CodeDom.Compiler.CompilerParameters cpar = new System.CodeDom.Compiler.CompilerParameters();
cpar.GenerateInMemory = true;
cpar.GenerateExecutable = false;
cpar.ReferencedAssemblies.Add("system.dll");
cpar.ReferencedAssemblies.Add("ComputingMath.dll");
string src = "using System;" +
"class myclass : ComputingMath.Parsing.Function" +
"{" +
"public myclass(){}" +
"public override double evaluate(double[] x)" +
"{" +
"return " + expression + ";" +
"}" +
"}";
System.CodeDom.Compiler.CompilerResults cr = ic.CompileAssemblyFromSource(cpar, src);
foreach (System.CodeDom.Compiler.CompilerError ce in cr.Errors)
{
throw new ParsingErrorException(ce.ErrorText);
}
if ((cr.Errors.Count == 0) && (cr.CompiledAssembly != null))
{
Type ObjType = cr.CompiledAssembly.GetType("myclass");
try
{
if (ObjType != null)
{
myFunction = (Function)Activator.CreateInstance(ObjType);
}
}
catch (Exception exception)
{
throw new ParsingErrorException("Unexpected error due to parsing function!", exception);
}
}
else
{
throw new ParsingErrorException("Error parsing function!");
}
}
示例14: GenerateWebProxyDLL
public static ProjectReference GenerateWebProxyDLL(Project project, ServiceDescription desc)
{
ProjectReference refInfo = null;
string nmspace = GetNamespaceFromUri(desc.RetrievalUrl);
StringBuilder savedir = new StringBuilder();
savedir.Append(project.BaseDirectory);
savedir.Append(Path.DirectorySeparatorChar);
savedir.Append("WebReferences");
// second, create the path if it doesn't exist
if(!Directory.Exists(savedir.ToString()))
Directory.CreateDirectory(savedir.ToString());
// generate the assembly
ServiceDescriptionImporter importer = new ServiceDescriptionImporter();
importer.AddServiceDescription(desc, null, null);
CodeNamespace codeNamespace = new CodeNamespace(nmspace);
CodeCompileUnit codeUnit = new CodeCompileUnit();
codeUnit.Namespaces.Add(codeNamespace);
importer.Import(codeNamespace, codeUnit);
CodeDomProvider provider = new Microsoft.CSharp.CSharpCodeProvider();
System.CodeDom.Compiler.ICodeCompiler compiler;
if(provider != null) {
compiler = provider.CreateCompiler();
CompilerParameters parms = new CompilerParameters();
parms.ReferencedAssemblies.Add("System.Dll");
parms.ReferencedAssemblies.Add("System.Xml.Dll");
parms.ReferencedAssemblies.Add("System.Web.Services.Dll");
parms.OutputAssembly = project.BaseDirectory + Path.DirectorySeparatorChar + "WebReferences" + Path.DirectorySeparatorChar + nmspace + ".Reference.Dll";
CompilerResults results = compiler.CompileAssemblyFromDom(parms, codeUnit);
Assembly assembly = results.CompiledAssembly;
if(assembly != null) {
refInfo = new ProjectReference();
refInfo.ReferenceType = ReferenceType.Assembly;
refInfo.Reference = parms.OutputAssembly;
}
}
return refInfo;
}
示例15: DoBenchmark
private static void DoBenchmark(XmlTextWriter xtw, IBenchmark b)
{
Microsoft.CSharp.CSharpCodeProvider provider = new Microsoft.CSharp.CSharpCodeProvider();
Console.WriteLine("Benchmark: {0}", b.Name);
if (File.Exists("BenchmarkAssembly." + b.Name + ".dll"))
File.Delete("BenchmarkAssembly." + b.Name + ".dll");
CompilerParameters options = new CompilerParameters();
options.OutputAssembly = "BenchmarkAssembly." + b.Name + ".dll";
options.GenerateInMemory = true;
options.GenerateExecutable = false;
foreach (string s in b.References)
options.ReferencedAssemblies.Add(s);
options.CompilerOptions = "/optimize+";
//options.IncludeDebugInformation = true;
string sourceCode = GenerateTestSourceCode(b);
using (StreamWriter sw = File.CreateText("BenchmarkAssembly." + b.Name + ".cs"))
{
sw.Write(sourceCode);
}
CompilerResults results = provider.CreateCompiler().CompileAssemblyFromSource(options, sourceCode);
foreach (CompilerError ce in results.Errors)
{
Console.WriteLine("ERROR in line {0}: {1}", ce.Line, ce.ErrorText);
}
if (results.Errors.Count > 0)
{
Console.WriteLine("Errors in generated code for " + b.Name + " Ignoring.");
return;
}
//Console.WriteLine("Compiled to assembly: {0}", results.CompiledAssembly.FullName);
xtw.WriteStartElement("framework");
xtw.WriteAttributeString("name", b.Name);
Type t = results.CompiledAssembly.GetType("TheBenchmark");
double min, max, avg;
TimeAndDiscardUnusual(null, (RunDelegate)Delegate.CreateDelegate(typeof(RunDelegate), t, "DoNothing"), null, 100000, 10, out min, out max, out avg);
_overhead = min;
Console.WriteLine("overhead: {0}", _overhead);
RunDelegate init = (RunDelegate)Delegate.CreateDelegate(typeof(RunDelegate), t, "Init");
RunDelegate flush = (RunDelegate)Delegate.CreateDelegate(typeof(RunDelegate), t, "Flush");
init();
TimeAndDisplay("Guarded no logging", xtw, null, (RunDelegate)Delegate.CreateDelegate(typeof(RunDelegate), t, "GuardedNoLogging"), null, 100000, 5);
TimeAndDisplay("Unguarded no logging", xtw, null, (RunDelegate)Delegate.CreateDelegate(typeof(RunDelegate), t, "NoLogging"), null, 100000, 5);
TimeAndDisplay("Unguarded no logging with formatting 1", xtw, null, (RunDelegate)Delegate.CreateDelegate(typeof(RunDelegate), t, "NoLoggingWithFormatting1"), null, 10000, 5);
TimeAndDisplay("Unguarded no logging with formatting 2", xtw, null, (RunDelegate)Delegate.CreateDelegate(typeof(RunDelegate), t, "NoLoggingWithFormatting2"), null, 10000, 5);
TimeAndDisplay("Unguarded no logging with formatting 3", xtw, null, (RunDelegate)Delegate.CreateDelegate(typeof(RunDelegate), t, "NoLoggingWithFormatting3"), null, 10000, 5);
TimeAndDisplay("Null target without rendering", xtw, init, (RunDelegate)Delegate.CreateDelegate(typeof(RunDelegate), t, "NoRenderingLoggingWithoutFormatting"), flush, 10000, 5);
TimeAndDisplay("Null target without rendering 1", xtw, init, (RunDelegate)Delegate.CreateDelegate(typeof(RunDelegate), t, "NoRenderingLoggingWithFormatting1"), flush, 10000, 5);
TimeAndDisplay("Null target without rendering 3", xtw, init, (RunDelegate)Delegate.CreateDelegate(typeof(RunDelegate), t, "NoRenderingLoggingWithFormatting3"), flush, 10000, 5);
TimeAndDisplay("Null target with rendering", xtw, init, (RunDelegate)Delegate.CreateDelegate(typeof(RunDelegate), t, "NullLoggingWithoutFormatting"), flush, 1000, 5);
TimeAndDisplay("Null target with rendering 1", xtw, init, (RunDelegate)Delegate.CreateDelegate(typeof(RunDelegate), t, "NullLoggingWithFormatting1"), flush, 1000, 5);
TimeAndDisplay("Null target with rendering 3", xtw, init, (RunDelegate)Delegate.CreateDelegate(typeof(RunDelegate), t, "NullLoggingWithFormatting3"), flush, 1000, 5);
TimeAndDisplay("Simple file", xtw, init, (RunDelegate)Delegate.CreateDelegate(typeof(RunDelegate), t, "SimpleFile"), flush, 10, 5);
//TimeAndDisplay("Buffered file", xtw, init, (RunDelegate)Delegate.CreateDelegate(typeof(RunDelegate), t, "BufferedFile"), flush, 100, 5);
//TimeAndDisplay("Asynchronous File without a flush", xtw, init, (RunDelegate)Delegate.CreateDelegate(typeof(RunDelegate), t, "AsyncFile"), null, 100, 5);
//flush();
//TimeAndDisplay("Asynchronous File with a flush", xtw, init, (RunDelegate)Delegate.CreateDelegate(typeof(RunDelegate), t, "AsyncFile"), flush, 5000, 5);
xtw.WriteEndElement();
}