We have a MS SQL 2005 database. The data is uploaded in this database from Excel sheets. These Excel sheets come from various vendors and most of them never maintain a predefined structure so that we can create a separate insertion/update module.
Until now I have created a module which accepts an Excel sheet in a predefined format and uploads the data from it. For every vendor someone has to format it in the predefined manner manually which takes too long and is a donkey work.
Now we have removed the manual formatting and put all database columns in one column, and drop-downs containing all Excel columns in another column. The user maps the desired columns and updates the database.
But most of the time this simple mapping falls short, since mostly we have to split/combine values based on some logic. To make it more user friendly and since most of my users are themselves C# programmers I have decided to remove the drop-downs and use text boxes where users can enter direct logic. For example:
dbcol1 = excel[col1].ToString().Replace("-"," ")
+(int.Parse( excel[col6].ToString())*.1).ToString();
While searching for this I came across dynamically compiling C# code. Since I have never done so before and also I am not sure that this method will be efficient I need to know that am I moving in the right direction with this. Or is there a more efficient and faster way to do this?
Script it up? C# Script is pretty handy, if you want to compile and run code on the fly;
If you can string format something that is correct C# it'll let you compile and run it.
http://www.csscript.net/
For example:
dynamic script = CSScript.Evaluator
.LoadMethod(#"void SayHello(string greeting)
{
Console.WriteLine(greeting);
}");
script.SayHello("Hello World!");
Probably not great for production, but you can at least prototype your idea
Normally you would use Reflection.Emit to generate a .NET assembly on the fly and execute that. However, it accepts only Intermediate Language instructions, not C#. And creating a whole new assembly each time you want to execute a piece of code is not efficient at all.
Roslyn is Microsoft's attempt at a compiler as a service. This is a new rewritten compiler for C# and VB.Net that can be called by an application to compile code, and it provides information about the code it is compiling.
Anders Hejlsberg (I believe) showed an example using the Roslyn compiler to implement a C# scripting interface: type some C# and it gets executed on the fly. While Roslyn is still in development, you might want to see if it would meed your needs by trying the Roslyn CTP.
C# as a Scripting Language in Your .NET Applications Using Roslyn is a CodeProject article that goes into some detail.
Finally, if you cannot (yet) or don't want to use Roslyn, or if it does not provide the execution speed you were looking for, then I think your best bet (in terms of performance) is to parse and interpret the scripting code yourself. However, this is error-prone hard work.
Related
Ok, so I was wondering how one would go about creating a program, that creates a second program(Like how most compression programs can create self extracting self excutables, but that's not what I need).
Say I have 2 programs. Each one containing a class. The one program I would use to modify and fill the class with data. The second file would be a program that also had the class, but empty, and it's only purpose is to access this data in a specific way. I don't know, I'm thinking if the specific class were serialized and then "injected" into the second file. But how would one be able to do that? I've found modifying files that were already compiled fascinating, though I've never been able to make changes that didn't cause errors.
That's just a thought. I don't know what the solution would be, that's just something that crossed my mind.
I'd prefer some information in say c or c++ that's cross-platform. The only other language I'd accept is c#.
also
I'm not looking for 3-rd party library's, or things such as Boost. If anything a shove in the right direction could be all I need.
++also
I don't want to be using a compiler.
Jalf actually read what I wrote
That's exactly what I would like to know how to do. I think that's fairly obvious by what I asked above. I said nothing about compiling the files, or scripting.
QUOTE "I've found modifying files that were already compiled fascinating"
Please read and understand the question first before posting.
thanks.
Building an executable from scratch is hard. First, you'd need to generate machine code for what the program would do, and then you need to encapsulate such code in an executable file. That's overkill unless you want to write a compiler for a language.
These utilities that generate a self-extracting executable don't really make the executable from scratch. They have the executable pre-generated, and the data file is just appended to the end of it. Since the Windows executable format allows you to put data at the end of the file, caring only for the "real executable" part (the exe header tells how big it is - the rest is ignored).
For instance, try to generate two self-extracting zip, and do a binary diff on them. You'll see their first X KBytes are exactly the same, what changes is the rest, which is not an executable at all, it's just data. When the file is executed, it looks what is found at the end of the file (the data) and unzips it.
Take a look at the wikipedia entry, go to the external links section to dig deeper:
http://en.wikipedia.org/wiki/Portable_Executable
I only mentioned Windows here but the same principles apply to Linux. But don't expect to have cross-platform results, you'll have to re-implement it to each platform. I couldn't imagine something that's more platform-dependent than the executable file. Even if you use C# you'll have to generate the native stub, which is different if you're running on Windows (under .net) or Linux (under Mono).
Invoke a compiler with data generated by your program (write temp files to disk if necessary) and or stored on disk?
Or is the question about the details of writing the local executable format?
Unfortunately with compiled languages such as C, C++, Java, or C#, you won't be able to just ``run'' new code at runtime, like you can do in interpreted languages like PHP, Perl, and ECMAscript. The code has to be compiled first, and for that you will need a compiler. There's no getting around this.
If you need to duplicate the save/restore functionality between two separate EXEs, then your best bet is to create a static library shared between the two programs, or a DLL shared between the two programs. That way, you write that code once and it's able to be used by as many programs as you want.
On the other hand, if you're really running into a scenario like this, my main question is, What are you trying to accomplish with this? Even in languages that support things like eval(), self modifying code is usually some of the nastiest and bug-riddled stuff you're going to find. It's worse even than a program written completely with GOTOs. There are uses for self modifying code like this, but 99% of the time it's the wrong approach to take.
Hope that helps :)
I had the same problem and I think that this solves all problems.
You can put there whatever code and if correct it will produce at runtime second executable.
--ADD--
So in short you have some code which you can hard-code and store in the code of your 1st exe file or let outside it. Then you run it and you compile the aforementioned code. If eveything is ok you will get a second executable runtime- compiled. All this without any external lib!!
Ok, so I was wondering how one would
go about creating a program, that
creates a second program
You can look at CodeDom. Here is a tutorial
Have you considered embedding a scripting language such as Lua or Python into your app? This will give you the ability to dynamically generate and execute code at runtime.
From wikipedia:
Dynamic programming language is a term used broadly in computer science to describe a class of high-level programming languages that execute at runtime many common behaviors that other languages might perform during compilation, if at all. These behaviors could include extension of the program, by adding new code, by extending objects and definitions, or by modifying the type system, all during program execution. These behaviors can be emulated in nearly any language of sufficient complexity, but dynamic languages provide direct tools to make use of them.
Depending on what you call a program, Self-modifying code may do the trick.
Basically, you write code somewhere in memory as if it were plain data, and you call it.
Usually it's a bad idea, but it's quite fun.
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
I found a fairly complex function in a greasemonkey script that I would like to use in my C# app. Basically I am parsing a page and I need to collect all or 4 members of var avar = {}; (i haven't done this yet but they are all strings using var avar.name = "val")
Then I need to call the gm func which returns a string and takes in 3 strings. How can I call the function in C#? I am using .NET 3.5
I'm assuming that you are after some code-reuse on the server-side or in some other freestanding app that processes HTML data.
You can compile (at least a subset of) JavaScript in .net using the Microsoft.JScript.JScriptCodeProvider class -- though note that the class warns
This API supports the .NET Framework
infrastructure and is not intended to
be used directly from your code.
Once compiled the assembly generated (as specified by the CompilerParameters supplied to the provider) should be dynamically loadable. It would be advisable to examine the generated assembly with a tool like Reflector to see what it is you've actually generated, in terms of classes and namespaces.
Disclaimer -- I've only ever used this technique with the CSharpCodeProvider acting on C# source, but I would expect there to be a reasonable level of compatibility across .net languages for this sort of thing.
EDIT -- For an example of compiling JavaScript from C# see this blog post on Verifying JavaScript syntax using C#.
First, you probably want to consider exactly why you're trying to do this. Is it that you want to use the algorithm from the JS in C#? If so, go ahead. If you want to use C# in client-side code (i.e. the browser), go investigate Silverlight instead.
Second, I'm not sure that what you're trying to do is actually possible. Depending on what youre trying to achieve, you may be better off translating the Javascript from the Greasemonkey app into C# 3.5 (assuming that the script's licensing conditions allow this), for use in your app.
The translation shouldn't be hugely difficult - C# has been getting more and more like JS in the last few versions. Just watch out for the "var" keyword; it means something slightly different in C# to what it means in JS (contrast "type inference" in C# with "dynamic typing" in JS).
Of course, maintaining both versions of the code after you've done this will be tricky and painful. I recommend keeping 1 authoritative version of the code if you can.
Good luck!
Can you provide more information about your script and what you want to accomplish? Most Greasemonkey scripts interact with the DOM via the use of Javascript. You can run Javascript in C# but the DOM will not be available to you.
I happened upon a brief discussion recently on another site about C# runtime compilation recently while searching for something else and thought the idea was interesting. Have you ever used this? I'm trying to determine how/when one might use this and what problem it solves. I'd be very interested in hearing how you've used it or in what context it makes sense.
Thanks much.
Typically, I see this used in cases where you are currently using Reflection and need to optimize for performance.
For example, instead of using reflection to call method X, you generate a Dynamic Method at runtime to do this for you.
You can use this to add scripting support to your application. For examples look here or here.
It is quite easily possible to publish parts of your internal object framework to the scripting part, so you could with relative ease add something to your application that has the same effect as for example VBA for Office.
I've seen this (runtime compilation / use of System.Reflection.Emit classes) in generating dynamic proxies ( Code project sample ) or other means of optimizing reflection calls (time-wise).
At least one case you might use it is when generating dynamic code. For example, the framework is using this internally to generate XML serializers on the fly. After looking into a class at runtime, it can generate the code to serialize / deserialize the class. It then compiles that code and users it as needed.
In the same way you can generate code to handle arbitrary DB tables etc. and then compile and load the generated assembly.
Well, all C# code is run-time compiled, since it's a JIT (just-in-time) compiler. I assume you are referring to Reflection.Emit to create classes etc. on the fly. Here's an example I have seen recently in the Xml-Rpc.Net library.
I create a C# interface that has the same signature as an XML-RPC service's method calls, e.g.
IMyProxy : IXmlRpcProxy
{
[XmlRpcMethod]
int Add(int a, int b);
}
Then in my code I call something like
IMyProxy proxy = (IMyProxy)XmlRcpFactory.Create(typeof(IMyProxy));
This uses run-time code generation to create a fully functional proxy for me, so I can use it like this:
int result = proxy.Add(1, 2);
This then handles the XML-RPC call for me. Pretty cool.
I used runtime compiler services from .NET in my diploma thesis. Basically, it was about visually creating some graphical component for a process visualization, which is generated as C# code, compiled into an assembly and can then be used on the target system without being interpreted, to make it faster and more compact. And, as a bonus, the generated images could be packaged into the very same assembly as resources.
The other use of that was in Java. I had an application that had to plot a potentially expensive function using some numerical algorithm (was back at university) the user could enter. I put the entered function into a class, compiled and loaded it and it was then available for relatively fast execution.
So, these are my two experiences where runtime code generation was a good thing.
something I used it for was for allowing C# and VB code to bu run by the user ad-hoc. They could type in a line of code (or a couple lines) and it would be compiled, loaded into an app domain, and executed, and then unloaded. This probably isnt the best example of its usage, but an example of it none-the-less