This question already has answers here:
What is the best scripting language to embed in a C# desktop application? [closed]
(15 answers)
Closed 6 years ago.
I have a C# program that uses objects from a class that has a method looking something like this:
public double TheMethod(double argument1, double argument2, ...,double argumentN)
{
//method body: do something with the arguments
//return the result
}
I would like to give the user the ability to write their own logic into the method body and then have that be used when the program is run.
It seems to me that scripting may be the way to go, but I am having trouble trying to get started. What is the best way to approach this situation?
Note: If it matters, the program would be run from within a larger main desktop application. I would like the user to be able to write their code when the application is already running through some sort of editor program. Their code would then be saved and used once they launch the program that actually uses the method.
You can certainly dynamically compile and execute C#. See Is it possible to dynamically compile and execute C# code fragments?
Depending on who your users are and how their script needs to integrate into the wider application, IronPython might be a nicer option - essentially scripting in python. See https://blogs.msdn.microsoft.com/charlie/2009/10/25/running-ironpython-scripts-from-a-c-4-0-program/ for details on integrating C# and IronPython.
As always when running any dynamically injected code from an external source, think about security.
If you want your users to write in c#, the simplest thing would probably be to swap out the file (or at least the body of the method) with different copies and recompile the sub-application before each run.
It is possible to do a live replace of a method body during run-time, but it's not for the light hearted! https://msdn.microsoft.com/en-us/library/system.reflection.emit.aspx
If you are happy to do the work to create your own mini scripting language, take a look at Antlr http://www.antlr.org/
Related
So, I'm making myself a small C# library for dialogues to use in an cRPG game.
The idea is, that the Dialogue object and it's fields (like DialogueNode and DialogueOption objects) are created based on an XML file, which I aim to make as simple as possible. The fields, except for lists or objects of types contained within the library, are - at best - string identifiers, to be acquired and parsed by outside means when needed.
I've basic funcionality implemented - XML serialization, running through the dialogue and exiting it - as well as basic, console based application interpreter and a WPF editor to create the dialogues, because writing the dialogue in plain XML is not the most comfortable thing in the world. (the last two are meant to be as much independent from the library as possible, except maybe for implementing what's inside to show/create)
All that being said, I've encountered a problem (actually two, the other one I'll cover in different question when I've the time after my exams).
After giving it some of my unexperienced 'noobish' thought, I've come to think, that I'd like to have some basic predicates stored either in my nodes or options - they would be later checked in game to determine, whether to display the node/option or leave it be (or whatever meddling with those to be honest). For example - an option is displayed if the player character have item X in his inventory, or the node is displayed when player has a certain minimum value of an attribute.
My idea of implementing is so far like that:
Having a field PredicateScript in an object
Having a bool method, that would be executed in runtime by the interpreter like this:
public bool DisplayPredicate(string predicateCode)
{
bool result = FunctionExecutingCSharpCode(predicateCode);
return result;
}
I've read some topics about compiling on the fly very brielfy, but I'm not sure if it's exactly what I want - I'm not sure how it would affect the performance of application (either the interpreter or the game itself), if it would be recompiled every few seconds...
I'm not pasting any code of what I'm trying to do, because either I'm yet to do this (as I'm not writing the code I'm not sure it will work) or it's the library structure which I don't think would be of relevance aside from what I explained I aim to do. ^^
Thanks. ^^
Given the standard .NET framework, there's no such thing as a C# "interpreter" you can feed code that gets executed. You could try to dynamically create C# code and have that compiled on the fly into an in-memory assembly, which you can then use using the .NET compiler services.
And example of this is given here: http://www.codeproject.com/Tips/715891/Compiling-Csharp-Code-at-Runtime.
For my university course I want to make system for learning programming. The main idea is writing code through debug, just look at picture (from Bret Victor video):
I don't want to make my own compiler (just becouse it's very complicated and hard, especially for C# language), so I want use all features of .NET and other libraries. I see there two ways:
Rewrite code by replacing assigments to assigment & sending debug information to main program
Compile code and debug it -> ...
Anyway, I need some start point. What classes and libraries I must google, in which manuals I can read useful information, what is the best way to implement it?
I think what could work is, if you just treat C# as a script language. There are multiple tutorials on how to use C# within C# as a script language, like this one. So you just start the "script" compiler again on predefined conditions (like a line break) and if the compilation is successfull you return the result in your second pane. This is just a basic idea.
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Is it possible to make a call to a C# application from a C++ application?
I am playing with the idea of writing a proof of concept application that contains a script engine that runs (executes) a .CLI language (e.g. C#, VB.Net etc).
I had originally wanted to create the script engine application in C++, but that appears to be fraught with problems and work arounds. Instead, I want to write the script engine in C# instead now.
I have sketched together a very rough idea of what it is I'm trying to do below:
The code is still pseudo C++, but hopefully, the semantics should be clear:
class GenericDotNetLangInterpreter
{
public:
Results run(const Arguments& args);
protected:
GenericDotNetLangInterpreter(const std::string &script);
};
class MyInterpreter : private GenericDotNetLangInterpreter
{
public:
MyInterpreter(const LanguageType l);
Results run(const Arguments& args);
}
Couple of questions:
Has someone done this kind of thing before, and is there some code I can use as a reference point?
what are some gotchas I need to be aware of going down this path?
Not really an answer, but pointing out that C# and VB.Net aren't interpreted, but compiled to IL (similar to Java's Bytecode). In other words, your API name and signature would probably change. You would need to invoke the associated compiler and then execute the code.
There are .Net languages that can run interpreted on the DLR, but I'm not clear on calling that from a native language.
The limit between managed and unmanaged applications is thinner than it looks. Your C++ app can link with mscorelib (basic .NET support).
From there on, your C++ app can compile your text "script" to .NET byte code and execute it.
Whether it makes sense or is a good idea is left up to you.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 7 years ago.
Improve this question
Is there a ready-to-use C# interpreter out there, that is does not rely on runtime compilation?
My requirements are :
A scripting engine
Must Handle C# syntax
Must work on medium-trust environments
Must not use runtime compilation (CodeDomProvider ...)
Open source (or at least free of charge both for personal and professional use)
If this is not clear, I need something like Jint (http://jint.codeplex.com/), but which allows me to write C# scripts instead of JavaScript ones.
Thanks for your help.
Have you looked at paxScript.NET?
Check out the Mono project. They recently demoed CsharpRepl which sounds like what you're after. The PDC 2008 video here.
Update:
On a close look it seems like using Mono.CSharp service to evaluate scripts won't be possible. Currently it is linked to the Mono runtime and they don't expect it to run in a medium trust environment. See this discussion for more info.
On alternative possibility is to include the Mono C# compiler (sources here) in your project and use it to generate assemblies that you load from the file system. It you are worried about the resources required to load all those assemblies you might have to load them in a separate AppDomain.
I need to evaluate 10000+ small
scripts that are all differents,
compiling all of them would be just
dramatically slow
Interpretting these would be even more painfully slow. We have a similar issue that we address as follows:
We use the Gold Parser project to parse source code and convert it to an XML based 'generic language'. We run this through a transform that generates VB.Net source code (simply because it's case insensitive). We then compile these using the .Net runtime into a standalone DLL, and call this using heavily restricted access.
It sounds as though you are creating something like a dynamic website where people can create custom modules or snippets of functionality, but using C# to do this introduces a couple of main problems; C# has to be compiled, and the only way around this is to interpet it at runtime, and this is unfeasible, and even if you do compile each snippet then you end up with 10,000 DLLs, which is impractical and unusable.
If your snippets are rarely changing, then I would consider programatically wrapping them into a single set of source, with each having a unique name, then compile them in a single shot (or as a timed process every 10mins?). This is what we do, as it also allows 'versioning' of peoples sessions so they continue using the version of DLL they had at the start of their session, but when every session stops using an old version then it's removed.
If your snippets change regularly throughout the day then I would suggest you look at an interpretted scripting language instead, even PHP, and mix your languages depending on the functionality you require. Products such as CScript and LinqPad all use the CodeDomProvider, because you have to have IMSL somewhere if you want to program compiled logic.
The only other option is to write your own interpretter and use reflection to access all the other libraries you need to access, but this is extremely complex and horrible.
As your requirements are effectively unachievable, I would suggest you take a step back and figure out a way of removing one or more restrictions. Whether you find a FullTrust environment to compile your snippets in, remove the need for full code support (i.e. move to interpretted code snippet support), or even change the whole framework to something non .Net.
LINQPad can work as a code snippet IDE. The application is very small and lightweight. It is free (as in beer) but not open-source. Autocompletion costs extra but not much ($19).
Edit: after reading over the comments in this post a little more carefully, I don't think LINQPad is what you want. You need something that can programmatically evaluate thousands of little scripts dynamically, right? I did this at work using Iron Ruby very easily. If you're willing to use a DLR language, this would probably be more feasible. I also did some similar work with some code that could evaluate a C# lambda expression passed in as a string but that was extremely limited.
I have written an open source project, Dynamic Expresso, that can convert text expression written using a C# syntax into delegates (or expression tree). Expressions are parsed and transformed into Expression Trees without using compilation or reflection.
You can write something like:
var interpreter = new Interpreter();
var result = interpreter.Eval("8 / 2 + 2");
or
var interpreter = new Interpreter()
.SetVariable("service", new ServiceExample());
string expression = "x > 4 ? service.SomeMethod() : service.AnotherMethod()";
Lambda parsedExpression = interpreter.Parse(expression,
new Parameter("x", typeof(int)));
parsedExpression.Invoke(5);
My work is based on Scott Gu article http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx .
or http://www.csscript.net/
Oleg was writing a good intro at code project
It doesn't handle exact C# syntax, but PowerShell is so well enmeshed with the .NET framework and is such a mature product, I think you would be unwise to ignore it as at least a possible solution. Most server products being put out by Microsoft are now supporting PowerShell for their scripting interface including Microsoft Exchange and Microsoft SQL Server.
I believe Mono has mint, an interpreter they use before implementing the JIT for a given platform. While the docs in the official site (e.g. Runtime) say it's just an intermediate state before consolidating the jitting VM, I'm pretty sure it was there the last time I compiled it on Linux. I can't quite check it right now, unfortunately, but maybe it's in the direction you want.
bungee# is the thing that you want, in a short time, bungee sharp will be an open source project in
http://www.crssoft.com/Services/Bungee
. you can create scripts with the same c# syntaxt. there is no assembly creation when you run the script, interpretation is done on the fly, so the performance is high. all the keywords are available like c#. I hope u will like it very much..
I faced the same problem. In one project I was looking to provide a generic way to specify conditions controlling when a certain letter has to be generated. In another project the conditions were controlling how cases were assigned to queues. In both of them The following solution worked perfectly:
The Language for the snippets - I chose JScript so that I do not have to worry about variable types.
The Compilation - yes it requires full trust, but you can place your code in a separate assembly and give it full trust. Do not forget to mark it with AllowPartiallyTrustedCaller attribute.
Number of code snippets - I treated every snippet as a method, not a class. This way multiple methods can be combined into a single assembly
Disk usage - I did all compilation in memory without saving the assembly to disk. It also helps if you need to reload it.
All of this works in production without any problems
Edit
Just to clarify 'snippet' - The conditions I am talking about are just boolean expressions. I programatically add additional text to turn it to methods and methods to compilable classes.
Also I can do the same with C# although I still think JScript is better for code snippets
And BTW my code is open source feel free to browse. Just keep in mind there is a lot of code there unrelated to this discussion. Let me know if you need help to locate the pieces concerning the topic
This one works really well
c# repl and interactive interpreter
Is Snippet Compiler something you looking for?
I'm writing a small visualization tool in wpf, the idea is that average users can create interesting visualizations without being programming wizards.
I have a controller class that has methods like StartPath(double x, double y) and LineTo(x,y) CurveTo(...) etc.
The idea is that a user can type these commands into a textbox and have it draw the result on a canvas.
StartPath(0,0);
LineTo(30,50);
LineTo(50,40);
EndPath();
One Idea I had was to use a .cs template that has all the methods implemented, and has an additional Run() command with a replacement token inside. I load the template as a string, insert the user commands into the Run() method, use the new .net 4.0 compilation service to create an assembly on the fly, then load it and invoke its Run() method and access the exposed Path to draw it on a canvas.
Another one would be to actually just parse the textbox, error check it and call the appropriate methods.
Are there any other methods, especially with the new dynamic keyword?
You don't need to use anything new from .NET 4.0. The ability to compile C# code in the framework has been present for ages. In fact, my Snippy tool does pretty much exactly what you say - it's a template that user code goes in. You're welcome to base your tool on mine, should you wish to. You can download the code from the C# in Depth site.
Aside from anything else, that way you won't require your users to have .NET 4.0.
As for dynamic - it doesn't really help in this case, unless you fancy letting your users write code in IronPython/IronRuby. C# still doesn't have a sort of "eval" call letting you just execute an arbitrary string.
I think you are better to try to define a LL1 language and generate a parser and a scanner and build your own interpreter.
Coco/R is a very stable and well known tool for this kind of job.
Check this out is should not be difficult for what you have in mind:
http://www.scifac.ru.ac.za/coco/cshcoco.htm
If you want to use the new dynamic you will still have problem parsing the input command text.
You could use dynamic to build your interpreter on top of the parser.
Hope this helps