Exemple #1
0
        static void Main(string[] args)
        {
            string line;
            var    jint = new JintEngine();

            jint.SetFunction("print", new Action <object>(s => { Console.ForegroundColor = ConsoleColor.Blue; Console.Write(s); Console.ResetColor(); }));
            jint.SetFunction("import", new Action <string>(s => { Assembly.LoadWithPartialName(s); }));
            jint.DisableSecurity();

            while (true)
            {
                Console.Write("jint > ");

                StringBuilder script = new StringBuilder();

                while (String.Empty != (line = Console.ReadLine()))
                {
                    if (line.Trim() == "exit")
                    {
                        return;
                    }

                    if (line.Trim() == "reset")
                    {
                        jint = new JintEngine();
                        break;
                    }

                    if (line.Trim() == "help" || line.Trim() == "?")
                    {
                        Console.WriteLine(@"Jint Shell");
                        Console.WriteLine(@"");
                        Console.WriteLine(@"exit                - Quits the application");
                        Console.WriteLine(@"import(assembly)    - assembly: String containing the partial name of a .NET assembly to load");
                        Console.WriteLine(@"reset               - Initialize the current script");
                        Console.WriteLine(@"print(output)       - Prints the specified output to the console");
                        Console.WriteLine(@"");
                        break;
                    }

                    script.AppendLine(line);
                }

                Console.SetError(new StringWriter(new StringBuilder()));

                try {
                    jint.Run(script.ToString());
                }
                catch (Exception e) {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine(e.Message);
                    Console.ResetColor();
                }

                Console.WriteLine();
            }
        }
            public void Invoke(string methodName, object[] parameters)
            {
                var jint = new JintEngine();

                jint.DisableSecurity();
                jint.Visitor.Usings.CopyFrom(_extension._usings);
                jint.SetParameter("ExtensionHooks", _extension.Hooks);
                jint.Run(_extension._script);
                jint.CallFunction(methodName, parameters);
            }
Exemple #3
0
        static void Main(string[] args)
        {
            string line;
            var jint = new JintEngine();

            jint.SetFunction("print", new Action<object>(s => { Console.ForegroundColor = ConsoleColor.Blue; Console.Write(s); Console.ResetColor(); }));
            #pragma warning disable 612,618
            jint.SetFunction("import", new Action<string>(s => { Assembly.LoadWithPartialName(s); }));
            #pragma warning restore 612,618
            jint.DisableSecurity();

            while (true) {
                Console.Write("jint > ");

                StringBuilder script = new StringBuilder();

                while (String.Empty != (line = Console.ReadLine())) {
                    if (line.Trim() == "exit") {
                        return;
                    }

                    if (line.Trim() == "reset") {
                        jint = new JintEngine();
                        break;
                    }

                    if (line.Trim() == "help" || line.Trim() == "?") {
                        Console.WriteLine(@"Jint Shell");
                        Console.WriteLine(@"");
                        Console.WriteLine(@"exit                - Quits the application");
                        Console.WriteLine(@"import(assembly)    - assembly: String containing the partial name of a .NET assembly to load");
                        Console.WriteLine(@"reset               - Initialize the current script");
                        Console.WriteLine(@"print(output)       - Prints the specified output to the console");
                        Console.WriteLine(@"");
                        break;
                    }

                    script.AppendLine(line);
                }

                Console.SetError(new StringWriter(new StringBuilder()));

                try {
                    jint.Execute(script.ToString());
                }
                catch (Exception e) {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine(e.Message);
                    Console.ResetColor();
                }

                Console.WriteLine();
            }
        }
Exemple #4
0
        public object execute(params KeyValuePair <string, object>[] parameters)
        {
            JintEngine executor = new JintEngine();

            foreach (KeyValuePair <String, object> KeyVal in parameters)
            {
                executor.SetParameter(KeyVal.Key, KeyVal.Value);
            }
            executor.AllowClr = true;
            executor.DisableSecurity();
            return(executor.Run(@compiledCode, false));
        }
Exemple #5
0
 public override void Compile()
 {
     this.executor = null;
     this.executor = new JintEngine();
     foreach (MethodInfo method in this.GetType().GetMethods())
     {
         if (method.GetCustomAttributes(typeof(JSFunction), true) != null)
         {
             executor.SetFunction(method.Name, delegateOf(method));
         }
     }
     executor.AllowClr = true;
     executor.DisableSecurity();
     executor.Run(SourceCode, false);
 }
Exemple #6
0
 public JavaScriptInterpreter()
 {
     Console.Write("Loading JavaScript interpreter: ");
     try
     {
         m_engine          = new JintEngine();
         m_engine.AllowClr = false;
         m_engine.DisableSecurity();
         Console.WriteLine("done.");
     }
     catch (Exception e)
     {
         Console.WriteLine("FAIL.");
         Console.WriteLine("Unable to load JavaScript engine\n*********************************************\n\t" + e.Message + "\n*********************************************");
     }
 }
Exemple #7
0
        public void ShouldRunInRun()
        {
            var filename = Path.GetTempFileName();
            File.WriteAllText(filename, "a='bar'");

            var engine = new JintEngine().AddPermission(new FileIOPermission(PermissionState.Unrestricted));
            engine.AllowClr();

            // The DLR compiler won't compile with permissions set
            engine.DisableSecurity();

            engine.SetFunction("load", new Action<string>(p => engine.ExecuteFile(p)));
            engine.SetFunction("print", new Action<string>(Console.WriteLine));
            engine.Execute("var a='foo'; load('" + EscapeStringLiteral(filename) + "'); print(a);");

            File.Delete(filename);
        }
Exemple #8
0
        public void init()
        {
            en = new JintEngine();
            en.DisableSecurity();
            en.AllowClr = true;

            en.SetFunction("print", new Action <object>(Console.WriteLine));
            en.SetFunction("alert", new Action <object>(n => {
                MessageBox.Show(n.ToString());
            }));

            //en.SetFunction("cs_exe", new Action<string>(Exe));
            //en.SetFunction("cs_exe", new Action<string, string>(Exe));
            //en.SetFunction("cs_exeWait", new Action<string, string, string>(ExeWait));
            //en.SetFunction("cs_exe", new Action<string, string, string>(Exe));
            en.SetFunction("cs_exeWait", new Action <string, string, bool, string>(ExeWait));

            en.SetFunction("cs_process", new Action <string, string, bool, string>(ExeWait));
        }
Exemple #9
0
 static public JintEngine Create()
 {
     if (jintEngine != null)
     {
         return(jintEngine);
     }
     jintEngine = new JintEngine()
                  .SetFunction("sleep", new Action <object>(Sleep))
                  .SetFunction("alert", new Action <object>(Alert))
                  .SetFunction("log", new Action <object>(logger.Info))
                  .SetFunction("error", new Action <object>(logger.Fatal))
                  .SetFunction("watchStart", new Jint.Delegates.Action(WatchStart))
                  .SetFunction("watchStop", new Action <string>(WatchStop))
                  .SetFunction("qq", new Jint.Delegates.Func <string>(qq))
                  .SetFunction("name", new Jint.Delegates.Func <string>(name))
                  .SetFunction("prompt", new Jint.Delegates.Func <string, string>(Prompt));
     jintEngine.DisableSecurity();
     jintEngine.SetDebugMode(true);
     return(jintEngine);
 }
Exemple #10
0
        private static void ExecuteV8()
        {
            const string fileName = @"..\..\..\Jint.Benchmarks\Suites\V8\raytrace.js";

            var jint = new JintEngine();

            jint.DisableSecurity();

            jint.ExecuteFile(@"..\..\..\Jint.Benchmarks\Suites\V8\base.js");

            jint.SetFunction(
                "NotifyResult",
                new Action<string, string>((name, result) => { })
            );
            jint.SetFunction(
                "NotifyError",
                new Action<string, object>((name, error) => { })
            );

            string score = null;

            jint.SetFunction(
                "NotifyScore",
                new Action<string>(p => { score = p; })
            );

            jint.ExecuteFile(fileName);

            Console.WriteLine("Attach");
            Console.ReadLine();

            jint.Execute(@"
                BenchmarkSuite.RunSuites({
                    NotifyResult: NotifyResult,
                    NotifyError: NotifyError,
                    NotifyScore: NotifyScore,
                    Runs: 1
            });");

            Console.WriteLine("Score: " + score);
        }
Exemple #11
0
        public ScriptRunner(ServiceManager svc, ExtensionClientManager clientManager)
        {
            _svc           = svc;
            _clientManager = clientManager;
            _engine.DisableSecurity();
            _engine.SetFunction("__svc_jsonCall", new Func <string, string, string>(ServiceManagerJsonCall));
            _engine.SetFunction("__ext_jsonCall", new Func <string, string, string, string>(ExtensionJsonCall));

            _preScript = string.Concat(
                Resources.json2,
                Resources.scriptrunner,
                JavaScriptInterface.GenerateJavaScriptWrapper(svc),
                clientManager.GetJavaScriptWrappers()
                );
            try
            {
                _engine.Run(_preScript);
            }
            catch (Exception ex)
            {
                LastException = ex;
            }
        }
Exemple #12
0
        static void Main3(string[] args)
        {
            JintEngine engine = new JintEngine();

            engine.DisableSecurity();
            engine.Run("1;");
            Marshaller marshal = engine.Global.Marshaller;

            JsConstructor ctor = engine.Global.Marshaller.MarshalType(typeof(Baz));

            ((JsObject)engine.Global)["Baz"]   = ctor;
            ((JsObject)engine.Global)["Int32"] = engine.Global.Marshaller.MarshalType(typeof(Int32));

            JsObject o = new JsObject();

            o["abc"] = new JsString("sure", engine.Global.StringClass.PrototypeProperty);
            engine.SetParameter("o", o);
            engine.SetParameter("ts1", new TimeSpan(1000));
            engine.SetParameter("ts2", new TimeSpan(2000));

            engine.Run(@"
if (ts1 <= ts2) {
    System.Console.WriteLine('ts1 < ts2');
}
System.Console.WriteLine('{0}',o.abc);
System.Console.WriteLine('{0}',Jint.Temp.InfoType.Name);
");



            engine.Run(@"
System.Console.WriteLine('=========FEATURES==========');
var test = new Baz();
var val;
System.Console.WriteLine('test.Name: {0}', test.Name);
System.Console.WriteLine('test.CurrentValue: {0}', test.CurrentValue);

System.Console.WriteLine('Update object using method');
test.SetTimestamp(System.DateTime.Now);
System.Console.WriteLine('test.CurrentValue: {0}', test.CurrentValue);

System.Console.WriteLine('Update object using property');
test.CurrentValue = new System.DateTime(1980,1,1);
System.Console.WriteLine('test.CurrentValue: {0}', test.CurrentValue);

System.Console.WriteLine('Update object using field');
test.t = new System.DateTime(1980,1,2);
System.Console.WriteLine('test.CurrentValue: {0}', test.CurrentValue);


System.Console.WriteLine('Is instance of Baz: {0}', test instanceof Baz ? 'yes' : 'no' );
System.Console.WriteLine('Is instance of Object: {0}', test instanceof Object ? 'yes' : 'no' );
System.Console.WriteLine('Is instance of String: {0}', test instanceof String ? 'yes' : 'no' );

System.Console.WriteLine('Constant field Int32.MaxValue: {0}', Int32.MaxValue);

System.Console.WriteLine('========= INHERITANCE FROM A CLR TYPE ==========');
function Foo(name,desc) {
    Baz.call(this,name);

    this.Description = desc;
    this.SetTimestamp(System.DateTime.Now);
}

(function(){
    var func = new Function();
    func.prototype = Baz.prototype;
    Foo.prototype = new func();
    Foo.prototype.constructor = Foo;
})();

Foo.prototype.PrintInfo = function() {
    System.Console.WriteLine('{0}: {1} ({2})', this.Name,this.Description,this.t);
}

var foo = new Foo('Gib','Mega mann');
foo.PrintInfo();

System.Console.WriteLine('========= DUMP OBJECT ==========');

function ___StandAlone() {}

for (var prop in foo){
    try {
        val = foo[prop];
    } catch(err) {
        val = 'Exception: ' + err.toString();
    }
    System.Console.WriteLine('{0} = {1}',prop,val.toString());
}

System.Console.WriteLine('========= DUMP PROTOTYPE ==========');

foo = Foo.prototype;

for (var prop in foo){
    try {
        val = foo[prop];
    } catch(err) {
        val = 'Exception: ' + err.toString();
    }
    System.Console.WriteLine('{0} = {1}',prop,val.toString());
}

System.Console.WriteLine('========= DUMP OBJECT PROTOTYPE ==========');

foo = Object.prototype;

for (var prop in foo){
    try {
        val = foo[prop];
    } catch(err) {
        val = 'Exception: ' + err.toString();
    }
    System.Console.WriteLine('{0} = {1}',prop,val.toString());
}

System.Console.WriteLine('========= TYPE INFORMATION ==========');
//System.Console.WriteLine('[{1}] {0}', test.GetType().FullName, test.GetType().GUID);
for(var prop in Baz) {
    try {
        val = Baz[prop];
    } catch (err) {
        val = 'Exception: ' + err.toString();
    }

    System.Console.WriteLine('{0} = {1}',prop,val);
}

System.Console.WriteLine('========= PERFORMANCE ==========');
");
            int ticks = Environment.TickCount;

            engine.Run(@"
            var temp;
            for (var i = 0; i < 100000; i++)
                temp = new Baz('hi');
            ");

            Console.WriteLine("new objects: {0} ms", Environment.TickCount - ticks);

            ticks = Environment.TickCount;
            engine.Run(@"
            var temp = new Baz();
            var val = ToInt32(20);
            System.Console.WriteLine('Debug: {0} + {1} = {2}', '10', val, temp.Foo('10',val));
            for (var i = 0; i < 100000; i++)
                temp.Foo('10',val);
            ");

            Console.WriteLine("method call in {0} ms", Environment.TickCount - ticks);

            ticks = Environment.TickCount;
            engine.Run(@"
            var temp = new Baz();
            for (var i = 0; i < 100000; i++)
                temp.Foo();
            ");

            Console.WriteLine("method call without args {0} ms", Environment.TickCount - ticks);

            ticks = Environment.TickCount;
            engine.Run(@"
            var temp = new Baz();
            for (var i = 0; i < 100000; i++)
                temp.CurrentValue;
            ");

            Console.WriteLine("get property {0} ms", Environment.TickCount - ticks);

            ticks = Environment.TickCount;
            engine.Run(@"
            var temp = new Baz();
            for (var i = 0; i < 100000; i++)
                temp.t;
            ");

            Console.WriteLine("get field {0} ms", Environment.TickCount - ticks);

            ticks = Environment.TickCount;
            engine.Run(@"
            for (var i = 0; i < 100000; i++)
                /**/1;
            ");

            Console.WriteLine("empty loop {0} ms", Environment.TickCount - ticks);

            //JsInstance inst = ctor.Construct(new JsInstance[0], null, visitor);

            Console.ReadKey();

            return;
        }