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

Commented Issue: ClearScript hangs application due to aggressive assembly loads in AssemblyHelpers.BuildAssemblyTable [84]

$
0
0
An application I wrote was using ClearScript successfully locally. However, when I deployed the application to one of our application servers, the application would hang on start up. I captured a dump and used WinDbg to find that ClearScript was within AssemblyHelpers.BuildAssemblyTable().

This is a private method that is called within the static constructor of AssemblyHelpers. It gets the .NET framework install directory from the registry, then enumerates every DLL within that directory and all subdirectories and attempts to load it as an assembly.

I cannot imagine why you would need to load literally every single assembly on the machine...

But the main problem with this is that the .NET install directory includes "Temporary ASP.NET Files", which contains assemblies generated from views, templates, etc, and often times copies of their dependencies.

The app server where the hang was occurring has been in production for a long time, and every deployment we make to it ends up creating an additional folder in the Temporary ASP.NET Files directory. There was in fact many gigabytes worth of DLLs in this directory.

So ClearScript spun its wheels trying to enumerate and load over 100,000 DLLs! Out of curiosity I left it running overnight -- it actually finished after several 6 or 7 hours.

I have cleaned up the temp directory, but this isn't a solution. The problem will only come back. Every time we deploy, we're creating more files in that directory, which will progressively slow down the app start up time as ClearScript will have more and more assemblies to load.

Please reconsider the approach. Loading an assembly is not only expensive in terms of time and RAM, it can actually cause negative side effects. I can't imagine why loading assemblies so aggressively is necessary. If it's an issue with discovering 'scriptable' types, consider requiring the caller to provide the list of scriptable types via a call, or to annotate their assembly with the list. Something other than this, pretty please ;) I love ClearScript and would love to continue using it. But I am using this in a business application that is relied upon by thousands of users, and I can't have the potential and unpredictable side effects of random assembly loads, nor the long startup time it's causing.



Comments: The source code fix is [now available](https://clearscript.codeplex.com/SourceControl/changeset/8baf6a9ee6215bb9c35621ec75a1a7aec409400d). Please let us know if it doesn't work for you. Thanks again!

Edited Issue: [FIXED] ClearScript hangs application due to aggressive assembly loads in AssemblyHelpers.BuildAssemblyTable [84]

$
0
0
An application I wrote was using ClearScript successfully locally. However, when I deployed the application to one of our application servers, the application would hang on start up. I captured a dump and used WinDbg to find that ClearScript was within AssemblyHelpers.BuildAssemblyTable().

This is a private method that is called within the static constructor of AssemblyHelpers. It gets the .NET framework install directory from the registry, then enumerates every DLL within that directory and all subdirectories and attempts to load it as an assembly.

I cannot imagine why you would need to load literally every single assembly on the machine...

But the main problem with this is that the .NET install directory includes "Temporary ASP.NET Files", which contains assemblies generated from views, templates, etc, and often times copies of their dependencies.

The app server where the hang was occurring has been in production for a long time, and every deployment we make to it ends up creating an additional folder in the Temporary ASP.NET Files directory. There was in fact many gigabytes worth of DLLs in this directory.

So ClearScript spun its wheels trying to enumerate and load over 100,000 DLLs! Out of curiosity I left it running overnight -- it actually finished after several 6 or 7 hours.

I have cleaned up the temp directory, but this isn't a solution. The problem will only come back. Every time we deploy, we're creating more files in that directory, which will progressively slow down the app start up time as ClearScript will have more and more assemblies to load.

Please reconsider the approach. Loading an assembly is not only expensive in terms of time and RAM, it can actually cause negative side effects. I can't imagine why loading assemblies so aggressively is necessary. If it's an issue with discovering 'scriptable' types, consider requiring the caller to provide the list of scriptable types via a call, or to annotate their assembly with the list. Something other than this, pretty please ;) I love ClearScript and would love to continue using it. But I am using this in a business application that is relied upon by thousands of users, and I can't have the potential and unpredictable side effects of random assembly loads, nor the long startup time it's causing.



New Post: Fetch all the Variables and their values

$
0
0
I am implementing a debugger for Vbscript 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;
public static JScriptEngine engine1;

dynamic ome = engine.Evaluate("me");

engine1.Evaluate("Enum=function(x){this.x=new Array();for (var i in x) {this.x[i]=i};return this.x}");
        dynamic ojas = Script.engine1.Evaluate("this");
dynamic x = ojas.Enum(ome);


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


Please help!

New Post: Fetch all the Variables and their values

$
0
0
Hello!

Unfortunately there's no simple way to enumerate VBScript local variables. However, like most Windows Script engines, VBScript plugs into the Windows debugging infrastructure and therefore supports debugging via Visual Studio and other debuggers. Creating a custom debugger for this framework is possible, but it's a large undertaking, and unfortunately the interfaces are not well documented. You can find an overview here.

By the way, there's no need to use JavaScript to enumerate the properties of a VBScript object. This is something ClearScript lets you do directly from .NET:
dynamic ome = engine.Evaluate("me"); // or engine.Scriptforeach (var name in ome.GetDynamicMemberNames())
    Console.WriteLine("{0}: {1}", name, ome[name]);
Good luck!

Released: ClearScript 5.4 (Oct 22, 2014)

$
0
0
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.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.

Edited Issue: ClearScript hangs application due to aggressive assembly loads in AssemblyHelpers.BuildAssemblyTable [84]

$
0
0
An application I wrote was using ClearScript successfully locally. However, when I deployed the application to one of our application servers, the application would hang on start up. I captured a dump and used WinDbg to find that ClearScript was within AssemblyHelpers.BuildAssemblyTable().

This is a private method that is called within the static constructor of AssemblyHelpers. It gets the .NET framework install directory from the registry, then enumerates every DLL within that directory and all subdirectories and attempts to load it as an assembly.

I cannot imagine why you would need to load literally every single assembly on the machine...

But the main problem with this is that the .NET install directory includes "Temporary ASP.NET Files", which contains assemblies generated from views, templates, etc, and often times copies of their dependencies.

The app server where the hang was occurring has been in production for a long time, and every deployment we make to it ends up creating an additional folder in the Temporary ASP.NET Files directory. There was in fact many gigabytes worth of DLLs in this directory.

So ClearScript spun its wheels trying to enumerate and load over 100,000 DLLs! Out of curiosity I left it running overnight -- it actually finished after several 6 or 7 hours.

I have cleaned up the temp directory, but this isn't a solution. The problem will only come back. Every time we deploy, we're creating more files in that directory, which will progressively slow down the app start up time as ClearScript will have more and more assemblies to load.

Please reconsider the approach. Loading an assembly is not only expensive in terms of time and RAM, it can actually cause negative side effects. I can't imagine why loading assemblies so aggressively is necessary. If it's an issue with discovering 'scriptable' types, consider requiring the caller to provide the list of scriptable types via a call, or to annotate their assembly with the list. Something other than this, pretty please ;) I love ClearScript and would love to continue using it. But I am using this in a business application that is relied upon by thousands of users, and I can't have the potential and unpredictable side effects of random assembly loads, nor the long startup time it's causing.



Commented Issue: ClearScript hangs application due to aggressive assembly loads in AssemblyHelpers.BuildAssemblyTable [84]

$
0
0
An application I wrote was using ClearScript successfully locally. However, when I deployed the application to one of our application servers, the application would hang on start up. I captured a dump and used WinDbg to find that ClearScript was within AssemblyHelpers.BuildAssemblyTable().

This is a private method that is called within the static constructor of AssemblyHelpers. It gets the .NET framework install directory from the registry, then enumerates every DLL within that directory and all subdirectories and attempts to load it as an assembly.

I cannot imagine why you would need to load literally every single assembly on the machine...

But the main problem with this is that the .NET install directory includes "Temporary ASP.NET Files", which contains assemblies generated from views, templates, etc, and often times copies of their dependencies.

The app server where the hang was occurring has been in production for a long time, and every deployment we make to it ends up creating an additional folder in the Temporary ASP.NET Files directory. There was in fact many gigabytes worth of DLLs in this directory.

So ClearScript spun its wheels trying to enumerate and load over 100,000 DLLs! Out of curiosity I left it running overnight -- it actually finished after several 6 or 7 hours.

I have cleaned up the temp directory, but this isn't a solution. The problem will only come back. Every time we deploy, we're creating more files in that directory, which will progressively slow down the app start up time as ClearScript will have more and more assemblies to load.

Please reconsider the approach. Loading an assembly is not only expensive in terms of time and RAM, it can actually cause negative side effects. I can't imagine why loading assemblies so aggressively is necessary. If it's an issue with discovering 'scriptable' types, consider requiring the caller to provide the list of scriptable types via a call, or to annotate their assembly with the list. Something other than this, pretty please ;) I love ClearScript and would love to continue using it. But I am using this in a business application that is relied upon by thousands of users, and I can't have the potential and unpredictable side effects of random assembly loads, nor the long startup time it's causing.



Comments: Fixed in [Version 5.4.2.1](https://clearscript.codeplex.com/SourceControl/changeset/8baf6a9ee6215bb9c35621ec75a1a7aec409400d).

Updated Wiki: Announcements

$
0
0

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.2.1 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.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);
}

New Post: Fetch all the Variables and their values

$
0
0
Thanks for the reply.

So can you please suggest me a way to have variables in Microsoft Script Debugger and how do i run the script in debug mode?

much Thanks!

New Post: Fetch all the Variables and their values

$
0
0
Hi again,

You can enable script debugging in your VBScript instances by passing WindowsScriptEngineFlags.EnableDebugging to the VBScriptEngine constructor. You should then be able to attach Visual Studio or another debugger to your running application for script debugging.

Another way to attach a debugger is to insert a VBScript stop statement somewhere in the script code. When VBScript executes this statement, a dialog will appear giving you the opportunity to launch or attach a script debugger paused at that point in the script.

Good luck!

Commented Issue: ClearScript hangs application due to aggressive assembly loads in AssemblyHelpers.BuildAssemblyTable [84]

$
0
0
An application I wrote was using ClearScript successfully locally. However, when I deployed the application to one of our application servers, the application would hang on start up. I captured a dump and used WinDbg to find that ClearScript was within AssemblyHelpers.BuildAssemblyTable().

This is a private method that is called within the static constructor of AssemblyHelpers. It gets the .NET framework install directory from the registry, then enumerates every DLL within that directory and all subdirectories and attempts to load it as an assembly.

I cannot imagine why you would need to load literally every single assembly on the machine...

But the main problem with this is that the .NET install directory includes "Temporary ASP.NET Files", which contains assemblies generated from views, templates, etc, and often times copies of their dependencies.

The app server where the hang was occurring has been in production for a long time, and every deployment we make to it ends up creating an additional folder in the Temporary ASP.NET Files directory. There was in fact many gigabytes worth of DLLs in this directory.

So ClearScript spun its wheels trying to enumerate and load over 100,000 DLLs! Out of curiosity I left it running overnight -- it actually finished after several 6 or 7 hours.

I have cleaned up the temp directory, but this isn't a solution. The problem will only come back. Every time we deploy, we're creating more files in that directory, which will progressively slow down the app start up time as ClearScript will have more and more assemblies to load.

Please reconsider the approach. Loading an assembly is not only expensive in terms of time and RAM, it can actually cause negative side effects. I can't imagine why loading assemblies so aggressively is necessary. If it's an issue with discovering 'scriptable' types, consider requiring the caller to provide the list of scriptable types via a call, or to annotate their assembly with the list. Something other than this, pretty please ;) I love ClearScript and would love to continue using it. But I am using this in a business application that is relied upon by thousands of users, and I can't have the potential and unpredictable side effects of random assembly loads, nor the long startup time it's causing.



Comments: Sorry for the delay on this, but the fix seems great. Thanks for the super fast response on this, very impressed. Any chance the new version is going to be published to nuget?

New Post: Passing DateTime from c# to javascript function

$
0
0
Hi!

I want to pass DateTime from C# code to javascript function and use it as javascript Date object
my sample code :
V8ScriptEngine engine = new V8ScriptEngine();
engine.Execute("function my_func(props){ var m_date  = props[\"my_date\"]; var m_code = props[\"my_code\"];  var yeay = m_date.getFullYear(); }");
PropertyBag properties = new PropertyBag();
HostFunctions hostObj = new HostFunctions();
hostObj.setProperty(properties, "my_code", 20);
hostObj.setProperty(properties, "my_date", DateTime.Now);
dynamic result = engine.Script["my_func"](properties);
An exception was thrown: TypeError: m_date.getFullYear is not a function

How can I fix it ?

kind regard,

Commented Issue: Fatal error in heap setup, Allocation failed - process out of memory [44]

$
0
0
Hi,

While investigating some memory related issues in my application, I managed to reproduce what seems to be a problem. The following minimal application terminates on my PC after ~50 cycles and prints the following to console:

```
#
# Fatal error in heap setup
# Allocation failed - process out of memory
#
```

```
class Program
{
static void Main(string[] args)
{
for (int i = 0; i < 1000; i++)
{
using (V8ScriptEngine engine = new V8ScriptEngine())
{
Console.WriteLine("Created engine #{0}", i);
engine.Execute("function zz(){}");
var tmp = engine.Evaluate("zz");
}
}
}
}
```


Strangely, the memory usage doesn't seem high when it terminates.

I used both a Nuget package, and a manually built latest ClearScript + V8 with same results.

Any help will be greatly appreciated.
Thanks in advance again,
Ron

Comments: We had the same problem, starting a pool of 100 V8 engines (not disposing, having them all in memory at once).. it broke at 58 or 59. Switching to a 64 bit application solved the issue :)

New Post: Passing DateTime from c# to javascript function

$
0
0
Greetings!

As you've noticed, ClearScript doesn't automatically convert DateTime instances into JavaScript dates; such conversion is lossy and not always desirable. However, because it's often useful, we recommend the following.

First, here's a general-purpose class for lazily evaluating a JavaScript expression and caching the result:
publicclass CachedJsValue {
    privateclass Holder { publicobject Value; }
    privatereadonly ConditionalWeakTable<ScriptEngine, Holder> table = new ConditionalWeakTable<ScriptEngine, Holder>();
    privatereadonlystring expression;
    public CachedJsValue(string expression) {
        this.expression = "(" + expression + ").valueOf()";
    }
    publicobject Get(ScriptEngine engine) {
        var holder = table.GetOrCreateValue(engine);
        if (holder.Value == null)
            Interlocked.CompareExchange(ref holder.Value, engine.Evaluate(expression), null);
        return holder.Value;
    }
    publicdynamic GetDynamic(ScriptEngine engine) {
        return Get(engine);
    }
}
And here's a class that uses it to define a ToJsDate extension method for DateTime:
publicstaticclass DateTimeScriptExtensions {
    privatestaticreadonly CachedJsValue createDateFunc = new CachedJsValue(@"
        function (y, m, d, h, min, s, ms) {
            return new Date(y, m, d, h, min, s, ms);
        }
    "); 
    publicstaticobject ToJsDate(this DateTime dt, ScriptEngine engine) {
        return createDateFunc.GetDynamic(engine)(
            dt.Year, dt.Month - 1, dt.Day,
            dt.Hour, dt.Minute, dt.Second, dt.Millisecond
        );
    }
}
Finally, your sample code can look like this (with a few tweaks and recommended simplifications):
var engine = new V8ScriptEngine();
engine.Execute(@"
    function my_func(props) {
        var m_date = props.my_date;
        var m_code = props.my_code;
        var yeay = m_date.getFullYear();
        return yeay;
    }
");
var properties = new PropertyBag();
properties["my_code"] = 20;
properties["my_date"] = DateTime.Now.ToJsDate(engine);
Console.WriteLine(engine.Script.my_func(properties));
Good luck!

Commented Issue: ClearScript hangs application due to aggressive assembly loads in AssemblyHelpers.BuildAssemblyTable [84]

$
0
0
An application I wrote was using ClearScript successfully locally. However, when I deployed the application to one of our application servers, the application would hang on start up. I captured a dump and used WinDbg to find that ClearScript was within AssemblyHelpers.BuildAssemblyTable().

This is a private method that is called within the static constructor of AssemblyHelpers. It gets the .NET framework install directory from the registry, then enumerates every DLL within that directory and all subdirectories and attempts to load it as an assembly.

I cannot imagine why you would need to load literally every single assembly on the machine...

But the main problem with this is that the .NET install directory includes "Temporary ASP.NET Files", which contains assemblies generated from views, templates, etc, and often times copies of their dependencies.

The app server where the hang was occurring has been in production for a long time, and every deployment we make to it ends up creating an additional folder in the Temporary ASP.NET Files directory. There was in fact many gigabytes worth of DLLs in this directory.

So ClearScript spun its wheels trying to enumerate and load over 100,000 DLLs! Out of curiosity I left it running overnight -- it actually finished after several 6 or 7 hours.

I have cleaned up the temp directory, but this isn't a solution. The problem will only come back. Every time we deploy, we're creating more files in that directory, which will progressively slow down the app start up time as ClearScript will have more and more assemblies to load.

Please reconsider the approach. Loading an assembly is not only expensive in terms of time and RAM, it can actually cause negative side effects. I can't imagine why loading assemblies so aggressively is necessary. If it's an issue with discovering 'scriptable' types, consider requiring the caller to provide the list of scriptable types via a call, or to annotate their assembly with the list. Something other than this, pretty please ;) I love ClearScript and would love to continue using it. But I am using this in a business application that is relied upon by thousands of users, and I can't have the potential and unpredictable side effects of random assembly loads, nor the long startup time it's causing.



Comments: Thank you very much for your help! Sorry, we don't provide ClearScript binaries. For questions about specific NuGet packages, please contact the package owners.

New Post: Passing DateTime from c# to javascript function

$
0
0
Hi!

Thank you for the solution,

So, suppose that my fonction return javascript Date object, and I want to convert it to DateTime object (c#) :
var engine = new V8ScriptEngine();
engine.Execute(@"
    function my_func(props) {
                    var m_date = props.my_date;
                    var m_code = props.my_code;
                    var nextMonth = m_date.getMonth() + 1;
                    m_date.setMonth(nextMonth);
                    return  m_date;
                }
");
var properties = new PropertyBag();
properties["my_code"] = 20;
properties["my_date"] = DateTime.Now.ToJsDate(engine);
dynamic result = engine.Script.my_func(properties);
var  nextMonth = new DateTime(result.getFullYear(), result.getMonth() + 1, result.getDate(), result.getHours(), result.getMinutes(), result.getSeconds());
Is this is a good approach? or Is there an alternative way?

thanks in advance!

kind regard,

New Post: Passing DateTime from c# to javascript function

$
0
0
Hi again,

Your approach uses several calls into script code to convert a single date. That could perform acceptably, but you might get better performance by minimizing the number of trips across the host-to-script boundary. Consider something like this:
dynamic jsDate = engine.Evaluate("new Date()");
var dt = DateTime.Parse(jsDate.toJSON());
Cheers!

New Post: US-CERT: Vulnerability in the V8 JavaScript engine...

$
0
0
There was a recent US-CERT alert in regards to V8 vulnerability found in applications using node.js and io.js, which is followed with updates to those platforms. Brief details of it could be found here: https://www.us-cert.gov/ncas/current-activity/2015/07/06/Security-Updates-Nodejs-and-iojs (read blog links in the article above for more info).

Is this something that ClearScript team is aware of? And if so, is there a preventive measure for it in the ClearScript API or not? I'm not quite sure whether Google's V8 team have had any chance to "fix" it on their side.

Thanks,
Max
Viewing all 2297 articles
Browse latest View live


Latest Images