Quantcast
Are you the publisher? Claim or contact us about this channel


Embed this content in your HTML

Search

Report adult content:

click to rate:

Account: (login)

More Channels


Showcase


Channel Catalog



Channel 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.

older | 1 | .... | 95 | 96 | (Page 97) | 98 | 99 | .... | 115 | newer

    0 0

    Context: Azure, C#, ClearScript.V8.5.4.5

    I have a number of C# programs running under the scheduler in an Azure VM. All but two are currently working due to an error which identifies itself by a last run result of 0xE0434352.

    In Event Viewer -> Windows Logs -> Application there are a number of errors listed, all of which say mostly the same as the following

    ```
    Application: NormanEmailHandler.exe Framework Version: v4.0.30319 Description: The process was terminated due to an unhandled exception. Exception Info: System.ComponentModel.Win32Exception at MS.Win32.UnsafeNativeMethods.RegisterClassEx(WNDCLASSEX_D) at MS.Win32.HwndWrapper..ctor(Int32, Int32, Int32, Int32, Int32, Int32, Int32, System.String, IntPtr, MS.Win32.HwndWrapperHook[]) at System.Windows.Threading.Dispatcher..ctor() at System.Windows.Threading.Dispatcher.get_CurrentDispatcher() at Microsoft.ClearScript.Windows.WindowsScriptEngine..ctor(System.String, System.String, Microsoft.ClearScript.Windows.WindowsScriptEngineFlags) at Microsoft.ClearScript.Windows.JScriptEngine..ctor(System.String, System.String, Microsoft.ClearScript.Windows.WindowsScriptEngineFlags) at Microsoft.ClearScript.Windows.JScriptEngine..ctor(Microsoft.ClearScript.Windows.WindowsScriptEngineFlags) at NormanEmailHandler.Program..cctor() Exception Info: System.TypeInitializationException at NormanEmailHandler.Program.Main(System.String[])
    ```

    I have looked at and tried the code samples at [AppDomain.UnhandledException Event](https://msdn.microsoft.com/en-us/library/system.appdomain.unhandledexception(v=vs.71).aspx) however the EXE fails before that code gets executed, even when it's the first thing encountered in the Main().

    It does occur to me as I write this that instantiating the object before Main() kicks in might have something to do with the exception handler not firing. What's be nice, though would be to know why I'm having the problem at all.

    ```
    namespace NormanEmailHandler
    {
    class Program
    {
    static JScriptEngine JSengine = new JScriptEngine(WindowsScriptEngineFlags.EnableDebugging | WindowsScriptEngineFlags.EnableJITDebugging);

    ```

    Comments: Hmm, if restarting the VM fixed the issue, then Win32 resource exhaustion is the likely culprit, just like in the discussion linked above. If the issue returns, we'd love to know the `Win32Exception` error code. Windows script engines have thread affinity. That is, not only are they unsafe for concurrent use, but each instance can only be used on the thread that created it. ClearScript uses .NET's [Dispatcher class](https://msdn.microsoft.com/en-us/library/system.windows.threading.dispatcher(v=vs.110).aspx) (which apparently uses Win32 window handles under the covers) to enforce this restriction and route event callbacks to the appropriate thread; all WPF controls use the same facility. The script control's `AllowUI` property lets the host block message boxes, but it doesn't affect the script engine's thread affinity.

    0 0

    Greetings!

    There a several ways to go here. Suppose you have a JavaScript function that takes such an object:
    engine.AddHostType(typeof(Console));
    engine.Execute(@"
        function foo(arg) {
            Console.WriteLine(arg['a.b']);
            Console.WriteLine(arg['foo.bar']);
        }
    ");
    You can use a dynamic .NET object for the argument:
    IDictionary<string, object> arg = new ExpandoObject();
    arg["a.b"] = 123;
    arg["foo.bar"] = 456;
    engine.Script.foo(arg);
    Another possibility is to use ClearScript's PropertyBag class:
    var arg = new PropertyBag();
    arg["a.b"] = 123;
    arg["foo.bar"] = 456;
    engine.Script.foo(arg);
    A third option is simply to use a script object:
    dynamic arg = engine.Evaluate("({})");
    arg["a.b"] = 123;
    arg["foo.bar"] = 456;
    engine.Script.foo(arg);
    Keep in mind though that if the argument is a large dictionary with hundreds of elements, then JSON tunneling, as clunky as it is, could provide better performance, as it minimizes the number of dynamic calls and objects flowing across the host-script boundary.

    Good luck!

    0 0

    Thanks for the answer. I'll stick with the JSON tunneling then, as I do need performance.

    0 0
  • 03/21/16--09:48: Updated Wiki: Home
  • 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()));
    }

    0 0

    Context: Azure, C#, ClearScript.V8.5.4.5

    I have a number of C# programs running under the scheduler in an Azure VM. All but two are currently working due to an error which identifies itself by a last run result of 0xE0434352.

    In Event Viewer -> Windows Logs -> Application there are a number of errors listed, all of which say mostly the same as the following

    ```
    Application: NormanEmailHandler.exe Framework Version: v4.0.30319 Description: The process was terminated due to an unhandled exception. Exception Info: System.ComponentModel.Win32Exception at MS.Win32.UnsafeNativeMethods.RegisterClassEx(WNDCLASSEX_D) at MS.Win32.HwndWrapper..ctor(Int32, Int32, Int32, Int32, Int32, Int32, Int32, System.String, IntPtr, MS.Win32.HwndWrapperHook[]) at System.Windows.Threading.Dispatcher..ctor() at System.Windows.Threading.Dispatcher.get_CurrentDispatcher() at Microsoft.ClearScript.Windows.WindowsScriptEngine..ctor(System.String, System.String, Microsoft.ClearScript.Windows.WindowsScriptEngineFlags) at Microsoft.ClearScript.Windows.JScriptEngine..ctor(System.String, System.String, Microsoft.ClearScript.Windows.WindowsScriptEngineFlags) at Microsoft.ClearScript.Windows.JScriptEngine..ctor(Microsoft.ClearScript.Windows.WindowsScriptEngineFlags) at NormanEmailHandler.Program..cctor() Exception Info: System.TypeInitializationException at NormanEmailHandler.Program.Main(System.String[])
    ```

    I have looked at and tried the code samples at [AppDomain.UnhandledException Event](https://msdn.microsoft.com/en-us/library/system.appdomain.unhandledexception(v=vs.71).aspx) however the EXE fails before that code gets executed, even when it's the first thing encountered in the Main().

    It does occur to me as I write this that instantiating the object before Main() kicks in might have something to do with the exception handler not firing. What's be nice, though would be to know why I'm having the problem at all.

    ```
    namespace NormanEmailHandler
    {
    class Program
    {
    static JScriptEngine JSengine = new JScriptEngine(WindowsScriptEngineFlags.EnableDebugging | WindowsScriptEngineFlags.EnableJITDebugging);

    ```


    0 0

    Context: Azure, C#, ClearScript.V8.5.4.5

    I have a number of C# programs running under the scheduler in an Azure VM. All but two are currently working due to an error which identifies itself by a last run result of 0xE0434352.

    In Event Viewer -> Windows Logs -> Application there are a number of errors listed, all of which say mostly the same as the following

    ```
    Application: NormanEmailHandler.exe Framework Version: v4.0.30319 Description: The process was terminated due to an unhandled exception. Exception Info: System.ComponentModel.Win32Exception at MS.Win32.UnsafeNativeMethods.RegisterClassEx(WNDCLASSEX_D) at MS.Win32.HwndWrapper..ctor(Int32, Int32, Int32, Int32, Int32, Int32, Int32, System.String, IntPtr, MS.Win32.HwndWrapperHook[]) at System.Windows.Threading.Dispatcher..ctor() at System.Windows.Threading.Dispatcher.get_CurrentDispatcher() at Microsoft.ClearScript.Windows.WindowsScriptEngine..ctor(System.String, System.String, Microsoft.ClearScript.Windows.WindowsScriptEngineFlags) at Microsoft.ClearScript.Windows.JScriptEngine..ctor(System.String, System.String, Microsoft.ClearScript.Windows.WindowsScriptEngineFlags) at Microsoft.ClearScript.Windows.JScriptEngine..ctor(Microsoft.ClearScript.Windows.WindowsScriptEngineFlags) at NormanEmailHandler.Program..cctor() Exception Info: System.TypeInitializationException at NormanEmailHandler.Program.Main(System.String[])
    ```

    I have looked at and tried the code samples at [AppDomain.UnhandledException Event](https://msdn.microsoft.com/en-us/library/system.appdomain.unhandledexception(v=vs.71).aspx) however the EXE fails before that code gets executed, even when it's the first thing encountered in the Main().

    It does occur to me as I write this that instantiating the object before Main() kicks in might have something to do with the exception handler not firing. What's be nice, though would be to know why I'm having the problem at all.

    ```
    namespace NormanEmailHandler
    {
    class Program
    {
    static JScriptEngine JSengine = new JScriptEngine(WindowsScriptEngineFlags.EnableDebugging | WindowsScriptEngineFlags.EnableJITDebugging);

    ```

    Comments: We have no way to reproduce this issue, and there has been no new information from BruceAxtens in 10 days. Resolving as Not Repro.

    0 0

    Context: Azure, C#, ClearScript.V8.5.4.5

    I have a number of C# programs running under the scheduler in an Azure VM. All but two are currently working due to an error which identifies itself by a last run result of 0xE0434352.

    In Event Viewer -> Windows Logs -> Application there are a number of errors listed, all of which say mostly the same as the following

    ```
    Application: NormanEmailHandler.exe Framework Version: v4.0.30319 Description: The process was terminated due to an unhandled exception. Exception Info: System.ComponentModel.Win32Exception at MS.Win32.UnsafeNativeMethods.RegisterClassEx(WNDCLASSEX_D) at MS.Win32.HwndWrapper..ctor(Int32, Int32, Int32, Int32, Int32, Int32, Int32, System.String, IntPtr, MS.Win32.HwndWrapperHook[]) at System.Windows.Threading.Dispatcher..ctor() at System.Windows.Threading.Dispatcher.get_CurrentDispatcher() at Microsoft.ClearScript.Windows.WindowsScriptEngine..ctor(System.String, System.String, Microsoft.ClearScript.Windows.WindowsScriptEngineFlags) at Microsoft.ClearScript.Windows.JScriptEngine..ctor(System.String, System.String, Microsoft.ClearScript.Windows.WindowsScriptEngineFlags) at Microsoft.ClearScript.Windows.JScriptEngine..ctor(Microsoft.ClearScript.Windows.WindowsScriptEngineFlags) at NormanEmailHandler.Program..cctor() Exception Info: System.TypeInitializationException at NormanEmailHandler.Program.Main(System.String[])
    ```

    I have looked at and tried the code samples at [AppDomain.UnhandledException Event](https://msdn.microsoft.com/en-us/library/system.appdomain.unhandledexception(v=vs.71).aspx) however the EXE fails before that code gets executed, even when it's the first thing encountered in the Main().

    It does occur to me as I write this that instantiating the object before Main() kicks in might have something to do with the exception handler not firing. What's be nice, though would be to know why I'm having the problem at all.

    ```
    namespace NormanEmailHandler
    {
    class Program
    {
    static JScriptEngine JSengine = new JScriptEngine(WindowsScriptEngineFlags.EnableDebugging | WindowsScriptEngineFlags.EnableJITDebugging);

    ```


    0 0

    Context: Azure, C#, ClearScript.V8.5.4.5

    I have a number of C# programs running under the scheduler in an Azure VM. All but two are currently working due to an error which identifies itself by a last run result of 0xE0434352.

    In Event Viewer -> Windows Logs -> Application there are a number of errors listed, all of which say mostly the same as the following

    ```
    Application: NormanEmailHandler.exe Framework Version: v4.0.30319 Description: The process was terminated due to an unhandled exception. Exception Info: System.ComponentModel.Win32Exception at MS.Win32.UnsafeNativeMethods.RegisterClassEx(WNDCLASSEX_D) at MS.Win32.HwndWrapper..ctor(Int32, Int32, Int32, Int32, Int32, Int32, Int32, System.String, IntPtr, MS.Win32.HwndWrapperHook[]) at System.Windows.Threading.Dispatcher..ctor() at System.Windows.Threading.Dispatcher.get_CurrentDispatcher() at Microsoft.ClearScript.Windows.WindowsScriptEngine..ctor(System.String, System.String, Microsoft.ClearScript.Windows.WindowsScriptEngineFlags) at Microsoft.ClearScript.Windows.JScriptEngine..ctor(System.String, System.String, Microsoft.ClearScript.Windows.WindowsScriptEngineFlags) at Microsoft.ClearScript.Windows.JScriptEngine..ctor(Microsoft.ClearScript.Windows.WindowsScriptEngineFlags) at NormanEmailHandler.Program..cctor() Exception Info: System.TypeInitializationException at NormanEmailHandler.Program.Main(System.String[])
    ```

    I have looked at and tried the code samples at [AppDomain.UnhandledException Event](https://msdn.microsoft.com/en-us/library/system.appdomain.unhandledexception(v=vs.71).aspx) however the EXE fails before that code gets executed, even when it's the first thing encountered in the Main().

    It does occur to me as I write this that instantiating the object before Main() kicks in might have something to do with the exception handler not firing. What's be nice, though would be to know why I'm having the problem at all.

    ```
    namespace NormanEmailHandler
    {
    class Program
    {
    static JScriptEngine JSengine = new JScriptEngine(WindowsScriptEngineFlags.EnableDebugging | WindowsScriptEngineFlags.EnableJITDebugging);

    ```


    0 0

    Setting a Value to Put Property outside the Script execution context fails, saying member not found.

    here is a simple demonstration code:

    ```
    var e = new VBScriptEngine();
    e.Execute(@"
    class test
    private var_

    public property get var
    var = var_
    end property
    public property let var(val)
    var_ = val
    end property

    Private Sub Class_Initialize()
    var_ = ""value""
    End Sub

    end class
    dim mytest : set mytest = new test
    ");
    dynamic a = e.Script.mytest;
    Console.WriteLine(a.var);

    a.var = "adad"; // !! this used to fail also, but found a quick workaround. see code below
    Console.WriteLine(a.var);

    var e2 = new VBScriptEngine();
    e2.Execute("dim mytest, tyna");
    e2.Script.mytest = a;

    e2.Execute("tyna = typename(mytest)");
    e2.Execute("mytest.var = \"sad\""); // !! this fails !!
    ```


    the quick fix is achived in COMDispatchHelper.cs inside the SetProperty(..) method, simply trying next DispatchFlags:

    ```
    Marshal.ThrowExceptionForHR(result);
    using (var argVariantArrayBlock = new CoTaskMemVariantArgsBlock(args))
    {
    using (var namedArgDispidBlock = new CoTaskMemBlock(sizeof(int)))
    {
    EXCEPINFO excepInfo;
    Marshal.WriteInt32(namedArgDispidBlock.Addr, SpecialDispIDs.PropertyPut);
    var dispArgs = new DISPPARAMS { cArgs = args.Length, rgvarg = argVariantArrayBlock.Addr, cNamedArgs = 1, rgdispidNamedArgs = namedArgDispidBlock.Addr };
    try
    {
    dispatchEx.InvokeEx(dispid, 0, DispatchFlags.PropertyPut | DispatchFlags.PropertyPutRef, ref dispArgs, IntPtr.Zero, out excepInfo);
    return true;
    }
    catch (COMException)
    {
    try
    {
    dispatchEx.InvokeEx(dispid, 0, DispatchFlags.PropertyPut, ref dispArgs, IntPtr.Zero, out excepInfo);
    return true;
    }
    catch (COMException)
    {
    try
    {
    dispatchEx.InvokeEx(dispid, 0, DispatchFlags.PropertyPutRef, ref dispArgs, IntPtr.Zero, out excepInfo);
    return true;
    }
    catch (COMException) { }
    }
    }
    return false;
    }
    }
    ```

    any ideas of why this happens at all?

    0 0

    Setting a Value to Put Property outside the Script execution context fails, saying member not found.

    here is a simple demonstration code:

    ```
    var e = new VBScriptEngine();
    e.Execute(@"
    class test
    private var_

    public property get var
    var = var_
    end property
    public property let var(val)
    var_ = val
    end property

    Private Sub Class_Initialize()
    var_ = ""value""
    End Sub

    end class
    dim mytest : set mytest = new test
    ");
    dynamic a = e.Script.mytest;
    Console.WriteLine(a.var);

    a.var = "adad"; // !! this used to fail also, but found a quick workaround. see code below
    Console.WriteLine(a.var);

    var e2 = new VBScriptEngine();
    e2.Execute("dim mytest, tyna");
    e2.Script.mytest = a;

    e2.Execute("tyna = typename(mytest)");
    e2.Execute("mytest.var = \"sad\""); // !! this fails !!
    ```


    the quick fix is achived in COMDispatchHelper.cs inside the SetProperty(..) method, simply trying next DispatchFlags:

    ```
    Marshal.ThrowExceptionForHR(result);
    using (var argVariantArrayBlock = new CoTaskMemVariantArgsBlock(args))
    {
    using (var namedArgDispidBlock = new CoTaskMemBlock(sizeof(int)))
    {
    EXCEPINFO excepInfo;
    Marshal.WriteInt32(namedArgDispidBlock.Addr, SpecialDispIDs.PropertyPut);
    var dispArgs = new DISPPARAMS { cArgs = args.Length, rgvarg = argVariantArrayBlock.Addr, cNamedArgs = 1, rgdispidNamedArgs = namedArgDispidBlock.Addr };
    try
    {
    dispatchEx.InvokeEx(dispid, 0, DispatchFlags.PropertyPut | DispatchFlags.PropertyPutRef, ref dispArgs, IntPtr.Zero, out excepInfo);
    return true;
    }
    catch (COMException)
    {
    try
    {
    dispatchEx.InvokeEx(dispid, 0, DispatchFlags.PropertyPut, ref dispArgs, IntPtr.Zero, out excepInfo);
    return true;
    }
    catch (COMException)
    {
    try
    {
    dispatchEx.InvokeEx(dispid, 0, DispatchFlags.PropertyPutRef, ref dispArgs, IntPtr.Zero, out excepInfo);
    return true;
    }
    catch (COMException) { }
    }
    }
    return false;
    }
    }
    ```

    any ideas of why this happens at all?
    Comments: Thanks for reporting this issue! To be honest, we haven't done much with VBScript recently beyond the coded tests in the project. It looks like VBScript class objects are unforgiving when it comes to those invocation flags, behaving quite differently from native JScript objects. We'll post a fix shortly (for both of the failure scenarios you've identified), as well as a few new tests. Thanks again!

    0 0

    Setting a Value to Put Property outside the Script execution context fails, saying member not found.

    here is a simple demonstration code:

    ```
    var e = new VBScriptEngine();
    e.Execute(@"
    class test
    private var_

    public property get var
    var = var_
    end property
    public property let var(val)
    var_ = val
    end property

    Private Sub Class_Initialize()
    var_ = ""value""
    End Sub

    end class
    dim mytest : set mytest = new test
    ");
    dynamic a = e.Script.mytest;
    Console.WriteLine(a.var);

    a.var = "adad"; // !! this used to fail also, but found a quick workaround. see code below
    Console.WriteLine(a.var);

    var e2 = new VBScriptEngine();
    e2.Execute("dim mytest, tyna");
    e2.Script.mytest = a;

    e2.Execute("tyna = typename(mytest)");
    e2.Execute("mytest.var = \"sad\""); // !! this fails !!
    ```


    the quick fix is achived in COMDispatchHelper.cs inside the SetProperty(..) method, simply trying next DispatchFlags:

    ```
    Marshal.ThrowExceptionForHR(result);
    using (var argVariantArrayBlock = new CoTaskMemVariantArgsBlock(args))
    {
    using (var namedArgDispidBlock = new CoTaskMemBlock(sizeof(int)))
    {
    EXCEPINFO excepInfo;
    Marshal.WriteInt32(namedArgDispidBlock.Addr, SpecialDispIDs.PropertyPut);
    var dispArgs = new DISPPARAMS { cArgs = args.Length, rgvarg = argVariantArrayBlock.Addr, cNamedArgs = 1, rgdispidNamedArgs = namedArgDispidBlock.Addr };
    try
    {
    dispatchEx.InvokeEx(dispid, 0, DispatchFlags.PropertyPut | DispatchFlags.PropertyPutRef, ref dispArgs, IntPtr.Zero, out excepInfo);
    return true;
    }
    catch (COMException)
    {
    try
    {
    dispatchEx.InvokeEx(dispid, 0, DispatchFlags.PropertyPut, ref dispArgs, IntPtr.Zero, out excepInfo);
    return true;
    }
    catch (COMException)
    {
    try
    {
    dispatchEx.InvokeEx(dispid, 0, DispatchFlags.PropertyPutRef, ref dispArgs, IntPtr.Zero, out excepInfo);
    return true;
    }
    catch (COMException) { }
    }
    }
    return false;
    }
    }
    ```

    any ideas of why this happens at all?

    0 0

    Setting a Value to Put Property outside the Script execution context fails, saying member not found.

    here is a simple demonstration code:

    ```
    var e = new VBScriptEngine();
    e.Execute(@"
    class test
    private var_

    public property get var
    var = var_
    end property
    public property let var(val)
    var_ = val
    end property

    Private Sub Class_Initialize()
    var_ = ""value""
    End Sub

    end class
    dim mytest : set mytest = new test
    ");
    dynamic a = e.Script.mytest;
    Console.WriteLine(a.var);

    a.var = "adad"; // !! this used to fail also, but found a quick workaround. see code below
    Console.WriteLine(a.var);

    var e2 = new VBScriptEngine();
    e2.Execute("dim mytest, tyna");
    e2.Script.mytest = a;

    e2.Execute("tyna = typename(mytest)");
    e2.Execute("mytest.var = \"sad\""); // !! this fails !!
    ```


    the quick fix is achived in COMDispatchHelper.cs inside the SetProperty(..) method, simply trying next DispatchFlags:

    ```
    Marshal.ThrowExceptionForHR(result);
    using (var argVariantArrayBlock = new CoTaskMemVariantArgsBlock(args))
    {
    using (var namedArgDispidBlock = new CoTaskMemBlock(sizeof(int)))
    {
    EXCEPINFO excepInfo;
    Marshal.WriteInt32(namedArgDispidBlock.Addr, SpecialDispIDs.PropertyPut);
    var dispArgs = new DISPPARAMS { cArgs = args.Length, rgvarg = argVariantArrayBlock.Addr, cNamedArgs = 1, rgdispidNamedArgs = namedArgDispidBlock.Addr };
    try
    {
    dispatchEx.InvokeEx(dispid, 0, DispatchFlags.PropertyPut | DispatchFlags.PropertyPutRef, ref dispArgs, IntPtr.Zero, out excepInfo);
    return true;
    }
    catch (COMException)
    {
    try
    {
    dispatchEx.InvokeEx(dispid, 0, DispatchFlags.PropertyPut, ref dispArgs, IntPtr.Zero, out excepInfo);
    return true;
    }
    catch (COMException)
    {
    try
    {
    dispatchEx.InvokeEx(dispid, 0, DispatchFlags.PropertyPutRef, ref dispArgs, IntPtr.Zero, out excepInfo);
    return true;
    }
    catch (COMException) { }
    }
    }
    return false;
    }
    }
    ```

    any ideas of why this happens at all?

    0 0

    Setting a Value to Put Property outside the Script execution context fails, saying member not found.

    here is a simple demonstration code:

    ```
    var e = new VBScriptEngine();
    e.Execute(@"
    class test
    private var_

    public property get var
    var = var_
    end property
    public property let var(val)
    var_ = val
    end property

    Private Sub Class_Initialize()
    var_ = ""value""
    End Sub

    end class
    dim mytest : set mytest = new test
    ");
    dynamic a = e.Script.mytest;
    Console.WriteLine(a.var);

    a.var = "adad"; // !! this used to fail also, but found a quick workaround. see code below
    Console.WriteLine(a.var);

    var e2 = new VBScriptEngine();
    e2.Execute("dim mytest, tyna");
    e2.Script.mytest = a;

    e2.Execute("tyna = typename(mytest)");
    e2.Execute("mytest.var = \"sad\""); // !! this fails !!
    ```


    the quick fix is achived in COMDispatchHelper.cs inside the SetProperty(..) method, simply trying next DispatchFlags:

    ```
    Marshal.ThrowExceptionForHR(result);
    using (var argVariantArrayBlock = new CoTaskMemVariantArgsBlock(args))
    {
    using (var namedArgDispidBlock = new CoTaskMemBlock(sizeof(int)))
    {
    EXCEPINFO excepInfo;
    Marshal.WriteInt32(namedArgDispidBlock.Addr, SpecialDispIDs.PropertyPut);
    var dispArgs = new DISPPARAMS { cArgs = args.Length, rgvarg = argVariantArrayBlock.Addr, cNamedArgs = 1, rgdispidNamedArgs = namedArgDispidBlock.Addr };
    try
    {
    dispatchEx.InvokeEx(dispid, 0, DispatchFlags.PropertyPut | DispatchFlags.PropertyPutRef, ref dispArgs, IntPtr.Zero, out excepInfo);
    return true;
    }
    catch (COMException)
    {
    try
    {
    dispatchEx.InvokeEx(dispid, 0, DispatchFlags.PropertyPut, ref dispArgs, IntPtr.Zero, out excepInfo);
    return true;
    }
    catch (COMException)
    {
    try
    {
    dispatchEx.InvokeEx(dispid, 0, DispatchFlags.PropertyPutRef, ref dispArgs, IntPtr.Zero, out excepInfo);
    return true;
    }
    catch (COMException) { }
    }
    }
    return false;
    }
    }
    ```

    any ideas of why this happens at all?
    Comments: Fix posted [here](https://clearscript.codeplex.com/SourceControl/changeset/985cde1ece46554c8806583b4d879ab446108d36).

    0 0

    Setting a Value to Put Property outside the Script execution context fails, saying member not found.

    here is a simple demonstration code:

    ```
    var e = new VBScriptEngine();
    e.Execute(@"
    class test
    private var_

    public property get var
    var = var_
    end property
    public property let var(val)
    var_ = val
    end property

    Private Sub Class_Initialize()
    var_ = ""value""
    End Sub

    end class
    dim mytest : set mytest = new test
    ");
    dynamic a = e.Script.mytest;
    Console.WriteLine(a.var);

    a.var = "adad"; // !! this used to fail also, but found a quick workaround. see code below
    Console.WriteLine(a.var);

    var e2 = new VBScriptEngine();
    e2.Execute("dim mytest, tyna");
    e2.Script.mytest = a;

    e2.Execute("tyna = typename(mytest)");
    e2.Execute("mytest.var = \"sad\""); // !! this fails !!
    ```


    the quick fix is achived in COMDispatchHelper.cs inside the SetProperty(..) method, simply trying next DispatchFlags:

    ```
    Marshal.ThrowExceptionForHR(result);
    using (var argVariantArrayBlock = new CoTaskMemVariantArgsBlock(args))
    {
    using (var namedArgDispidBlock = new CoTaskMemBlock(sizeof(int)))
    {
    EXCEPINFO excepInfo;
    Marshal.WriteInt32(namedArgDispidBlock.Addr, SpecialDispIDs.PropertyPut);
    var dispArgs = new DISPPARAMS { cArgs = args.Length, rgvarg = argVariantArrayBlock.Addr, cNamedArgs = 1, rgdispidNamedArgs = namedArgDispidBlock.Addr };
    try
    {
    dispatchEx.InvokeEx(dispid, 0, DispatchFlags.PropertyPut | DispatchFlags.PropertyPutRef, ref dispArgs, IntPtr.Zero, out excepInfo);
    return true;
    }
    catch (COMException)
    {
    try
    {
    dispatchEx.InvokeEx(dispid, 0, DispatchFlags.PropertyPut, ref dispArgs, IntPtr.Zero, out excepInfo);
    return true;
    }
    catch (COMException)
    {
    try
    {
    dispatchEx.InvokeEx(dispid, 0, DispatchFlags.PropertyPutRef, ref dispArgs, IntPtr.Zero, out excepInfo);
    return true;
    }
    catch (COMException) { }
    }
    }
    return false;
    }
    }
    ```

    any ideas of why this happens at all?
    Comments: thanks for the fast response and working fix. much appreciate your efforts for this great project.

    0 0

    hi,

    have a json array and it will be converted to object by JSON.Net. But when im trying to sue it with;

    obj[0]

    it fails with result of undefined

    0 0

    Rated 5 Stars (out of 5) - great project merging together .net and scripting and filling the huge gap

    0 0

    Hi furesoft,

    Please provide more info. A code sample would be great. We are not aware of any issues accessing script arrays from the host or vice versa.

    Thanks!

    0 0

    json:
    [
    {"content", "hello world"}
    ]
    var j = Json.parse(result);
    
    $alert(j[0],content);

    0 0

    Hi again,

    There are several issues with the above. The JSON sample isn't proper JSON, and the code sample (assuming it's JavaScript) seems to have at least one typo and is unlikely to work unless Json is a reference to a custom object of some kind.

    Please refer to the working sample below, which uses the console for output (since we're not sure what $alert is):
    engine.AddHostType(typeof(Console));
    engine.Script.result = "[{\"content\": \"hello world\"}]";
    engine.Execute(@"
        var j = JSON.parse(result);
        Console.WriteLine(j[0].content);
    ");
    This sample writes "hello world" to the console. Note that if you're using JScript, you'll need WindowsScriptEngineFlags.EnableStandardsMode to enable the standard JSON object.

    Good luck!

    0 0
  • 03/30/16--13:10: New Post: Func and delegate
  • Hi,

    I saw that the following code works :

    C# :
    public class ScriptAPI
    {
           public MyMethod(Func<string, object> aFunc)
           {
                  MessageBox.Show(aFunc("123").ToString())
           }
    }
    
    scriptEngine.AddHostObject("DotNet", new HostTypeCollection ("mscorlib", "System.Core", "System.Data"));
    scriptEngine.AddHostObject("host", new HostFunctions());
    scriptEngine.AddRestrictedHostObject("ScriptAPI", HostItemFlags.GlobalMembers, new ScriptAPI());
    scriptEngine.AddHostType("SomeDelegate", typeof(Func<string, object>));
    
    Javascript :
    var f = new SomeDelegate(function (x) { return x; });
    MyMethod(f);
    I would go further, but I lack the syntax.


    1°/ Question :
    Instead of creating a delegate (like in my example "SomeDelegate") with preset type for the generic, I would like to do something like that :

    C# :
      scriptEngine.AddHostType("SomeDelegate", typeof(Func<,>));
    Javascript :
    var f = new SomeDelegate(host.typeOf(DotNet.System.String), host.typeOf(DotNet.System.Object) (function (x) { return x; });
    My last javascript line of code is not correct, and I hope you have understood what i search to do.
    Could you give me please the correct syntax please ?

    2°/ Question :
    If one goes even further, is there a more elegant way to do than to declare as the following ? :

    C# :
    scriptEngine.AddHostType("Func1", typeof(Func<>));
    scriptEngine.AddHostType("Func2", typeof(Func<,>));
    scriptEngine.AddHostType("Func3", typeof(Func<,,>));
    scriptEngine.AddHostType("Func4", typeof(Func<,,,>));
    Thanks for advance for your answers.

    Sybaris

older | 1 | .... | 95 | 96 | (Page 97) | 98 | 99 | .... | 115 | newer