Quantcast
Channel: ClearScript
Viewing all 2297 articles
Browse latest View live

New Post: How to Pause and Play the [V8ScriptEngine.Execute] of script

$
0
0
How to Pause and Play the [V8ScriptEngine.Execute] of script.
Link to any simple example will be better.

New Post: How to Pause and Play the [V8ScriptEngine.Execute] of script

$
0
0
Unfortunately ClearScript provides no way to pause and resume script execution. You can use ScriptEngine.Interrupt() to terminate a runaway script.

New Post: Reuse script engine instance

$
0
0
Dear Sirs,
I wonder what would be your advice on how to implement reuse of JScriptEngine instance or is it at all advisable.
Given that assemblies, types and libraries of helper scripts are all the same between two sample scripts and are all loaded, is it possible to unload first script with its host objects and load the second with its own set of host objects.
Immediate issue for me was not being able to use AddHostObject() to set new object in case when name of host objects match between scripts.

Please advise.

Yours
MW

New Post: Reuse script engine instance

$
0
0
Hello MW,

It's certainly possible to execute multiple scripts sequentially within a given script engine instance, and no unloading is necessary in between. However, a malicious or buggy script could easily corrupt the environment for subsequent scripts – by deleting or replacing built-in objects, leaving unexpected objects in the root namespace, etc.

Therefore a careful evaluation of script trust level is always a good idea, combined with an assessment of the impact of a corrupted script environment. Some applications such as web browsers rely on the ability to execute multiple untrusted scripts within the same context, and have robust mechanisms for detecting and discarding contexts that are stuck or otherwise problematic.

The bottom line is that if it's important that all scripts start out in a pristine environment, and you cannot assume that each script will clean up after itself, then you should create a new context (script engine instance) for each one.

On a separate note, if you need to expose a host object in a way that allows it to be replaced later, consider using dynamic property assignment instead of AddHostObject():
engine.Script.foo = new Foo();
// or
engine.Script["foo"] = new Foo();
Good luck!

Updated Wiki: Home

$
0
0

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
  • 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

Examples

using System;
using Microsoft.ClearScript;
using Microsoft.ClearScript.V8;

// create a script engineusing (var engine = new V8ScriptEngine())
{
    // expose a host type
    engine.AddHostType("Console", typeof(Console));
    engine.Execute("Console.WriteLine('{0} is an interesting number.', Math.PI)");

    // expose a host object
    engine.AddHostObject("random", new Random());
    engine.Execute("Console.WriteLine(random.NextDouble())");

    // expose entire assemblies
    engine.AddHostObject("lib", new HostTypeCollection("mscorlib", "System.Core"));
    engine.Execute("Console.WriteLine(lib.System.DateTime.Now)");

    // create a host object from script
    engine.Execute(@"
        birthday = new lib.System.DateTime(2007, 5, 22);
        Console.WriteLine(birthday.ToLongDateString());
    ");

    // use a generic class from script
    engine.Execute(@"
        Dictionary = lib.System.Collections.Generic.Dictionary;
        dict = new Dictionary(lib.System.String, lib.System.Int32);
        dict.Add('foo', 123);
    ");

    // call a host method with an output parameter
    engine.AddHostObject("host", new HostFunctions());
    engine.Execute(@"
        intVar = host.newVar(lib.System.Int32);
        found = dict.TryGetValue('foo', intVar.out);
        Console.WriteLine('{0} {1}', found, intVar);
    ");

    // create and populate a host array
    engine.Execute(@"
        numbers = host.newArr(lib.System.Int32, 20);
        for (var i = 0; i < numbers.Length; i++) { numbers[i] = i; }
        Console.WriteLine(lib.System.String.Join(', ', numbers));
    ");

    // create a script delegate
    engine.Execute(@"
        Filter = lib.System.Func(lib.System.Int32, lib.System.Boolean);
        oddFilter = new Filter(function(value) {
            return (value & 1) ? true : false;
        });
    ");

    // use LINQ from script
    engine.Execute(@"
        oddNumbers = numbers.Where(oddFilter);
        Console.WriteLine(lib.System.String.Join(', ', oddNumbers));
    ");

    // use a dynamic host object
    engine.Execute(@"
        expando = new lib.System.Dynamic.ExpandoObject();
        expando.foo = 123;
        expando.bar = 'qux';
        delete expando.foo;
    ");

    // call a script function
    engine.Execute("function print(x) { Console.WriteLine(x); }");
    engine.Script.print(DateTime.Now.DayOfWeek);

    // examine a script object
    engine.Execute("person = { name: 'Fred', age: 5 }");
    Console.WriteLine(engine.Script.person.name);
}

Commented Feature: Support for specifying host method arguments by name [80]

$
0
0
Neither JavaScript nor VBScript have native support for named arguments, but some way to specify host method arguments by name might be useful.
Comments: If we can access named argument from script like this it would be great. it keeps function readable and we can pass arguments in any order. ex: CalculateBMI(name:'Jhon', weight: 123, height: 64) Person person = new Person(firstName: 'John', lastName: 'Smith')

Edited Feature: Support for specifying host method arguments by name [80]

$
0
0
Neither JavaScript nor VBScript have native support for named arguments, but some way to specify host method arguments by name might be useful.

Commented Feature: Support for specifying host method arguments by name [80]

$
0
0
Neither JavaScript nor VBScript have native support for named arguments, but some way to specify host method arguments by name might be useful.
Comments: That would be nice; unfortunately it isn't valid JavaScript syntax. [Object literal](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Grammar_and_types?redirectlocale=en-US&redirectslug=JavaScript%2FGuide%2FValues%2C_variables%2C_and_literals#Object_literals) syntax seems to be the next best thing, but you'd have to pass it through a host method to get something that can be recognized as a set of named arguments as opposed to an object.

New Post: Usage of ES6 with ClearScript

$
0
0
Hello,

is there a way to use the EcmaScript6 functionalities with ClearScript?

Thanks a lot and keep up the good work, amazing library :-)

New Post: Usage of ES6 with ClearScript

$
0
0
Greetings and thanks for your kind words!

Unfortunately JScript doesn't support ECMAScript 6, and that isn't likely to change in the future.

V8 on the other hand already supports some ECMAScript 6 features, and well-tested ones such as Promises are already enabled by default. Others, if supported, are probably not ready for general consumption, but you can enable them by modifying ClearScript. For more information, see here.

Good luck!

New Post: Usage of ES6 with ClearScript

$
0
0
Sounds great, thanks for the pointer!

Commented Feature: Support for specifying host method arguments by name [80]

$
0
0
Neither JavaScript nor VBScript have native support for named arguments, but some way to specify host method arguments by name might be useful.
Comments: Hi, Object literal syntax should be a nice alternative. I don't know what host.args would return to make Console.WriteLine work. engine.Execute(@" Console.WriteLine(host.args({ format: 'Pi = {0}', arg0: Math.PI })); "); Just to avoid host.args from being part of every line of the script can the engine somehow detect that Console.WriteLine (or any other such exposed method) expects multiple (or non-object) parameters but is being passed an object and accordingly do whatever host.args plans to do? engine.Execute(@" Console.WriteLine({ format: 'Pi = {0}', arg0: Math.PI }); "); So that the script would look like above which would be great. Regards, Ram

Commented Feature: Support for specifying host method arguments by name [80]

$
0
0
Neither JavaScript nor VBScript have native support for named arguments, but some way to specify host method arguments by name might be useful.
Comments: Hi Ram, ​ >Object literal syntax should be a nice alternative. I don't know what host.args would return to make Console.WriteLine work. ​ It would return an object that could be recognized as a set of named arguments rather than an arbitrary script object or managed dictionary. Such an object would probably be an instance of a specific internal type that's reserved for this purpose. ​ >Just to avoid host.args from being part of every line of the script can the engine somehow detect that Console.WriteLine (or any other such exposed method) expects multiple (or non-object) parameters but is being passed an object and accordingly do whatever host.args plans to do? ​ ClearScript uses C#-style method binding, where the arguments play a critical role, whether they're selecting a method overload, specializing a generic method, or both. The problem is that an arbitrary script object is ambiguous; it could be interpreted as a single argument or a set of named arguments, and the intended method could be declared or overloaded such that both interpretations are viable. The killer is that this ambiguity could be intractable. For example, it could come into play only when the object's property names happen to match the method's parameter names, something the script writer may not be able to predict. The bottom line is that this approach, while yielding convenient syntax, would probably be too unsafe to merit recommendation. It would also greatly complicate method binding, which is already expensive. Consider also that you could alias "host.args" down to a single character: ``` JavaScript // JavaScript $ = host.args; myObject.DoSomething($({ a: 123, b: 456 })); ``` Opinions?

Commented Feature: Support for specifying host method arguments by name [80]

$
0
0
Neither JavaScript nor VBScript have native support for named arguments, but some way to specify host method arguments by name might be useful.
Comments: Hi, > alias "host.args" down to a single character This is a reasonable alternative. I like this approach. Regards, Ram

Commented Feature: Support for specifying host method arguments by name [80]

$
0
0
Neither JavaScript nor VBScript have native support for named arguments, but some way to specify host method arguments by name might be useful.
Comments: Hi, I feel this is good approach. also I don't have to change signatures in host functions. Looking forward to see this feature in action.. Thanks

Created Unassigned: V8 Debug agent not functioning? [82]

$
0
0
A basic test using "telnet 127.0.0.1 9222" gives:

```
Type:connect
V8-Version:3.30.33.16
Protocol-Version:1
Embedding-Host:CodeTools
Content-Length:0
```

Then enter:

```
Content-Length:46

{"seq":0,"type":"request","command":"version"}
```
I get no response from the debug agent.

Is this basic test valid?

Commented Unassigned: V8 Debug agent not functioning? [82]

$
0
0
A basic test using "telnet 127.0.0.1 9222" gives:

```
Type:connect
V8-Version:3.30.33.16
Protocol-Version:1
Embedding-Host:CodeTools
Content-Length:0
```

Then enter:

```
Content-Length:46

{"seq":0,"type":"request","command":"version"}
```
I get no response from the debug agent.

Is this basic test valid?

Comments: Hello! A couple of quick questions: 1. What telnet client are you using? 2. Is your host an ASP.NET web application? We can't reproduce this with ClearScriptConsole, but you appear to be using ClearScript 5.4.1, which has known issues with the V8 debug agent in ASP.NET environments. Try switching to ClearScript 5.4.2. Here's what the telnet exchange should look like: ``` Type:connect V8-Version:3.30.33.16 Protocol-Version:1 Embedding-Host:ClearScriptConsole Content-Length:0 Content-Length:46 {"seq":0,"type":"request","command":"version"}Content-Length:121 {"seq":1,"type":"response","command":"version","success":true,"body":{"V8Version":"3.30.33.16"},"refs":[],"running":true} ``` Good luck!

Commented Unassigned: V8 Debug agent not functioning? [82]

$
0
0
A basic test using "telnet 127.0.0.1 9222" gives:

```
Type:connect
V8-Version:3.30.33.16
Protocol-Version:1
Embedding-Host:CodeTools
Content-Length:0
```

Then enter:

```
Content-Length:46

{"seq":0,"type":"request","command":"version"}
```
I get no response from the debug agent.

Is this basic test valid?

Comments: Thanks for the quick response! I tried ClearScript 5.4.2 and had the same results. However I realised that my javascript was calling a blocking C# method which I expose from the host, and it was during this blocking when I was trying to connect to the debug agent. Of course the debug agent wouldn't respond. It's working great now thank you. Kind regards

New Post: ClearScript and JStat

$
0
0
Hi,

Is it unwise to use a javascript statistical library like JStat with ClearScript?

I'm trying to avoid using R, and since I'm already using ClearScript in my application I thought this might be a possibility..

http://jstat.github.io/

Commented Unassigned: V8 Debug agent not functioning? [82]

$
0
0
A basic test using "telnet 127.0.0.1 9222" gives:

```
Type:connect
V8-Version:3.30.33.16
Protocol-Version:1
Embedding-Host:CodeTools
Content-Length:0
```

Then enter:

```
Content-Length:46

{"seq":0,"type":"request","command":"version"}
```
I get no response from the debug agent.

Is this basic test valid?

Comments: Ah, right; V8's debugger requires access to the V8 runtime to process most commands. If the runtime is idle, running script, or stopped at a breakpoint, the debugger can process commands, but not when the runtime is locked and invoking a host method. Thanks for following up!
Viewing all 2297 articles
Browse latest View live




Latest Images