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 | .... | 52 | 53 | (Page 54) | 55 | 56 | .... | 115 | newer

    0 0

    This is in the basic java engine (not v8)

    I have some basic code here (in javascript):
    ```
    var accountstr = host.newVar(CLRString);
    if (!downloadInfo.TryGetValue("Account", accountstr.out))
    {
    accountstr = "No Key found";
    }
    var output = "_" + accountstr;

    return output;
    ```

    This should be returning "_908561", but is instead giving me "_undefined". When I remove the underscore concatenation, I get the proper result.

    Is there some sort of trick when concatenating a c sharp string and a javascript string?


    EDIT:
    I managed to find a solution to my problem. For some reason, I have to call .ToString on my System.String. Very weird I had to do this, but it worked.

    0 0

    +1 for deploying via nuget

    0 0

    This is awesome.

    Works perfectly, but you should considder updating the documentation with it.

    Great project!

    0 0
  • 11/03/14--09:59: New Post: javascript blob
  • What method would be best to get a javascript blob object into a .net byte array?

    0 0
  • 11/04/14--04:12: New Post: javascript blob
  • Hi Pretzelfisch,

    The Blob object is part of the Web API. It isn't part of the JavaScript standard, and ClearScript doesn't provide it.

    Did you mean ArrayBuffer by any chance?

    Thanks!

    0 0
  • 11/07/14--10:08: New Post: javascript blob
  • I think I can get the blob to a ArrayBuffer, will that map to a byte array?

    0 0

    I initialize my engine with the following lines:

    ```
    Dim engine As JScriptEngine
    engine = New JScriptEngine(WindowsScriptEngineFlags.EnableDebugging)
    engine.AddHostType("Console", GetType(Console))

    ```

    I add the following script to the engine:

    ```
    function Test(param) {
    Console.WriteLine("Called Test with param: " + param);
    }
    ```

    When I call

    ```
    engine.Script.Test(20)
    ```

    It prints: "Called Test with param: undefined"

    Does JScriptEngine not support calling internal functions with parameters?

    0 0

    I initialize my engine with the following lines:

    ```
    Dim engine As JScriptEngine
    engine = New JScriptEngine(WindowsScriptEngineFlags.EnableDebugging)
    engine.AddHostType("Console", GetType(Console))

    ```

    I add the following script to the engine:

    ```
    function Test(param) {
    Console.WriteLine("Called Test with param: " + param);
    }
    ```

    When I call

    ```
    engine.Script.Test(20)
    ```

    It prints: "Called Test with param: undefined"

    Does JScriptEngine not support calling internal functions with parameters?
    Comments: Hello! ClearScript 5.4 fixed several issues related to dynamic script item invocation for non-C# hosts. Please make sure you're using ClearScript 5.4.0 or later. Thanks!

    0 0
  • 11/09/14--19:20: New Post: javascript blob
  • Hi again,

    Generally speaking, ClearScript doesn't convert script objects to host objects automatically. Instead, it aims to allow hosts to manipulate script objects directly.

    Here's a sample class that demonstrates reading bytes from an ArrayBuffer:
    internalclass ArrayBufferUtil {
        privatereadonlydynamic createUint8Array;
        public ArrayBufferUtil(ScriptEngine engine) {
            createUint8Array = engine.Evaluate(@"(function (arrayBuffer) {
                return new Uint8Array(arrayBuffer);
            }).valueOf()");
        }
        public IEnumerable<byte> ToEnumerable(object arrayBuffer) {
            var uint8Array = createUint8Array(arrayBuffer);
            var length = Convert.ToInt32(uint8Array.length);
            for (var i = 0; i < length; i++) {
                yieldreturn Convert.ToByte(uint8Array[i]);
            }
        }
    }
    And here's how you might use this class to provide a printArrayBuffer function for script code:
    var util = new ArrayBufferUtil(engine);
    engine.Script.printArrayBuffer = new Action<object>(arrayBuffer => {
        var bytes = util.ToEnumerable(arrayBuffer);
        Console.WriteLine(string.Join(",", bytes));
    });
    Note that this requires a host-to-engine round trip for each byte. For large buffers a more efficient approach might be to use an encoding such as Base64 to transfer all the data to the host in one hop.

    Good luck!

    0 0

    I initialize my engine with the following lines:

    ```
    Dim engine As JScriptEngine
    engine = New JScriptEngine(WindowsScriptEngineFlags.EnableDebugging)
    engine.AddHostType("Console", GetType(Console))

    ```

    I add the following script to the engine:

    ```
    function Test(param) {
    Console.WriteLine("Called Test with param: " + param);
    }
    ```

    When I call

    ```
    engine.Script.Test(20)
    ```

    It prints: "Called Test with param: undefined"

    Does JScriptEngine not support calling internal functions with parameters?
    Comments: I was testing with version 5.3.11. I will try again with version 5.4.x. Thanks for your quick reply.

    0 0
  • 11/13/14--07:21: New Post: javascript blob
  • Hi,

    How to evaluate an expression and validate it using the ClearScript.

    0 0
  • 11/13/14--07:57: New Post: javascript blob
  • Hello!

    You can call ScriptEngine.Evaluate() to evaluate a script code expression. What kind of validation are you looking for?

    Cheers!

    0 0

    I'm running into a problem trying to use V8RuntimeConstraints when creating a V8ScriptEngine, and I'm not doing anything weird so I'm guessing there must be something wrong with my project. I'm posting here in case anyone else has hit this and has a suggestion.

    I'm using ClearScript 5.4.0 built myself from the official download. If I don't pass in any constraints, everything works fine. With constraints, I get a System.Reflection.TargetInvocationException when V8Proxy tries to create an instance of V8ContextProxyImpl.

    The details:

    Code:

    var constraints = new V8RuntimeConstraints();
    constraints .MaxExecutableSize = 1024*1024;
    constraints .MaxNewSpaceSize = 1024 * 1024;
    constraints .MaxOldSpaceSize = 1024 * 1024;

    var engine = new V8ScriptEngine(EngineConstraints); // Exception thrown in here

    The exception:
    • $exception {"Exception has been thrown by the target of an invocation."} System.Exception {System.Reflection.TargetInvocationException}
    • [System.Reflection.TargetInvocationException] {"Exception has been thrown by the target of an invocation."} System.Reflection.TargetInvocationException
      _className  null    string
    • _data {System.Collections.ListDictionaryInternal} System.Collections.IDictionary {System.Collections.ListDictionaryInternal}
      _dynamicMethods null    object
      _exceptionMethod    null    System.Reflection.MethodBase
      _exceptionMethodString  null    string
      _helpURL    null    string
      _HResult    -2146232828 int
    • _innerException {"Attempted to read or write protected memory. This is often an indication that other memory is corrupt."} System.Exception {System.AccessViolationException}
    • _ipForWatsonBuckets 0 System.UIntPtr
      _message    "Exception has been thrown by the target of an invocation." string
      _remoteStackIndex   0   int
      _remoteStackTraceString null    string
    • _safeSerializationManager {System.Runtime.Serialization.SafeSerializationManager} System.Runtime.Serialization.SafeSerializationManager
      _source null    string
    • _stackTrace {sbyte[48]} object {sbyte[]}
      _stackTraceString   null    string
    • _watsonBuckets {byte[5616]} object {byte[]}
      _xcode  -532462766  int
    • _xptrs 0 System.IntPtr
    • Data {System.Collections.ListDictionaryInternal} System.Collections.IDictionary {System.Collections.ListDictionaryInternal}
      HelpLink    null    string
      HResult -2146232828 int
    • InnerException {"Attempted to read or write protected memory. This is often an indication that other memory is corrupt."} System.Exception {System.AccessViolationException}
    • IPForWatsonBuckets 0 System.UIntPtr
      IsTransient false   bool
      Message "Exception has been thrown by the target of an invocation." string
      RemoteStackTrace    null    string
      Source  "mscorlib"  string
      StackTrace  "   at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)\r\n   at System.Reflection.RuntimeConstructorInfo.Invoke(BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)"   string
    • TargetSite {System.Object InvokeMethod(System.Object, System.Object[], System.Signature, Boolean)} System.Reflection.MethodBase {System.Reflection.RuntimeMethodInfo}
    • WatsonBuckets {byte[5616]} object {byte[]}
    • Static members
    Seems like there's a bad pointer or something at the C++ level. I have no idea why that would be going wrong. Any ideas?

    0 0

    Greetings!

    We ran a quick test using your V8RuntimeConstraints configuration. It turns out that those numbers are too tight for V8 to get off the ground, much less run any script code. It exceeds those limits during initialization and kills the process.

    Unfortunately this is how newer V8 builds deal with out-of-memory situations: immediate process termination. In the past V8 had graceful out-of-memory handling, but its developers sacrificed that in favor of performance. You can find more information here.

    Because V8 now crashes instead of reporting out-of-memory errors, V8RuntimeConstraints is no longer generally useful. We recommend that you avoid it unless your application uses a Chrome-like multi-process architecture that withstands process crashes.

    Good luck!

    0 0
  • 11/13/14--21:00: New Post: javascript blob
  • Hi

    Expression whether true or false ?? by using if condition.

    like a javascript as below.

    <html>
    <body>

    <a id="demo"></a>
    <script> var a=1; var result; if(1==1) { result=true; } else {result=false;} document.getElementById("demo").innerHTML = result;</script></body>
    </html>

    how can we do this by using ClearScript . Can you help me out with this sinario.

    0 0
  • 11/14/14--04:28: New Post: javascript blob
  • Sure, here's a simple C# example:
    using (var engine = new V8ScriptEngine()) {
        if (Convert.ToBoolean(engine.Evaluate("Math.PI > 3.0"))) {
            Console.WriteLine("Pi is greater than 3!");
        }
    }
    As you can see, you can pass script expressions to ScriptEngine.Evaluate() and inspect or convert the result as necessary. Note that ClearScript provides access to script engines only; it doesn't process HTML or implement the Web API.

    Good luck!

    0 0
  • 11/14/14--04:39: 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.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);
    }

    0 0
  • 11/14/14--05:10: New Post: javascript blob
  • Hi,

    Thank you. Can you give some example to access the function in CleaeScript as in javaScript like

    function myfunction( ){

    }

    0 0
  • 11/14/14--06:42: New Post: javascript blob
  • Suppose you've defined a JavaScript function like this:
    engine.Execute("function myFunction(a, b, c) { return a * b + c; }");
    Here are a few ways to execute it from the host and print out the return value:
    Console.WriteLine(engine.Script.myFunction(1, 2, 3));
    Console.WriteLine(engine.Script["myFunction"](4, 5, 6));
    Console.WriteLine(engine.Invoke("myFunction", newobject[] { 7, 8, 9 }));
    Thanks!

    0 0

    Good to know, thanks for the update.

older | 1 | .... | 52 | 53 | (Page 54) | 55 | 56 | .... | 115 | newer