using c# like script in runtime - c#

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/

Related

Is there a way I can parse/run C# within an application, almost like a script?

I am currently writing some code and I am wondering if it would be possible to execute some C# code from my application. I'll give you an idea, lets say I want to give the user a textbox and have them type some code and hit go, I want them to ask for a list of fruit and then go through each fruit and output it.. an example:
var fruitList = getFruit();
foreach(var fruit in fruitList)
{
print(fruit.Name);
}
I would like to be able to go through this and assign a list of Fruit objects to fruitList, the parser should be able to tie up getFruit() to a method I've written in the c# code. The same goes for print, it should equate this to a print function I've written that outputs it to a textbox.
Now I know that C# isn't a script, it is compiled, and I've done a lot of Googling but can't really find anything. My only option to me appears to be to write a little language parser myself - which sounds fun - but I've done this before and I know it's hard work. So this is just a preliminary check to see if some solution does exist before I commit to the long haul.
So, my fellow programmers, do you know of anything that may be able to assist me?
If not, no problem, I appreciate all feedback whether it's tips, advice, links to articles such as this http://blogs.msdn.com/b/ericwhite/archive/2010/06/29/writing-a-recursive-descent-parser-using-c-and-linq.aspx or a solution.
Regards,
Adam
EDIT: I have managed to get a working example. Note this code is a bit messy as I've pasted some other code in to the test app, but it works. Basically, I compile the code into a DLL, then I load the DLL, find the type, find the method, and invoke it. It's pretty damn quick too! I don't want to spam you so the full code is below:
http://imdsm.blogspot.com/2012/01/compile-c-into-assembly-then-load-it.html
Thank you to everyone who posted here. You just saved me days of confusion!
You mean like in this screenshot here?
We use this in our software, HeuristicLab, you can add a ProgrammableOperator into an operator graph which will execute the code that you typed in at the place that you typed it in a custom-built algorithm.
In the System.CodeDom namespace you've got all you need to dynamically compile code. You can create an assembly from the compilation, get the assembly's types and execute their code.
I think the new compiler project of microsoft is what you are looking for. With it you can run C# as were a script indeed.
Project "Roslyn"
Have a look if Roslyn can help , it's still in CTP status.
You can use the CSharpCodeProvider
Or you could use a scripting language and run the interpreter in your application
Ex IronRuby

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)

How to run C# code using C# code?

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\");

c# compile source code from database

I would like to build an application framework that is mainly interpreted.
Say that the source code would be stored in the database that could be edited by the users and always the latest version would be executed.
Can anyone give me some ideas how does one implement sth like this !
cheers,
gabor
In .Net, you can use reflection and CodeDOM to compile code on the fly. But neither approach is really very simple or practical. Mono has some ability to interpret c# on the fly as well, but I haven't looked closely at it yet.
Another alternative is to go with an interpreted .Net language like Boo or IronPython as the language for your database code.
Either way, make sure you think long and hard about the security of your platform. Allowing users to execute arbitrary code is always an exercise fraught with peril. It's often too tempting to look for a simple eval() method, and even if one exists, that is not good enough for this kind of scenario.
Try Mono ( http://www.monoproject.org ). It supports many scripting languages including JavaScript.
If you don't want to use any scripting you can use CodeDOM or Reflection (see Reflection.Emit).
Here are really useful links on the topic :
Dynamically executing code in .Net (Here you can find a tool which can be very helpul)
Late Binding and On-the-Fly Code
Generation Using Reflection in C#
Dynamic Source Code Generation and
Compilation
Usually the Program uses a scripting language for the scriptable parts, i.e. Lua or Javascript.
To answer your technical question: You don't want to write your own language and interpreter. That's too much work for you to do. So pick some other language, say Python or Lua, and look for the documentation that lets your C program hand it blocks of code to execute. Of course, the script needs to be able to do something, so you'll need to find how to expose your program's objects to the script. Also, what will happen if a client is running the program when you update its source code in the database? Should the client restart? Are you going to store the entire program as a single row in this database, or did you want to store individual functions? That affects how you structure your updates.
To address other issues with your question: Why do you want to do this? Making "interpreted language" part of your design spec for a system is not often a good sign. Is the real requirement something like this: "I update the program often and I want users to always have the latest copy?" If so, there are other, better ways to go about this (just give us your actual scenario and requirements).

Categories

Resources