GithubHelp home page GithubHelp logo

javascript.net's Introduction

Example

// Initialize a context
using (JavascriptContext context = new JavascriptContext()) {

    // Setting external parameters for the context
    context.SetParameter("console", new SystemConsole());
    context.SetParameter("message", "Hello World !");
    context.SetParameter("number", 1);

    // Script
    string script = @"
        var i;
        for (i = 0; i < 5; i++)
            console.Print(message + ' (' + i + ')');
        number += i;
    ";

    // Running the script
    context.Run(script);

    // Getting a parameter
    Console.WriteLine("number: " + context.GetParameter("number"));
}

See our wiki for more information.

Nuget

Old versions have been published as Noesis.JavaScript.

Publishing a newer version is a work in progress.

Redistribution

Noesis.Javascript.dll needs the Microsoft C Runtime Libraries.

If you don't include the correct version of the runtime libraries when you redistribute Noesis.Javascript.dll then you will get errors when loading the DLL on some users machines. (Many, but not all users will already have it.)

Targets: .NET Framework 4.5

Building from Source

Open the .sln file in Visual Studio, use Configuration Manager to switch to platform to x64, and build. I've been working using Visual Studio 2017, but 2015 will probably work too.

The following warnings are expected:

  • warning LNK4248: unresolved typeref token (0100003F) for 'v8.internal.Object'; image may not run

  • warning MSB3270: There was a mismatch between the processor architecture of the project being built "MSIL" and the processor architecture of the reference "C:\Users\oliver\Documents\GitHub\Javascript.Net\x64\Release\JavaScript.Net.dll", "AMD64". This mismatch may cause runtime failures. Please consider changing the targeted processor architecture of your project through the Configuration Manager so as to align the processor architectures between your project and references, or take a dependency on references with a processor architecture that matches the targeted processor architecture of your project.

Also note that when using the DLL built from source, you will need to add a Post Build Step to your consuming project, which copies the v8 DLLs and .bin files into your output directory. See Noesis.Javascript.Tests.csproj for an example, noting that it has some extra sections manually inserted to define V8Platform.

Updating v8

The log at https://docs.google.com/a/g7.org/document/d/1g8JFi8T_oAE_7uAri7Njtig7fKaPDfotU6huOa1alds/edit may help, if it is still being updated.

Running Tests

The unit tests are standard Visual Studio - run them using the GUI.

How it Works

Simple values and arrays are copied between the native memory space (where v8 resides) and the Common Language Runtime (CLR) (where .Net applications live). Complex .Net types (delegates, objects) are proxied. When calls are made into proxied types then the parameters are copied into the CLR and the call is executed. The results are copied back.

Internationalization

??? buildv8.bat turns off internationalization when invoking gyp to avoid the need to distribute the (large) ICU DLLs and data file.

javascript.net's People

Contributors

ablu avatar brisingraerowing avatar chillitom avatar oliverbock avatar rast1234 avatar spahnke avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

javascript.net's Issues

Adopting this project

Hi, this is a great project!

Since it appears you don't find much free time to maintain this project, I would like to propose my adoption of this project.

I will maintain it and publish a nuget and review/merge PRs as needed.

If you are willing to do this, please reach out to me at robinrodricks7 at gmail dot com.

Thank you very much!

Question: What will be the best way of implementing a good/real sleep() function?

V8 does not support setTimeout, hence implementing of a sleep() function must be done above V8.

Calling of any C# method outside the JS context does not pause the interpreter, and the only way of work this around is by using a callback function which makes the code unreadable (especially for simple scripting).

Also using something like this:

function sleep(milliseconds) {
    var start = new Date().getTime();
    for (var i = 0; i < 1e7; i++) {
        if ((new Date().getTime() - start) > milliseconds){
            break;
        }
    }
}

is a very very bad idea...

Do you think there is a better way of implementing a simple (real) sleep function that will pause the interpreter for a certain amount of milliseconds?

Stack Error?

when i am running in a javascript function.
then I call some .net Function like 'DoSubRender()'.
in the DoSubRender function I use the JavascriptContext.Run to call sub javascript function.

at last I get the "null reference" error.

Decimal type does not work when it's a property of an object

When passing a decimal parameter directly, everything works as it should. Example:

JavascriptContext context = new JavascriptContext();
context.SetParameter("test", new decimal(0.333));
context.Run("test = test * 2");
context.GetParameter("test");  //returns 0.666... all is good

But when I pass in an object with a decimal property, and try to use that property, it acts strange. For example:

public class Product
{
    public decimal Price {get; set;}
}

JavascriptContext context = new JavascriptContext();
context.SetParameter("test", new Product(){ Price = new decimal(0.333)});
context.Run("test.Price = test.Price * 2");
context.GetParameter("test");  //returns 0.... not good

I noticed that the decimal support was added in version 0.7, which is what I'm using. Maybe there was an oversight when decimal support was added that didn't extend to decimal properties of objects?

Thanks for the help!
KB

Proper prototype handling

Problem

Currently JavaScript.Net does not fully support prototype related use cases:

While it is possible to register a function which creates a new object like this:

_context.SetParameter("TestClass", new Func<TestClass>(() => new TestClass()));

_context.Run(@"
    let c = new TestClass();
    c.foo()").Should().Be(true);

problems with this approach:

  • instanceOf checks are not working. c instanceof TestClass is false
  • Prototype extensions are not working (TestClass.prototype.newMethod = function() {...})

Things to consider for the solution

  • Objects which are created by C# code should also be able to pass to JavaScript under an existing prototype
  • Fine grained control about which types are constructable by JS is required

Solution proposal

  • add method like SetConstructor(ConstructorInfo constructor) to the context which generates a prototype and registers under the name
  • when wrapping an object:
    • lookup whether a prototype already exists for the type
    • if no prototype is known: generate a prototype (but do not make it available to the context under a name)
    • wrap object by using the newly generated or existing prototype

Side notes

This could also improve performance of wrapping objects since the analysis of type is only required once, repetitive passing could become a lot faster.


/cc @spahnke

@oliverbock do you think the proposal above is sane? Then I would start to implement it.

Tabs or spaces for new code?

Hi,

when looking at the code I am not sure how to configure my editor, part of the code is with tabs, part is with spaces.

What do you prefer here? Then I would add an editor config and format my planned contribution that way.

.Net Core

Is it possible to compile this targeting .Net Core instead of .Net Framework?

Tom

SetAndReadDateTimeLocal_DateRange test fails due to DST changes in America/Sao_Paulo timezone

Below is what happens on my PT-BR system. Compiled against v8-v142 (7.5.288.23), target net45.

Since the test case runs through the all dates at 0:00, it receives back 1:00 AM when it hits
DST shift time in Brazil (and other local time adjustments like the one in 1914). This is the expected behavior for V8, since such combinations of date/time does not exist in America/Sao_Paulo timezone.

Message: 
    Assert.Fail failed. Expected 01/01/1914 00:00:00, but got 01/01/1914 00:06:28
    Expected 03/10/1932 00:00:00, but got 03/10/1932 01:00:00
    Expected 01/12/1949 00:00:00, but got 01/12/1949 01:00:00
    Expected 01/12/1950 00:00:00, but got 01/12/1950 01:00:00
    Expected 01/12/1951 00:00:00, but got 01/12/1951 01:00:00
    ....
    Expected 16/10/2016 00:00:00, but got 16/10/2016 01:00:00
    Expected 15/10/2017 00:00:00, but got 15/10/2017 01:00:00
    Expected 04/11/2018 00:00:00, but got 04/11/2018 01:00:00
    Expected 03/11/2019 00:00:00, but got 03/11/2019 01:00:00
    ....
    Expected 03/11/2097 00:00:00, but got 03/11/2097 01:00:00
    Expected 02/11/2098 00:00:00, but got 02/11/2098 01:00:00
    Expected 01/11/2099 00:00:00, but got 01/11/2099 01:00:00

I added val.toString() and val.getTime() to the test output, so I could verify that V8 Date objects are correct. Here is what I got back:

....
    Expected 16/10/2016 00:00:00, but got 16/10/2016 01:00:00 
    str: Sun Oct 16 2016 01:00:00 GMT-0200 (Horário de Verão de Brasília), 
    timestamp: 1476586800000

    Expected 15/10/2017 00:00:00, but got 15/10/2017 01:00:00 
    str: Sun Oct 15 2017 01:00:00 GMT-0200 (Horário de Verão de Brasília), 
    timestamp: 1508036400000
....

It is exactly the same behavior as I get in chrome console for that dates:

>new Date(2016,9,16)
<Sun Oct 16 2016 01:00:00 GMT-0200 (Horário de Verão de Brasília)
>1476586800000

So the problem is with the test itself, as long as you are only dealing with local (timezone-unaware) DateTime objects. However, it will be a different story for timezone-aware DateTime objects (those with timezone information).

In order to have stable behavior across different locales, I recommend to avoid component-based Date conversion. Instead, it would be better to always have any .NET DateTime object first converted to UTC timestmp (locaized or not), an then use this timestamp to construct V8 Date constructor (it could be int64 value or ISOString).

Warnings : Should I be concerned?

I get these no matter how I build, it compiles fine, just concerned these warnings might mean something serious as I read your statement about the 0100003F on your main page, I get these? I have VS2017 and the same exact SDK version as your notes suggest. Happens if I build for x32 or x64 or anything else for that matter ...

Severity Code Description Project File Line Suppression State
Warning C4244 'argument': conversion from 'double' to 'int', possible loss of data

JavaScript.Net javascriptinterop.cpp 412
Warning LNK4248 unresolved typeref token (0100004E) for 'v8.internal.Isolate'; image may not run JavaScript.Net JavascriptInterop.obj 1

Warning LNK4248 unresolved typeref token (01000038) for 'v8.internal.Isolate'; image may not run JavaScript.Net JavascriptFunction.obj 1

Warning LNK4248 unresolved typeref token (01000042) for 'v8.internal.Isolate'; image may not run JavaScript.Net JavascriptExternal.obj 1

Warning LNK4248 unresolved typeref token (01000041) for 'v8.internal.Isolate'; image may not run JavaScript.Net JavascriptContext.obj 1

Unhandled Execution Error

Hi

I am randomly getting this error on a Hello World example-code on a "clean" asp.net project.
The error happens very randomly, with no apparent pattern.
I am using this nuget package:
<package id="Noesis.Javascript" version="0.7.1.0" targetFramework="net471" />

1

This is the code:

2

App pool settings:

4

C++ installations:

3

If the site starts up without the error, it is able to run like that for a long time. Therefore i created a Powershell script to better provoke the error:

5

The script will continuously do an issreset and then call the page. The result is about 50/50 chance of getting a 200 statuscode back and getting the error back.

Question: fetch/xmlhttprequest/http request OR run a local executable file

Hello,

Just trying my luck.

I want to send an HTTP request.
Is this feature supported?
Apparently not when I tried "fetch" and "XMLHttpRequest".
It seems like a browser-implemented feature.

Is there any workaround similar to the suggested for ClearScript?
https://stackoverflow.com/questions/53810084/referenceerrorxmlhttprequest-is-not-defined-while-using-clearscriptv8scripteng


The other option for me is to let JavaScript.net run a local executable file.
Is this possible? Due to security risks, it may not be possible though.

Thank you!

Precompiled binary for the latest code?

Is there any precompiled library for the latest code release? I'd be very interested in the javascript callbacks for .net code ...

I unfortunately didn't get it to compile so far, and as far as I can understand from this issure here #2 it won't work as described anyway.

about run environment : Could not load file or assembly 'JavaScrip t.Net.dll'

hi,all contributor.

I download the source code , Compile success in my computer. and run the test project Fiddling success.

But in other computer(same win7 x64), when run project Fiddling apper error (had copy all documents) .

The error is

System.IO.FileNotFoundException: Could not load file or assembly 'JavaScrip
t.Net.dll' or one of its dependencies.

I wont to solve the problem, so i install vc++2008 , vc++2010, vc++2013,vc++2015 and .net 4.5.2. but is not work.

So, what i need to do?

Thinks.

Randomly throws exception for the same code

Hi,

I've got the following code

`string code = "function imageUrl(){ if(seasonType==="summer"){ return "https://i.ibb.co/P9Sz25M/summer.jpg\"; } if(seasonType==="winter"){ return "https://cdn.pixabay.com/photo/2018/11/22/12/48/clothing-3831823_1280.jpg\"; } if(seasonType==="spring"){ return "https://cdn.pixabay.com/photo/2016/11/16/03/55/blue-1828094_1280.jpg\"; } }; imageUrl();";

var javascriptContext = new JavascriptContext();
javascriptContext.SetParameter("seasonType", "summer");
var expressionJSResult = javascriptContext.Run(code);
javascriptContext.Dispose();
Console.WriteLine(expressionJSResult.ToString());`

My issue is that when the same code is run it works sometimes and sometimes it throws the below exception.

at Noesis.Javascript.CompileScript(Local<v8::Script>* , Char* source_code, Char* resource_name) at Noesis.Javascript.JavascriptContext.Run(String iSourceCode) at Program.<Main>$(String[] args)

Appreciate any help on this. I'm using .Net version 4.8.

System.AccessViolationException

Hello,

we using Javascript.net in our ASP.NET Web Applications.
It works good but regularly get errors in our Server log.

error modul v8.dll

System.AccessViolationException
at .v8.Locker.Initialize(v8.Locker*, v8.Isolate*)
at Noesis.Javascript.JavascriptContext.Enter(Noesis.Javascript.JavascriptContext ByRef)
at Noesis.Javascript.JavascriptFunction.~JavascriptFunction()
at Noesis.Javascript.JavascriptFunction.Dispose(Boolean)
at Noesis.Javascript.JavascriptFunction.Dispose()
at Noesis.Javascript.JavascriptFunction.Dispose(Boolean)

looks like there is something wrong with the dispose.

maybe someone got an idea. =)

thx

C++ Redistributable

There are a number of different MS C++ redistributable libraries. It would be helpful to include in the documentation, both here and in NuGet, to specify exactly which one is needed, and where to get it.

UnauthorizedAccessException when trying to open a mutex

we using IIS with many different application pools all using application pool identity.
we sometimes get this error:

[UnauthorizedAccessException: Access to the path "FA12B681-E968-4D3A-833D-43B25865BEF1" is denied.]
System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath) +435
System.Threading.MutexTryCodeHelper.MutexTryCode(Object userData) +311
System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData) +0
System.Threading.Mutex.CreateMutexWithGuaranteedCleanup(Boolean initiallyOwned, String name, Boolean& createdNew, SECURITY_ATTRIBUTES secAttrs) +237
System.Threading.Mutex..ctor(Boolean initiallyOwned, String name, Boolean& createdNew, MutexSecurity mutexSecurity) +266
System.Threading.Mutex..ctor(Boolean initiallyOwned, String name) +55
Noesis.Javascript.JavascriptContext..cctor() +80

[typeinitializationexception the type initializer for "Noesis.Javascript.JavascriptContext" threw an exception.] Noesis.Javascript.JavascriptContext..ctor() +0

Do i need to create a new AppDomain for every create instance of JavaScript.Net or how i prevent this exception from happening?

Linux build instructions

Could you provide build instructions (for the library itself, not for v8) for Linux (command line possibly)?
Thanks.

[QUESTION/REQUEST] Create JS function which calls C# APIs

Is there a way to create a JS functions/classes which implements C# APIs? I want to use the JS engine, but I need some C# only APIs.

Edit: It can be done using SetParameter. Should be in the wiki (no mention that JS.NET supports it)

SyntaxError: Unexpected reserved word

I've tryed out these interpreter. An simple console.log will work - But when i try to use ES6 classes, i've got following Exception:

Noesis.Javascript.JavascriptException: SyntaxError: Unexpected reserved word

   bei Noesis.Javascript.CompileScript(Local<v8::Script>* , Char* source_code, Char* resource_name)
   bei Noesis.Javascript.JavascriptContext.Run(String iSourceCode)
   bei ReactSharp.Program.Main(String[] args) in c:\Users\info\Documents\SharpDevelop Projects\ReactSharp\ReactSharp\Program.cs:Zeile 48.

Program.cs

using System;
using System.IO;
using Noesis.Javascript;

namespace Sample {
	public class SystemConsole {
		public SystemConsole() {}

		public void log(string iString) {
			Console.WriteLine(iString);
			System.Diagnostics.Debug.WriteLine(iString);
		}
	}

	internal sealed class Program {
		[STAThread]
		private static void Main(string[] args) {
			System.Diagnostics.Debug.WriteLine("HI");
		
			using(JavascriptContext context = new JavascriptContext()) {
				context.SetParameter("console", new SystemConsole());
				
				// Read the "main.js"
				string contents = File.ReadAllText(@"main.js");
				
				// Run the script
				context.Run(contents);
			}
		}
	}
}

main.js

class Example {
	constructor() {
		console.log("Hello World, APP!");
	}
}

Explain how to manipulate C# (CLR) objects from js and vice versa

I can’t determine from the limited documentation what interchange of information is possible between CLR objects and js objects.

Where does this project sit, along a spectrum of “no coupling”: two independent domains, using json (or whatever) to communicate back and forth, to “fully coupled”: where js and c# can directly manipulate objects from the other domain?

  1. Can js hold a handle to a C# (CLR) object?
  2. Can js use .net reflection to discover properties and functions useable on a c# object? And read/write properties, invoke functions with parameters?

And similar questions in the other direction, where c# manipulates js objects.

FWIW: Investigating whether this project would be any help towards a larger goal: A super-strict subset of typescript, removing (hiding) some of js loose-typing functionality, with 1:1 translation between it and c#, calling .net 5 libraries. Then a static analyzer that determines all possible data flow in the CLR representation, for better debugging. Then all needed code is (optionally) translated back into ts/js, so there is an option to run in js without WASM compilation of c#. Just in case / or as in interim solution. Assuming WASM ultimately becomes capable of doing everything js can, without performance issues, this also becomes a path for moving super-strictly-typed ts/js code forward into a pure C#/WASM implementation.

—————————————

UPDATE:

I just discovered Jurassic which is more suitable for my purpose. Compiles js into .NET bytecodes (CIL). Nevertheless, answers to questions above might be useful to add to your read me page.

License statement

Hi,

we are wondering wether we can use this project. Some files seem to have license headers, but we are missing a project level LICENSE file. Could you give a statement about the complete licensing of this piece of software?

Regards,
Ablu

Extended Documentation or Wiki

Hey,

I would like to see a way more extensive documentation.
There are essential questions like

  • Internal Behavior ( overview )
  • How does the lib behave if called in parallel Environments especially the TerminateExecution method
  • Can i set a timeout for the execution
  • Documentation of parameter on methods. For example: what is iScriptResourceName on "Run"
  • Is this In-Process
  • What about the Performance compared to other tools or just in general
  • What is the behavior on giving tasks into the js code ( like executing a function from js that returns a Task)
  • Are there any security features for shared use ( like on a WebApp )
  • Can i use any kind of DI loader like requireJs

Passing C# field through javascript and back into C# results in null

Here is my setup:

I plan to use JavaScript as the language for modding my game, I currently have it setup to create a javascript context with 3 variables: log, mod and require, require isn't being used yet...

mod is a C# object with the field I am trying to use.
log is also a C# object with functions that redirect to log4net, (mainly info(string format, object[] objs))

Here is the issue, in my javascript file I have:

log.info("Hello from {0}!", [mod.display_name]);

Which results in:

Hello from !

Even though mod's C# object has the field display_name set to "sandbox"
I even checked with the debugger, the C# instance of mod is correct, I debugged the C# function for log.info and noticed that mod.display_name was evaluating to null before being passed through the function. Why is this happening? And how can I fix it?

JavascriptFunction.Call cannot be GC?

object caller = context.GetParameter("__triggerEventCall");
if (null != caller && caller is JavascriptFunction)
{
    ((JavascriptFunction)caller).Call(name, args);
}

using this code leaves huge amount of references which then cannot be GC

Is there a better way of calling JS function (rather than context.Run("__triggerEventCall()") ) ?

fatal error in v8::context::new

Hello, Sometimes when I'm using JavaScriptContext in a loop I get the exception "fatal error in v8::context::new". What cause of this problem it could be?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.