Question

I am implementing a dynamic code execution in C# which allows users to write their own c# for that particular application.

I am using C# code compiler for executing the dynamic codes. The C# compiler reads the code file and construct the code in new namespace (a complete new code), compiles and runs it. In other view the base application host all these.

I have few methods that are present in host application that I want to be executed by the dynamic code. Is there any way by which the method of other namespace or application can be executed?

Was it helpful?

Solution

Could you force the author of your script to implement an interface, or you could even wrap their code with your own implementation..

Something like

public interface IMyApplication
{
      void DoSomethingInMyMainApp();
}
public interface IScriptKiddie
{
      void Init(IMyApplication app);
}

Then your l33t scripters can write

public class MyScript : IScriptKiddie //< you could emit this yourself
{

     public void Init(IMyApplication app) //<could emit this yourself if scripter knows app keyword
     {
          app.DoSomethingInMyMainApp();
     }
}

and in your app you can provide a concrete implementation of IMyApplication to pass into the class when you have compiled, constructed the class then pass into Init method.

OTHER TIPS

In order for the dynamic code to be able to call methods on the static code, you have to provide the needed reference when you compile the dynamic code.

In more details:

Say you have a class called MyClass that you want to access from the dynamic code. Put the MyClass class in a separate assembly, let's call it MyAssembly. When you compile the dynamic code, one of the properties of the ICodeCompiler allows you to provide assemblies as references. So you should provide typeof(MyClass).Assembly through that property.

Now, when you compile the code, it will be able to do stuff like:

MyClass.CallSomeMethod();

Namespaces are not an issue here. You can ensure the dynamic code uses the full type name (e.g. MyNameSpace.MyClass, or you can generate a using MyNamespace; at the beginning of the dynamic code.

Finally, I join Richard's recommendation to define a clear interface which the dynamic code would be able to consume. You just have to provide the assembly containing this interface as a reference when you compile.

You can use reflection. Something like this:

Type objType = null;
objType = _Assemblies.GetType(className);
MethodInfo methodInfo = null;
methodInfo = objType.GetMethod(TheCommandString);
methodInfo.Invoke(objType, userParameters); 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top