// Constructor
        public MainPage()
        {
            InitializeComponent();

            engine = new JintEngine();
            engine.SetFunction("alert", new Action<string>(t => MessageBox.Show(t)));
        }
Exemple #2
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();
            }
        }
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 void ShouldNotRunInRun()
        {
            var filename = Path.GetTempFileName();
            File.WriteAllText(filename, "a='bar'");

            var engine = new JintEngine().AddPermission(new FileIOPermission(PermissionState.None));
            engine.AllowClr();
            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);");
        }
Exemple #5
0
    void Start()
    {
        JintEngine e = new JintEngine();

        e.SetFunction("log",
                      new Jint.Delegates.Action <object>((a) => Debug.Log(a)));

        e.SetFunction("add",
                      new Jint.Delegates.Func <double, double, double>((a, b) => a + b));

        TextAsset script = (TextAsset)Resources.Load("Test");

        e.Run(script.text);
    }
Exemple #6
0
 protected override void CustomizeEngine(JintEngine jintEngine)
 {
     jintEngine.SetParameter("documentId", docId);
     jintEngine.SetFunction("replicateTo", new Action <string, JsObject>(ReplicateToFunction));
     foreach (var sqlReplicationTable in config.SqlReplicationTables)
     {
         var current = sqlReplicationTable;
         jintEngine.SetFunction("replicateTo" + sqlReplicationTable.TableName, (Action <JsObject>)(cols =>
         {
             var tableName = current.TableName;
             ReplicateToFunction(tableName, cols);
         }));
     }
 }
Exemple #7
0
        static public JintEngine Create(IAppContext appcontext)
        {
            context = appcontext;
            JintEngine jint = Create();

            WatiN.Core.Browser browser = new BrowserWindow(context.Browser);
            jint.SetParameter("ie", new JsBrowser(browser));
            var q = new Q(context, browser);

            jint.SetParameter("$", q);
            jint.SetFunction("Var", new Jint.Delegates.Func <string, object>(q.GetVariable));
            jint.SetFunction("getMapValue", new Jint.Delegates.Func <string, string>(getMapValue));
            return(jint);
        }
Exemple #8
0
    private void Run()
    {
        JintEngine engine = new JintEngine();

        engine.SetFunction("GTest", new Jint.Delegates.Func <object, double>(LUA_GTest));
        engine.Run("GTest([['3,3']])");
    }
        // Constructor
        public MainPage()
        {
            InitializeComponent();

            engine = new JintEngine();
            engine.SetFunction("alert", new Action <string>(t => MessageBox.Show(t)));
        }
Exemple #10
0
        internal static JintEngine CreateEngine(ScriptedPatchRequest patch)
        {
            AssertValidScript(patch.Script);
            var wrapperScript = String.Format(@"
function ExecutePatchScript(docInner){{
  (function(doc){{
	{0}{1}
  }}).apply(docInner);
}};
", patch.Script, patch.Script.EndsWith(";") ? String.Empty : ";");

            var jintEngine = new JintEngine()
                             .AllowClr(false);


            jintEngine.Run(GetFromResources("Raven.Database.Json.Map.js"));

            jintEngine.Run(GetFromResources("Raven.Database.Json.RavenDB.js"));

            jintEngine.SetFunction("LoadDocument", ((Func <string, object>)(value =>
            {
                var loadedDoc = loadDocumentStatic(value);
                if (loadedDoc == null)
                {
                    return(null);
                }
                loadedDoc[Constants.DocumentIdFieldName] = value;
                return(ToJsObject(jintEngine.Global, loadedDoc));
            })));

            jintEngine.Run(wrapperScript);

            return(jintEngine);
        }
Exemple #11
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 #12
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 #13
0
        static void Main(string[] args)
        {
            var jint   = new JintEngine().DisableSecurity();
            var script = new StreamReader(@"scripts\test.js").ReadToEnd();

            jint.SetFunction("print", new Action <object>(Console.WriteLine));

            jint.Run(script);

            Console.ReadKey();
        }
Exemple #14
0
        static void textEditor_RunBefore(object sender, EventArgs e)
        {
            codeRichEditor textEditor = sender as codeRichEditor;
            JintEngine     jint       = textEditor.JintEngine;

            WatiN.Core.Browser browser = new BrowserWindow(context.Browser);
            jint.SetParameter("ie", new JsBrowser(browser));
            jint.SetParameter("$", new Q(context, browser));
            jint.SetFunction("getMapValue", new Jint.Delegates.Func <string, string>(getMapValue));
            //jint.SetFunction("listprint", new Action<string>(listprint));
            //jint.SetFunction("tableprint", new Action<string>(tableprint));
            textEditor.FindForm().Tag = browser;
        }
Exemple #15
0
 protected override void CustomizeEngine(JintEngine jintEngine)
 {
     jintEngine.SetParameter("documentId", docId);
     jintEngine.SetFunction("sqlReplicate", (Action <string, string, JsObject>)((table, pkName, cols) =>
     {
         var itemToReplicates = dictionary.GetOrAdd(table);
         itemToReplicates.Add(new ItemToReplicate
         {
             PkName     = pkName,
             DocumentId = docId,
             Columns    = ToRavenJObject(cols)
         });
     }));
 }
Exemple #16
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 #17
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 #18
0
        static void Main(string[] args)
        {
            JsGlobal   dummy;
            JintEngine eng  = new JintEngine();
            JsArray    root = null;


            root = new JsArray();
            eng.GlobalScope["PersistentRoot"] = root;


            eng.SetDebugMode(true);
            eng.SetFunction("log"
                            , new Jint.Delegates.Func <JsInstance, JsInstance>((JsInstance obj) =>
            {
                Console.WriteLine(obj == null?"NULL":obj.Value == null?"NULL 2":obj.Value.ToString());
                return(JsUndefined.Instance);
            }));


//            ((JsFunction)eng.GlobalScope["log"]).Execute(eng.Visitor, null, new JsInstance[] { new JsUndefined() });

            //   Console.WriteLine("\r\n" + eng.Run(File.ReadAllText(@"Scripts\func_jsonifier.js")));
            Console.WriteLine("\r\n" + eng.Run(File.ReadAllText(@"Scripts\test.js")));
            while (true)
            {
                Console.Write("] ");
                var l = Console.ReadLine();
                if (l.Length == 0)
                {
                    break;
                }
                var res = eng.Run(l);
                Console.WriteLine(res == null ? "<.NET NULL>" : res.ToString());
            }
            Console.WriteLine("Saving...");
            //            Console.ReadLine();
            //    root.Modify();
            //   s.Close();
            //    Console.Write("Enter to close");
            //  Console.ReadLine();
        }
Exemple #19
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 #20
0
        private JintEngine CreateEngine(ScriptedPatchRequest patch)
        {
            var scriptWithProperLines = NormalizeLineEnding(patch.Script);
            var wrapperScript         = String.Format(@"
function ExecutePatchScript(docInner){{
  (function(doc){{
	{0}
  }}).apply(docInner);
}};
", scriptWithProperLines);

            var jintEngine = new JintEngine()
                             .AllowClr(false)
#if DEBUG
                             .SetDebugMode(true)
#else
                             .SetDebugMode(false)
#endif
                             .SetMaxRecursions(50)
                             .SetMaxSteps(maxSteps);

            AddScript(jintEngine, "Raven.Database.Json.lodash.js");
            AddScript(jintEngine, "Raven.Database.Json.ToJson.js");
            AddScript(jintEngine, "Raven.Database.Json.RavenDB.js");

            jintEngine.SetFunction("LoadDocument", ((Func <string, object>)(value =>
            {
                var loadedDoc = loadDocumentStatic(value);
                if (loadedDoc == null)
                {
                    return(null);
                }
                loadedDoc[Constants.DocumentIdFieldName] = value;
                return(ToJsObject(jintEngine.Global, loadedDoc));
            })));

            jintEngine.Run(wrapperScript);

            return(jintEngine);
        }
Exemple #21
0
        public JavascriptEngine()
        {
            engine = new JintEngine(Options.Ecmascript5 | Options.Strict);

            engine.SetFunction("include", (Func <string, object>)Include);
        }
Exemple #22
0
        public void ShouldRunInRun() {
            var filename = Path.GetTempFileName();
            File.WriteAllText(filename, "a='bar'");

            var engine = new JintEngine().AddPermission(new FileIOPermission(PermissionState.Unrestricted));
            engine.AllowClr();
            engine.SetFunction("load", new Action<string>(delegate(string fileName) { using (var reader = File.OpenText(fileName)) { engine.Run(reader); } }));
            engine.SetFunction("print", new Action<string>(Console.WriteLine));
            engine.Run("var a='foo'; load('" + JintEngine.EscapteStringLiteral(filename) + "'); print(a);");

            File.Delete(filename);
        }
Exemple #23
0
        public void ObjectShouldBePassedToDelegates() {
            var engine = new JintEngine();
            engine.SetFunction("render", new Action<object>(s => Console.WriteLine(s)));

            const string script =
                @"
                var contact = {
                    'Name': 'John Doe',
                    'PhoneNumbers': [ 
                    {
                       'Location': 'Home',
                       'Number': '555-555-1234'
                    },
                    {
                        'Location': 'Work',
                        'Number': '555-555-9999 Ext. 123'
                    }
                    ]
                };

                render(contact.Name);
                render(contact.toString());
                render(contact);
            ";

            engine.Run(script);
        }
 public static void SetFunction(this JintEngine engine, string name, Action action)
 {
     engine.SetFunction(name, new Action(action));
 }
 public static void SetFunction <TParamType, TResult>(this JintEngine engine, string name, Func <TParamType, TResult> func)
 {
     engine.SetFunction(name, new Func <TParamType, TResult>(func));
 }
Exemple #26
0
        protected virtual JintEngine CreateContext(Action<string> errorAction)
        {
            var ctx = new JintEngine();

            Action<string> failAction = Assert.Fail;
            Action<string> printAction = message => Trace.WriteLine(message);
            Action<string> includeAction = file => RunInclude(ctx, file);

            ctx.SetFunction("$FAIL", failAction);
            ctx.SetFunction("ERROR", errorAction);
            ctx.SetFunction("$ERROR", errorAction);
            ctx.SetFunction("$PRINT", printAction);
            ctx.SetFunction("$INCLUDE", includeAction);

            return ctx;
        }
Exemple #27
0
        public JavaScriptPlugin(string fileName)
        {
            PluginFile = fileName;

            _engine = new JintEngine();
            _engine.AddPermission(new FileIOPermission(PermissionState.Unrestricted));
            _engine.AllowClr = true;

            Properties = new PluginProperties(Path.GetFileName(PluginFile), PluginManager.PluginDirectoryPath);
            Properties.Load();

            _engine.SetParameter("properties", Properties);
            _engine.SetParameter("plugindir", PluginManager.PluginDirectoryPath);

            _engine.SetFunction("WriteToConsole", new Action <object>(Console.WriteLine));
            _engine.SetFunction("SubscribeToEvent", new Action <string, JsFunction>(SubscribeToEvent));
            _engine.SetFunction("UnsubscribeFromEvent", new Action <string>(UnsubscribeFromEvent));
            _engine.SetFunction("RegisterCommand", new Action <string, JsFunction>(RegisterCommand));
            _engine.SetFunction("UnregisterCommand", new Action <string>(UnregisterCommand));
            _engine.SetFunction("RegisterConsoleCommand", new Action <string, JsFunction>(RegisterConsoleCommand));
            _engine.SetFunction("UnregisterConsoleCommand", new Action <string>(UnregisterConsoleCommand));
            _engine.SetFunction("SendPacket", new Action <SharpStarClient, IPacket>(SendPacket));
            _engine.SetFunction("SendClientPacketToAll", new Action <IPacket>(SendClientPacketToAll));
            _engine.SetFunction("SendServerPacketToAll", new Action <IPacket>(SendServerPacketToAll));
            _engine.SetFunction("GetPlayerClients", new Func <IClient[]>(GetPlayerClients));
            _engine.SetFunction("GetServerClients", new Func <IClient[]>(GetServerClients));

            _engine.SetFunction("ToArray", new Func <JsArray, object[]>(JsArrayToArray));

            _registeredEvents          = new Dictionary <string, JsFunction>();
            _registeredCommands        = new Dictionary <string, JsFunction>();
            _registeredConsoleCommands = new Dictionary <string, JsFunction>();
        }
Exemple #28
0
        void init()
        {
            PythonEngine.Inst.init();

            jint = new JintEngine();

            string absUserDir = Directory.GetCurrentDirectory() + "/Js";

            jint.AddPermission(new FileIOPermission(FileIOPermissionAccess.AllAccess, absUserDir));

            //set some simple funcitons.
            Func <object, int> alert = delegate(object s)
            {
                MessageBox.Show(s.ToString());
                return(0);
            };

            Func <string, double, string, double[]> ema = delegate(string label, double days, string outLabel)
            {
                if (arrays.ContainsKey(label))
                {
                    double[] inputs  = arrays[label];
                    double[] outputs = MathUtil.calcEMA(inputs, days);
                    addArray(outLabel, outputs);
                    return(outputs);
                }
                return(null);
            };



            Func <string, string, string, double[]> diff = delegate(string label0, string label1, string outLabel)
            {
                if (arrays.ContainsKey(label0) && arrays.ContainsKey(label1))
                {
                    double[] inputs0 = arrays[label0];
                    double[] inputs1 = arrays[label1];
                    double[] outputs = MathUtil.calcDiff(inputs0, inputs1);

                    addArray(outLabel, outputs);
                    return(outputs);
                }
                return(null);
            };

            //tell canvas to line
            Func <string, double, double, double, double, double, double, int> line = delegate(string label, double part, double r, double g, double b, double a, double thickness)
            {
                if (!arrays.ContainsKey(label))
                {
                    return(1);
                }

                Color c = new Color()
                {
                    R = (byte)r,
                    G = (byte)g,
                    B = (byte)b,
                    A = (byte)a
                };

                canvas.addDrawingObj(label, arrays[label], (int)part, c, thickness, DrawingObjectType.Line);
                return(0);
            };

            Func <string, double, double, double, double, double, double, int> zeroBars = delegate(string label, double part, double r, double g, double b, double a, double thickness)
            {
                if (!arrays.ContainsKey(label))
                {
                    return(1);
                }

                Color c = new Color()
                {
                    R = (byte)r,
                    G = (byte)g,
                    B = (byte)b,
                    A = (byte)a
                };
                canvas.addDrawingObj(label, arrays[label], (int)part, c, thickness, DrawingObjectType.zVLines);

                return(0);
            };
            ////kdj('close','high','low',9,'k','d','j');

            Func <string, string, string, double, string, string, string, int> kdj
                = delegate(string close, string high, string low, double days, string k, string d, string j)
                {
                if (arrays.ContainsKey(close) && arrays.ContainsKey(high) && arrays.ContainsKey(low))
                {
                    double[] inputs0 = arrays[close];
                    double[] inputs1 = arrays[high];
                    double[] inputs2 = arrays[low];

                    double[] kArray;
                    double[] dArray;
                    double[] jArray;
                    MathUtil.calcKDJ((int)days, inputs0, inputs1, inputs2, out kArray, out dArray, out jArray);

                    addArray(k, kArray);
                    addArray(d, dArray);
                    addArray(j, jArray);

                    return(0);
                }
                return(1);
                };


            //draw candle line.
            Func <string, double, string, string, string, string, int> candleLine = delegate(string id, double part, string open, string close, string high, string low)
            {
                if (!arrays.ContainsKey(open) || !arrays.ContainsKey(close) ||
                    !arrays.ContainsKey(high) || !arrays.ContainsKey(low))
                {
                    return(1);
                }

                canvas.addKLineObj(id, (int)part, arrays[open], arrays[close], arrays[high], arrays[low]);
                return(0);
            };

            Func <string, object, int> addConfig = delegate(string id, object value)
            {
                addConfigVal(id, value);
                return(0);
            };


            Func <string, int> runScript = delegate(string scriptName)
            {
                runJsScript(scriptName);
                return(0);
            };


            Func <string, double, string, double, double, double, double, double, int> vLines = delegate(string id, double part, string label, double r, double g, double b, double a, double thickness)
            {
                if (!arrays.ContainsKey(label))
                {
                    return(1);
                }

                Color c = new Color()
                {
                    R = (byte)r,
                    G = (byte)g,
                    B = (byte)b,
                    A = (byte)a
                };

                //
                canvas.addDrawingObj(id, arrays[label], (int)part, c, thickness, DrawingObjectType.vLines);
                return(0);
            };

            //
            Func <string, string, int> setDrawItemEventHandler = delegate(string id, string handlerName)
            {
                canvas.setDrawItemEventHandler(id, handlerName);
                return(0);
            };



            jint.SetFunction("addConfig", addConfig);
            jint.SetFunction("runScript", runScript);

            jint.SetFunction("setDrawItemEventHandler", setDrawItemEventHandler);


            jint.SetFunction("alert", alert);
            jint.SetFunction("ema", ema);
            jint.SetFunction("kdj", kdj);
            jint.SetFunction("diff", diff);
            jint.SetFunction("line", line);
            jint.SetFunction("zeroBars", zeroBars);
            jint.SetFunction("candleLine", candleLine);
            jint.SetFunction("vLines", vLines);
        }
Exemple #29
0
 public void SetFunction(string name, Delegate function)
 {
     m_engine.SetFunction(name, function);
 }