Where would you use C# Runtime Compilation? - c#

I happened upon a brief discussion recently on another site about C# runtime compilation recently while searching for something else and thought the idea was interesting. Have you ever used this? I'm trying to determine how/when one might use this and what problem it solves. I'd be very interested in hearing how you've used it or in what context it makes sense.
Thanks much.

Typically, I see this used in cases where you are currently using Reflection and need to optimize for performance.
For example, instead of using reflection to call method X, you generate a Dynamic Method at runtime to do this for you.

You can use this to add scripting support to your application. For examples look here or here.
It is quite easily possible to publish parts of your internal object framework to the scripting part, so you could with relative ease add something to your application that has the same effect as for example VBA for Office.

I've seen this (runtime compilation / use of System.Reflection.Emit classes) in generating dynamic proxies ( Code project sample ) or other means of optimizing reflection calls (time-wise).

At least one case you might use it is when generating dynamic code. For example, the framework is using this internally to generate XML serializers on the fly. After looking into a class at runtime, it can generate the code to serialize / deserialize the class. It then compiles that code and users it as needed.
In the same way you can generate code to handle arbitrary DB tables etc. and then compile and load the generated assembly.

Well, all C# code is run-time compiled, since it's a JIT (just-in-time) compiler. I assume you are referring to Reflection.Emit to create classes etc. on the fly. Here's an example I have seen recently in the Xml-Rpc.Net library.
I create a C# interface that has the same signature as an XML-RPC service's method calls, e.g.
IMyProxy : IXmlRpcProxy
{
[XmlRpcMethod]
int Add(int a, int b);
}
Then in my code I call something like
IMyProxy proxy = (IMyProxy)XmlRcpFactory.Create(typeof(IMyProxy));
This uses run-time code generation to create a fully functional proxy for me, so I can use it like this:
int result = proxy.Add(1, 2);
This then handles the XML-RPC call for me. Pretty cool.

I used runtime compiler services from .NET in my diploma thesis. Basically, it was about visually creating some graphical component for a process visualization, which is generated as C# code, compiled into an assembly and can then be used on the target system without being interpreted, to make it faster and more compact. And, as a bonus, the generated images could be packaged into the very same assembly as resources.
The other use of that was in Java. I had an application that had to plot a potentially expensive function using some numerical algorithm (was back at university) the user could enter. I put the entered function into a class, compiled and loaded it and it was then available for relatively fast execution.
So, these are my two experiences where runtime code generation was a good thing.

something I used it for was for allowing C# and VB code to bu run by the user ad-hoc. They could type in a line of code (or a couple lines) and it would be compiled, loaded into an app domain, and executed, and then unloaded. This probably isnt the best example of its usage, but an example of it none-the-less

Related

Exclude other methods, variables and classes that are not needed for your method to work

You load a foreign code example with libraries attached to it in Visual Studio. Now there is a method that you want to reuse in your code. Is there a function in VS that lets you strip the code from all unnecessary code to only have code left that is necessary for your current method to run?
It is not about the library. Loading a .sln or .csproj and having classes over classes when you just want one method out of it is a waste of performance, ram and space. It is about code you can easily omit or references(what I call libraries) you can easily omit. A part-question of this is: Which "using" statement do you need that is only necessary for your current method and the methods that pass paramaters to it? In short, showing relevant code only. Code that is tied to each other.
Let's use an example: You go to github and download source code in c#. Let's call the solution S. You open S in Visual Studio. You don't disassemble, you just load the source code of S, that is there in plain text. Then you find a method M - in plain text - that you want to use. M contains some objects whose classes were defined somewhere in the project. The goal is to recreate the surrounding only for this method to copy & paste it into my own solution without having red underlined words in almost every line within the method
after reading the question and the comments, I think I have a vague idea what you are referring to.
In case we ignore the context of the method you are referring, you can extract any code piece from a "library" by using a .NET decompiler and assembly browser.
There are many of them for free, such as:
dotPeek,
ILSpy
...
This will allow you to see the method's code. From there on, you can proceed as you like. In case your copy the method to your code base, you might still have to change it a bit in order to adapt it to work with your objects and context. If you don't, this will give you insight on how the method works and might help you to understand the logic, so you can write your own.
Disclaimer: With this post, I am pointing out that it is possible to extract code from an assembly. I am not discussing the ethics or legal perspective behind such actions.
Hope this helps,
Happy Coding!
If it`s just one method, look at the source code and copy it to your libarary. Make sure you make a comment where you obtained the code and who has the copyright! Don't forget to include the licence, which you should have done with a libary reference anyway.
That said it is currently not (official) possible to automaticly remove unused public declared code from a library (assembly). This process is called Treeshaking by the way. Exception: .NET Native.
But .NET Native is only available for Windows Store Apps. You can read more about it here.
That said, we have the JIT (Just in Time)-Compiler which is realy smart. I wouldn't worry about a few KB library code. Spend your time optimizing your SQL Queries and other bottlenecks. The classes are only loaded, when you actualy use them.
Using some unstable solutions or maintaining a fork of a library, where you use more then one method (with no documentation and no expertise, since it is your own fork) isn't worth the headache, you will have!
If you realy want to go the route of removing everything you do not want, you can open the solution, declare everything as internal (search and replace is your friend) and restore the parts to public, which are giving you are Buildtime error / Runtime error (Reflection). Then remove everything which is internal. There are several DesignTime tools like Resharper, which can remove Dead Code.
But as I said, it's not worth it!
For .NET Core users, in 6-8 weeks, we have the .NET IL Linker as spender has commented, it looks promising. What does this mean? The .NET framework evolves from time to time. Let it envolve and look at your productivity in the meantime.

Throw an error at compile time if a particular external function is used anywhere in the code?

I'm using an external library and I want to make sure I never call some particular functions in the library. I don't have the source code for that library so I'd like to make sure that at compile time it throws an error if I ever accidentally (or one of my developers) ever use that function. Is there a way to do this?
You can't do this easily. You could mark the method as obsolete, but of course that requires access to the external library source code, at which point you could also just remove the methods.
The next best thing I can come up with is to build a facade around the library object:
public class LibraryFacade
{
//All the library methods as pass-through methods
//Except the bad ones!
}
Of course, your developers have to actually use the facade for this to help. If you don't trust them at all, you could get new developers, or put the facade in a separate assembly so the client code doesn't have direct access to the external library.
Obviously thats a lot of work for this kind of feature, but it will get you where you are trying to go.
If you have plenty of extra time you can make a clone of the external assembly and link against your slimmed down version with identical method signatures instead of real one and replace with real assembly at run-time/post compile. Easy for non-signed assemblies, I think you can even do that if other assembly is signed by using delay-sign feature.
Benefits: complete intellisence/refactoring support, perfect build errors.
Drawbacks: picking right subset of methods may be major pain if library uses a lot of dependencies, getting 100% parity may be hard.

code snippets interpretation

Let's say I have a WinForm App...written in C#.
Is it possible?
After all, put my eye on Iron Python.
C# is not interpreted, so unlike javascript or other interpreted languages you can't do that natively. You can go four basic routes, listed here in order of least to most complex...
1) Provide a fixed set of operations that the user can apply. Parse the user's input, or provide checkboxes or other UI elements to indicate that a given operation should be applied.
2) Provide a plugin-based or otherwise dynamically defined set of operations. Like #1, this has the advantage of not needing special permissions like full trust. MEF might come in handy for this approach: http://mef.codeplex.com/
3) Use a dynamic c# compilation framework like paxScript: http://eco148-88394.innterhost.net/paxscriptnet/. This would, in theory, allow you to compile small c# snippets on demand.
4) Use IL Emit statements to parse code and generate your operations on the fly. This is by far the most complex solution, likely requires full trust, and is extremely error prone. I don't recommend it unless you have some very obscure requirements and sophisticated users.
The CSharpCodeProvider class will do what you want. For a (VERY outdated, but still working with a few tweaks) example of its use, check out CSI.
If you are willing to consider targeting the Mono runtime, the type Mono.CSharp.Evaluator provides an API for evaluating C# expressions and statements at runtime.

Run javascript in C#

I found a fairly complex function in a greasemonkey script that I would like to use in my C# app. Basically I am parsing a page and I need to collect all or 4 members of var avar = {}; (i haven't done this yet but they are all strings using var avar.name = "val")
Then I need to call the gm func which returns a string and takes in 3 strings. How can I call the function in C#? I am using .NET 3.5
I'm assuming that you are after some code-reuse on the server-side or in some other freestanding app that processes HTML data.
You can compile (at least a subset of) JavaScript in .net using the Microsoft.JScript.JScriptCodeProvider class -- though note that the class warns
This API supports the .NET Framework
infrastructure and is not intended to
be used directly from your code.
Once compiled the assembly generated (as specified by the CompilerParameters supplied to the provider) should be dynamically loadable. It would be advisable to examine the generated assembly with a tool like Reflector to see what it is you've actually generated, in terms of classes and namespaces.
Disclaimer -- I've only ever used this technique with the CSharpCodeProvider acting on C# source, but I would expect there to be a reasonable level of compatibility across .net languages for this sort of thing.
EDIT -- For an example of compiling JavaScript from C# see this blog post on Verifying JavaScript syntax using C#.
First, you probably want to consider exactly why you're trying to do this. Is it that you want to use the algorithm from the JS in C#? If so, go ahead. If you want to use C# in client-side code (i.e. the browser), go investigate Silverlight instead.
Second, I'm not sure that what you're trying to do is actually possible. Depending on what youre trying to achieve, you may be better off translating the Javascript from the Greasemonkey app into C# 3.5 (assuming that the script's licensing conditions allow this), for use in your app.
The translation shouldn't be hugely difficult - C# has been getting more and more like JS in the last few versions. Just watch out for the "var" keyword; it means something slightly different in C# to what it means in JS (contrast "type inference" in C# with "dynamic typing" in JS).
Of course, maintaining both versions of the code after you've done this will be tricky and painful. I recommend keeping 1 authoritative version of the code if you can.
Good luck!
Can you provide more information about your script and what you want to accomplish? Most Greasemonkey scripts interact with the DOM via the use of Javascript. You can run Javascript in C# but the DOM will not be available to you.

String to method

Being able to create javascript code on the fly is pretty cool.
That is by using
HtmlPage.Window.Eval("alert('Hello World')");
But is there a way to do the same thing, with a C# method? Lets say something like
void MethodEval("MessageBox.Show('Hello World')");
Is it even possible, without having to recompile your code?
It's possible using tricks posted by others. However, it's usually a very bad idea.
.Net code typically runs in a more trusted context than a javascript browser sandbox, and has access to a much richer, and therefore potentially damaging, api.
Instead you use the System.Addin namespace to provide a very strict interface for extensions, plugins, and the like. If you're just trying to use a more "fluid" or functional programming environment you can use fun features like lamdba expressions and closures to pass functionality around internally.
You can do it right now. The ag DLR (Silverlight Dynamic Languages Runtime) can host javascript.
While Javascript cannot be hosted with the DLR outside the browser Ruby and Python can. Here's an example of a C# snippet using the DLR and hosting a piece of Python of code to demonstrate.
using IronPython.Hosting;
PythonEngine pythonEngine = new PythonEngine();
string script = #"import clr
clr.AddReference(""System.Windows.Forms"")
import System.Windows.Forms as WinForms
WinForms.MessageBox.Show(""Hello"", ""Hello World"")";
pythonEngine.Execute(script);
This is possible, but a little more tricky, using Microsoft's .NET framework.
The C# compiler is part of the base runtime, so you can compile an in-memory assembly, and execute code in there on the fly.
Here is a good MSDN blog post describing the basic process.
I have used this before to make a scripting engine for a C# project. With a little work wrapping this, you can make this quite easy to use. An open source project I've worked on has a project dedicated to this: Pluto.Scripting
We had examples and tests in that project which show dynamic compilation and execution of C#, VB.NET, and Boo.
If you don't mind Boo, you can use its interpreter.
Actually I kept on getting an error "unexpected indent" so changing the code to
PythonEngine pythonEngine = new PythonEngine();
string script = #"import clr; clr.AddReference(""System.Windows"");";
script += #"import System.Windows as Wins;";
script += #"Wins.MessageBox.Show(""Hello World"");";
pythonEngine.Execute(script);
Worked! interesting... Thanks
Why do you need this feature ? Shouldnt your code know its paths and include that logic ? If you cant forsee such use cases - then perhaps its not needed. The only real benefit is it opens an opportunity to be abused and attacked. It sounds like your in directly creating a potential for an exploit - its a shame because managed runtimes like Java/CLR dont allow code injection but you are bringing all that goodness back in...

Categories