|

Introduction
There are several languages out there (primarily interpreted languages) which provide a convenient eval statement or function. These usually accept simple fragments of code and execute them on the fly, often used for mathematical expressions. .NET leaves this useful feature out of its BCL (Base Class Library), and buries access to its compiler under incomplete documentation. I was working on a project of my own when I realized that I needed some form of runtime compilation, and went off on a tangent to build an easy-to-use library (also adding full XML documentation).
Using the code
The library is centered around the Eval class, which contains the static methods that access the compiler.
The methods provided are as follows: public static AssemblyResults CreateAssembly(ICodeCompiler compiler,
string assemblySource,
CompilerParameters options,
Language language);
public static TypeResults CreateType(ICodeCompiler compiler,
string typeSource,
string typeName,
CompilerParameters options,
Language language);
public static MethodResults CreateMethod(ICodeCompiler compiler,
string methodSource,
string methodName,
CompilerParameters options,
Language language);
public static AssemblyResults CreateVirtualAssembly(ICodeCompiler compiler,
string assemblySource,
bool debug,
Language language,
params string[] references);
public static TypeResults CreateVirtualType(ICodeCompiler compiler,
string typeSource,
string typeName,
Language language,
bool debug,
params string[] references);
public static MethodResults CreateVirtualMethod(ICodeCompiler compiler,
string methodSource,
string methodName,
Language language,
bool debug,
params string[] references);
Each method compiles the source provided, loads the result into memory, and returns a reference to an object wrapping the final result (along with any warnings generated by the compiler). If any errors are generated during the compilation, a CompilationException is thrown, which contains the compiler's errors. The "Virtual" group of methods stores the results of compilation directly to memory, using a pre-generated set of CompilerParameters.
The Language class and its subclasses provide information about an individual language to the Eval class, exposing methods that generate various language-specific segments of the code which are necessary in the CreateType and CreateMethod methods of the Eval class.
The result classes each expose the actual result through a property named by the type of the result (respectively through the Assembly, Type, and Method properties), as well as the collection of warnings generated during compilation (through the Warnings property). In addition, each class provides indirect access to some of the more commonly used abilities of its underlying result (each of which acts as described in its XML documentation).
The AssemblyResult class provides the following method: public TypeResults GetType(string typeName, bool throwOnError);
The TypeResults class provides the following methods: public MethodResults GetMethod(string name);
public MethodResults GetMethod(string name,
params Type[] paramTypes);
public object Instantiate(params object[] parameters);
Finally, the MethodResults class provides the following method: public object Invoke(params object[] parameters);
This method automatically creates an instance of the declaring class on which to invoke the wrapped method, allowing non-static methods to be invoked as if they were static.
Points of interest
Microsoft included nearly everything that I needed to write this library in their standard .NET Framework, except the final wrapper. If you find that you need something beyond the capabilities of my library, the System.CodeDom.Compiler and System.Reflection namespaces should provide most of what you need.
To do
More than a few things, most likely... Currently only one update comes to mind. If there is any demand for it, I will make the results of my runtime compilation interface unloadable from memory by using AppDomains (inspired by and probably borrowing from the DevX article Dynamically Executing Code in .NET).
This is my first article posted, so I'd appreciate any feedback. E-mail feedback is accepted, but I'd prefer feedback through the message board provided by the CodeProject.
History
- 12th January, 2006
- Updated code (again) to fix a bug with referenced libraries and an issue with in-memory compilation. Both features should now work as intended.
- 6th December, 2003
- Refactored code (added
Language class and subclasses, updated Eval class) in order to make the Eval class work fully with languages other than C#, added VB.NET example, and updated the article to reflect these changes.
- 14th January, 2003
- Updated code to fix minor bugs with referenced libraries.
- 11th January, 2003
- Zip files finally corrected (extensive paths removed).
- 2nd January, 2003
- Example project, screenshot, and To do added, a few bugs fixed.
- 31st December, 2002:
- Article first posted.
- ~5:31 PM EST:
<pre> blocks fixed (Sorry!).
| You must Sign In to use this message board. |
|
| | Msgs 1 to 25 of 59 (Total in Forum: 59) (Refresh) | FirstPrevNext |
|
 |
|
|
It might be stupid, but I'm able to pass arguments by reference to a virtual method I created. I can pass the argument, but they work as if they were by value. I'm I missing something stupid? Please tell me how to do this. Thanks.
|
| Sign In·View Thread·PermaLink | |
|
|
|
 |
|
|
Hi Eric,
Thanks for the article. This has really helped alot.
I would like to pass an array to the method, so I tried changing the source text to:
Public Function Method1(ByVal s() As String) As String
This gave a parameter count mismatch exception.
Any idea how to do this?
Thanks, Tom
|
| Sign In·View Thread·PermaLink | |
|
|
|
 |
|
|
hi
could someone point what im missing, i cp this code from C# version, C# compile ok, but not in MC++,
compile error 'Evaluator::Eval::CreateVirtualMethod' : function does not take 5 arguments
CSharpCodeProvider* aaa = new CSharpCodeProvider();
stringChanger = Eval::CreateVirtualMethod( aaa->CreateCompiler(), source->ToString(), S"StringChanger", new CSharpLanguage(), false);
what am i missing?
thx
|
| Sign In·View Thread·PermaLink | |
|
|
|
 |
|
|
 |
|
|
Hi,
is it possible to somehow create the interop.dll needed for COM-Objects on the fly, too? So the user just tells me "I need want to use the COM-Object with this and this GUID" and I internally create the interop for him and add it to the compiler-references.
Regards, Daniel
|
| Sign In·View Thread·PermaLink | 2.00/5 (1 vote) |
|
|
|
 |
|
|
Hi Eric,
thanks for the lib! I've a problem when using the CreateVirtualMethod. I want to compile a method with classes from my own namespace. How do i make the compiler accept my classes?
Thanks!
|
| Sign In·View Thread·PermaLink | |
|
|
|
 |
|
|
Well now I've solved the problem, the sollution is so simple (doh!)
I had no idea that you could send a .exe file to CompilerOptions. All I did was to send my .exe file to the compiler options like this:
CompilerOptions cpOptions = new CompilerOptions(); cpOptions.ReferencedAssemblies.Add("myexe.exe");
Happy coding ppl! /Mellmountain
|
| Sign In·View Thread·PermaLink | |
|
|
|
 |
|
|
Hi, i'm not sure really how to approach this situation.
I want the option to do stuff where one script can call another, and it doesn't matter which .net language they are writtin in cause i'm calling them with reflection anyway.
So maybe theirs so compiler option flag? hmm.
Also how can multiple source files be handled?...zzz confussing to do anything but compile an assembly and call it.
|
| Sign In·View Thread·PermaLink | |
|
|
|
 |
|
|
Thanks for the library Eric!
I have an application that instantiates a number of classes called FGI, which each have a Calculation property that holds a simple mathematically equation. I am using CreateVirtualMethod to create an in-memory method called Calculate, to run this equation and return the result. The calculations are all loaded from a database when the program starts, and are (probably) not going to be modified while the program is running.
Because this Evaluation library creates the DLL, even for "in-memory" functions, I end up with threading issues where multiple threads are presumably trying to write to the DLL at one time, causing an occassional FileNotFoundException.
- Is there anyway to avoid using the DLL completely? - Is there anyway to create the method in an existing instance of a class? (ie: directly within each instance of FGI, bearing in mind that each instance of the class will use a different calculation) - Or do I really need to lock all the other objects in the application?
Thanks Carey Bishop
-- modified at 15:47 Wednesday 22nd February, 2006
|
| Sign In·View Thread·PermaLink | |
|
|
|
 |
|
|
Carey,
I'm glad the library's helping you! Out of curiosity, are you using the most up-to-date version of the library, as posted above? I cleared up a few issues with the in-memory compilation in this revision.
I'm afraid there's no way to completely avoid using the DLL - the compiler appears to need to be invoked with a file targeted, even when invoked programmatically. As to creating the method within an existing instance, this is certainly impossible with this library. I know locking on an external object may remove quite a bit of the benefit - but I don't think I can be very helpful.
However, it sounds like the issue is that the compiler is automatically targeting the same DLL somehow, despite the supposed guarantee of uniquely chosen names from the "in-memory" compilation (not my code, part of the .NET Framework)... it's possible that the compiler simply isn't equipped to be run this way programmatically.
Could you possibly refactor this part of your code to output to different DLLs for each thread, and then simply delete them? Their deletion should be possible as soon as you've loaded the Assembly into your AppDomain - which, at least theoretically, has already happened once you get a Results object back.
I'm somewhat short on time at the moment... I'd be glad to hear about any further problems you have or progress you make, though, and I'll certainly look into integrating fixes/improvements for them into this library once I have the time.
Thanks, Eric Astor
|
| Sign In·View Thread·PermaLink | |
|
|
|
 |
|
|
Thanks for your help Eric.
Yes, I am using the most recent version of the library.
I was considering the different DLLs solution, but I've found a better and simpler way. My previous VB6 experience led me to believe that having to lock objects would be complex and buggy, but it seems that using the Enter() and Exit() methods of System.Threading.Monitor on an arbitary global variable works fine. I just lock the global variable, create the method, then unlock it. Works like a charm!
Thanks again, Carey
|
| Sign In·View Thread·PermaLink | 2.00/5 (1 vote) |
|
|
|
 |
|
|
Finally ... looks like a decent replacement for the MSScript control.
I have a few projects that were coded around the MSScript control originally, and I've tried to move them ... one tried out using JScript.NET's eval method; another continues to use MSScript control, and crashes pretty often; another gave up on full eval functionality and became an XML-based text substitutor, with XML attributes controlling some additional abilities (like toupper() and string.format() calls). A real eval function looks like it will definitely fit the bill.
Now I only need time to migrate...
|
| Sign In·View Thread·PermaLink | |
|
|
|
 |
|
|
Well, for everyone who's asked me how to do this: My apologies! I've finally gotten around to investigating this, and it looks like I actually introduced an error in my Eval library at some point. For those who are interested, the actual error is using the Assembly's FullName in the "using" statements, rather than digging a couple of levels deeper and getting the name I should actually be referencing.
Regardless, I'll put the edited version into the CodeProject updating process in the near-future, and if you want the fixed library before it goes up, just send me an e-mail!
|
| Sign In·View Thread·PermaLink | |
|
|
|
 |
|
|
Please note that with this fix, the references part of the compiler options should now function as intended. For a DLL in the same directory that your application is running in, simply add a reference to "YOURDLLNAMEHERE.dll"! For a library located elsewhere, just make sure that the string specifies a path to the library, relative to the application directory (an absolute path works also, but probably isn't a good idea).
|
| Sign In·View Thread·PermaLink | |
|
|
|
 |
|
|
Hi, i hope anyone can help me. I would like include a extern Namespace in the Runtimer Compiler, it is a dll from my own class.
/// public static TypeResults CreateType(ICodeCompiler compiler, string typeSource, string typeName, CompilerParameters options, Language language) { StringBuilder sourceBuilder = new StringBuilder(); options.ReferencedAssemblies.Add("MyUSB.dll"); //<--- ERROR foreach(string referenced in options.ReferencedAssemblies) { sourceBuilder.Append(language.useStatement(Assembly.LoadFrom(referenced).FullName)); }
how can i include the Dll with her functions in the compiler? on compile i become the error mesage BC30203 Identifer expected
I would like access with the functions in this dll the usb port. In my other projects i can include this with using MyUsb;.
Sebastian
|
| Sign In·View Thread·PermaLink | |
|
|
|
 |
|
|
Your library is very useful, thanks. If you wanted to further develop it, my feature suggestion would be support for a separate set of "using" statements, since you can't just stick it in the body of the code you're eval'ing.
Without support for 'using', it makes it hard to use external packages.
|
| Sign In·View Thread·PermaLink | |
|
|
|
 |
|
|
Hi,
I've compiled and ran with success a project using this class. I'm able to compile inline C# from an asp .net webapp. But now I've discovered a problem on an other computer with the same webapp :
While options set GenerateInMemory to true, a file is written (Evaluated.dll) in the current directory. On the second computer the current dirctory is C:\WinNNt\System32. Because it is file-write protected the script fails with an access denied error (CS0016).
So how can I set the output directory to an authorized one? I've tried to set options.CompilerOptions to "/out:blahblah", it writes the dll in the good directory but in this case I'm said that C:\winnt\System32\evaluated.dll cannot be found!
Thanks for your answers,
Lionel
|
| Sign In·View Thread·PermaLink | |
|
|
|
 |
|
|
OK, problem solved :
There is a little mistake in the code. If you define an output assembly in the compiler options, file output will be on even if you set GenerateInMemory to True. So because file output is true the generated dll is written in the current directory (c:\winnt\system32 if you are running a webapp).
When GenerateInMemory is working, a temporary dll (whose name is a unique and autogenerated one) is put in your temp directory, which is file-writeable.
Nota : in my case my custom type couldn't be found in the temporary assembly. To solve this problem I've removed this part of code from the createType method :
options.OutputAssembly + "." +
|
| Sign In·View Thread·PermaLink | |
|
|
|
 |
|
|
Thanks very much for pinning down the problem... it seems we were working in parallel on this since you posted the original request, but I had no luck locating the line giving the difficulty. I'll make this update available with a new version of Eval soon.
|
| Sign In·View Thread·PermaLink | |
|
|
|
 |
|
|
can anyone help, I need
--example of command line to compile into assembly and; -- example of using this from an .aspx file
|
| Sign In·View Thread·PermaLink | |
|
|
|
 |
|
|
Hi,
this is a awesome piece of code 12 out of 10!! I works really good, but I am a vb person and wanted to do the following, and is just not sure where to modify the code to achieve it:
The virtual function that I built up it the string builder, I want to pass a structure to the function, but the structure is declare in another project of mine, which is in the solution and I have referenced it in the Evaluator project, but during compile time, it still does not reconigce that structure ie it states the type is not defined.
Can you perhaps help, guide me in the right direction please Thanks Gert
|
| Sign In·View Thread·PermaLink | |
|
|
|
 |
|
|
 |
|
|
 |
|
|
 |
|
|
Could you please repost the "Using methods from external class" post. It is no longer on the message board. Thanks.
|
| Sign In·View Thread·PermaLink | 2.00/5 (1 vote) |
|
|
|
 |
|
|
General News Question Answer Joke Rant Admin
|