using System;
using System.Collections.Generic;
using System.Text;
using System.CodeDom.Compiler;
using Microsoft.CSharp;
using System.Reflection;
using System.Configuration;
namespace ReuseCode
{
public abstract class RunTimeMethodInvoker
{
public static object CompliedObject(string strClassCode)
{
ICodeCompiler loCompiler = CodeDomProvider.CreateProvider("csharp").CreateCompiler();
CompilerParameters loParameters = new CompilerParameters();
//this is the path where the complier will look for the referenced libaray
//loParameters.CompilerOptions = "/debug /lib:" + ConfigurationManager.AppSettings["InstallationPath"];
loParameters.ReferencedAssemblies.Add("System.dll");
// *** Load the resulting assembly into memory
loParameters.GenerateInMemory = true;
// *** Now compile the whole thing
CompilerResults loCompiled = loCompiler.CompileAssemblyFromSource(loParameters, strClassCode);
if (loCompiled.Errors.HasErrors)
{
string lcErrorMsg = "";
// *** Create Error String
lcErrorMsg = loCompiled.Errors.Count.ToString() + " Errors:";
for (int x = 0; x < loCompiled.Errors.Count; x++)
lcErrorMsg = lcErrorMsg + "\r\nLine: " + loCompiled.Errors[x].Line.ToString() + " - " +
loCompiled.Errors[x].ErrorText;
return null;
}
Assembly loAssembly = loCompiled.CompiledAssembly;
//object loObject = loAssembly.CreateInstance("Delphi.PassPods.SeatParser.CDynamicSeatDataFieldFormatter");
object loObject = loAssembly.CreateInstance("TestClass");
return loObject;
}
public static object RuntimeMethodCall(object loObject, string strFunctionName,
object[] loCodeParms)
{
object loResult = null;
loResult = loObject.GetType().InvokeMember(strFunctionName,
BindingFlags.InvokeMethod, null, loObject, loCodeParms);
return loResult;
}
}
class Program
{
static void Main(string[] args)
{
TestDynamicCode();
}
static void TestDynamicCode()
{
string strTest = "using System; using System.IO; public class TestClass { public string outputResult() { return \"hello from test\"; }}";
// *** Retrieve an object reference - since this object is 'dynamic' we can't explicitly
// *** type it so it's of type Object
object loObject = RunTimeMethodInvoker.CompliedObject(strTest);
object loResult = RunTimeMethodInvoker.RuntimeMethodCall(loObject, "outputResult", null);
Console.WriteLine(loResult.ToString());
}
}
}
Friday, April 13, 2007
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment