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 | .... | 13 | 14 | (Page 15) | 16 | 17 | .... | 115 | newer

    0 0

    Hello joshrmt,

    Async/Await is just convenient syntax for creating and consuming methods that use the callback-intensive Tasks API. Instead of returning a normal value, an async method returns a task object that represents the method's execution in the background.

    Since JavaScript provides no await syntax, it forces you to deal directly with the task object. As long as you don't simply wait for the task to be completed, your JavaScript code won't hold the thread.

    Here's an example. Suppose you have a class with an async method for reading a text file:
    publicstaticclass SlowFileReader {
        publicstatic async Task<string> ReadFileAsStringAsync(string path) {
            await Task.Delay(TimeSpan.FromMilliseconds(5000));
            using (var reader = new StreamReader(path)) {
                return await reader.ReadToEndAsync();
            }
        }
    }
    Here's how to consume the async method from JavaScript without blocking the thread:
    engine.AddHostObject("lib", HostItemFlags.GlobalMembers, new HostTypeCollection("mscorlib"));
    engine.AddHostType("SlowFileReader", typeof(SlowFileReader));
    engine.Execute(@"
        var ReaderCallback = System.Action(System.Threading.Tasks.Task(System.String));
        var readerTask = SlowFileReader.ReadFileAsStringAsync('C:\\Path\\To\\SomeFile.txt');
        readerTask.ContinueWith(new ReaderCallback(function (task) {
            System.Console.WriteLine(task.Result);
        }));
    ");
    The JavaScript code in this example returns immediately, and uses a script delegate to set up a callback into script code. In a real-world scenario you might want to provide a helper method for orchestrating this, rather than exposing all of mscorlib :)

    Thanks for your question!

    0 0

    Hi All,
    probably it's due to my lack of experience with this very useful library, but I was not able to find method or a set of methods to validate scripts syntax before running them. Something like this: say we have a file (or even a string) containing the whole script, let us call this file "myscript.jscript", have a method like

    engine.Compile("myscript.jscript")

    to allow me an anticipated validation of script syntax.
    Thank you

    0 0

    Greetings!

    ClearScript generally does not expose script parsing as a separate function from script execution. The methods that execute script code report syntax errors as well.

    However, V8ScriptEngine.Compile() may be close to what you're looking for.

    Cheers!

    0 0

    Thank for answer and HNY to everyone,
    I was also interested in JScript compilation facilities....

    Just for a better understanding: is it a design choice to prevent syntax checking and script compilation from being called independently from script execution?

    The reason of this question is: when executing, I agree that library makes the interpretation, and also syntax checking and compilation. But if execution leads to side effects on host objects, I'd prefer to make a syntax check before exec instead of realizing that script was wrong once several host objects have been changed.

    WDYT?

    My current workaround is: make a copy of host objects involved and make a "dry run" over them, and releasing after script is over, being execution successful or not.
    I am not happy with this solution because if host objects are huge, duplicating them might be overwhelming in terms of memory.

    Thanks in advance,
    Tomaso

    0 0

    Hi Tomaso,

    is it a design choice to prevent syntax checking and script compilation from being called independently from script execution?

    Originally ClearScript supported only JScript and VBScript. As far as we know, these script engines don't have syntax checking APIs, nor do they support compilation. V8 supports compilation, so we added V8ScriptEngine.Compile().

    But if execution leads to side effects on host objects, I'd prefer to make a syntax check before exec instead of realizing that script was wrong once several host objects have been changed.

    A script with syntax errors can't be executed, so it can't have harmful side effects. On the other hand, if a script originates from an untrusted source, checking its syntax won't guarantee that it's bug free and won't abuse your host objects. The best approach is to expose a host API that prevents scripts from doing damage by exposing read-only operations when possible, enforcing limits, etc.

    Please send us your further thoughts.

    Happy New Year!

    0 0

    Thank you for the very clear and complete answer!

    Reading it I start thinking that I am simply misunderstanding the way ClearScript works and worrying about a problem that does not exist. I'd make an example, let's assume this is the script to be executed (ho=an host object exposed which has 4 methods):
    ho.Method1("One");
    ho.Method2("Two");
    hoMethod3("Three"); // the "dot" is missing - real syntax error
    ho.Method4("Four");
    How do things go in this case?
    Does the engine recognize that Method3 call is syntactically wrong before starting the execution or when the 3-rd line is processed??

    And also if this is the script:
    ho.Method1("One");
    ho.Method2("Two");
    ho.Method34("Three"); // Typo, Method34 doesn't exist - syntax is correct (? maybe it's not from ClearScript point of view??), but host object doesn't expose this functionality
    ho.Method4("Four");
    Does it recognize that Method34 doesn't exist before starting the execution or when the 3-rd line is processed??

    Best regards
    Tomaso Tosolini

    0 0

    Hi Tomaso,

    hoMethod3("Three"); // the "dot" is missing - real syntax error

    There's no syntax error here; this line simply invokes a function named "hoMethod3". If no such function exists when the line is executed, the script engine generates a runtime error. It may be semantically incorrect, but this line is 100% legal JavaScript, and because JavaScript has no static typing, the engine can't detect this kind of error prior to execution.

    Does it recognize that Method34 doesn't exist before starting the execution or when the 3-rd line is processed??

    As in the first example, the line is legal JavaScript, so the error would not be detected until runtime.

    Cheers!

    0 0

    Ok, thank you very much for all the clarifications :)

    0 0

    I have a very simple app at this time. I am developing in VB.NET (CLR 4.5) and using the VBScript Engine. My application is to be used for industrial process simulations so my .Net application will call the same script method (Sub Main) roughly every second. The code in VB.Net looks like this.
      engine.Script.Main()
    In VBScript
    Public Sub Main()
      Dim x
      x = 5
    End Sub
    Right now I am just using a button to test this. The first time I click the button, I Execute the entire script
      engine.Execute(ScriptText)
    On subsequent button pushes I call Main
      engine.Script.Main()
    And I get the following error

    "Exception has been thrown by the target of an invocation."

    I have found that the following works fine however I read a post here that recommends against invoking script this way for performance reasons. Because my application will likely call many different Sub Main() scripts every second, performance will be very important.
      engine.Execute("Main")
    I have stripped this down as much as possible and still can't get it to work as recommended - any suggestions?

    0 0

    Hello!

    We're having trouble reproducing your issue. We just ran this test program without any problems:
    Module ConsoleTest
        Sub Main()
            Using engine AsNew Microsoft.ClearScript.Windows.VBScriptEngine
                engine.Execute("Public Sub Main() : Dim x : x = 5 : End Sub")
                engine.Script.Main()
            EndUsingEndSubEndModule
    Can you think of anything you're doing that might be significantly different?

    Also, the exception text you posted indicates TargetInvocationException, which should always have a non-null InnerException property. Can you examine that and tell us what you find?

    Thanks!

    0 0

    Hi,
    I am trying to parse a json string as below (please let me know what i am doing wrong here)
    engine.ExecuteCommand("JSON.parse('{\"x\":1}');");
    I get the following exception:
    Microsoft.ClearScript.ScriptEngineException: 'JSON' is undefined
    Result StackTrace:
    at Microsoft.ClearScript.ScriptEngine.ThrowScriptError(IScriptEngineException scriptError)
    at Microsoft.ClearScript.Windows.WindowsScriptEngine.<>c__DisplayClass14.<ScriptInvoke>b__13()
    at Microsoft.ClearScript.ScriptEngine.ScriptInvoke(Action action)
    at Microsoft.ClearScript.Windows.WindowsScriptEngine.Execute(String documentName, String code, Boolean evaluate, Boolean discard)
    at Microsoft.ClearScript.ScriptEngine.ExecuteCommand(String command)

    0 0

    Hello!

    Unfortunately JScriptEngine currently does not support the JSON object. It is compatible with JScript 5.7, but the JSON object was added in JScript 5.8. We're going to fix this in the next release.

    BTW, V8ScriptEngine supports JSON.

    Thank you for reporting this issue!

    0 0
  • 01/04/14--18:53: New Post: Strong Name
  • One possibility is to keep a development key in the repository, and sign official releases with a key that isn't in the repository.

    0 0

    I copied your code into my app and executed on a Windows form Button_Click and I get the same error as before. The InnerException says.
    Public member 'Main' on type 'VBScriptTypeInfo' not found.
    I am using Clearscript Version 5.3.10.0 that I installed as a NuGet package.

    I then created a new console app in VB.net, installed ClearScript NuGet package and copied your code directly into my Sub Main. When I run the app, it generates the same error message when trying to execute engine.Script.Main(). In this case, because I created a bare bones console app with nothing more than the code you provided, I can't think of anything I am doing that may be different in any way.

    Does ClearScript have other dependencies that may not be correct on my machine? Are you using ClearScript 5.3.10.0?

    0 0

    I have an existing List<string> which is passed into the engine as an object.
    engine.AddObject("Datas", datas);
    This is the script that i want to execute
    Datas.ForEach(function(d){
    //read the string here
    });
    When i try to execute the it using a function, it throws an error "The best overloaded match for List<string>.ForEach(System.Action<string>) has some invalid arguments".

    I guess that the javascript function is not transform into C# Action?

    0 0

    Hi again!

    We've reproduced this issue, and you nailed it - in our previous tests we used a newer ClearScript version (not yet released) where this issue is already fixed. We'll get the fix out ASAP.

    This bug only affects parameterless functions. You can work around it by adding a dummy parameter:
    Using engine AsNew Microsoft.ClearScript.Windows.VBScriptEngine
        engine.Execute("Public Sub Main(dummy) : Dim x : x = 5 : End Sub")
        engine.Script.Main(0)
    EndUsing
    Thanks again, and good luck!

    0 0
  • 01/05/14--05:27: New Post: Strong Name
  • Hi Dan15,

    Actually, we don't release official binaries. What we've decided to do is add optional support for building strong named assemblies using a key pair supplied by the builder.

    Cheers!

    0 0

    Greetings!

    I guess that the javascript function is not transform into C# Action?

    Not automatically. ClearScript provides C#-like type inference, where method overloads are selected according to the argument types. Script functions are not strongly typed, and that presents a problem. To create a callback into script code, you must therefore specify the callback type:
    engine.AddHostObject("Datas", new List<string> { "foo", "bar", "baz" });
    engine.AddHostType("Callback", typeof(Action<string>));
    engine.AddHostType("Console", typeof(Console));
    engine.Execute(@"
        Datas.ForEach(new Callback(function(d) {
            Console.WriteLine(d);
        }))
    ");
    Good luck!

    0 0

    By the way, for a more generic and transparent solution, you could expose a helper class that provides script-specific list extensions:
    publicstaticclass ListExtensions {
        publicstaticvoid ForEach<T>(this List<T> list, dynamic function) {
            list.ForEach(item => function(item));
        }
    }
    and then:
    engine.AddHostType("ListExtensions", typeof(ListExtensions));
    engine.AddHostType("Console", typeof(Console));
    engine.AddHostObject("Datas", new List<string> { "foo", "bar", "baz" });
    engine.Execute(@"
        Datas.ForEach(function(d) {
            Console.WriteLine(d);
        })
    ");
    Cheers!

    0 0

    Thank a lot! The extension method works!

older | 1 | .... | 13 | 14 | (Page 15) | 16 | 17 | .... | 115 | newer