Git Product home page Git Product logo

microsoft / clearscript Goto Github PK

View Code? Open in Web Editor NEW
1.7K 68.0 147.0 56.39 MB

A library for adding scripting to .NET applications. Supports V8 (Windows, Linux, macOS) and JScript/VBScript (Windows).

Home Page: https://microsoft.github.io/ClearScript/

License: MIT License

C# 87.61% C++ 9.48% C 0.08% Batchfile 0.20% JavaScript 2.25% VBScript 0.05% Makefile 0.16% Shell 0.14% PowerShell 0.04%
dotnet javascript vbscript v8

clearscript's Introduction

Banner

Twitter Follow

Description

ClearScript is a library that makes it easy to add scripting to your .NET applications. It currently supports JavaScript (via V8 and JScript) and VBScript.

Features

  • Simple usage; create a script engine, add your objects and/or types, run scripts
  • Support for several script engines: Google's V8, Microsoft's JScript and VBScript
  • Exposed resources require no modification, decoration, or special coding of any kind
  • Scripts get simple access to most of the features of exposed objects and types:
    • Methods, properties, fields, events
    • (Objects) Indexers, extension methods, conversion operators, explicitly implemented interfaces
    • (Types) Constructors, nested types
  • Full support for generic types and methods, including C#-like type inference and explicit type arguments
  • Exposed .NET collections support native script iteration mechanisms:
  • Scripts can invoke methods with output parameters, optional parameters, and parameter arrays
  • Script delegates enable callbacks into script code
  • Support for exposing all the types defined in one or more assemblies in one step
  • Optional support for importing types and assemblies from script code
  • The host can invoke script functions and access script objects directly
  • Full support for script debugging
  • V8 Support for fast data transfer to and from JavaScript typed arrays
  • V8 Support for JavaScript modules
  • V8 JScript Support for CommonJS modules
  • V8 Automatic conversion between .NET BigInteger and JavaScript BigInt.
  • V8 Optional automatic conversion between .NET DateTime and JavaScript Date.
  • V8 Optional automatic conversion between .NET tasks and JavaScript promises.
  • Support for .NET 5.0+, .NET Framework 4.5+, .NET Core 3.1, and .NET Standard 2.1.
  • Support for Windows (x86/x64/arm64), Linux (x64/arm/arm64), and macOS (x64/arm64).

Installation

Complete package

All in one, for all supported platforms.

ClearScript.Complete

Composite packages

Everything you need for one platform.

Platform Packages
Windows ClearScript ClearScript.win-arm64
Linux ClearScript.linux-x64 ClearScript.linux-arm ClearScript.linux-arm64
macOS ClearScript.osx-x64 ClearScript.osx-arm64

Component packages

Cross-platform libraries and data.

Component Packages
Core ClearScript.Core
JScript/VBScript ClearScript.Windows.Core ClearScript.Windows
V8 ClearScript.V8 Microsoft.ClearScript.V8.ICUData

V8 native assembly packages

Platform-specific V8 libraries.

Platform Packages
Windows ClearScript.V8.Native.win-x86 ClearScript.V8.Native.win-x64 ClearScript.V8.Native.win-arm64
Linux ClearScript.V8.Native.linux-x64 ClearScript.V8.Native.linux-arm ClearScript.V8.Native.linux-arm64
macOS ClearScript.V8.Native.osx-x64 ClearScript.V8.Native.osx-arm64

Documentation

Acknowledgments

We'd like to thank:

clearscript's People

Contributors

clearscriptlib avatar dcrusader avatar dependabot[bot] avatar drewnoakes avatar fyers avatar kurtgokhan avatar microsoft-github-policy-service[bot] avatar phxnsharp avatar serpen avatar skacurt avatar taritsyn 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

clearscript's Issues

ERROR:Cannot load V8 interface assembly. Load failure information for v8-ia32.dll:

System.TypeLoadException

Cannot load V8 interface assembly. Load failure information for v8-ia32.dll: D:\App\cb\hangfire_pro\v8-ia32.dll: 找不到指定的模块。
image

System.TypeLoadException: Cannot load V8 interface assembly. Load failure information for v8-ia32.dll:
D:\App\cb\hangfire_pro\v8-ia32.dll: 找不到指定的模块。
在 Microsoft.ClearScript.V8.V8Proxy.LoadNativeLibrary()
在 Microsoft.ClearScript.V8.V8Proxy.LoadAssembly()
在 Microsoft.ClearScript.V8.V8Proxy.GetAssembly()
在 Microsoft.ClearScript.V8.V8Proxy.GetImplType(Type type)
在 Microsoft.ClearScript.V8.V8Proxy.CreateImpl[T](Object[] args)
在 Microsoft.ClearScript.V8.V8IsolateProxy.Create(String name, V8RuntimeConstraints constraints, Boolean enableDebugging, Int32 debugPort)
在 Microsoft.ClearScript.V8.V8Runtime..ctor(String name, V8RuntimeConstraints constraints, V8RuntimeFlags flags, Int32 debugPort)
在 Microsoft.ClearScript.V8.V8Runtime..ctor(V8RuntimeConstraints constraints)
在 JavaScript.Manager.RuntimeManager..ctor(IManagerSettings settings)
在 Hangfire.Job.Common.TabrisUtil.Excute(JobItem item, String jobName, PerformContext context)

Fetch Local Variables value in VBScript implented using clearscript

I am implementing a debugger for Vbscript using Clearscript which is expected to display all the variables and their values upon hitting break point.

I am able to fetch all the variables using following code:

public static VBScriptEngine engine;
dynamic ome = engine.Evaluate("me"); 
foreach (var name in ome.GetDynamicMemberNames())
Console.WriteLine("{0}: {1}", name, ome[name]);

The challenge here i am facing is that i am not able to fetch the context specific variables: e.g. A break point is set inside a function then upon hitting the break-point the variable list gets empty as per the above code.

Is there a way to fetch the context specific variables also(the variables inside the function)

Consider the following code:

abc = 123

def = 1432
Call hello()

Function hello()

 jas=123

 [breakpoint]

 ja = 14

End Function

Here on hitting the breakpoint it should display jas = 123

Expectations to expose the V8 snapshot API?

Hello! I hope this is the right plage to open discussions related to the library - same as we did on CodePlex. I apologize in advance if it's not the right place.

As of 5.4.9 you guys have been using the V8 snapshot functionality to improve engine start-up times. Do you have any plans to expose the same functionality to the .NET layer, thus allowing users to build their own snapshotted versions of engines and do the same?

Thanks!

`Date.now()` expression returns incorrect result

Hello!

After upgrading to version 5.5.1, V8ScriptEngine.Evaluate method began to return an incorrect result of the Date.now() expression. Current result (16336909) differs significantly from the result of version 5.5.0 (1514915269409).

For verification, you can use the following code:

using System;
using Microsoft.ClearScript.V8;

namespace TestClearScript
{
	class Program
	{
		static void Main(string[] args)
		{
			using (var engine = new V8ScriptEngine())
			{
				double totalMilliseconds = Convert.ToDouble(engine.Evaluate("Date.now();"));
				Console.WriteLine("totalMilliseconds = {0}", totalMilliseconds);
			}
		}
	}
}

Pass a javascript to C#

how can i pass a js function to the C# function as a paramter
like:

static void Main(string[] args)
{
var script = "cddd.Callback(function(){cddd.log('dddddd')})";

        var engine = new V8ScriptEngine();

        engine.AddHostObject("cddd", new Cddd());

        engine.Execute(script);

        Console.ReadLine();

}
public class Cddd
{
public void Callback(object callbacl)
{
//at here to call the js function in "callbacl"
}

    public void log(string str)
    {
           //TODO:  Do something
    }

}

the problem is in Callback function , callbacl will is a V8ScriptItem,,but it can't invoke

Multi-threaded callbacks not working

Hi all, have tried to use V8 javascript and Clearscript 5.4.10 to script TPL System.Threading.Tasks.Parallel.ForEach() however the calls never complete and seem blocked within the engine.

Any ideas?

Debugging with ClearScript and V8

I was wondering how one would go about using ClearScript with the v8 engine and attaching to it using chrome devtools. I cant seem to get that to work. Can someone point me in the right direction. I specifically don't want to use vscode if possible, but I will if I need to. The key need for me is to debug remotely.

Thanks in advance

Including new c++ routine inside ClearScript/V8

Hi,
I have some functions that I want to call whenever a some javascript is loaded. Those functions are written in C.
1- I don't want those function visible to .NET framework.
2- I want those function to be part of the V8 engine somehow...
3- I am wondering even how to start and achieve this kind of work.

I need some help and guidance.
Please don't throw us on to some abstract links to compile and build the V8 from scratch.
We have a product almost in completion stages and this the last thing we want to achieve ASAP.

Thanks in Advance.

DOMParser is undefined

I want to parse a XML, apply xpath and grab some data. Do we have any xml parser support in clearscript or any other alternative method?

using Microsoft.ClearScript;
using Microsoft.ClearScript.V8;
using Microsoft.ClearScript.JavaScript;
V8ScriptEngine _v8Engine = new V8ScriptEngine(V8ScriptEngineFlags.EnableDebugging);
            _v8Engine.Execute(@"
                var text, parser, xmlDoc;
                text = '<bookstore><book><title>Everyday Italian</title><author>Giada De Laurentiis</author><year>2005</year></book></bookstore>';
                parser = new DOMParser();
                xmlDoc = parser.parseFromString(text, 'text/xml');
            ");
Error:
Microsoft.ClearScript.ScriptEngineException: 'ReferenceError: DOMParser is not defined

I'm using clearscript under c#.

VBScript code cannot access nested types

Hello,

I have just discovered ClearScript, and think it's great. But I am having trouble exposing enums and consts to my scripts.

for example: I created a basic class with an enum defined.

Public Class test
    Public Enum Numbers
        one
        two
        three
    End Enum
End Class

I then add this to my engine

scriptEngine.AddHostType("test", GetType(test))

but I am unable to reference numbers in my scripts e.g.

test.Numbers.one

I would expect this to be an integer with a value of one? But instead get an error

Public member 'Numbers' on type 'HostType' not found.

Does ClearScript support enums? Any help appreciated.

Thanks

Stop interacting with people using an anonymous account

The use of @ClearScriptLib is detrimental in that it is nameless and faceless. The loss of the "feel of personal interaction" results in a feeling of either "talking to a bot" or dealing with a group of people who are actively trying to avoid proper engagement with the community.

I am sure this was not your intent, but you may want to reconsider your reasons taking this approach

Is there a way to capture the object thrown from the javascript?

For example, we can write JavaScript like this:

var test = {
    a:'this is a demo',
    b: 100
};
throw test;

then in the c#/host side, we can catch the ScriptEngineException. However, The exception will look like this (Converted to Json string for easy to read):

{
   "ClassName":"Microsoft.ClearScript.ScriptEngineException",
   "Message":"[object Object]",
   "Data":{

   },
   "InnerException":null,
   "HelpURL":null,
   "StackTraceString":"   ...,
   "RemoteStackTraceString":null,
   "RemoteStackIndex":0,
   "ExceptionMethod":"8\nV8Exception.ThrowScriptEngineException\nClearScriptV8-32, Version=5.4.6.0, Culture=neutral, PublicKeyToken=935d0c957da47c73\nVoid V8Exception.ThrowScriptEngineException(V8Exception*)",
   "HResult":-2146233079,
   "Source":"ClearScriptV8-32",
   "WatsonBuckets":null,
   "ScriptEngineName":"b5ddbce9-b0ce-4fdd-8bce-c0bc3096af33:",
   "ScriptErrorDetails":"[object Object]\n    at 23b147c2-5bbc-4ea2-b366-5998dc365279 [temp]:12:1 -> throw test;\n    at 23b147c2-5bbc-4ea2-b366-5998dc365279 [temp]:14:6\n    at 23b147c2-5bbc-4ea2-b366-5998dc365279 [temp]:16:2",
   "IsFatal":false,
   "ExecutionStarted":true
}

Is there a way in the c#/host, the ScriptEngineException can have the value of the object thrown by the exception? That can help the host side to process the exception.

After update to 5.5.0 "v8-base-ia32.dll" cannot be loaded.

I got the following exception after I update my projects ClearScript.V8 version 5.5.0.

Cannot load V8 interface assembly. Load failure information for v8-base-ia32.dll

When I return back to the version 5.4.9 the applications run fine.

Returning native Javascript objects from CLR

I have a situation where a registered library (e.g. AddHostObject("utils", new Utils())) has a function that returns an object based on a set of parameters. All is fine, so long as the type is a core system type marshalled to number, string, boolean etc, but if the return type is a DateTime object things get very messy.
I can modify my external call to return a long number, and require the user always wrap it in a Date(blah), but this is messy and unintuitive for users:
var x = utils.GetDate('tomorrow').getDay()
has to be coded as
var x = new Date(utils.GetDate('tomorrow')).getDay()

Looking at the returned types, the DotNet DateTime is returned as a HostObject, but a Javascript Date object is a V8ScriptItem.
Is there any way to have the result of a CLR function return a javascript Date object? I can't wrap the call in the expression because it may be used in the middle of another expression (e.g.
console.log(`Hi Dave, I can't do that until ${utils.GetDate('tomorrow').toLocalString()}`)

Better stack trace on JavaScript exceptions

Currently, when JavaScript throws an exception for almost any reason it throws exceptions like this:

No overload for method 'find' takes '2' arguments
   at V8Exception.ThrowScriptEngineException(V8Exception* ) in c:\clearscript-5.4.9\clearscript\v8\clearscriptv8\v8exception.cpp:line 81
   at Microsoft.ClearScript.V8.V8ContextProxyImpl.Execute(V8Script gcScript, Boolean evaluate) in c:\clearscript-5.4.9\clearscript\v8\clearscriptv8\v8contextproxyimpl.cpp:line 294
   at (...)

As you can see you don't know which object method find was executed and where it lacks overload. In good enough scenario this should like this (This is how error looks cached by VSCode debugger):

Error: No overload for method 'find' takes '2' arguments
    at findOneTutorialData (Script Document:12085:47)
    at getLatestTutorialDataVersion (Script Document:12154:28)
    at Script Document:27:31

In the best case scenario, if the error is the object that is HostObject we would get which object V8 has tried to access and failed.

Error: No overload for method 'find' takes '2' arguments for host object '<namespace>.MongoCollection'
    at findOneTutorialData (Script Document:12085:47)
    at getLatestTutorialDataVersion (Script Document:12154:28)
    at Script Document:27:31

Need an option to wait for a debugger connection

V8ScriptEngine with flags EnableDebugging or/and EnableRemoteDebugging do not wait for debugging engine to connect when debugger method is provided in javascript

Engine = new V8ScriptEngine(V8ScriptEngineFlags.EnableDebugging | V8ScriptEngineFlags.EnableRemoteDebugging);
Engine.Execute("debugger;");

EDIT
I will double chcek which version V8 I'm currently using
EDIT
Happens on version 6.2.414.40

Update documentation for V8 Debugging

Because Google Chrome Developer Tools for Java in Eclipse is no longer supported. Can you provide new instructions on how to connect to the debugger using a dedicated tool for V8 like Chrome "chrome://inspect" or another such tool that is still supported?

Inconsistency with "typeof" results

As of now I couldn't find a good way of creating internal JavaScript objects from text to pass them into engine, so I'm using kind of hack

        public static object CreateObject(string document)
        {
            var sb = new StringBuilder();
            sb.Append($"var __obj__ = {document}");
            _engine.ExecuteCommand(sb.ToString());
            return _engine.Script.__obj__;   
        } 

This method produces a mostly valid "object" for most of the purposes but typeof from this object returns function instead of the required type such as array or object etc...

This being mentioned such code is returning false
C#

managed.setScriptData("csharpObjectFromText", JSUtils.CreateObject("[]"));
V8ScriptEngine.Execute(script); 

JS

var array = Managed.getScriptData("csharpObjectFromText");
if(typeof array === typeof []) //expected true

I just hope this is not my misunderstanding of javascript objects using ClearScript.

Cannot attach debugger to script

This is follow up bug from #22

There are multiple issues but I think the reason is the same.
vscodev8debugging (around 20seconds)

  1. Starting C# application and attaching debugger with breakpoint before first Execution
  2. When breakpoint hits we lunch VSCode debugger
  3. Debugger connection is established as it does not stop after 10 seconds
  4. We step forward C# application and we want to enable VSCode debugger to stop.
  5. Nothing happens and when C# scripts end, VSCode throws an error.

Second is debugger connection
connected
My code is too complicated to be pasted in the simple snippet for you to fiddle with, but it all falls down start V8Engine, wait a little bit of time (other code is executed) and then evaluate and execute.

Unfortunately, this code is "oversimplified" and connection to the debugger is established correctly.

    private static void Main(string[] args)
    {
        var engine =
            new V8ScriptEngine(V8ScriptEngineFlags.EnableDebugging | V8ScriptEngineFlags.EnableRemoteDebugging);
        var timeout = 0;
        while (timeout < 200)
        {
            Thread.Sleep(5);
            timeout += 1;
        }
        engine.Evaluate("function test() { debugger; }");
        engine.Invoke("test");
    }

vscodev8debugging2

A short description what is going on this gif.

  1. Starting code execution with breakpoint just in case.
  2. Attaching VSCode debugger
  3. Waiting for C# code to hit the breakpoint. (You can see in the background that VSCode has successfully attached)
  4. At this point, we do see nothing as no script is compiled or executed
  5. We are resuming C# execution and at this point, VSCode should have all pieces of information required and ScriptDocument should appear but that's not the case.
  6. I'm trying to open any document from LoadedDocuments in VSCode (this is possible if attached correctly) but I cannot access any, I have tried all of them before.
  7. At last before I break execution of C# both debuggers are connected and disconnecting one will resume C# and de-attach VSCode.

Additional information:
Windows 10 x64 Version 10.0.15063 Build 15063
Visual Studio 2017 Community Version 15.4.0
VSCode 1.18.0 x64 Commit: dcee2202709a4f223185514b9275aa4229841aa7
Node 7.9.0
.NET Version of the project 4.6.1
ClearScript x64 built from Commit 3273d22
V8 Release x64 6.2.414.40

EDIT:
My Javascript code that is executed in this last gif is around 16000 lines of code. This might be connected to that. So simple example is working and my "Production code" is not.

Timeout parameter

The ClearScript.V8 engine needs a timeout parameter. I am running a service where I'll give control to the user by giving them programming access with a Javascript engine and I don't want things like infinite loops to happen so the need for a timeout.

For now I'll have to fall back on Jint until there is such a parameter in ClearScript.V8 engine.

Thanks.

Issue with ExpandoObject and ClearScript

I am having an issue with the ClearScript library. Here is what I am trying to do:

  1. Create HostObject that has an API
  2. Have the Host API return a dynamic object (ExpandoObject)
  3. Access the dynamic object in JavaScript.
    I have written a test program below that demonstrates the approach. I have made it as simple as possible to demonstrate what I am trying to do. The code below showcases the JavaScript code that I am executing

image

The object below showcases the TestDynamic object which is very simple

image

When I look at the object created by the host in @code. The key here is the extra methods
Equals(), GetHashCode(), GetType(), and ToString()

image

In my test program everything works perfectly.

Now in my real solution, I have an asp.net application (Web Forms). On postback from form (to save) I have a callback mechanism which is invoked in the form lifecycle. In this instance the callback is the BeforeSave() function below. I have super simplified the code to eliminate any possible issues. Right now the code below just calls a corresponding JavaScript method called beforeSave(). I was invoking it dynamically but for now I am directly calling the beforeSave() routine off of the Script object. As in the test scenario above, the TestDynamic object is exactly the same, so I am not showing the code again.

image

When I inspect the object from @code, just like in the test project. I get an exception in the ClearScript below.

image

The exception below is what is being thrown

image

Three exceptions are thrown. If you inspect the args parameter of the Invoke method, you see the following methods that are excepting.
args[0] = “ToString”
args[0] = “Equals”
args[0] = “GetHashCode”

Here is the call stack when the exception is thrown.
image

I have tried to trace through the code to see how these methods are added to the ExpandoObject that I am creating. I cant figure it out. Any help would be great. Thanks in advance.

DebuggerBreakpoints Not Hit in Debugger

Hi,

Here is the problem I experiencing with debugging a V8 script. Steps to reproduce:

  1. Setup VS Code debugger with the following launch config (as described here https://microsoft.github.io/ClearScript/Details/Build.html, section V):
    "launch": {
        "version": "0.2.0",
        "configurations": [
            {
                "name": "Attach to ClearScript V8 on port 9222",
                "type": "node",
                "request": "attach",
                "protocol": "inspector",
                "address": "localhost",
                "port": 9222
            }
        ]
    }
  1. Download the attached project:
    ClearScriptTest.zip
    open the solution in VS2017, restore packages, and run the application. As a result, a console with numbers running endlessly will open.

  2. Attach VS Code debugger to the script. After the debugger is attached, click the pause button on VS Code debugger toolbar. Execution stops on the while(true) line:
    image

  3. Set breakpoints on any line inside the loop, and continue execution.
    Expected result:
    Execution stops on breakpoint hit.
    Actual result:
    Execution continues as if no breakpoints were set

OR

  1. Click Step Over on the debugger toolbar.
    Expected result:
    Execution steps to the next line.
    Actual result:
    Execution continues without stopping.

Thank you.

How to clean up a V8ScriptEngine?

Not sure my question makes much sense.
First,

 var Runtime = new V8Runtime(Guid.NewGuid().ToString());
 var Engine = Runtime.CreateScriptEngine(V8ScriptEngineFlags.DisableGlobalMembers);

Then, i will execute some script

Engine.Execute(script);

Then I want to clean up the Engine to make sure the executed script will not have any side affects on the next script execution.

I can

Engine.CollectGarbage(true);

But i think that is NOT enough to make sure the Engine is clean.

I can also recreate the Enigne

Engine.Dispose();
Engine = Runtime.CreateScriptEngine(V8ScriptEngineFlags.DisableGlobalMembers);

But not sure the cost of recreating the Engine object. Will it have poor performance?

Is there a better way?

Thanks,

Multiple Compiles and Evaluates prevents debugger to connect

If using one instance of an engine, multiple Compilations and Evaluations prevents VSCode debugger to connect.

var engine = new V8ScriptEngine(V8ScriptEngineFlags.EnableDebugging);
var script = engine.Compile("var a = 0");
engine.Evaluate(script);
script = engine.Compile("debugger;");
engine.Evaluate(script);
//Try to connect debugger at this point.

VSCode debugger fails with error Cannot connect to runtime process (reason: read ECONNRESET).

Freezing issue due to V8

Hey,

just wanted to let you know that there is a deadlock issue that affects V8 (and ClearScript) - as detailed here: https://bugs.chromium.org/p/v8/issues/detail?id=6933

I've been noticing that sometimes CPU would get stuck to 100% (per core) since the upgrade to 5.5. After some investigation I've concluded that this is the likely culprit. Now I've been running the patched version of V8 since a couple of days and it looks like the issue is resolved.

This is what I did:

  • cherry-picked commit ac0fe8ec from V8 upstream (v8/v8@ac0fe8e)
  • recompiled V8

Basically the same thing node did here: nodejs/node#17695

I'm attaching the corresponding patch here - has anyone noticed the same behavior with ClearScript 5.5?

0001-interpreter-Remove-TryInstallOptimizedCode.patch,txt

Document name limitation

I'm running into a limitation with the way document name is implemented with the V8ScriptEngine. Currently if I pass in a document name with path it get's trimmed down to just the filename. This causes a problem as the document name is returned back through the debugging api as just the filename no path.

Could this behavior be changed or possibly overriden?

Paralell programming

Hi!

Is there any way to run multiple tasks at the the same time from javascript code without create new V8ScriptEngine instance? The tasks would use javascript code.

For example:

var task = System.Task.Run(new System.Action(function() { System.Console.WriteLine("I'm in the new task."); })); task.Wait();

Thanks,
Balazs

Bypassing AllowReflection = false using "host" object

Here's a proof of concept, similar to how #1 works except we add the host object.

// This gets the System.Reflection.Assembly object of mscorlib
var test = host.func(0, function(){});
var assembly = test.Method.ReturnType.Assembly;

The host object is added like this: (this is the same as the example given on the old Codeplex page)

engine.AddHostObject("host", new HostFunctions());

Not completely certain if this can be considered a bug though, since HostFunctions provides a lot of "internal" functionality.

Permission Denied For Msgbox

When we try to run the vbscript code with msgbox, Permission denied message is displayed.

Msgbox "Hello"

Below error shows up :



Permission denied: 'Msgbox'

OK

.net 3.5 support?

I tried using .net 3.5 however seems to be quite a few functions don't exist, best way to get it working with 3.5 .net or is it even possible?

Clearscript 5.5.1.1 and Chrome Developer Tools support

Hello all,
I've recently updated the ClearScript version from 5.5.0 to 5.5.1.1 and now I'm not able to debug my javascript code by using Chrome Developer Tools anymore.
Every time I try to connect to an engine using the CDT, a WebSocket connection is established and then closed by chrome as soon as the first message is received.

From a brief analysis seems to be an issue connected to the new WebSocket implementation.

I can reproduce the issue with the following steps:

  1. I create a minimal test console application:
using Microsoft.ClearScript.V8;
using System;

namespace Minimal
{
    class Program
    {
        static void Main(string[] args)
        {
            using (var engine = new V8ScriptEngine(V8ScriptEngineFlags.EnableDebugging | V8ScriptEngineFlags.EnableRemoteDebugging, 9876))
            {
                Console.WriteLine(engine.Evaluate("'Press enter to send debug command';"));
                Console.ReadKey();
                engine.Evaluate("debugger;");
            }
        }
    }
}
  1. while the console application is waiting for a key, I open chrome at URL:
    http://127.0.0.1:9876/json/list
  2. then I use the devtoolsFrontendUrl to start debugging the engine

My solution, for now, is to downgrade ClearScript version.

Thanks

Wait for event

Hi!

How can i wait for an event, and then continue execution? If I just connect a host event source to a script handler function, the script execution finished before it is raised. How can I solve it?

I would like something like this:

var obj = new StatedObject();

//...

//do process...

//wait obj.Status changed to "Stopped"

//continue process...

Thanks!

Using DynamicObjects in script

I am using V8 script engine and trying to use System.Dynamic.DynamicObject with overridden TryGetMember and TryGetIndex in the script. I am adding it via engine.AddHostObject(). Although I see that GetMetaObject() is called twice - when object is added to engine and when it is accessed from script - this does not seem to work. The overridden methods of DynamicObject get never called when access is attempted from within script yielding [undefined] results. If I use created object from host code in C#, it works as expected.

At the same time, ExpandoObject does work. E.g. if I create object in the host, add some dynamic field to it and then pass it to engine, script can access dynamic field I've created. I guess, there is something about implementation that causes this discrepancy but I could not find what.

Maybe, you could advise?

Thanks!

Is Microsoft Visual Studio C++ 2015 Redistributable a dependency for ClearScript

Today I have an issue with a production server of one of my clients. The actual error message was "Application popup: - System Error : The program can't start because MSVCP140.dll is missing from your computer. Try reinstalling the program to fix this problem. "

Problem occurs on instantiating V8 engine.

            using (var engine = new V8ScriptEngine())
            {...

After installing VS 2015 C++ redist, problem was solved.

First of all - why this is application popup. It blocks service until pressing "OK" on message box.
Second - on ClearScript install it's mentioned that the package has no dependencies. Actually it depends on VC C++ redist.

Add support for .NET Core

When I try to add it from Nuget it says

Restoring packages for ...\ClassLibrary1.csproj...
Package ClearScript.V8 5.4.9 is not compatible with netstandard1.4 (.NETStandard,Version=v1.4). Package ClearScript.V8 5.4.9 supports: net40 (.NETFramework,Version=v4.0)
One or more packages are incompatible with .NETStandard,Version=v1.4.
Package restore failed. Rolling back package changes for 'ClassLibrary1'.

Is the project still undergoing active development?

Dear ClearScript team,

I hope I don't sound entitled writing this (the library is absolutely excellent and a pleasure to use!), but I'm a bit worried to see that the last commit on this repository happened in May. Are you still planning to actively develop ClearScript in the future?

message, stack members not found unless manually set

I'm trying to pass JS Error objects to .NET functions. Accessing the message or stack members of this object results in the exception "Public member 'message' on type 'V8ScriptItem' not found."
If I pass a JS object that I created myself ({message:"Error",stack:"trace"}) I am able to access these members.
Further, passing in other objects such as {x:1} and attempting to access message or stack result in exceptions rather than returning Microsoft.ClearScript.Undefined.

Attaching to ClearScript with Node.js Tools for Visual Studio 2017

Hi,

I tried to attach Node.js Tools for Visual Studio 2017 debugger to a running ClearScript application, but couldn't get it to work.
Here is how I initialize ClearScript:
new V8ScriptEngine("Name", V8ScriptEngineFlags.EnableDebugging | V8ScriptEngineFlags.EnableRemoteDebugging, 4545))
The script I am running is basically an endless loop:

System.Console.WriteLine("Hello");

i = 0;
while (true)
{
    System.Console.WriteLine(i);
    System.Console.WriteLine(i);
    System.Console.WriteLine(i);

    if (i % 2 == 0)
        System.Console.WriteLine("e");
    else
        System.Console.WriteLine("odd");

    i++;
}

Then, I try to attach from VS2017 (as described here and here).

When I try to connect using TCP ("Node.js remote debugging"), the dialog hangs after clicking the Find button, and gives the following error when I stop the script:
image

When I try to connect using Websockets ("WebKit websocket (no authentication)"), it does find the target, and gives me two "code types" to choose from:
image

When I choose "JavaScript (Node.js 8+)", it looks like it attaches to the server, but when I select "Break All" from Debug menu, it does nothing.

When I choose "WebKit" code type, I get the following error:
image

I tried plain ws:// URL without the GUID also. Could you please point me to the right direction?

Question: Linq With Lists

Hi and thanks for such an amazing project!

I'm someone who really tries to scour the internet to answer my questions, but I'm simply at a roadblock and was wondering if anyone has a code snippet that they can share.

Here's a simple example of what I'm trying to accomplish; for the purpose of this, MyList is a List<MyObject>:

var test = MyList.AsEnumerable().Where(c => c.Active).First().Description;

But I get a script error that System.Collections.Generic.IEnumerable<MyObject> does not contain a definition for 'Where'.

I tried adding this before the above line (based on some code snippet I found):

var EnumerableT = host.type("System.Linq.Enumerable", "System.Core");

I've also tried adding this in the engine init where I load up a variety of types/object:

E.AddHostType(typeof(System.Linq.Enumerable));

This isn't critical, and I can live without it, but it would be great if I could get this to work and I hope I'm just missing something.

Thanks!

Bypassing AllowReflection = false via exceptions

It looks like it's possible to bypass AllowReflection = false via exceptions. Here is a very basic example that demonstrates the problem:

using System;
using Microsoft.ClearScript.V8;

namespace ClearScriptTest2
{
	public class Test
	{
	}

	class Program
	{
		static void Main(string[] args)
		{
			using (var engine = new V8ScriptEngine()) {
				engine.AddHostType("Console", typeof(Console));
				engine.AddHostObject("test", new Test());
				engine.AllowReflection = false;

				engine.Execute("try { test.GetType(); } catch (ex) { Console.WriteLine(ex.hostException.GetType().Assembly.FullName); }");
			}

			Console.ReadLine();
		}
	}
}

The first GetType() will throw an exception (and it is caught by javascript), but the second ex.hostException.GetType() does not throw an exception.

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.