0

I met an odd requirement:

There is a api list, and I have to write an example for each api, and the example must be present to user, so it reminded me "Expression tree", method can be stored and executed.

But the problem is, the method will be compiled...

When I debug the expression, I got the IL code.

What I need is:

Func<HttpResponseMessage> func = () =>
{
    // do something and call api
    // ...
    // return the response from api
}

Expression<Func<HttpResponseMessage> expression = SomeMethod(func);

Console.WriteLine(expression.ToString()); // get the func body(NOT COMPILED)
expression.Body.Compile().Invoke(); // compile expression and invoke the func.

Here is a solution, but it was based in MONO.
http://evain.net/blog/articles/2009/04/22/converting-delegates-to-expression-trees/

Teddy
  • 787
  • 5
  • 13
  • You already have the response and only need to return it from a `Func`? – Aage Nov 22 '13 at 07:29
  • @bump no, call api in the func :D – Teddy Nov 22 '13 at 07:32
  • 1
    "Here is a solution, but it was based in MONO." - That shouldn't prevent it from working just fine for you. Mono Cecil can be used with Microsoft's own .NET Framework too. –  Nov 22 '13 at 07:43
  • @hvd that mono code refers to many classes in the mono framework. :( – Teddy Nov 22 '13 at 07:47
  • You could *try* this one... I have no idea on how much it handles: https://www.nuget.org/packages/DelegateDecompiler/ - but on the plus side, it works direct from NuGet on .NET; example usage: https://github.com/hazzik/DelegateDecompiler – Marc Gravell Nov 22 '13 at 07:47
  • @MarcGravell It works fine, based in Mono.Reflection. but decompiling can only recover the code after optimization by IL, Alternative solution! thanks again. – Teddy Nov 22 '13 at 08:01
  • possible duplicate of [Reverse of Expression>.Compile()?](http://stackoverflow.com/questions/3809823/reverse-of-expressionfunct-tresult-compile) – nawfal Aug 08 '14 at 12:05

1 Answers1

1

Basically, what you're asking for is impossible, because compiling C# to IL is not a lossless operation. I think the best option would be to distribute the C# code itself (maybe as a .cs file resource, or something like that).

That way, you directly have the text. And to compile it at runtime, you can use CodeDOM. That would create an assembly, which you would load and then invoke your method using reflection.

Another option to do this would be to use Roslyn Scripting.

svick
  • 236,525
  • 50
  • 385
  • 514
  • Thanks, I got a new idea, just redirect to the webapi help detail page, do not show the demo code. – Teddy Nov 25 '13 at 01:03