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

New Post: Implementing Vbscript libraries

$
0
0
By Vbscript libraries i mean a file having a collection of Vbscript Functions and SubRoutines.

Consider the following file setup:

Driver File:
Call Func1
Call Func 2

Library File1:
Function Func1
Some code
End Function

Library File2:
Function Func2
Some code
End Function


Right now i am appending all the code in both library 1 and library2 with Driver file before having them to execute.

Can you please suggest the best way to add vbscript libarary.
As i would also need to implement stacktrace in reports where the location of the code calling will also be reported

New Post: Fetch all the Variables and their values

New Post: Implementing Vbscript libraries

$
0
0
Greetings!

You can execute as many scripts as you'd like within a given engine instance, so how you organize your script code is up to you. Each script can install procedures, functions, classes, etc. You might also be able to design something like RequireJS for VBScript if you're looking for a more robust, on-demand module system.

As for stack traces, ClearScript provides ScriptEngine.GetStackTrace(), but debugging must be enabled for it to work.

Good luck!

Created Unassigned: V8 debugging host is silent [85]

$
0
0
I have a similar issue as was described by one member in June 10: I cannot connect to V8 host to debug some code.

I launch the application with _V8ScriptEngineFlags.EnableDebugging_ flag. When I connect with telnet/putty to endpoint "127.0.0.1 9222", I get nothing, no "hello" message. The port is opened, I can see that with "netstat"; so the host is listenining. When I use Eclipse to connect to Standalone V8 VM, I get "Timed out waiting for handshake" error.

I use ClearScript 4.5.2 version. Any advice?

Thanks,
Garbielius

New Post: A procedure imported by 'ClearScriptV8-64.dll' could not be loaded.

$
0
0
Hey scuty - I know this was a year ago but can you elaborate on exactly what fixed this for you?

Thanks

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

$
0
0
Hi Max,

We were not aware of this issue, but presumably the V8 team is.

In any case, our normal procedure is to pair each ClearScript release with the latest stable version of V8 on Windows as indicated here. The stable V8 versions are supported and receive security fixes as long as they remain in use and continue to be listed on that site. Bug fix releases on the stable branch should work with ClearScript, but you'll have to build them manually, overriding V8Update's compatibility warning.

All that having been said, ClearScript's latest release is paired with V8 4.2.77, which is no longer being updated. Although the latest version (.21) is newer than the one we tested, it doesn't appear to have the security fix.

All we can recommend at this time is that you try using a newer V8 branch or apply the Node.js or io.js patches to V8 4.2.77. The next ClearScript release will be paired with a new V8 version that should contain the fix.

Thanks, and good luck!

Commented Unassigned: V8 debugging host is silent [85]

$
0
0
I have a similar issue as was described by one member in June 10: I cannot connect to V8 host to debug some code.

I launch the application with _V8ScriptEngineFlags.EnableDebugging_ flag. When I connect with telnet/putty to endpoint "127.0.0.1 9222", I get nothing, no "hello" message. The port is opened, I can see that with "netstat"; so the host is listenining. When I use Eclipse to connect to Standalone V8 VM, I get "Timed out waiting for handshake" error.

I use ClearScript 4.5.2 version. Any advice?

Thanks,
Garbielius
Comments: Hello Gabrielius, When you connect to the correct port, you should see a response like this: ``` Type:connect V8-Version:4.2.77.18 Protocol-Version:1 Embedding-Host:ClearScriptConsole Content-Length:0 ``` If you're not seeing that, and you can confirm that your application is listening on the port, then it's likely that a firewall or other security software is blocking the connection. Can you connect to other local services? Thanks!

New Post: A procedure imported by 'ClearScriptV8-64.dll' could not be loaded.

$
0
0
Do you still need help with this?

New Post: How to exit the vbscript code at runtime

$
0
0
Hi,

As we are able to exit the vbscript at runtime in Windows scripting Host by using:
WScript.Quit

How can we exit the script at run time in clearscript?

Regards
Jaskaran

New Post: How to exit the vbscript code at runtime

$
0
0
Hi Jaskaran,

The WScript.Quit method simply exits the process, and you can easily expose a similar API with ClearScript:
engine.Script.Quit = new Action<int>(Environment.Exit);
On the other hand, if you're looking for a way to terminate the current script without exiting the process, you can call ScriptEngine.Interrupt():
engine.Script.Quit = new Action(() => ScriptEngine.Current.Interrupt());
Note that doing so will generate a ScriptInterruptedException that you'll have to catch.

Another possibility might be to have your Quit API throw a custom exception. The problem there is that the script can disable error propagation via On Error.

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

New Post: How to exit the vbscript code at runtime

$
0
0
Thanks for the reply.

Yes, I am trying to terminate the current script without exiting the process.

While using ScriptEngine.Interrupt(): a popup with following message appears:
"Script execution interrupted by host"

I want to terminate the script silently without displaying any popup.

Is this possible?

Regards
Jaskaran

New Post: How to exit the vbscript code at runtime

$
0
0
Hi again,

It sounds like you're letting the ScriptInterruptedException propagate out to a handler that displays the error message in a popup. To suppress that behavior, simply catch the exception:
engine.Script.Quit = new Action(() => ScriptEngine.Current.Interrupt());
try {
    engine.Execute(codeThatCallsQuit);
}
catch (ScriptInterruptedException) {
}
Cheers!

New Post: How to exit the vbscript code at runtime

$
0
0
Hi,

Unfortunately i am not able to suppress the popup displaying "Script execution interrupted by host" :

I have tried following codes:

Code1:
        try
        {
           Script.engine.Interrupt(); 

        }
        catch (ScriptInterruptedException)
        {
        }

Code2:
(Unable to compile : Says "Microsoft.ClearScript.ScriptEngine does not contain defination for current)
engine.Script.Quit = new Action(() => ScriptEngine.Current.Interrupt());
try {
engine.Execute(util.Quit);
}
catch (ScriptInterruptedException) {
}

please help!

New Post: How to exit the vbscript code at runtime

$
0
0
Hi Jaskaran,

If ScriptEngine.Current is undefined, you're using a relatively old version of ClearScript, and we recommend that you switch to the latest version.

In any case, try the following in a console application:
engine.Script.Quit = new Action(() => engine.Interrupt());
engine.AddHostType("Console", typeof(Console));

try {
    engine.Execute(@"
        call Console.WriteLine(""Before"")
        call Quit
        call Console.WriteLine(""After (shouldn't get here)"")
    ");
}
catch (ScriptInterruptedException) {
}
This code should work with older versions of ClearScript.

Thanks!

New Post: How to exit the vbscript code at runtime

$
0
0
Thanks for the solution.
Also i have updated the clearscript version.

New Post: memory leak when passing javascript object to managed code

$
0
0
I am seeing a memory leak when passing a javascript object to a managed code function. I am using the latest nuget clearscript V8. Please see below for the code that reproduces this issue.

Program.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Microsoft.ClearScript;
using Microsoft.ClearScript.V8;

namespace ClearScriptMemoryLeak
{
    public class Program
    {
        protected V8ScriptEngine m_engine;
        public Program(V8ScriptEngine engine)
        {
            m_engine = engine;
        }

        public void doSomething(dynamic foo)
        {
        }

        public void garbageCollect()
        {
            V8RuntimeHeapInfo beforeInfo = m_engine.GetRuntimeHeapInfo();
            
            m_engine.CollectGarbage(true);
            V8RuntimeHeapInfo afterInfo = m_engine.GetRuntimeHeapInfo();

            Console.WriteLine("garbageCollect: memstats (before/after): used: " + beforeInfo.UsedHeapSize + "/" + afterInfo.UsedHeapSize);
        }

        public static String loadScript(String filePath)
        {
            StringBuilder builder = new StringBuilder();
            FileInfo fileInfo = new FileInfo(filePath);

            using (StreamReader sr = fileInfo.OpenText())
            {
                String s = "";
                while ((s = sr.ReadLine()) != null)
                {
                    builder.AppendLine(s);
                }
            }
            return builder.ToString();
        }

        static void Main(string[] args)
        {
            V8ScriptEngine engine = new V8ScriptEngine(V8ScriptEngineFlags.EnableDebugging);
            Program p = new Program(engine);
            
            engine.AddHostObject("nativeBridge", p);

            engine.Execute(loadScript(args[0]));
        }
    }
}
MemLeak.js
var count = 0;
var obj;
while (true) {
    if (++count % 10000 == 0) {
        nativeBridge.garbageCollect();
    }
    obj = {
        a: "b",
        c: "d"
    };
    nativeBridge.doSomething(obj);
}
Running the above javascript will eventually crash with the following exception:
garbageCollect: memstats (before/after): used: 227850008/227529964
garbageCollect: memstats (before/after): used: 228050008/227729964
garbageCollect: memstats (before/after): used: 228250008/227929964
garbageCollect: memstats (before/after): used: 228450008/228129964

Unhandled Exception: Microsoft.ClearScript.ScriptEngineException: Error: Exception of type 'System.OutOfMemoryException' was thrown. ---> System.OutOfMemoryException: Exception of type 'System.OutOfMemoryException' was thrown.
   at Microsoft.ClearScript.HostItem.AdjustInvokeFlags(BindingFlags& invokeFlags)
   at Microsoft.ClearScript.HostItem.InvokeMember(String name, BindingFlags invokeFlags, Object[] args, Object[] bindArgs, CultureInfo culture, Boolean bypassTunneling, Boolean& isCacheable)
   at Microsoft.ClearScript.HostMethod.TryInvoke(IHostInvokeContext context, BindingFlags invokeFlags, Object[] args, Object[] bindArgs, Object& result)
   at Microsoft.ClearScript.Util.InvokeHelpers.TryInvokeObject(IHostInvokeContext context, Object target, BindingFlags invokeFlags, Object[] args, Object[] bindArgs, Boolean tryDynamic, Object& result)
   at Microsoft.ClearScript.HostItem.InvokeHostMember(String name, BindingFlags invokeFlags, Object[] args, Object[] bindArgs, CultureInfo culture, Boolean& isCacheable)
   at Microsoft.ClearScript.HostItem.InvokeMember(String name, BindingFlags invokeFlags, Object[] args, Object[] bindArgs, CultureInfo culture, Boolean bypassTunneling, Boolean& isCacheable)
   at Microsoft.ClearScript.HostItem.<>c__DisplayClass4b.<InvokeReflectMember>b__4a()
   at Microsoft.ClearScript.ScriptEngine.HostInvoke[T](Func`1 func)
   at Microsoft.ClearScript.HostItem.HostInvoke[T](Func`1 func)
   at Microsoft.ClearScript.HostItem.InvokeReflectMember(String name, BindingFlags invokeFlags, Object[] wrappedArgs, CultureInfo culture, String[] namedParams, Boolean& isCacheable)
   at Microsoft.ClearScript.HostItem.System.Reflection.IReflect.InvokeMember(String name, BindingFlags invokeFlags, Binder binder, Object invokeTarget, Object[] wrappedArgs, ParameterModifier[] modifiers, CultureInfo culture, String[] namedParams)
   at Microsoft.ClearScript.HostItem.Microsoft.ClearScript.Util.IDynamic.Invoke(Object[] args, Boolean asConstructor)
   at HostObjectHelpers.Invoke(V8Value* , Void* pvObject, vector<V8Value\,std::allocator<V8Value> >* args, Boolean asConstructor)
   --- End of inner exception stack trace ---
   at V8Exception.ThrowScriptEngineException(V8Exception* )
   at Microsoft.ClearScript.V8.V8ContextProxyImpl.Execute(String gcDocumentName, String gcCode, Boolean evaluate, Boolean discard)
   at Microsoft.ClearScript.V8.V8ScriptEngine.<>c__DisplayClass1b.<Execute>b__19()
   at Microsoft.ClearScript.ScriptEngine.ScriptInvoke[T](Func`1 func)
   at Microsoft.ClearScript.V8.V8ScriptEngine.BaseScriptInvoke[T](Func`1 func)
   at Microsoft.ClearScript.V8.V8ScriptEngine.<>c__DisplayClass25`1.<ScriptInvoke>b__24()
   at Microsoft.ClearScript.V8.?A0x792c8756.InvokeAction(Void* pvActionRef)
   at Microsoft.ClearScript.V8.V8ContextProxyImpl.InvokeWithLock(Action gcAction)
   at Microsoft.ClearScript.V8.V8ScriptEngine.ScriptInvoke[T](Func`1 func)
   at Microsoft.ClearScript.V8.V8ScriptEngine.Execute(String documentName, String code, Boolean evaluate, Boolean discard)
   at Microsoft.ClearScript.ScriptEngine.Execute(String code)
If I remove the 'nativeBridge.doSomething(obj);' line, then there is no memory leak. Likewise, if I move the "obj = {...}" statement outside of the while loop, there is no leak.

Am I doing something wrong with this code? If not, is there any workaround for this issue?

thanks,
Tom

New Post: memory leak when passing javascript object to managed code

$
0
0
Hi Tom,

Unfortunately memory management can get tricky with long-running scripts.

When you pass a script object into managed code, ClearScript creates a managed proxy for it. The proxy holds a strong reference to its target, so the script object can't be garbage-collected until the proxy is disposed or finalized.

Therefore one way to avoid the leak is to dispose the proxy when you're done with it:
publicvoid doSomething(dynamic foo) {
    var disposable = foo as IDisposable;
    if (disposable != null) {
        disposable.Dispose();
    }
}
Another possibility is to invoke managed garbage collection and finalization before calling ScriptEngine.CollectGarbage():
publicvoid garbageCollect() {
    GC.Collect();
    GC.WaitForPendingFinalizers();
    // [...]
    m_engine.CollectGarbage(true);
    // [...]
}
An unfortunate wrinkle with this approach is that you can no longer call garbageCollect() from script code. Proxy finalization requires help from the script engine, which is locked during script execution, so the GC.WaitForPendingFinalizers() call causes a deadlock. Instead, you'll have to restructure your code like this:
engine.Execute(@"var count = 0");
while (true) {
    engine.Execute(@"
        while (true) {
            if (++count % 10000 == 0) {
                break;
            }
            obj = {
                a: ""b"",
                c: ""d""
            };
            nativeBridge.doSomething(obj);
        }
    ");
    p.garbageCollect();
}
Thanks, and good luck!

New Post: memory leak when passing javascript object to managed code

$
0
0
The first solution you mentioned should work for me. Thanks for the prompt and detailed reply!

-Tom

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.
Viewing all 2297 articles
Browse latest View live




Latest Images