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

New Post: Date marshalling

$
0
0
Hi guillaume86,

You can add valueOf as an extension method:
publicstaticclass DateTimeExtensions {
    publicstaticdouble valueOf(this DateTime value) {
        return value.Ticks;
    }
}
and then:
engine.AddHostType(typeof(DateTime));
engine.AddHostType(typeof(DateTimeExtensions));
Console.WriteLine(engine.Evaluate("a = DateTime.Now; b = DateTime.Now; b >= a"));
Note that this only works on V8, as JScript doesn't follow the valueOf protocol for host objects.

Good luck!

New Post: Date marshalling

$
0
0
Hi,

I can't get it to work, do I need a version more recent that the latest nuget release? (actually I had already tried a class with a valueOf method and it didn't work either)
Your test case prints true but I suspects only because it's the same value and it doesn't actually use valueOf().

Do this one prints true for you?
            engine.AddHostType(typeof(DateTime));
            engine.AddHostType(typeof(DateTimeExtensions));
            Console.WriteLine(engine.Evaluate("a = new DateTime(2016, 1, 1); b = new DateTime(2016, 1, 2); b > a"));
In my tests valueOf never gets called.

New Post: Date marshalling

$
0
0
Hi again,

Yes, sorry, you need this fix. The hiding of built-in properties such as toString and valueOf is broken in the current release.

Cheers!

New Post: Date marshalling

$
0
0
Thanks a lot!

Le jeu. 3 mars 2016 à 19:57, ClearScript <[email removed]> a écrit :

From: ClearScript

Hi again,

Yes, sorry, you need this fix. The hiding of built-in properties such as toString andvalueOf is broken in the current release.

Cheers!

Read the full discussion online.

To add a post to this discussion, reply to this email ([email removed])

To start a new discussion for this project, email [email removed]

You are receiving this email because you subscribed to this discussion on CodePlex. You can unsubscribe on CodePlex.com.

Please note: Images and attachments will be removed from emails. Any posts to this discussion will also be available online at CodePlex.com

New Post: Event Listener Creation

$
0
0
Thanks for your reply, basically, I want to replicate this sample code on the script side. I did transported the code but I couldn´t get it to work.
    public static void ListenUDP()
    {
        _lst = new UdpClient(4567);
        var groupEp = new IPEndPoint(IPAddress.Any, 4567);          

        try
        {
            while (true)
            {
                Thread.Sleep(50);
                var receiveByteArray = _lst.Receive(ref groupEp);
                ClientIp = groupEp.Address.ToString();
                var receivedData = Encoding.ASCII.GetString(receiveByteArray, 0, receiveByteArray.Length);

                DoSomething(receivedData);
            }
        }
        catch (Exception ex)
        {
            Log.Log.LogError(ex.ToString());
        }
    }

New Post: Event Listener Creation

$
0
0
Hello!

Here's a JavaScript sample that works and is very similar to your C# code:
using (var engine = new V8ScriptEngine()) {
    engine.AddHostObject("host", new HostFunctions());
    engine.AddHostType(typeof(UdpClient));
    engine.AddHostType(typeof(IPEndPoint));
    engine.AddHostType(typeof(IPAddress));
    engine.AddHostType(typeof(Encoding));
    engine.AddHostType(typeof(Console));
    engine.Execute(@"
        _lst = new UdpClient(4567);
        var groupEp = host.newVar(new IPEndPoint(IPAddress.Any, 4567));
        try {
            while (true) {
                var bytes = _lst.Receive(groupEp.ref);
                Console.WriteLine(Encoding.ASCII.GetString(bytes, 0, bytes.Length));
            }
        }
        catch (ex) {
            Console.WriteLine(ex.hostException);
        }
    ");
}
Good luck!

New Post: ASP.NET Core migration

$
0
0
Hi,

Are you going to migrate CleaScript on .NET Core platform?

Regards,

Guillaume.

New Post: ASP.NET Core migration

$
0
0
Hi Guillaume,

We have no such effort underway. ClearScript's V8 bridge uses C++/CLI, so it can only work on Windows regardless of the runtime. And since the legacy script engines (JScript/VBScript) are also Windows-only, cross-platform runtime support isn't a priority, at least for now.

The best path toward a cross-platform ClearScript could be the recently open-sourced Chakra. This JavaScript engine is similar to V8 in performance and features, but with an API that's consumable directly from managed code. We're looking into the possibility of supporting Chakra in ClearScript.

Thanks!

New Post: Date marshalling

$
0
0
Sorry to bother you again, could you "release" a new version so that the Nuget maintainers can also push an update with correct version numbers?

Have a nice day.

Commented Unassigned: Cannot create a file when that file already exists [100]

$
0
0

Clearscript 5.3.11.0 return error "Cannot create a file when that file already exists".

My project is an Windows application in C#, framework 4.5.
In the application each 1/2 seconds is called :

VBScriptEngine engine = new VBScriptEngine();
foreach (ParsedItem pi in _parsedItems) engine.AddHostObject(pi.Id, pi);
engine.Dispose();

The application is run in multiple instance (20 applications contemporary).
Sometimes in the log I get error "Cannot create a file when that file already exists".


Comments: We have no way to reproduce this issue and have received no additional information in 10 days. Closing as Not Repro.

Closed Unassigned: Cannot create a file when that file already exists [100]

$
0
0

Clearscript 5.3.11.0 return error "Cannot create a file when that file already exists".

My project is an Windows application in C#, framework 4.5.
In the application each 1/2 seconds is called :

VBScriptEngine engine = new VBScriptEngine();
foreach (ParsedItem pi in _parsedItems) engine.AddHostObject(pi.Id, pi);
engine.Dispose();

The application is run in multiple instance (20 applications contemporary).
Sometimes in the log I get error "Cannot create a file when that file already exists".


New Post: Date marshalling

$
0
0
No bother at all. We're hoping to post Version 5.4.5 sometime this week. Thanks again!

Edited Issue: Event Listener Creation [102]

$
0
0
I´m trying to create a UDPClient from javascript but I cannot find the way to add the event to the object I´ve created on the javascript side and assign a callback function.

Can someone help me with some simple sample code of how I can accomplish this?..

Thanks.

Edited Issue: Cannot create a file when that file already exists [100]

$
0
0

Clearscript 5.3.11.0 return error "Cannot create a file when that file already exists".

My project is an Windows application in C#, framework 4.5.
In the application each 1/2 seconds is called :

VBScriptEngine engine = new VBScriptEngine();
foreach (ParsedItem pi in _parsedItems) engine.AddHostObject(pi.Id, pi);
engine.Dispose();

The application is run in multiple instance (20 applications contemporary).
Sometimes in the log I get error "Cannot create a file when that file already exists".


New Post: Event Listener Creation

$
0
0
Thank you for that!. The code worked just fine!. Every day happier to work with ClearScript!.

Released: ClearScript 5.4 (Oct 22, 2014)

$
0
0
5.4.5
  • Breaking Change: Added strongly-typed indexing support for IList<T>. Because IList<T> takes precedence over IList, array and list elements retrieved by index are now correctly type-restricted. Use the new propertyScriptEngine.DisableListIndexTypeRestriction to restore the previous behavior, orScriptEngine.DisableTypeRestriction to control type restriction globally.
  • Added V8ScriptEngine.SuppressExtensionMethodEnumeration (Issue #101).
  • Fixed native property hiding on V8 (Issue #98).
  • Fixed host method clobbering on V8.
  • Reduced V8 stack overflow detection false positives.
  • Added HostItemFlags.DirectAcces.
  • Added tests for bug fixes and new APIs.
  • Tested with V8 4.9.385.30.

5.4.4
  • Added fast data transfer between host arrays and JavaScript typed arrays (and other ArrayBuffer views) (Issue #83).
  • IEnumerable instances now supportES6 iteration andfor...of when exposed inV8ScriptEngine.
  • Added fully dynamic treatment for exposed IDispatchEx instances (Issue #96).
  • Fixed host member enumeration and deletion on JScript with Standards Mode (Issue #94).
  • Improved numeric argument conversion and matching (Issue #95).
  • Fixed nested termination behavior on V8.
  • Added tests for bug fixes and new APIs.
  • Tested with V8 4.7.80.25.

5.4.3
  • Added support for Visual Studio 2015.
  • Changed V8Update to use installed Python 2.x.
  • Fixed hangs in V8 proxy finalizers during script execution (Issue #86).
  • Fixed V8 weak handle callback context leak (Issue #90).
  • Fixed dynamic method invocation with value-typed arguments (Issue #89).
  • Improved V8ScriptEngine.Interrupt() latency and reliability.
  • Added tests for bug fixes.
  • Tested with V8 4.4.63.29.

5.4.2.1
  • Fixed unnecessary assembly table construction (Issue #84).

5.4.2
  • Updated ClearScriptBenchmarks to use SunSpider 1.0.2.
  • Host methods and delegates in V8ScriptEngine now supporttoFunction(), which creates a native JavaScript function wrapper.
  • Fixed syntax error reporting in nested WindowsScriptEngine invocations.
  • Added defensive code to tolerate IProcessDebugManager::AddApplication() failure (Issue #76).
  • Added ScriptEngine.AddHostType() overloads that derive the script item name from the type name.
  • Implemented host item data sharing and other optimizations, boosting memory efficiency in many scenarios.
  • Added default ScriptAccess settings at the type, assembly, and engine levels.
  • Enhanced support for default properties, fixing Issue #74.
  • Added IHostWindow and WindowsScriptEngine.HostWindow (Issue #73).
  • V8RuntimeConstraints limits are now specified inMiB. For compatibility with hosts that predate an inadvertent breaking change in Version 5.4.1, values greater than 1048576 (1TiB) are still interpreted as bytes.
  • Fixed V8 debug agent in ASP.NET and eliminated excessive thread usage (Issue #75).
  • Added ScriptMemberFlags.WrapNullResult, ScriptEngine.EnableNullResultWrapping, and HostFunctions.isNull() (Issue #72).
  • Added enforcement of restricted access to non-public accessors of public properties (Issue #71).
  • (Andrey Taritsyn) Switched assembly targets to .NET 4 Client Profile.
  • Added tests for bug fixes and new APIs.
  • Tested with V8 4.2.77.18.

5.4.1
  • Fixed several issues affecting GlobalMembers on V8.
  • Implemented a V8 debug agent to compensate for removed V8 API.
  • V8Update now fetches V8 source and dependencies from Git repositories.
  • Fixed V8 assembly unloading and patched V8 to tolerate redundant initialization (Issue #60).
  • Added ScriptEngine.EnableAutoHostVariables.
  • Fixed by-reference arguments to VBScript functions (Issue #58).
  • Removed support for Visual Studio 2012 (V8 build now requires at least Visual Studio 2013).
  • Added explicit loading of primary interop assemblies to fix Issue #68.
  • Added host exception marshaling for V8.
  • Fixed V8ScriptEngine crash when script code calls theHostObject constructor.
  • Fixed host item caching for host variables.
  • Added non-generic overloads of newArr() andfunc() to HostFunctions.
  • Added ScriptEngine.Current.
  • HostFunctions instances can now be exposed in multiple script engines.
  • Added a GetDynamicMemberNames() override toMetaScriptItem (Issue #64).
  • Fixed indexed property binding ambiguity for inherited interfaces (Issue #69).
  • Added tests for bug fixes and new APIs.
  • Tested with V8 3.30.33.16.

5.4.0
  • Added COM object projection (Issue #38):
    • New ScriptEngine methods: AddCOMObject() and AddCOMType().
    • New ExtendedHostFunctions methods: newComObj() and comType().
  • Improved performance and memory usage:
    • Host methods, events, and const/readonly fields are now cached as direct V8 object properties.
    • Added shared bind cache for improved performance and enhanced binder leak mitigation.
    • Made V8ScriptEngine.CollectGarbage() much more aggressive.
    • Switched to weak context/isolate bindings for V8 script objects and compiled scripts, fixingIssue #44.
    • Bypassed reflection for Windows script item property and method access, fixingIssue #47.
    • Added explicit disposal of cached V8 objects to fix Issue #48.
  • Enhanced support for legacy scripts:
    • Added null, decimal, and array marshaling options to WindowsScriptEngine.
    • Added ScriptEngine.UseReflectionBindFallback.
    • VBScript's For Each ... Next and JScript's Enumerator now operate on IEnumerable instances.
  • Other enhancements:
    • Added optional heap size monitoring to V8ScriptEngine andV8Runtime (experimental).
    • Added HostFunctions.tryCatch().
    • Added ScriptEngine.Invoke() and V8ScriptEngine.Execute(V8Script).
    • Added ScriptEngine.DisableTypeRestriction.
    • Enhanced error reporting for V8 assembly load failures (Issue #39).
    • V8Update now supports branched V8 revisions.
  • Miscellaneous fixes:
    • Added a V8 array buffer allocator, fixing Issue #46.
    • Overhauled ClearScriptV8 string usage to fix Issue #42 and improve performance.
    • Hardened ClearScriptV8 smart pointers.
    • Changed ActiveScript sites to return the current thread culture.
    • Added defensive code to make V8-related API objects resurrection-safe, fixingIssue #51.
    • Fixed exception when using WindowsScriptEngineFlags.EnableDebugging with no suitable script debugger installed (Issue #36).
  • Updates for breaking V8 API changes.
  • Added tests for bug fixes and new APIs.
  • Tested with V8 3.26.31.15.

Updated Release: ClearScript 5.4 (Oct 22, 2014)

$
0
0
5.4.5
  • Breaking Change: Added strongly-typed indexing support for IList<T>. Because IList<T> takes precedence over IList, array and list elements retrieved by index are now correctly type-restricted. Use the new property ScriptEngine.DisableListIndexTypeRestriction to restore the previous behavior, or ScriptEngine.DisableTypeRestriction to control type restriction globally.
  • Added V8ScriptEngine.SuppressExtensionMethodEnumeration (Issue #101).
  • Fixed native property hiding on V8 (Issue #98).
  • Fixed host method clobbering on V8.
  • Reduced V8 stack overflow detection false positives.
  • Added HostItemFlags.DirectAcces.
  • Added tests for bug fixes and new APIs.
  • Tested with V8 4.9.385.30.

5.4.4
  • Added fast data transfer between host arrays and JavaScript typed arrays (and other ArrayBuffer views) (Issue #83).
  • IEnumerable instances now support ES6 iteration and for...of when exposed in V8ScriptEngine.
  • Added fully dynamic treatment for exposed IDispatchEx instances (Issue #96).
  • Fixed host member enumeration and deletion on JScript with Standards Mode (Issue #94).
  • Improved numeric argument conversion and matching (Issue #95).
  • Fixed nested termination behavior on V8.
  • Added tests for bug fixes and new APIs.
  • Tested with V8 4.7.80.25.

5.4.3
  • Added support for Visual Studio 2015.
  • Changed V8Update to use installed Python 2.x.
  • Fixed hangs in V8 proxy finalizers during script execution (Issue #86).
  • Fixed V8 weak handle callback context leak (Issue #90).
  • Fixed dynamic method invocation with value-typed arguments (Issue #89).
  • Improved V8ScriptEngine.Interrupt() latency and reliability.
  • Added tests for bug fixes.
  • Tested with V8 4.4.63.29.

5.4.2.1
  • Fixed unnecessary assembly table construction (Issue #84).

5.4.2
  • Updated ClearScriptBenchmarks to use SunSpider 1.0.2.
  • Host methods and delegates in V8ScriptEngine now support toFunction(), which creates a native JavaScript function wrapper.
  • Fixed syntax error reporting in nested WindowsScriptEngine invocations.
  • Added defensive code to tolerate IProcessDebugManager::AddApplication() failure (Issue #76).
  • Added ScriptEngine.AddHostType() overloads that derive the script item name from the type name.
  • Implemented host item data sharing and other optimizations, boosting memory efficiency in many scenarios.
  • Added default ScriptAccess settings at the type, assembly, and engine levels.
  • Enhanced support for default properties, fixing Issue #74.
  • Added IHostWindow and WindowsScriptEngine.HostWindow (Issue #73).
  • V8RuntimeConstraints limits are now specified in MiB. For compatibility with hosts that predate an inadvertent breaking change in Version 5.4.1, values greater than 1048576 (1 TiB) are still interpreted as bytes.
  • Fixed V8 debug agent in ASP.NET and eliminated excessive thread usage (Issue #75).
  • Added ScriptMemberFlags.WrapNullResult, ScriptEngine.EnableNullResultWrapping, and HostFunctions.isNull() (Issue #72).
  • Added enforcement of restricted access to non-public accessors of public properties (Issue #71).
  • (Andrey Taritsyn) Switched assembly targets to .NET 4 Client Profile.
  • Added tests for bug fixes and new APIs.
  • Tested with V8 4.2.77.18.

5.4.1
  • Fixed several issues affecting GlobalMembers on V8.
  • Implemented a V8 debug agent to compensate for removed V8 API.
  • V8Update now fetches V8 source and dependencies from Git repositories.
  • Fixed V8 assembly unloading and patched V8 to tolerate redundant initialization (Issue #60).
  • Added ScriptEngine.EnableAutoHostVariables.
  • Fixed by-reference arguments to VBScript functions (Issue #58).
  • Removed support for Visual Studio 2012 (V8 build now requires at least Visual Studio 2013).
  • Added explicit loading of primary interop assemblies to fix Issue #68.
  • Added host exception marshaling for V8.
  • Fixed V8ScriptEngine crash when script code calls the HostObject constructor.
  • Fixed host item caching for host variables.
  • Added non-generic overloads of newArr() and func() to HostFunctions.
  • Added ScriptEngine.Current.
  • HostFunctions instances can now be exposed in multiple script engines.
  • Added a GetDynamicMemberNames() override to MetaScriptItem (Issue #64).
  • Fixed indexed property binding ambiguity for inherited interfaces (Issue #69).
  • Added tests for bug fixes and new APIs.
  • Tested with V8 3.30.33.16.

5.4.0
  • Added COM object projection (Issue #38):
    • New ScriptEngine methods: AddCOMObject() and AddCOMType().
    • New ExtendedHostFunctions methods: newComObj() and comType().
  • Improved performance and memory usage:
    • Host methods, events, and const/readonly fields are now cached as direct V8 object properties.
    • Added shared bind cache for improved performance and enhanced binder leak mitigation.
    • Made V8ScriptEngine.CollectGarbage() much more aggressive.
    • Switched to weak context/isolate bindings for V8 script objects and compiled scripts, fixing Issue #44.
    • Bypassed reflection for Windows script item property and method access, fixing Issue #47.
    • Added explicit disposal of cached V8 objects to fix Issue #48.
  • Enhanced support for legacy scripts:
    • Added null, decimal, and array marshaling options to WindowsScriptEngine.
    • Added ScriptEngine.UseReflectionBindFallback.
    • VBScript's For Each ... Next and JScript's Enumerator now operate on IEnumerable instances.
  • Other enhancements:
    • Added optional heap size monitoring to V8ScriptEngine and V8Runtime (experimental).
    • Added HostFunctions.tryCatch().
    • Added ScriptEngine.Invoke() and V8ScriptEngine.Execute(V8Script).
    • Added ScriptEngine.DisableTypeRestriction.
    • Enhanced error reporting for V8 assembly load failures (Issue #39).
    • V8Update now supports branched V8 revisions.
  • Miscellaneous fixes:
    • Added a V8 array buffer allocator, fixing Issue #46.
    • Overhauled ClearScriptV8 string usage to fix Issue #42 and improve performance.
    • Hardened ClearScriptV8 smart pointers.
    • Changed ActiveScript sites to return the current thread culture.
    • Added defensive code to make V8-related API objects resurrection-safe, fixing Issue #51.
    • Fixed exception when using WindowsScriptEngineFlags.EnableDebugging with no suitable script debugger installed (Issue #36).
  • Updates for breaking V8 API changes.
  • Added tests for bug fixes and new APIs.
  • Tested with V8 3.26.31.15.

Updated Wiki: Documentation

$
0
0

Documentation

To learn more about ClearScript:
  • Check out the ClearScript tutorial: [Word], [PDF].
  • Browse the ClearScript Library Reference: [Reference.chm]. Save this file before opening it. If you get a security warning when you open it, uncheck "Always ask before opening this file".
  • View the latest information in the ClearScript ReadMe.
  • Take a look at our latest Announcements.

Updated Wiki: Announcements

$
0
0

3/10/2016: Version 5.4.5 released.

View the release notes and download the source code here.

12/8/2015: Version 5.4.4 released.

View the release notes and download the source code here.

8/17/2015: Version 5.4.3 released.

View the release notes and download the source code here. Note: This release adds support for Visual Studio 2015 and updates the procedure for downloading and building V8. See the ClearScript ReadMe for the latest information.

6/30/2015: Version 5.4.2.1 released.

View the release notes and download the source code here. This is a bug fix release only.

5/10/2015: Version 5.4.2 released.

View the release notes and download the source code here.

2/8/2015: Version 5.4.1 released.

View the release notes and download the source code here. Note: This release removes support for Visual Studio 2012 and updates the procedure for downloading and building V8. See the ClearScript ReadMe for the latest information.

10/22/2014: ClearScript 5.4 released.

View the release notes and download the source code here.

1/16/2014: Version 5.3.11 released.

View the release notes and download the source code here.

11/28/2013: Version 5.3.10 released.

View the release notes and download the source code here.

10/29/2013: Version 5.3.9 released.

View the release notes and download the source code here.

10/14/2013: Version 5.3.8 released.

View the release notes and download the source code here.

8/22/2013: Version 5.3.7 released.

View the release notes and download the source code here.

8/14/2013: Version 5.3.6 released.

View the release notes and download the source code here.

8/2/2013: Version 5.3.5 released.

View the release notes and download the source code here.

7/10/2013: Version 5.3.4 released.

View the release notes and download the source code here.

7/2/2013: Version 5.3.3 released.

View the release notes and download the source code here.

6/6/2013: Version 5.3.2 released.

View the release notes and download the source code here. Due to issues with several recent V8 trunk releases (build failures, breaking API changes, etc.), and because more breaking changes are coming soon, this release modifies V8Update so that it fetches a tested, known-good V8 revision by default. See the ClearScript ReadMe for more information.

5/31/2013: Version 5.3.1 released.

View the release notes and download the source code here.

5/21/2013: ClearScript 5.3 released.

View the release notes and download the source code here.

5/15/2013: Version 5.2.2 released.

View the release notes and download the source code here. This release addresses the build issue reported yesterday and can be used with the latest V8 version. Here's how to update your copy of V8:
C:\ClearScript> set V8REV=
C:\ClearScript> V8Update

5/14/2013: ClearScript build failure due to API deprecation in V8 3.19.1.

We are aware of a ClearScript build issue with the latest version of V8. Until this issue is resolved we recommend that you explicitly use V8 3.19.0:
C:\ClearScript> set V8REV=14604
C:\ClearScript> V8Update

5/2/2013: Version 5.2.1 released.

View the release notes and download the source code here.

4/18/2013: V8Update failure resolved by V8 3.18.1.

The V8Update issue reported yesterday has been fixed by a new version of V8 released today. Here's how to update to the latest V8 version:
C:\ClearScript> set V8REV=
C:\ClearScript> V8Update

4/17/2013: V8Update failure with V8 3.18.0.

We are aware of a V8Update issue with the latest version of V8. Until this issue is resolved we recommend that you explicitly use V8 3.17.16:
C:\ClearScript> set V8REV=14138
C:\ClearScript> V8Update

3/27/2013: ClearScript 5.2 released.

View the release notes and download the source code here.

3/8/2013: Version 5.1.3 released.

View the release notes and download the source code here.

3/4/2013: V8Update failure resolved by V8 3.17.7.

The V8Update issue reported earlier has been fixed by a new version of V8 released today. Here's how to update to the latest V8 version:
C:\ClearScript> set V8REV=
C:\ClearScript> V8Update

3/4/2013: V8Update failure with V8 3.17.6.

We are aware of a V8Update issue with the latest version of V8. The issue affects the "Building 64-bit V8" step. The V8 team appears to have already submitted a fix, but the fix has not yet been merged into the trunk. In the meantime, we recommend that you explicitly use V8 3.17.5:
C:\ClearScript> set V8REV=13745
C:\ClearScript> V8Update

Updated Wiki: Home

$
0
0
InfoIcon.jpgVersion 5.4.5 released. More...

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.JavaScript;
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);

    // read a JavaScript typed array
    engine.Execute("values = new Int32Array([1, 2, 3, 4, 5])");
    var values = (ITypedArray<int>)engine.Script.values;
    Console.WriteLine(string.Join(", ", values.ToArray()));
}
Viewing all 2297 articles
Browse latest View live




Latest Images