tags:

views:

2480

answers:

8

I want to run javascript/Python/Ruby inside my application.

I have an application that creates process automatically based on user's definition. The process is generated in C#. I want to enable advanced users to inject script in predefined locations. Those scripts should be run from the C# process. For example, the created process will have some activities and in the middle the script should be run and then the process continues as before. Is there a mechanism to run those scripts from C#?

+1  A: 

You can compile C# code from within a C# application using the CSharpCodeProvider class.

If the compile succeeds you can run the resulting assembly as returned via the CompiledAssembly property of the CompilerResults class.

jussij
+2  A: 

Look into IronPython and IronRuby -- these will allow you to easily interoperate with C#.

Cody Brocious
A: 

You can compile C# code "on the fly" into an in-memory assembly. I think this is possible with IronPython and IronRuby as well. Look at the CodeDomProvider.CreateProvider method.

If you need to run scripts a lot, or if your process runs for a long time, you might want to load these assemblies into another AppDomain. And unload the AppDomain after you're done with the script. Otherwise you are unable to remove them from memory. This has some consequenses on the other classes in your project, because you have to marshall all calls.

GvS
A: 

Have you thought about Visual Studio for Applications? I haven't heard much about it since .NET 1.1, but it might be worth a look.

http://msdn.microsoft.com/en-us/library/ms974548.aspx

AngryHacker
A: 

I've done exactly this just recently - allowed run-time addition of C# scripting.

It's not hard at all, and this article:

http://www.divil.co.uk/net/articles/plugins/scripting.asp

is a very useful summary of the details.

Will Dean
+5  A: 

Basically, you have two problems: how to define point of injections in your generated code, and how to run python / ruby / whatev scripts from there.

Depending on how you generate the process, one possible solution would be to add a function to each possible point of injection. The function would check, whether the user has associated any scripts with given points, and if so, runs the script by invoking IronPython / IronRuby (with optionally given parameters).

Disadvantages include: limited accessibility from the scripts to the created process (basically, only variables passed as parameters could be accessed); as well as implementation limits (IronPython's current version omits several basic system functions).

Silver Dragon
+1  A: 

Awesome C# scripting language - Script.Net

paiNie
Thats pretty cool. I could have used something like that a while back.
mattlant
+1  A: 

.NET has a scripting language including runtime engine in PowerShell which can be embedded in any .NET application.

Steven Murawski