Generate dynamic code from string with Reflection.Emit - c#

I have stored some C# code in a database table.
I have the whole code of a base class in a string.
With the stored C# code in hand, I add to the class a method named m1 that contains a return <<some C# code>>; (the method always returns object so the C# code can be: 88 + 90, "hello world", this.ToString(), etc.), save it to a file and compile it with CSharpCodeProvider, and run it on my program.
The stored C# code can use some methods in the base class.
This scheme works very well.
Now, I would to use Reflection.Emit to do this, to avoid the compiling step.
Is this possible, and if so, how would it be done?

Now, I would to use Reflection.Emit to do this, to avoid the compiling step.
That doesn't make much sense to me. If you have source code that you want to execute, you basically have two options:
Compile it to some other form that can then be directly executed. (Classic compiled languages like C work like this.)
Parse it into some in-memory structure and then execute that, piece by piece. (Classic interpreted languages work like this, like JavaScript in older browsers.)
Things aren't actually as simple as that these days, because of virtual machines and intermediate languages etc., but those are the basic choices.
If you don't want to use CodeDOM, that leaves you two choices (corresponding to the two options above):
Parse the code and then create some executable form from it, possibly using Reflection.Emit.
Parse the code and directly execute the result. You don't need Reflection.Emit for that.
Choice 1 means you would need to implement full C# compiler. Choice 2 means you would need to implement a half of C# compiler, plus an interpreter of your in-memory structure. In both cases, it would be a giant project and you wouldn't really “avoid the compiling step”.

Related

Generate C# assembly from source code text file

I have a C# source code in the file (or in text string). How can I use reflection emit to generate and execute this code?
There are so many examples where people generate one class, then add a method etc, but I need top compile-on-the-fly huge piece of C# code, couple kilobytes.
Reflection.Emit is for working with code at the IL level, it knows nothing about how to compile C# source code, so you can't use it for that.
What you can use for this instead is CodeDOM, specifically the CSharpCodeProvider class and its CompileAssemblyFromFile () or CompileAssemblyFromSource() methods.

Avoid duplicate logic in JavaScript and C#

I am writing a wizard to let users map strings to properties on an object. This is done by using some predefined rules that the user selects and supplies the arguments to. These collections of rules are saved to a database and run later via service calls.
The problem is that in the wizard I have it highlighting and updating some example text as the user selects the rules and types the arguments. This is done using JavaScript so obviously is duplicating the logic contained inside the C# rules.
So I'm looking for ways to get around this.
The rules are quite simple and just contain a list of arguments to apply and a single method that takes the input string and returns the result.
You can use AJAX to send the data to the backend, process it, and drop it in the right place. This wouldn't duplicate that logic then. You'll likely need to maintain a bit of JS code to keep the screen and the service attached though.
I have a similar situation with JavaScript and Java. My solution was to just use JavaScript: On the client, that's run by the browser. On the server, in my case, it's compiled with Rhino (JavaScript for the JVM), but it's the same source code in both cases.
The .Net platform supports JScript.Net, which is very similar to JavaScript. I expect without too much effort you could write the code once, in JavaScript, and have JScript.Net compile it into a module you could use server-side, alongside your C# code.

How to manage creating/compiling dynamic objects in .net 4.0

I am writing an application that allows the user to create custom algorithms for computing values over a collection of objects. Simply put, i will be having a string with the source code of class with one method.
The solution I have implemented is to compile the string source code in a separate dll for each such custom algorithm and then load them using Assembly.Load and instantiate the class saved in the dll. From a maintainability point of views, this means that i have to store the source code in the db (for example) and also manage the existence of the compiled dlls (recreate by compiling again the source code if it is missing)
Is there a better way to do this, considering the new features of .Net 4.0?
EDIT:
The input source code is C# and i am using CSharpCodeProvider to compile the code. The custom classes are all derived from a base class and they override the method that actually holds the computation logic. What i would really like to do is to get rid of the dll management and not lose (too much) performance in compiling all the classes every time my application starts up
I would look at scripting languages; IronPython is easy to embed, or there are JavaScript engines for .NET. Simple, and usually fast enough.
If (comments) you need to use c#, I would:
build all the current methods at the same time into one assembly; solves a lot of problems
if the data changes during execution, make use of AppDomains so that I can unload them
I've done something similar where the model/rules were XML, running it through a transform to get c#, and compiling with CSharpCodeProvider (or whatever); and simply polling every minute or so to see if a new build is required
The CSharpCodeProvider has been around for a while and should fit the ticket. It can be used to generate the separate libraries like you have been doing (perhaps you are using the CSharpCodeProvider), but it can also be used to generate dynamic class objects. If they all implement an interface you can cast the objects as an interface or you can use reflection to invoke your logic. Here is a codeproject article to achieve something similar:
http://www.codeproject.com/KB/dotnet/dynacodgen.aspx

.jar to .cs class/file transform technique or utility?

I am looking for a way to transform some classes from Java to .Net in a code gen way.
Not at run time, but re-generate a handful of business objects as needed (not often).
the catch is, i want to have full control of how they end up. So while java classes have get and set methods, i will create a property out of them.
the only way i can think of for now, is to read the file using c#, get the necessary members, and maybe feed them to a code gen template. at the very lease, i could throw them into a database, and something like code smith could generate .net classes based on a template and the updated database table.
any other ideas/utilities?
my solution was to use reflection to write out java class members as xml, and than plugging that into codesmith template to create .net classes. the neat part is that it can be automated as a step on build server
Have a look at IKVM.

Is there an equivalent to Java's ClassFileTransformer in .NET? (a way to replace a class)

I've been searching for this for quite a while with no luck so far. Is there an equivalent to Java's ClassFileTransformer in .NET? Basically, I want to create a class CustomClassFileTransformer (which in Java would implement the interface ClassFileTransformer) that gets called whenever a class is loaded, and is allowed to tweak it and replace it with the tweaked version.
I know there are frameworks that do similar things, but I was looking for something more straightforward, like implementing my own ClassFileTransformer. Is it possible?
EDIT #1. More details about why I need this:
Basically, I have a C# application and I need to monitor the instructions it wants to run in order to detect read or write operations to fields (operations Ldfld and Stfld) and insert some instructions before the read/write takes place.
I know how to do this (except for the part where I need to be invoked to replace the class): for every method whose code I want to monitor, I must:
Get the method's MethodBody using MethodBase.GetMethodBody()
Transform it to byte array with MethodBody.GetILAsByteArray(). The byte[] it returns contains the bytecode.
Analyse the bytecode as explained here, possibly inserting new instructions or deleting/modifying existing ones by changing the contents of the array.
Create a new method and use the new bytecode to create its body, with MethodBuilder.CreateMethodBody(byte[] il, int count), where il is the array with the bytecode.
I put all these tweaked methods in a new class and use the new class to replace the one that was originally going to be loaded.
An alternative to replacing classes would be somehow getting notified whenever a method is invoked. Then I'd replace the call to that method with a call to my own tweaked method, which I would tweak only the first time is invoked and then I'd put it in a dictionary for future uses, to reduce overhead (for future calls I'll just look up the method and invoke it; I won't need to analyse the bytecode again). I'm currently investigating ways to do this and LinFu looks pretty interesting, but if there was something like a ClassFileTransformer it would be much simpler: I just rewrite the class, replace it, and let the code run without monitoring anything.
An additional note: the classes may be sealed. I want to be able to replace any kind of class, I cannot impose restrictions on their attributes.
EDIT #2. Why I need to do this at runtime.
I need to monitor everything that is going on so that I can detect every access to data. This applies to the code of library classes as well. However, I cannot know in advance which classes are going to be used, and even if I knew every possible class that may get loaded it would be a huge performance hit to tweak all of them instead of waiting to see whether they actually get invoked or not.
POSSIBLE (BUT PRETTY HARDCORE) SOLUTION. In case anyone is interested (and I see the question has been faved, so I guess someone is), this is what I'm looking at right now. Basically I'd have to implement the profiling API and I'll register for the events that I'm interested in, in my case whenever a JIT compilation starts. An extract of the blogpost:
In your ICorProfilerCallback2::ModuleLoadFinished callback, you call ICorProfilerInfo2::GetModuleMetadata to get a pointer to a metadata interface on that module.
QI for the metadata interface you want. Search MSDN for "IMetaDataImport", and grope through the table of contents to find topics on the metadata interfaces.
Once you're in metadata-land, you have access to all the types in the module, including their fields and function prototypes. You may need to parse metadata signatures and this signature parser may be of use to you.
In your ICorProfilerCallback2::JITCompilationStarted callback, you may use ICorProfilerInfo2::GetILFunctionBody to inspect the original IL, and ICorProfilerInfo2::GetILFunctionBodyAllocator and then ICorProfilerInfo2::SetILFunctionBody to replace that IL with your own.
The great news: I get notified when a JIT compilation starts and I can replace the bytecode right there, without having to worry about replacing the class, etc. The not-so-great news: you cannot invoke managed code from the API's callback methods, which makes sense but means I'm on my own parsing the IL code, etc, as opposed to be able to use Cecil, which would've been a breeze.
I don't think there's a simpler way to do this without using AOP frameworks (such as PostSharp). If anyone has any other idea please let me know. I'm not marking the question as answered yet.
I don't know of a direct equivalent in .NET for this.
However, there are some ways to implement similar functionality, such as using Reflection.Emit to generate assemblies and types on demand, uing RealProxy to create proxy objects for interfaces and MarshalByRefObject objects. However, to advise what to use, it would be important to know more about the actual use case.
After quite some research I'm answering my own question: there isn't an equivalent to the ClassFileTransformer in .NET, or any straightforward way to replace classes.
It's possible to gain control over the class-loading process by hosting the CLR, but this is pretty low-level, you have to be careful with it, and it's not possible in every scenario. For example if you're running on a server you may not have the rights to host the CLR. Also if you're running an ASP.NET application you cannot do this because ASP.NET already provides a CLR host.
It's a pity .NET doesn't support this; it would be so easy for them to do this, they just have to notify you before a class is loaded and give you the chance to modify the class before passing it on the CLR to load it.

Categories

Resources