/*code taken from: http://www.codeproject.com/csharp/RuntimeCompiling.asp*/
using System;
using System.Text;
using Microsoft.CSharp;
using System.CodeDom.Compiler;
using System.Reflection;
namespace TUG.Mogentes
{
///
/// This class can be used to execute dynamic uncompiled code at runtime
/// This class is not exception safe, all function calls should be exception handled.
///
public class CSharpCodeCompiler
{
///
/// This is the main code execution function.
/// It allows for any compilable c# code to be executed.
///
/// the code to be compiled then executed
/// the name of the namespace to be executed
/// the name of the class of the function in the code that you will execute
/// the name of the function that you will execute
/// True if the function you will execute is static, otherwise false
/// any parameters that must be passed to the function
/// what ever the executed function returns, in object form
public static object ExecuteCode(Assembly asm, string namespacename, string classname,
string functionname, params object[] args)
{
// Assembly asm = BuildAssembly(code, new string[] {"System.dll", "SepiasTool.exe"});
object instance = null;
object returnval = null;
Type type = asm.GetType(namespacename + "." + classname);
System.Reflection.MethodInfo method = type.GetMethod(functionname);
if (!method.IsStatic)
{
instance = asm.CreateInstance(namespacename + "." + classname);
}
returnval = method.Invoke(instance, args);
return returnval;
}
///
/// This private function builds the assembly file into memory after compiling the code
///
/// C# code to be compiled
/// the compiled assembly object
///
public static Assembly BuildAssembly(string [] code, string[] referencedassemblies)
{
CodeDomProvider provider = new CSharpCodeProvider();
CompilerParameters compilerparams = new CompilerParameters();
compilerparams.GenerateExecutable = false;
compilerparams.GenerateInMemory = true;
compilerparams.ReferencedAssemblies.AddRange(referencedassemblies);
CompilerResults results = provider.CompileAssemblyFromSource(compilerparams, code);
if (results.Errors.HasErrors)
{
StringBuilder errors = new StringBuilder("Compiler Errors :\r\n");
foreach (CompilerError error in results.Errors)
{
errors.AppendFormat("Line {0},{1}\t: {2}\n", error.Line, error.Column, error.ErrorText);
}
throw new UlyssesCompileException(errors.ToString());
}
else
{
return results.CompiledAssembly;
}
}
}
}