0

Scenario:

I have my function names and there parameters stored in the database. The function name along with the parameters are return from the database as

"FunctionName(Convert.ToString("harry"),Convert.ToString("Password"),Convert.ToInt32("5"),Convert.ToString(""),Convert.ToString("AMER_02772"),Convert.ToInt32("0"))"

Question:

Now I want to execute this function returned to me as a string? Please guide me the way to execute this string?

I have read similar sort of post but could not find the exact result.

Valamas
  • 24,169
  • 25
  • 107
  • 177
BKS
  • 3
  • 2
  • Take a look at Reflection – Pierre-Luc Pineault Feb 04 '14 at 05:27
  • This is actually quite complex. It would essentially involve creating a dynamic assembly; e.g., the code in the string has to be compiled at runtime. System.CodeDom namespace is needed. Take a look at this SO question: http://stackoverflow.com/questions/4800267/how-to-execute-code-that-is-in-a-string – Dmitriy Khaykin Feb 04 '14 at 05:43

3 Answers3

1

You can use the CodeDomProvider to compile C# code. Then use reflection to get type information, create a object and call a method of it.

See this answer for a example.

This is basically how it works:

    string source = ...
    string references = ...

    // Compile
    CodeDomProvider provider = new CSharpCodeProvider();
    CompilerParameters cp = new CompilerParameters(references);
    cp.GenerateExecutable = false;
    cp.GenerateInMemory = true;
    CompilerResults res = provider.CompileAssemblyFromSource(cp, source);

    // Extract object
    Type t = res.CompiledAssembly.GetType(className);
    MethodInfo method = t.GetMethod(methodName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);          // Get method

    // Run
    object instance =  Activator.CreateInstance(t, this);
    object ret = method.Invoke(instance, null); 
Community
  • 1
  • 1
joe
  • 8,344
  • 9
  • 54
  • 80
0

You can use GetMethod , this is example code

using System;
using System.Reflection;

static class Methods
 {
public static void Inform(string parameter)
{
Console.WriteLine("Inform:parameter={0}", parameter);
}
 }

class Program
{
    static void Main()
    {
    // Name of the method we want to call.
    string name = "Inform";

    // Call it with each of these parameters.
    string[] parameters = { "Sam", "Perls" };

    // Get MethodInfo.
    Type type = typeof(Methods);
    MethodInfo info = type.GetMethod(name);

    // Loop over parameters.
    foreach (string parameter in parameters)
    {
        info.Invoke(null, new object[] { parameter });
    }
    }
}

Output

Inform:parameter=Sam
Inform:parameter=Perls

Or

You can reference Dynamically invoking any function by passing function name as string !
And the CodeProject link Dynamically Invoke A Method, Given Strings with Method Name and Class Name !

Community
  • 1
  • 1
zey
  • 5,939
  • 14
  • 56
  • 110
0

Have a look at the CSharpCodeProvider class

As an example:

var csc = new CSharpCodeProvider(new Dictionary<string, string>() { { "CompilerVersion", "v3.5" } });
        var parameters = new CompilerParameters(new[] { "mscorlib.dll", "System.Core.dll" });
        parameters.GenerateExecutable = false;
        CompilerResults results = csc.CompileAssemblyFromSource(parameters,
        @"using System.Linq;
            class MyClass {
              public void MyFunction() {
                var q = from i in Enumerable.Range(1,100)
                          where i % 2 == 0
                          select i;
              }
            }");
        results.Errors.Cast<CompilerError>().ToList().ForEach(error => Console.WriteLine(error.ErrorText));
shenku
  • 11,969
  • 12
  • 64
  • 118