Influence the available commands while execution

Coordinator
Nov 8, 2013 at 12:17 PM
Torsten (user zimmybln) posted the following question:

Hi ClearScript,

when I execute JavaScript code I have to add objects, types etc. before I call execute. The JavaScript code itself has not influence which objects or types are available.

But what I want is that the JavaScript Code itself has got an option to define what objects / types etc. it needs an the runtime has the option to add it, like following pseudocode

1st. the bootstrap
using (var engine = new V8ScriptEngine())
{
    engine.AddHostObject("using", MyApp.PackageManager);
    ...     ' something what is additionally need
    engine.Execute(myscript);
}
2nd, the JavaScript
using.AddType("System.Environment");

var username = Enviroment.UserName;
3rd, the "MyApp.PackageManager"
static void AddType(string name)
{
 _  V8ScriptEngine.Current.AddHostType(name);_ 
}
I know, there is no option like V8ScriptEngine.Current at the moment. But is there another way to do this?

Best regards,
Torsten
Coordinator
Nov 8, 2013 at 12:44 PM
Hi Torsten,

Why not something like this:
public class PackageManager
{
    private readonly ScriptEngine _engine;

    public PackageManager(ScriptEngine engine)
    {
        _engine = engine;
    }

    public void AddType(string name)
    {
        var type = Type.GetType(name);
        if (type != null)
        {
            _engine.AddHostType(type.Name, type);
        }
    }
}
and then:
using (var engine = new V8ScriptEngine())
{
    engine.AddHostObject("using", new PackageManager(engine));
    engine.Execute(@"
        using.AddType('System.Environment');
        using.AddType('System.Console');
        Console.WriteLine(Environment.UserName);
    ");
}
Also see ClearScript's HostTypeCollection and ExtendedHostFunctions classes. The latter in particular allows script code to import any type from any assembly, and even all types from multiple assemblies in one step. It's completely unrestricted however, so it's probably not practical if your application runs untrusted script code.

Cheers!
Nov 10, 2013 at 5:29 PM
thank you for your explanation.

Torsten