本文整理汇总了C#中Microsoft.CSharp.CSharpCodeProvider类的典型用法代码示例。如果您正苦于以下问题:C# CSharpCodeProvider类的具体用法?C# CSharpCodeProvider怎么用?C# CSharpCodeProvider使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
CSharpCodeProvider类属于Microsoft.CSharp命名空间,在下文中一共展示了CSharpCodeProvider类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: init
private bool init(string generateCode, params string[] referenceAssemblies)
{
bool flag = false;
result = null;
using (CSharpCodeProvider provider = new CSharpCodeProvider())
{
ICodeCompiler objICodeCompiler = provider.CreateCompiler();
CompilerParameters objCompilerParameters = new CompilerParameters();
if (referenceAssemblies != null)
objCompilerParameters.ReferencedAssemblies.AddRange(referenceAssemblies);
objCompilerParameters.GenerateExecutable = false;
objCompilerParameters.GenerateInMemory = true;
result = objICodeCompiler.CompileAssemblyFromSource(objCompilerParameters, generateCode);
}
if (result != null)
{
if (result.Errors.Count > 0 && ErrorHandler != null)
{
ErrorHandler(result.Errors);
}
else
{
flag = true;
}
}
return flag;
}
示例2: Compile
public Tuple<StringCollection, Assembly> Compile(string[] dllFiles, string[] sourceFiles, string outputAssemblyPath)
{
var providerOptions = new Dictionary<string,
string> { {
"CompilerVersion",
"v4.0"
}
};
CodeDomProvider codeProvider = new CSharpCodeProvider(providerOptions);
var compilerParameters = new CompilerParameters
{
GenerateExecutable = false,
GenerateInMemory = true,
IncludeDebugInformation = true
};
compilerParameters.ReferencedAssemblies.AddRange(dllFiles);
compilerParameters.ReferencedAssemblies.Add("System.dll");
compilerParameters.ReferencedAssemblies.Add("System.Core.dll");
compilerParameters.ReferencedAssemblies.Add("System.Web.Services.dll");
compilerParameters.ReferencedAssemblies.Add("System.ComponentModel.dll");
compilerParameters.ReferencedAssemblies.Add("System.Xml.Serialization.dll");
var result = codeProvider.CompileAssemblyFromFile(compilerParameters, sourceFiles);
return new Tuple<StringCollection,
Assembly>(result.Output, result.Errors.Count > 0 ? null : result.CompiledAssembly);
}
示例3: CompileFile
public static CompilerResults CompileFile(string input, string output, params string[] references)
{
CreateOutput(output);
List<string> referencedAssemblies = new List<string>(references.Length + 3);
referencedAssemblies.AddRange(references);
referencedAssemblies.Add("System.dll");
referencedAssemblies.Add(typeof(IModule).Assembly.CodeBase.Replace(@"file:///", ""));
referencedAssemblies.Add(typeof(ModuleAttribute).Assembly.CodeBase.Replace(@"file:///", ""));
CSharpCodeProvider codeProvider = new CSharpCodeProvider();
CompilerParameters cp = new CompilerParameters(referencedAssemblies.ToArray(), output);
using (Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(input))
{
if (stream == null)
{
throw new ArgumentException("input");
}
StreamReader reader = new StreamReader(stream);
string source = reader.ReadToEnd();
CompilerResults results = codeProvider.CompileAssemblyFromSource(cp, source);
ThrowIfCompilerError(results);
return results;
}
}
示例4: CompileSiteModels
public void CompileSiteModels()
{
DirectoryInfo di = new DirectoryInfo(SysPath.SiteModelsDirectory);
FileInfo[] fiar = di.GetFiles("*.cs");
String[] fisar = new String[fiar.Length];
for (int i = 0; i < fiar.Length; i++)
{
fisar[i] = fiar[i].FullName;
}
CompilerParameters parameters = new CompilerParameters(new String[] { "System.dll", "NStag.dll", "nhibernate.dll" });
parameters.GenerateExecutable = false;
parameters.GenerateInMemory = true;
parameters.OutputAssembly = this.DomainName;
parameters.CompilerOptions = String.Concat("/lib:", SysPath.GetLibDirectory());
CSharpCodeProvider cprovider = new CSharpCodeProvider();
CompilerResults results = cprovider.CompileAssemblyFromFile(parameters, cspath);
if (results.Errors.HasErrors)
{
throw new Exception(results.Errors[0].ErrorText);
}
}
示例5: InvokeWebService
public static object InvokeWebService(string url, string classname, string methodname, object[] args)
{
string @namespace = "EnterpriseServerBase.WebService.DynamicWebCalling";
if ((classname == null) || (classname == ""))
{
classname = WebServiceProxy.GetWsClassName(url);
}
try
{
//获取WSDL
WebClient wc = new WebClient();
Stream stream = wc.OpenRead(url + "?WSDL");
ServiceDescription sd = ServiceDescription.Read(stream);
ServiceDescriptionImporter sdi = new ServiceDescriptionImporter();
sdi.AddServiceDescription(sd, "", "");
CodeNamespace cn = new CodeNamespace(@namespace);
//生成客户端代理类代码
CodeCompileUnit ccu = new CodeCompileUnit();
ccu.Namespaces.Add(cn);
sdi.Import(cn, ccu);
CSharpCodeProvider csc = new CSharpCodeProvider();
ICodeCompiler icc = csc.CreateCompiler();
//设定编译参数
CompilerParameters cplist = new 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");
//编译代理类
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));
}
}
示例6: Compile
public bool Compile(string src)
{
var param = new CompilerParameters(new string[]
{
"System.dll",
"mscorlib.dll",
"System.Data.dll",
"System.Xml.dll",
"System.Xml.Linq.dll",
"lib.dll",
"compiler.dll",
});
param.GenerateInMemory = true;
param.GenerateExecutable = false;
param.IncludeDebugInformation = false;
_provider = new CSharpCodeProvider(
new Dictionary<string, string>()
{
{ "CompilerVersion", "v4.0" },
});
_results = _provider.CompileAssemblyFromSource(param, src);
if (_results.Errors.Count > 0)
{
foreach (CompilerError err in _results.Errors)
{
if (err.IsWarning) Console.WriteLine("[Warning] {0}: [{1}] {2}", err.Line, err.ErrorNumber, err.ErrorText);
else Console.WriteLine("[Error] {0}: [{1}] {2}", err.Line, err.ErrorNumber, err.ErrorText);
}
return false;
}
return true;
}
示例7: ExecuteScript
private static object ExecuteScript(string script, ScriptExecutionOptions options)
{
object result = null;
CompilerParameters cpar = new CompilerParameters();
cpar.GenerateInMemory = true;
cpar.ReferencedAssemblies.Add("mscorlib.dll");
cpar.ReferencedAssemblies.Add("System.dll");
cpar.ReferencedAssemblies.Add("System.Core.dll");
cpar.ReferencedAssemblies.Add("System.Data.dll");
cpar.ReferencedAssemblies.Add("System.Xml.dll");
cpar.ReferencedAssemblies.Add(typeof(CSharpScriptingProvider).Assembly.Location);
string code = Properties.Resources.ScriptProviderCSharpTemplate;
code = code.Replace("{Source}", script);
CSharpCodeProvider csp = new CSharpCodeProvider();
CompilerResults res = csp.CompileAssemblyFromSource(cpar, code);
if (!res.Errors.HasErrors)
{
MethodInfo func = res.CompiledAssembly.ExportedTypes.First().GetMethods().First();
result = func.Invoke(null, new object[] { options });
}
return result;
}
示例8: OutputAssembly
public static void OutputAssembly(Dictionary<string, string> generated, IEnumerable<string> assemblies, string assemblyPath)
{
var providerOptions = new Dictionary<string, string> {{"CompilerVersion", "v4.0"}};
using (var codeProvider = new CSharpCodeProvider(providerOptions))
{
string[] sources = (from p in generated.Keys select generated[p]).ToArray();
List<string> assemblyPaths = new List<string>(assemblies);
assemblyPaths.Add(typeof (ManifestEventAttribute).Assembly.Location);
var compilerParameters = new CompilerParameters(
assemblyPaths.ToArray(),
assemblyPath,
false);
CompilerResults results = codeProvider.CompileAssemblyFromSource(compilerParameters, sources);
if (results.Errors.Count == 0)
return;
var sb = new StringBuilder();
foreach (object o in results.Errors)
{
sb.AppendLine(o.ToString());
}
string errors = sb.ToString();
throw new Exception(errors);
}
}
示例9: UpdateSource
public void UpdateSource()
{
_codeType = null;
_codeInstance = null;
if (Source == null)
return;
var provider = new CSharpCodeProvider();
var options = new CompilerParameters { GenerateInMemory = true };
string qn = typeof(Point3D).Assembly.Location;
options.ReferencedAssemblies.Add("System.dll");
options.ReferencedAssemblies.Add(qn);
string src = template.Replace("#code#", Source);
CompilerResults compilerResults = provider.CompileAssemblyFromSource(options, src);
if (!compilerResults.Errors.HasErrors)
{
Errors = null;
var assembly = compilerResults.CompiledAssembly;
_codeInstance = assembly.CreateInstance("MyNamespace.MyEvaluator");
_codeType = _codeInstance.GetType();
}
else
{
// correct line numbers
Errors = compilerResults.Errors;
for (int i = 0; i < Errors.Count; i++)
Errors[i].Line -= 17;
}
_w = ParameterW;
UpdateModel();
}
示例10: PrimitiveLiteral
/// <summary>
/// Returns the C# literal representation of a given primitive expression.
/// (Useful for escaping strings)
/// </summary>
private static string PrimitiveLiteral(this string input)
{
var writer = new StringWriter();
var provider = new CSharpCodeProvider();
provider.GenerateCodeFromExpression(new CodePrimitiveExpression(input), writer, null);
return writer.ToString();
}
示例11: CompileLegacy
protected static AssemblyDef CompileLegacy(string code, bool optimize, bool useDebug, int compilerVersion)
{
CSharpCodeProvider provider = new CSharpCodeProvider(new Dictionary<string, string> { { "CompilerVersion", "v" + new Version(compilerVersion, 0) } });
CompilerParameters options = new CompilerParameters();
options.CompilerOptions = "/unsafe /o" + (optimize ? "+" : "-") + (useDebug ? " /debug" : "");
if (compilerVersion >= 4)
options.ReferencedAssemblies.Add("System.Core.dll");
CompilerResults results = provider.CompileAssemblyFromSource(options, code);
try
{
if (results.Errors.Count > 0)
{
StringBuilder b = new StringBuilder("Compiler error:");
foreach (var error in results.Errors)
{
b.AppendLine(error.ToString());
}
throw new Exception(b.ToString());
}
return Utils.OpenAssembly(results.PathToAssembly);
}
finally
{
File.Delete(results.PathToAssembly);
results.TempFiles.Delete();
}
}
示例12: Compile
public static CompilerResults Compile(this DirectoryInfo[] compileTargets, string fileName, string[] referenceAssemblies, bool executable)
{
CSharpCodeProvider codeProvider = new CSharpCodeProvider();
CompilerParameters parameters = new CompilerParameters();
parameters.GenerateExecutable = executable;
parameters.OutputAssembly = fileName;
List<string> compilerOptions = new List<string>();
foreach (string referenceAssembly in referenceAssemblies)
{
compilerOptions.Add("/reference:" + referenceAssembly);
}
parameters.CompilerOptions = compilerOptions.ToArray().ToDelimited(" ");
List<string> fileNames = new List<string>();
foreach (DirectoryInfo targetDirectory in compileTargets)
{
foreach (FileInfo fileInfo in FsUtil.GetFilesWithExtension(targetDirectory.FullName, ".cs"))
{
fileNames.Add(fileInfo.FullName);
}
}
return codeProvider.CompileAssemblyFromFile(parameters, fileNames.ToArray());//.CompileAssemblyFromFileBatch(parameters, fileNames.ToArray());
}
示例13: 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);
}
}
}
}
示例14: 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;
}
示例15: Expression
public Expression(string expression)
{
CompilerParameters p = new CompilerParameters();
p.GenerateInMemory = true;
System.Text.RegularExpressions.MatchCollection mc = System.Text.RegularExpressions.Regex.Matches(expression, @"\{([^\}]*)\}");
string paramsStr = "";
for (int i = 0; i < mc.Count; i++)
{
string mcValue = mc[i].Value;
string mcGroupValue = mc[i].Groups[1].Value;
if (!ExpressionKey.Contains(mcGroupValue))
{
ExpressionKey.Add(mcGroupValue);
paramsStr += "double d" + i + ",";
expression = expression.Replace(mcValue, "d" + i);
}
}
this.ExpressionBody = expression;
paramsStr = paramsStr.TrimEnd(',');
string clsStr = String.Format("using System;sealed class Expression{{public double Compute({0}){{return {1};}}}}", paramsStr, expression);
CompilerResults cr = new CSharpCodeProvider().CompileAssemblyFromSource(p, clsStr);
if (cr.Errors.Count > 0)
{
string msg = "Expression(\"" + expression + "\"): \n";
foreach (CompilerError err in cr.Errors) msg += err.ToString() + "\n";
throw new Exception(msg);
}
instance = cr.CompiledAssembly.CreateInstance("Expression");
method = instance.GetType().GetMethod("Compute");
}