Integrating ECMA Script into a C# program, what is the fastest technique? - javascript

I'm trying to execute JavaScript in a C# program, and I'm trying to determine:
Would it be better to create a state machine for JavaScript, or should it be compiled into MSIL before executing it?
I'm really looking for techniques rather than solutions. Some attempt to compile the JavaScript, there by treating it as a programming language, others use a state machine and treat it as it was meant to be : a scripting language.
Any documentation on the methods used for executing is welcome also.

The easiest way to run JS in a C# program is to use one of the existing .Net JS runtimes: IronJS, Jurassic, and Jint. If you're interested in adding another .Net-based interpreter to the mix, examining their code is where I'd start; If you're embedding JS in your program then using a preexisting one is probably the way to go.

You haven't explained your scenario - how much javascript, how often does it get executed, how often does it change, how closely integrated it needs to be with the C# logic, and so on.
If it rarely changes, then it may be smart to compile it into MSIL via one of the alternatives.
If it changes "constantly" then it might make sense to stand up a JS compiler and send it JS as necessary. It's something like a REPL for Javascript, that you'd use programmatically. Node.js offers a server that can do REPL operations; it could listen on a port, you send it JS to evaluate, and it sends back the result. There's a free w3sockets component that could be used from cscript.exe to do something similar: for example you could build a "host" Javascript shell that listens on a socket, executes the js it receives, then sends back the result.
If it needs to be closely integrated with the C# code, then you'll have to be smarter about this. One way to do it might be to host the JS in a Windows Script Component and have the C# code invoke the JS logic via COM. You can also do the converse - have the JS host invoke the C# layer via COM to gather input and deliver results.
EDIT
A better way is to use the IActiveScript stuff - this is the official way Microsoft makes it possible to host scripting within an application. There's a winforms example published here.
OR better, see parse and execute JS by C#
Using that code I put together a demonstration of how to parse and invoke Javascript from a .NET app, using IActiveScript.
You can download a VS2010 project for this app here.

Related

Does node.js replace tomcat?

If I can build a server with node.js do I need tomcat?
Excuse me, I'm a pretty new to it and I'd like to understand this base concepts. Thank you so much!
No, you do not need Tomcat if you are using Node. You could run one or the other, or both at the same time as long as they are not trying to listen on the same port. Here's why.
Tomcat is an open source implementation of the Java Servlet, JavaServer Pages, Java Expression Language and Java WebSocket technologies.
Basically, this means that Tomcat is designed specifically to be a web server.
Node is a JavaScript runtime built on Chrome's V8 JavaScript engine.
Basically, this means that Node can take JavaScript code, optimize it, and give the code access to things that aren't normally exposed to JavaScript code that is run in a web browser, like direct access to the file system. JavaScript is similar to Python, lacking strict data typing, but unlike Python which is an interpreted language, Node reads JavaScript and turns it into machine code which does not require it to be interpreted before it is executed (so it can be much faster).
Node happens to be good for developing servers especially when using frameworks like Express, sort of like Rails for Ruby, or Flask for Python, but you can write anything you want, it doesn't have to be a server.

Electron GUI with C# backend

Use case
I've got an existing project developed in C# using WinForms with custom controls for the GUI. We are amazed by the approach to write GUIs using HTML/CSS/JS and we are looking for the best way to write a GUI for our desktop application using the above mentioned languages. We only need to support Windows devices.
My worries:
It doesn't take long to come across recommendations using electron-edge. While I am not so worried to get everything working, I am worried about:
Debugging my C# code (I still want to be able to start my whole application right from VS and debug it look I am used to it). I read that I would need to attach to the node.js application in order to debug my C# code afterwards. Since the whole program language is written in C# that sounds like a pain?
As far as I got edge will let it run as just one process. Can I consider the electron application as an own thread which would still run while my C# code is stuck somewhere?
My option:
I am still positive I want to write my desktop GUI with HTML/CSS/JS. What I considered instead of using electron-edge is writing an own electron application which does communicate with my C# backend using named pipes. I wonder if there are larger roadblocks why I wouldn't want to do this and use electron-edge instead?
My question:
I would like to get feedback for my two concerns mentioned above and I also would like to get input about my option to create the GUI as own electron process, so that I have two processes (GUI+Backend) when someone runs my application.
Electron.NET may be a option for you. You can write c# code with electron.
You can do it in many ways
1) COM. Create C# COM DLL. Create wrapper functions for the DLL using N-API (Native node module) or use FFI. You can access the functions from JS.
2) Create a .Net web server and include your functions as REST endpoints. From UI make http request to communicate (Clear separation of UI & BEnd)
You can checkout my github repo for a few alternatives to electron.
I think a most import question would be how your frontend interacts with the backend? Is there any notifications need push to the frontend?
WebSocket could be a good option for two ends communication.

What is the purpose of Node.js ? [eg: while implementing a graph algorithm on data set available on a server]

I have been using JS for simple front-end scripting for a while now, but am absolutely new to Node.js. After some surfing, I found out certain stuff about Node.js that it is fast, event-driven,uses modules, can be used both on server and client side, can be run from command line, etc.
As a project, the following task has been given to me:
"To develop a graph algorithm (such as minimum spanning tree) in javascript using node.js. Use the larger of the following graphs as inputs: http://snap.stanford.edu/data/ " [the link contains data from various network sites organised as nodes and edges and stored in .txt files]
Now I know how to implement a graph algorithm in a language (such as C), can even do it in JS using arrays. But I need some help regarding the "using node.js" part of the problem. What is its purpose in the problem ? Which of its features should I look up ?
Typically JS was made to run inside a browser.
Node.js is actually a javascript runtime invokable. You can invoke it from commandline. This means you can execute files of code from commandline like many other languages which you might be already familiar with. Beyond, that there is nothing much from your context.
But, yes it is fast, event-based, async and like server-scripting languages has server-handling capabilities inbuilt. That said it can be used for non-server contexts as well. Like computation in your case.
Node JS helps you to run backend logic, which is written on Javascript Language.
For example, in PHP, when you write backend code, you need some kind of application which will get all clients requests and run specific code to handle it. In PHP it will be done via Apache Server. In Java it will be done via Glassfish/JBoss/Tomcat.
Node JS is something like them, but for Javascript code.

Javascript C++ binding?

I have some C++ code that I want to expose to client side of a web app. Ideally, I want to write Javascript wrapper objects for my C++ classes so that I can use them clientside.
Has this been done before?. Does anyone have a link to show how this may be achieved?
There is a library to convert C++ code to javascript, it might help:
emscripten
Libjspp C++ template based wrapper for embedding and extending Javascript engine spidermonkey 1 . 8 . 5 and more
SpiderMonkey? is Mozilla Project's Javascript/ECMAScript engine.
Libjspp allows C++ developers to embed SpiderMonkey? simply and easily into their applications. Libjspp allows to run multiple Javascript Engines within same process which suits one engine per thread para dime which is helpful in achieving true parallisim. Also Libjspp no way stops user from running multiple threads within engine.
http://code.google.com/p/libjspp/
I guess that RPC is what you want. You'll need to wrap your functions on the server side using some sort of framework. I've not yet used it, but this one looks promising.
On the client side you use proxy objects to dispatch the function calls. The communication is handled usually either via XML-RPC or JSON-RPC. I used this client side framework and was quite content but I'm sure you'll find many others.
This is an old topi, however, I was in the exact situation right now, and all of the solutions I found on the net complicated or outdated.
Recently, I ran across a library which supports V8 engine (including the new isolation API, which makes 90% of the libraries I found outdated) and provides great exposure and interaction API.
https://github.com/QuartzTechnologies/v8bridge
I hope that my solution will help anybody.
There's a relatively new library for doing this called nbind. Maybe that would suit you? It looks very good to me, and I'm just about to start using it.
I think you want a C++ JSON parser. You should be able to find one here http://www.json.org/. It may not do all you want because it just serializes and deserializes C++ objects without any behavior, but it should be good enough. See https://stackoverflow.com/questions/245973/whats-the-best-c-json-parser for some discussion.
If the C++ code has to be on the client, then there is no simple way to do this for a web app. A solution may involve coding plugins for the browsers you want to support, which may then be accessed from javascript code.
If, for example, you need this for a client application, that is another case. Such a thing has been done and involves linking your application to (or running from outside) with for example chromium library, or any other javascript execution engine. That way you can create bindings to C++ classes and use such objects from javascript and vice-versa. Note that this is also not a trivial solution and may be a big effort to implement (also requires additional resources).
You could for example wrap the C++ classes in PHP or Python, and then implement an API over HTTP to access the required functions.
Or if you insist on exposing the functions as JavaScript you could try using Node.js, and create an C++ add-on to wrap you classes. See the Node.js documentation here: http://nodejs.org/api/addons.html#addons_wrapping_c_objects
But either way, I don't think avoid creating some sort of API (HTTP SOAP, XML RPC) to access the functions on your server.
Though QML is not exactly Javascript, Qt is not plain C++, but what they do together seem just like what you need

Interpreting and/or receiving dotNet code at run-time

Html can contain little bits of Javascript embedded in it (e.g. defined in onclick event handlers).
If I were writing an Html browser using a dotNet language like C#, what technologies or APIs could I use to run such Javascript fragments, given that I don't receive it until run-time (and receive it as string data, not as executable code)?
Is it any easier or harder if the code to be run were C# snippets rather than Javascript?
Is there any technique which doesn't require my code to have unusual priviledges? For example, a method like CodeCompiler.FromSource requires SecurityPermissionFlag.UnmanagedCode (which seems to me excessive: I don't see why it's so risky to compile code).
If I controlled the server-side as well as the client-side code, I could also consider compiling such script fragments on the server instead of on the client, and then sending it as precompiled code to the client side to be executed. Is there a way to send such code (a dotNet assembly, presumably) over the network to the client, have client-side code receive it from the network into client-side RAM, and invoke it on the client side without storing it as a file on a client-side disk drive?
Edit
I have answer to the first three questions: I've resigned myself to the fact that compiling takes high privileges. I don't see why; maybe (although I don't find this a very convincing reason) it's because the compiler is implemented using unmanaged code. Maybe this will change when they reimplement the compiler using managed code, in maybe the "C# version 5" timeframe. In any case, whatever the reason, that seems to be the way it is, and there are no work-arounds (other similar APIs but which require fewer privileges).
My remaining question then is how to get an Assembly instance from one machine to another. When I have time I'll find out whether untrusted code can run the Assembly.Load(byte[] rawAssembly) method.
Server side Javascript is one of the languages supported by the .NET platform. I used it many times in the scenrios when you need to insert small code snippets into existing code. Runtime it can be loaded from i.e. database and compiled, so there is no preformance penalty.
From the standpoint of making the plumbing work (retrieveing the source, compiling it, etc.) there is no difference. With strongly typed languages though it is much more difficult to assemble code snippets into a compilable compilation unit.
Permissions is certanly a challenge. I am not sure about the specific permission you mentioned, but security is a concern, after all the source you compile can be anything and if you are not careful about the source of your code it can become the backdoor into your system
The answer to this one is - yes of course. You can load an assembly from anywhere, not necessarily from a file, you can also compile in memory - that's what I do. There is no dll file in this case.
You're asking several questions, sort of, so I'll give you an idea on one of them.
There's a very good article and some code samples from:
http://www.west-wind.com/presentations/dynamicCode/DynamicCode.htm
which talks about compiling and executing C# code at runtime. I found it very useful and I am using this in a standard c# application. Seems like it would be usable for your problem as well.

Categories

Resources