How to run C# code using C# code? - c#

i had asked earlier about the same kind of question but that was in java....
now for the knowledge, i want to know...
is it possible to run the one C# code using another C# code?
bcz i know C# is very powerful, so their might be some way to do this.

It's the same sort of deal:
Compile the code, e.g. using CSharpCodeProvider
Execute the code, e.g. using reflection
If you download Snippy from the C# in Depth web site, you can see a smallish example of this - basically you type in snippets of C# and it can compile and execute them for you.

That is ultimately a runtime feature; in MS .NET, CSharpCodeProvider is the closest you'll get at the moment, although they have mentioned possibly looking at the "compiler as a service" in the future.
If you're happy to use Mono, it already exists , with REPL example.
Usage (from here):
// First setup the active using statements:
Evaluator.Run ("using System;");
Evaluator.Run ("Console.WriteLine (\"Hello, World\");

Related

Is it possible to create/execute code in run-time in C#?

I know you can dynamically create a .NET assembly using Emit, System.Reflection and manually created IL code as shown here.
But I was wondering is it possible to dynamically create and execute C# code block real-time, in a running application. Thanks for any input or ideas.
Edit:
As I understand CodeDOM allows you to compile C# code into EXE file rather than "just" executing it. Here's some background information and why (as far as I can tell) this isn't the best option for me. I'm creating an application that will have to execute such a dynamically created code quite a lot [for the record - it's for academic research, not a real-world application, thus this cannot be avoided]. Therefore, creating/executing thousands of dynamically created EXEs aren't really efficient. Secondly - all dynamic code fragments returns some data that is hard to read from separately running EXE. Please let me know if I'm missing something.
As for DynamicMethod approach, pointed out by Jon Skeet, everything would work like a charm if there would be an easier way to write the code itself rather than low level IL code.
In other words (very harshly speaking) I need something like this:
string x = "_some c# code here_";
var result = Exec(x);
Absolutely - that's exactly what I do for Snippy for example, for C# in Depth. You can download the source code here - it uses CSharpCodeProvider.
There's also the possibility of building expression trees and then compiling them into delegates, using DynamicMethod, or the DLR in .NET 4... all kinds of things.
Yes, it is. There are several applications that do just that - see LinqPad and Snippy.
I believe they use the CSharpCodeProvider.
Yes. See this MSDN page regarding using the CodeDOM.
Some example code extracted from the above mention page:
CodeEntryPointMethod start = new CodeEntryPointMethod();
CodeMethodInvokeExpression cs1 = new CodeMethodInvokeExpression(
new CodeTypeReferenceExpression("System.Console"),
"WriteLine", new CodePrimitiveExpression("Hello World!") );
start.Statements.Add(cs1);
You can Use CodeDom to generate code and create in memory assemblies based on that generated code. THose can then be used in the current application.
Here's a quick link to the msdn reference, it is quite extensive material.
MSDN: Using the CodeDom

C# dynamic code evaluation, Eval, REPL

Does anyone know if there is a way to evaluate c# code at runtime.
eg. I would like to allow a user to enter DateTime.Now.AddDays(1), or something similar, as a string and then evaluate the string to get the result.
I woder if it is possible to access the emmediate windows functionality, since it seems that is evaluates every line entered dynamically.
I have found that VB has an undocumented EbExecuteLine() API function from the VBA*.dll and wonder if there is something equivalent for c#.
I have also found a custom tool https://github.com/DavidWynne/CSharpEval (it used to be at kamimucode.com but the author has moved it to GitHub) that seems to do it, but I would prefer something that comes as part of .NET
Thanks
Mono has the interactive command line (csharp.exe)
You can look at it's source code to see exactly how it does it's magic:
https://github.com/mono/mono/raw/master/mcs/tools/csharp/repl.cs
As you've probably already seen, there is no built-in method for evaluating C# code at runtime. This is the primary reason that the custom tool you mentioned exists.
I also have a C# eval program that allows for evaluating C# code. It provides for evaluating C# code at runtime and supports many C# statements. In fact, this code is usable within any .NET project, however, it is limited to using C# syntax. Have a look at my website, http://csharp-eval.com, for additional details.
Microsoft's C# compiler don't have Compiler-as-a-Service yet (Should come with C# 5.0).
You can either use Mono's REPL, or write your own service using CodeDOM
Its not fast but you can compile the code on the fly, see my previous question,
Once you have the assembly and you know the type name you can construct an instance of your compiled class using reflection and execute your method..
The O2 Platform's C# REPL Script Environment use the Fluent# APIs which have a real powerful reflection API that allows you do execute code snippets.
For example:
"return DateTime.Now.ToLongTimeString();".executeCodeSnippet();
will return
5:01:22 AM
note that the "...".executeCodeSnippet(); can actually execute any valid C# code snippet (so it is quite powerful).
If you want to control what your users can execute, I could use AST trees to limite the C# features that they have access to.
Also take a look at the Microsoft's Roslyn, which is VERY powerful as you can see on Multiple Roslyn based tools (all running Stand-Alone outside VisualStudio)

using c# like script in runtime

I want to learn if there is any library in .net to write c# scripts. Let me describe you with more detail, for example I have an application. When I run it, a c# editor will be opened end user will write some c# codes and when click run, this code should be evaluated and dom should be created after interpret my run time c# code will run. this is brief description of my mind...
I put together a little app called SimpleDevelop which uses CSharpCodeProvider to do what you describe. My understanding is that this (CodeDom) is deprecated and generally discouraged; however, it seems to work just fine for simple scenarios.
Basically, you want to use something like the CSharpCodeProvider. The Razor view engine in MVC essentially uses this to compile your code into an executable to run. If you want your user to be able to write code and then have it interpreted, you would start here. Please note though, this is an incredibly complicated and time intensive feat to get right; plus, linking in and executing foreign code dynamically is a security nightmare. Just be safe.
Are you looking for a test bench sort of?
I use LinqPad for that.
It is mostly a test bench for Linq queries, but I find it very useful for C# statements and mini programs and such.
Check out the System.CodeDom namespace.
This article contains lots of useful information: http://www.developerfusion.com/article/4529/using-net-to-make-your-application-scriptable/2/
You can use the Compiler namespace and compilate the code at runtime. Take a look here for an explanation on how to do it.
I have created an application which will run c# like script without using visual studio.
It is on https://sourceforge.net/projects/csharpquickcode/

Translate vbscript to C# using ANTLR

I need to write a translator for vbscript to c#. What would be the basic steps invloved to translate using ANTLR? I am not very clear about whether to use grammar (lexer/parser? file or stringtemplate or AST or all.
Suggestions?
Thanks in advance.
Is this really possible?
I'm "translating" (read: rewriting) a MS Access/VBA application since two years to C# and found out that even the online available converters (like this one which is more VB.NET, but anyway) fails at most basic conversions.
So my assumption until now is that there are way too much kind of constructs that are simply not translatable from VBScript to C#.
See What kinds of patterns could I enforce on the code to make it easier to translate to another programming language?
The easiest way to translate VBScript to C# would be using VB.NET as an intermediate step. VBScript is very similar to VB.NET (there are some differences though), so all you need to do is copy-paste your code in a new solution in Visual Studio. After you make a few changes, the code will be able to compile.
You can leave it at that (you can call the resulting DLL from your C# code), but even if you don't want to do that, converting VB.NET to C# is trivial. You can even decompile your resulting DLL/EXE (although this will lead to some loss of information) or use any online VB.NET to C# converter.

C# how to create functions that are interpreted at runtime

I'm making a Genetic Program, but I'm hitting a limitation with C# where I want to present new functions to the algorithm but I can't do it without recompiling the program. In essence I want the user of the program to provide the allowed functions and the GP will automatically use them. It would be great if the user is required to know as little about programming as possible.
I want to plug in the new functions without compiling them into the program. In Python this is easy, since it's all interpreted, but I have no clue how to do it with C#. Does anybody know how to achieve this in C#? Are there any libraries, techniques, etc?
It depends on how you want the user of the program to "provide the allowed functions."
If the user is choosing functions that you've already implemented, you can pass these around as delegates or expression trees.
If the user is going to write their own methods in C# or another .NET language, and compile them into an assembly, you can load them using Reflection.
If you want the user to be able to type C# source code into your program, you can compile that using CodeDom, then call the resulting assembly using Reflection.
If you want to provide a custom expression language for the user, e.g. a simple mathematical language, then (assuming you can parse the language) you can use Reflection.Emit to generate a dynamic assembly and call that using -- you guessed it -- Reflection. Or you can construct an expression tree from the user code and compile that using LINQ -- depends on how much flexibility you need. (And if you can afford to wait, expression trees in .NET 4.0 remove many of the limitations that were in 3.5, so you may be able to avoid Reflection.Emit altogether.)
If you are happy for the user to enter expressions using Python, Ruby or another DLR language, you can host the Dynamic Language Runtime, which will interpret the user's code for you.
Hosting the DLR (and IronPython or IronRuby) could be a good choice here because you get a well tested environment and all the optimisations the DLR provides. Here's a how-to using IronPython.
Added in response to your performance question: The DLR is reasonably smart about optimisation. It doesn't blindly re-interpret the source code every time: once it has transformed the source code (or, specifically, a given function or class) to MSIL, it will keep reusing that compiled representation until the source code changes (e.g. the function is redefined). So if the user keeps using the same function but over different data sets, then as long as you can keep the same ScriptScope around, you should get decent perf; ditto if your concern is just that you're going to run the same function zillions of times during the genetic algorithm. Hosting the DLR is pretty easy to do, so it shouldn't be hard to do a proof of concept and measure to see if it's up to your needs.
You can try to create and manipulate Expression Trees. Use Linq to evaluate expression trees.
You can also use CodeDom to compile and run a function.
For sure you can google to see some examples that might fit your needs.
It seems that this article "How to dynamically compile C# code" and this article "Dynamically executing code in .Net" could help you.
You have access to the Compiler from within code, you can then create instances of the compiled code and use them without restarting the application. There are examples of it around
Here
and
Here
The second one is a javascript evaluator but could be adapted easily enough.
You can take a look at System.Reflection.Emit to generate code at the IL level.
Or generate C#, compile into a library and load that dynamically. Not nearly as flexible.
It is in fact very easy to generate IL. See this tutorial: http://www.meta-alternative.net/calc.pdf

Categories

Resources