本文整理汇总了C#中System.CodeDom.Compiler.CodeDomProvider.CompileAssemblyFromSource方法的典型用法代码示例。如果您正苦于以下问题:C# CodeDomProvider.CompileAssemblyFromSource方法的具体用法?C# CodeDomProvider.CompileAssemblyFromSource怎么用?C# CodeDomProvider.CompileAssemblyFromSource使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.CodeDom.Compiler.CodeDomProvider
的用法示例。
在下文中一共展示了CodeDomProvider.CompileAssemblyFromSource方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: CompileScriptFromSource
public static Assembly CompileScriptFromSource(string source, CodeDomProvider provider, ref string errors)
{
StringBuilder errorLog = new StringBuilder();
errors = "";
CompilerParameters compilerParameters = new CompilerParameters();
compilerParameters.GenerateExecutable = false;
compilerParameters.GenerateInMemory = true;
compilerParameters.IncludeDebugInformation = false;
compilerParameters.ReferencedAssemblies.Add("System.dll");
compilerParameters.ReferencedAssemblies.Add("System.Windows.Forms.dll");
compilerParameters.ReferencedAssemblies.Add("KedrahCore.dll");
compilerParameters.ReferencedAssemblies.Add("TibiaAPI.dll");
compilerParameters.ReferencedAssemblies.Add(System.Reflection.Assembly.GetExecutingAssembly().Location);
CompilerResults results = provider.CompileAssemblyFromSource(compilerParameters, source);
if (!results.Errors.HasErrors)
{
return results.CompiledAssembly;
}
else
{
foreach (CompilerError error in results.Errors)
{
errorLog.AppendLine(error.ErrorText);
}
}
errors = errorLog.ToString();
return null;
}
示例2: CompileWithProvider
public static Assembly CompileWithProvider(CodeDomProvider provider, params string[] input)
{
var param = new System.CodeDom.Compiler.CompilerParameters();
var result = provider.CompileAssemblyFromSource(param, input);
foreach (var e in result.Errors)
Console.WriteLine("Error occured during compilation {0}", e.ToString());
if (result.Errors.Count > 0)
return null;
else
return result.CompiledAssembly;
}
示例3: LoadSource
/// <summary>
/// Compilation from a class file
/// </summary>
/// <param name="src">Class file</param>
public bool LoadSource(string src)
{
try
{
cp = CodeDomProvider.CreateProvider("C#");
cpar = new CompilerParameters();
cpar.GenerateInMemory = true;
cpar.GenerateExecutable = false;
cpar.ReferencedAssemblies.Add("system.dll");
// Compilation and error managment
cr = cp.CompileAssemblyFromSource(cpar, src);
ObjType = cr.CompiledAssembly.GetType("CuttingTask");
myobj = Activator.CreateInstance(ObjType);
calculate = myobj.GetType().GetMethod("CutTask");
return true;
}
catch { return false; }
}
示例4: Compile
internal Assembly Compile(CodeDomProvider provider, string code)
{
CompilerParameters parameters = new CompilerParameters();
parameters.ReferencedAssemblies.Add("System.dll");
parameters.ReferencedAssemblies.Add("System.Windows.Forms.dll");
parameters.GenerateInMemory = false;
CompilerResults result = provider.CompileAssemblyFromSource(parameters, code);
if(result.Errors.Count > 0)
{
Output.WriteLine("Compiler Errors");
foreach (CompilerError error in result.Errors)
{
Output.WriteLine(error.Line + "\t" + error.ErrorText);
}
return null;
}
return result.CompiledAssembly;
}
示例5: Compiles
/// <summary>
/// Verifies that <paramref name="source"/> compiles using the provided compiler.
/// </summary>
/// <param name="compiler">
/// <see cref="ICodeCompiler"/> instance.</param>
/// <param name="options">Compilation options</param>
/// <param name="source">Source to compile</param>
/// <param name="throwOnWarning">
/// true if assertion should throw if any warning.
/// </param>
public static CompilerResults Compiles(CodeDomProvider provider, CompilerParameters options, string source, bool throwOnWarning)
{
Assert.IsNotNull(provider);
Assert.IsNotNull(options);
CompilerResults results = provider.CompileAssemblyFromSource(options, source);
if (results.Errors.HasErrors)
{
DisplaySource(source);
DisplayErrors(results, Console.Out);
throw new CompilationException(provider, options, results, source);
}
if (throwOnWarning && results.Errors.HasWarnings)
{
DisplaySource(source);
DisplayErrors(results, Console.Out);
throw new CompilationException(provider, options, results, source);
}
return results;
}
示例6: CompileCode
/// <summary>
/// Compiles the code from the code string
/// </summary>
/// <param name="compiler"></param>
/// <param name="parms"></param>
/// <param name="source"></param>
/// <returns></returns>
public static CompilerResults CompileCode(CodeDomProvider compiler, CompilerParameters parms, string source)
{
//actually compile the code
CompilerResults results = compiler.CompileAssemblyFromSource(
parms, source);
//Do we have any compiler errors?
if (results.Errors.Count > 0)
{
foreach (CompilerError error in results.Errors)
Console.WriteLine("Compile Error:" + error.ErrorText);
return null;
}
return results;
}
示例7: CompileCode
/// <summary>
/// Function to compile .Net C#/VB source codes at runtime
/// Adapted from:
/// (http://www.digitalcoding.com/Code-Snippets/C-Sharp/C-Code-Snippet-Compile-C-or-VB-source-code-run-time.html)
/// </summary>
/// <param name="codeProvider">Base class for compiler provider</param>
/// <param name="sourceCode">C# or VB source code as a string</param>
/// <param name="sourceFile">External file containing C# or VB source code</param>
/// <param name="exeFile">File path to create external executable file</param>
/// <param name="assemblyName">File path to create external assembly file</param>
/// <param name="resourceFiles">Required resource files to compile the code</param>
///
/// <param name="errors">String variable to store any errors occurred during the process</param>
/// <returns>Return TRUE if successfully compiled the code, else return FALSE</returns>
public static bool CompileCode(CodeDomProvider codeProvider, string sourceCode, string sourceFile,
string exeFile, string assemblyName, string[] resourceFiles, string[] referencedAssemblies,
out string errors, out CompilerResults compilerResults)
{
// Define parameters to invoke a compiler
CompilerParameters compilerParameters = new CompilerParameters();
if (exeFile != null)
{
// Set the assembly file name to generate.
compilerParameters.OutputAssembly = exeFile;
// Generate an executable instead of a class library.
compilerParameters.GenerateExecutable = true;
compilerParameters.GenerateInMemory = false;
}
else if (assemblyName != null)
{
// Set the assembly file name to generate.
compilerParameters.OutputAssembly = assemblyName;
// Generate a class library instead of an executable.
compilerParameters.GenerateExecutable = false;
compilerParameters.GenerateInMemory = false;
}
else
{
// Generate an in-memory class library instead of an executable.
compilerParameters.GenerateExecutable = false;
compilerParameters.GenerateInMemory = true;
}
// Generate debug information.
compilerParameters.IncludeDebugInformation = true;
// Should start displaying warnings.
compilerParameters.WarningLevel = 2;
// Set whether to treat all warnings as errors.
compilerParameters.TreatWarningsAsErrors = false;
// Set compiler argument to optimize output.
compilerParameters.CompilerOptions = "/optimize";
// Add referenced assemblies
if (referencedAssemblies != null)
compilerParameters.ReferencedAssemblies.AddRange(referencedAssemblies);
// Set a temporary files collection.
// The TempFileCollection stores the temporary files
// generated during a build in the current directory,
// and does not delete them after compilation.
//compilerParameters.TempFiles = new TempFileCollection(".", true);
compilerParameters.TempFiles = new TempFileCollection(".", false);
if (resourceFiles != null && resourceFiles.Length > 0)
{
foreach (string _ResourceFile in resourceFiles)
{
// Set the embedded resource file of the assembly.
compilerParameters.EmbeddedResources.Add(_ResourceFile);
}
}
try
{
// Invoke compilation
if (sourceFile != null && System.IO.File.Exists(sourceFile))
// source code in external file
compilerResults = codeProvider.CompileAssemblyFromFile(compilerParameters, sourceFile);
else
// source code pass as a string
compilerResults = codeProvider.CompileAssemblyFromSource(compilerParameters, sourceCode);
if (compilerResults.Errors.Count > 0)
{
// Return compilation errors
errors = "";
foreach (CompilerError compErr in compilerResults.Errors)
{
errors += "Line number " + compErr.Line +
", Column number " + compErr.Column +
", Error Number: " + compErr.ErrorNumber +
", '" + compErr.ErrorText + ";\r\n\r\n";
}
// Return the results of compilation - Failed
return false;
}
else
{
// no compile errors
errors = null;
}
}
catch (Exception exception)
//.........这里部分代码省略.........
示例8: CompilePlugin
private void CompilePlugin(FileInfo pluginFile, string pluginClassName, CodeDomProvider pluginsCodeDomProvider, CompilerParameters parameters) {
try {
string outputAssembly = Path.Combine(this.PluginBaseDirectory, pluginClassName + ".dll");
if (File.Exists(outputAssembly) == false) {
string fullPluginSource = File.ReadAllText(pluginFile.FullName);
parameters.OutputAssembly = outputAssembly;
// uncomment the following two lines for debugin plugins included in your VS project (taken from PapaCharlie9)
// parameters.IncludeDebugInformation = true;
// parameters.TempFiles = new TempFileCollection(Path.Combine(this.PluginBaseDirectory, "Temp"), true);
fullPluginSource = this.PrecompileDirectives(fullPluginSource);
fullPluginSource = fullPluginSource.Replace("using PRoCon.Plugin;", "using PRoCon.Core.Plugin;");
if (fullPluginSource.Contains("using PRoCon.Core;") == false) {
fullPluginSource = fullPluginSource.Insert(fullPluginSource.IndexOf("using PRoCon.Core.Plugin;"), "\r\nusing PRoCon.Core;\r\n");
}
if (fullPluginSource.Contains("using PRoCon.Core.Players;") == false) {
fullPluginSource = fullPluginSource.Insert(fullPluginSource.IndexOf("using PRoCon.Core.Plugin;"), "\r\nusing PRoCon.Core.Players;\r\n");
}
this.PrintPluginResults(pluginFile, pluginsCodeDomProvider.CompileAssemblyFromSource(parameters, fullPluginSource));
}
else {
this.WritePluginConsole("Compiling {0}... Skipping", pluginFile.Name);
}
}
catch (Exception) { }
}
示例9: CompileInternal
private static Assembly CompileInternal(String outputAssembly, IEnumerable<String> references, CodeDomProvider provider, CompilerErrorCollection Errors, Template tmp)
{
var options = new CompilerParameters();
foreach (var str in references)
{
options.ReferencedAssemblies.Add(str);
}
options.WarningLevel = 4;
CompilerResults results = null;
if (Debug)
{
#region 调试状态,把生成的类文件和最终dll输出到XTemp目录下
var tempPath = XTrace.TempPath;
//if (!String.IsNullOrEmpty(outputAssembly)) tempPath = Path.Combine(tempPath, Path.GetFileNameWithoutExtension(outputAssembly));
if (!String.IsNullOrEmpty(outputAssembly) && !outputAssembly.Equals(".dll")) tempPath = Path.Combine(tempPath, Path.GetFileNameWithoutExtension(outputAssembly));
if (!String.IsNullOrEmpty(tempPath) && !Directory.Exists(tempPath)) Directory.CreateDirectory(tempPath);
var files = new List<String>();
foreach (var item in tmp.Templates)
{
if (item.Included) continue;
String name = item.Name.EndsWith(".cs", StringComparison.OrdinalIgnoreCase) ? item.Name : item.ClassName;
// 猜测后缀
Int32 p = name.LastIndexOf("_");
if (p > 0 && name.Length - p <= 5)
name = name.Substring(0, p) + "." + name.Substring(p + 1, name.Length - p - 1);
else if (!name.EndsWith(".cs", StringComparison.OrdinalIgnoreCase))
name += ".cs";
name = Path.Combine(tempPath, name);
File.WriteAllText(name, item.Source, Encoding.UTF8);
files.Add(name);
}
#endregion
if (!String.IsNullOrEmpty(outputAssembly) && !outputAssembly.Equals(".dll"))
{
options.TempFiles = new TempFileCollection(tempPath, false);
options.OutputAssembly = Path.Combine(tempPath, outputAssembly);
options.GenerateInMemory = true;
options.IncludeDebugInformation = true;
}
results = provider.CompileAssemblyFromFile(options, files.ToArray());
}
else
{
List<String> sources = new List<String>();
foreach (var item in tmp.Templates)
{
sources.Add(item.Source);
}
options.GenerateInMemory = true;
results = provider.CompileAssemblyFromSource(options, sources.ToArray());
}
#region 编译错误处理
if (results.Errors.Count > 0)
{
Errors.AddRange(results.Errors);
var sb = new StringBuilder();
CompilerError err = null;
foreach (CompilerError error in results.Errors)
{
error.ErrorText = error.ErrorText;
//if (String.IsNullOrEmpty(error.FileName)) error.FileName = inputFile;
if (!error.IsWarning)
{
String msg = error.ToString();
if (sb.Length < 1)
{
String code = null;
// 屏蔽因为计算错误行而导致的二次错误
try
{
code = tmp.FindBlockCode(error.FileName, error.Line);
}
catch { }
if (code != null)
{
msg += Environment.NewLine;
msg += code;
}
err = error;
}
else
sb.AppendLine();
sb.Append(msg);
}
}
if (sb.Length > 0)
{
//.........这里部分代码省略.........
示例10: Compile
private static Assembly Compile(CodeDomProvider provider, string sourceCode, out TempFileCollection temporaryFiles)
{
var parameters = new CompilerParameters(new[] {
"mscorlib.dll", "System.dll", "System.Core.dll", "Microsoft.CSharp.dll",
typeof(JSIL.Meta.JSIgnore).Assembly.Location
}) {
CompilerOptions = "/unsafe",
GenerateExecutable = true,
GenerateInMemory = false,
IncludeDebugInformation = true,
TempFiles = new TempFileCollection(TempPath, true)
};
var results = provider.CompileAssemblyFromSource(parameters, sourceCode);
if (results.Errors.Count > 0) {
throw new Exception(
String.Join(Environment.NewLine, results.Errors.Cast<CompilerError>().Select((ce) => ce.ToString()).ToArray())
);
}
temporaryFiles = results.TempFiles;
return results.CompiledAssembly;
}
示例11: CompileModule
private string CompileModule(
CodeDomProvider codeProvider, string targetDirectory, List<AspViewFile> files,
ReferencedAssembly[] references, bool createAssembly, string[] modulesToAdd)
{
string prefix = string.IsNullOrEmpty(options.GeneratedAssemblyNamePrefix) ? null : options.GeneratedAssemblyNamePrefix + ".";
if (!createAssembly)
{
parameters.CompilerOptions = "/t:module";
parameters.OutputAssembly = Path.Combine(targetDirectory,
string.Format("{0}CompiledViews.{1}.netmodule", prefix, codeProvider.FileExtension));
}
else
parameters.OutputAssembly = Path.Combine(targetDirectory, prefix + "CompiledViews.dll");
List<ReferencedAssembly> actualReferences = new List<ReferencedAssembly>();
if (options.References != null)
actualReferences.AddRange(options.References);
if (references != null)
actualReferences.AddRange(references);
foreach (ReferencedAssembly reference in actualReferences)
{
string assemblyName = reference.Name;
if (reference.Source == ReferencedAssembly.AssemblySource.BinDirectory)
assemblyName = Path.Combine(targetDirectory, assemblyName);
parameters.CompilerOptions += " /r:\"" + assemblyName + "\"";
}
if (modulesToAdd != null && modulesToAdd.Length > 0)
{
StringBuilder sb = new StringBuilder();
sb.Append(" /addmodule: ");
foreach (string moduleToAdd in modulesToAdd)
sb.Append(Path.Combine(targetDirectory, moduleToAdd));
parameters.CompilerOptions += "\"" + sb.ToString() + "\"";
}
CompilerResults results;
if (options.KeepTemporarySourceFiles)
{
string targetTemporarySourceFilesDirectory = Path.Combine(targetDirectory, options.TemporarySourceFilesDirectory);
List<string> fileNames = new List<string>(files.Count);
foreach (AspViewFile file in files)
fileNames.Add(Path.Combine(targetTemporarySourceFilesDirectory, file.FileName));
results = codeProvider.CompileAssemblyFromFile(parameters, fileNames.ToArray());
}
else
{
List<string> sources = new List<string>(files.Count);
foreach (AspViewFile file in files)
sources.Add(file.ConcreteClass);
results = codeProvider.CompileAssemblyFromSource(parameters, sources.ToArray());
}
if (results.Errors.Count > 0)
{
StringBuilder message = new StringBuilder();
foreach (CompilerError err in results.Errors)
message.AppendLine(err.ToString());
throw new Exception(string.Format(
"Error while compiling'':\r\n{0}",
message.ToString()));
}
return results.PathToAssembly;
}
示例12: Compile
private Assembly Compile(CodeDomProvider provider, string source)
{
m_sCompileErrors.Clear();
CompilerParameters param = new CompilerParameters();
param.GenerateExecutable = false;
param.IncludeDebugInformation = false;
param.GenerateInMemory = true;
param.TreatWarningsAsErrors = false;
param.WarningLevel = 2;
foreach (string s in m_oAssemblies)
param.ReferencedAssemblies.Add(s);
CompilerResults cr = provider.CompileAssemblyFromSource(param, source);
if (cr.Errors.Count != 0)
{
m_sCompileErrors.Add("Error Compiling the model:");
CompilerErrorCollection es = cr.Errors;
foreach (CompilerError s in es)
{
m_sCompileErrors.Add(" Error at Line,Col: " + s.Line + "," + s.Column + " error number: " + s.ErrorNumber + " " + s.ErrorText);
}
return null;
}
return cr.CompiledAssembly;
}
示例13: Compile
bool Compile( CodeDomProvider provider, string dataContextCode, PadConfig config, String dllFile )
{
if (!dllFile.EndsWith(".dll"))
dllFile += ".dll";
dcAutoGenFile = dllFile;
CompilerParameters cp = new CompilerParameters();
// Generate a class library.
cp.GenerateExecutable = false;
// Generate debug information.
cp.IncludeDebugInformation = false;
// Add assembly references.
cp.ReferencedAssemblies.Add("System.dll");
cp.ReferencedAssemblies.Add("Iesi.Collections.dll");
// Save the assembly as a physical file.
cp.GenerateInMemory = false;
cp.OutputAssembly = dcAutoGenFile;
// Set the level at which the compiler
// should start displaying warnings.
cp.WarningLevel = 3;
// Set whether to treat all warnings as errors.
cp.TreatWarningsAsErrors = false;
// Set compiler argument to optimize output.
cp.CompilerOptions = "/optimize";
string workDir = Path.Combine(Path.GetTempPath(), "SpoolPad$temp$" + config.Name);
if (!Directory.Exists(workDir))
Directory.CreateDirectory(workDir);
foreach (MapConfig map in config.Mappings) {
if (map.IsValid) {
if (provider.Supports(GeneratorSupport.Resources)) {
if (!config.DataContext.AutoGen) {
if (map.IsFile)
cp.EmbeddedResources.Add(map.Map); else if (map.IsAssembly) {
string tempFile = Path.Combine(workDir, Path.GetFileName(map.ResourceName));
TextReader tr = new StreamReader(Assembly.ReflectionOnlyLoadFrom(map.Assembly).GetManifestResourceStream(map.ResourceName));
File.WriteAllText(tempFile, tr.ReadToEnd());
cp.EmbeddedResources.Add(tempFile);
} else
continue;
} else {
XDocument doc = null;
if (map.IsAssembly) {
doc = XDocument.Load(new XmlTextReader(Assembly.ReflectionOnlyLoadFrom(map.Assembly).GetManifestResourceStream(map.ResourceName)));
} else if (map.IsFile) {
doc = XDocument.Load(map.Map);
} else
continue;
var hibmap = doc.Root;
if (hibmap != null) {
hibmap.SetAttributeValue("assembly", config.Name);
hibmap.SetAttributeValue("namespace", config.DataContextAutoGenNamespace);
string tempFile = Path.Combine(workDir, Path.GetFileName(map.Map));
doc.Save(tempFile);
cp.EmbeddedResources.Add(tempFile);
}
}
}
}
}
CompilerResults cr = provider.CompileAssemblyFromSource(cp, dataContextCode);
Directory.Delete(workDir, true);
if (cr.Errors.Count > 0) {
// Display compilation errors.
_log.ErrorFormat("Errors building {0}", cr.PathToAssembly);
foreach (CompilerError ce in cr.Errors) {
_log.DebugFormat(" {0}", ce.ToString());
}
} else {
_log.DebugFormat("Source built into {0} successfully.", cr.PathToAssembly);
}
// Return the results of compilation.
if (cr.Errors.Count > 0) {
return false;
} else {
return true;
}
}
示例14: Compile
public CompilerErrorCollection Compile()
{
if (!this.HtmlPage)
{
CodeCompiler = CodeDomProvider.CreateProvider("CSharp");
CodeParameters = new CompilerParameters();
CodeParameters.CompilerOptions = "/lib:C:\\inetpub\\wwwroot\\bin";
CodeParameters.GenerateInMemory = this.GenerateInMemory;
CodeParameters.ReferencedAssemblies.AddRange(this.References);
CodeParameters.WarningLevel = this.WarnLevel;
/* Build the assembly */
string tmpcode = this.Code;
BlazeGames_CodeCompiler BGxCodeCompiler = new BlazeGames_CodeCompiler();
tmpcode = BGxCodeCompiler.CompileToCSharp(tmpcode);
CompilerResults CodeCompiled = CodeCompiler.CompileAssemblyFromSource(CodeParameters, tmpcode);
/* Check for errors */
if (CodeCompiled.Errors.HasErrors)
return CodeCompiled.Errors;
this.CompiledCode = System.IO.File.ReadAllBytes(CodeCompiled.PathToAssembly);
this.Compiled = true;
this.Save();
}
else
this.Save();
return null;
}
示例15: CompileAssemblyFromSource
/// <summary>
/// Compiles the assembly from source.
/// </summary>
/// <param name="source">The source.</param>
/// <param name="outputAssemblyName">Name of the output assembly.</param>
/// <param name="provider">The provider.</param>
/// <param name="referencedAssemblies">The referenced assemblies.</param>
/// <returns></returns>
public static CompilerResults CompileAssemblyFromSource(
string[] sources,
string outputAssemblyName,
CodeDomProvider provider,
string[] referencedAssemblies)
{
CompilerParameters parameters = new CompilerParameters();
parameters.GenerateExecutable = false;
parameters.GenerateInMemory = string.IsNullOrEmpty(outputAssemblyName);
parameters.IncludeDebugInformation = false;
parameters.TreatWarningsAsErrors = true;
parameters.CompilerOptions = "/optimize";
parameters.OutputAssembly = outputAssemblyName;
if (referencedAssemblies != null &&
referencedAssemblies.Length > 0)
{
parameters.ReferencedAssemblies.AddRange(referencedAssemblies);
}
// Add referenced asms
foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies())
{
try
{
string location = assembly.Location;
if (!String.IsNullOrWhiteSpace(location) &&
!parameters.ReferencedAssemblies.Contains(Path.GetFileName(location)))
{
parameters.ReferencedAssemblies.Add(location);
}
}
catch (NotSupportedException)
{
// this happens for dynamic assemblies, so just ignore it.
}
}
CompilerResults results = provider.CompileAssemblyFromSource(parameters, sources);
Assert.IsFalse(results.Errors.HasErrors, "Errors in CompileAssemblyFromSource: " + (results.Errors.HasErrors ? results.Errors[0].ErrorText : ""));
return results;
}