public static JintEngine CreateEngine(params string[] jsFiles)
 {
     var js = new JintEngine();
     foreach (var jsFile in jsFiles)
         js.Run(File.ReadAllText(Globals.WebRoot + jsFile));
     return js;
 }
Beispiel #2
0
        public void CheckinScript(ScriptedPatchRequest request, Jint.JintEngine context)
        {
            CachedResult value;

            if (cacheDic.TryGetValue(request, out value))
            {
                if (value.Queue.Count > 20)
                {
                    return;
                }
                value.Queue.Enqueue(context);
                return;
            }
            cacheDic.AddOrUpdate(request, patchRequest =>
            {
                var queue = new ConcurrentQueue <Jint.JintEngine>();
                queue.Enqueue(context);
                return(new CachedResult
                {
                    Queue = queue,
                    Timestamp = SystemTime.UtcNow,
                    Usage = 1
                });
            }, (patchRequest, result) =>
            {
                result.Queue.Enqueue(context);
                return(result);
            });
        }
		protected override void RemoveEngineCustomizations(JintEngine jintEngine)
		{
			jintEngine.RemoveParameter("documentId");
			jintEngine.RemoveParameter("replicateTo");
			foreach (var sqlReplicationTable in config.SqlReplicationTables)
			{
				jintEngine.RemoveParameter("replicateTo" + sqlReplicationTable.TableName);
			}
		}
Beispiel #4
0
        public static void Main(String[] args)
        {
            Logger logger = new ConsoleLogger();
            Logging.SetLogger(logger);

            string script = System.IO.File.ReadAllText(args[0]);
            JintEngine engine = new JintEngine();
            engine.SetParameter("language", "cs");
            engine.SetParameter("util", new Util(engine));
            engine.Run(script);
        }
		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);
				}));
			}
		}
Beispiel #6
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);
    }
Beispiel #7
0
		public void Initialize(SmugglerOptions options)
		{
		    if (options == null || string.IsNullOrEmpty(options.TransformScript))
		        return;

		    jint = new JintEngine()
		        .AllowClr(false)
		        .SetDebugMode(false)
		        .SetMaxRecursions(50)
		        .SetMaxSteps(options.MaxStepsForTransformScript);

		    jint.Run(string.Format(@"
					function Transform(docInner){{
						return ({0}).apply(this, [docInner]);
					}};", options.TransformScript));
		}
 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*********************************************");
     }
 }
Beispiel #9
0
        public static void Main(String[] args)
        {
            Logger logger = new ConsoleLogger();
            Logging.SetLogger(logger);

            string script = System.IO.File.ReadAllText(args[0]);
            JintEngine engine = new JintEngine();
            engine.SetParameter("language", "cs");
            #if TEST_WINPHONE
            engine.SetParameter("platform", "winphone");
            #else
            engine.SetParameter("platform", "windows");
            #endif
            engine.SetParameter("util", new Util(engine));
            engine.Run(script);
        }
Beispiel #10
0
        public ExecutionVisitor(Options options, IScriptEngineContext context, JintEngine jintEngine)
        {
            JintEngine = jintEngine;
            this.scriptEngineContext = context;
            this.methodInvoker = context.GetMethodInvoker(this);//new CachedMethodInvoker(this);
            this.propertyGetter = new CachedReflectionPropertyGetter(methodInvoker);
            this.constructorInvoker = new CachedConstructorInvoker(methodInvoker);
            this.typeResolver = context.GetTypeResolver();//new CachedTypeResolver();
            this.fieldGetter = new CachedReflectionFieldGetter(methodInvoker);
            _entitiyAccessor = new EntityAccessor();

            GlobalScope = new JsObject();
            Global = new JsGlobal(this, options);
            GlobalScope.Prototype = Global as JsDictionaryObject;
            EnterScope(GlobalScope);
            CallStack = new Stack<string>();
        }
Beispiel #11
0
		public static void Initialize(SmugglerOptions options)
		{
			if (options != null && !string.IsNullOrEmpty(options.TransformScript))
			{
				jint = new JintEngine()
					.AllowClr(false)
					.SetDebugMode(false)
					.SetMaxRecursions(50)
					.SetMaxSteps(options.MaxStepsForTransformScript);

				jint.Run(string.Format(@"
					function Transform(docInner){{
						return ({0}).apply(this, [docInner]);
					}};", options.TransformScript));
			}

			propertiesTypeByName = new Dictionary<string, JTokenType>();
		}
Beispiel #12
0
        public Plugin(DirectoryInfo directory, string name, string code)
        {
            Name = name;
            Code = code;
            RootDirectory = directory;
            Timers = new Dictionary<String, TimedEvent>();

            Engine = new JintEngine();
            Engine.AllowClr(true);

            InitGlobals();
            Engine.Run(code);
            try
            {
                Engine.CallFunction("On_PluginInit");
            }
            catch { }
        }
Beispiel #13
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));
        }
Beispiel #14
0
        public override void Load(string code = "")
        {

            try {
            Engine = new JintEngine(Options.Ecmascript5)
                .AllowClr(true);

            Engine.SetParameter("Commands", chatCommands)
                .SetParameter("DataStore", DataStore.GetInstance())
                .SetParameter("Find", Find.GetInstance())
                .SetParameter("GlobalData", GlobalData)
                .SetParameter("Plugin", this)
                .SetParameter("Server", Server.GetInstance())
                .SetParameter("ServerConsoleCommands", consoleCommands)
                .SetParameter("Util", Util.GetInstance())
                .SetParameter("Web", Web)
                .SetParameter("World", World.GetInstance())
                .SetFunction("importClass", new importit(importClass));
                Program = JintEngine.Compile(code, false);

                Globals = (from statement in Program.Statements
                                       where statement.GetType() == typeof(FunctionDeclarationStatement)
                                       select ((FunctionDeclarationStatement)statement).Name).ToList<string>();

                Engine.Run(Program);

                object author = GetGlobalObject("Author");
                object about = GetGlobalObject("About");
                object version = GetGlobalObject("Version");
                Author = author == null ? "" : author.ToString();
                About = about == null ? "" : about.ToString();
                Version = version == null ? "" : version.ToString();

                State = PluginState.Loaded;
            } catch (Exception ex) {
                Logger.LogException(ex);
                State = PluginState.FailedToLoad;
                PluginLoader.GetInstance().CurrentlyLoadingPlugins.Remove(Name);
            }

            PluginLoader.GetInstance().OnPluginLoaded(this);
        }
        public static string CallJInt(string expression)
        {
            string _result = "";
            string _expression = expression;

            try
            {
                // execute the expression
                object _returnValue = new JintEngine().Run(_expression);

                if (_returnValue != null)
                {
                    _result = _returnValue.ToString();
                }
            }
            catch (Exception ex)
            {
                _result = "$$ERR:" + ex.Message;
                IGenFormCommonRoutines._processMessages.Add("For expression: " + expression + ", err=" + ex.Message);
            }

            return _result;
        }
Beispiel #16
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();
        }
        public void JintTest()
        {
            string script = @"
return this;
 name = '209.97.203.60';
 port1 = 1312;
 port2 = 3749;
 port3 = 8691;
 port4 = 9215;
 port5 = 7419;
 port6 = 9777;
 port7 = 8194;
 port8 = 8864;
 port9 = 6929;
 port10 = 8378;
 WQGYJD = port9 + (101629-341) / 88;
 return(name + ':' + WQGYJD);
";
            JintEngine context = new JintEngine();
            var result = context.Run(script);
            Assert.IsNotNull(result);
        }
Beispiel #18
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;
		}
Beispiel #19
0
 public Util(JintEngine engine)
 {
     this.engine = engine;
 }
Beispiel #20
0
 public static JintEngine Load(Stream s) {
     JintEngine engine = new JintEngine();
     Load(engine, s);
     return engine;
 }
Beispiel #21
0
 public static void Load(JintEngine engine, Stream s) {
     BinaryFormatter formatter = new BinaryFormatter();
     var visitor = (ExecutionVisitor)formatter.Deserialize(s);
     engine.Visitor = visitor;
 }
Beispiel #22
0
        private object ProcessValue(string val)
        {
            var engine = new JintEngine();
            engine.SetParameter("$root", _data.Last());
            engine.SetParameter("$data", _data.Peek());
            engine.SetParameter("ko", Ko.Instance);
            if (_data.Count > 1)
                engine.SetParameter("$parent", _data.ElementAt(1));

            // TODO: Support jQuery and Knockout libraries.
            //engine.Run(Properties.Resources.jquery);
            //engine.Run(Properties.Resources.knockout);

            // Simplify $root vars by ignoring $parent(s) leading up to it.
            val = RootPat.Replace(val, m => "$root.");

            #region Handle $parent chains and $parents[i] pseudovariables.
            // Simplify $parent(s) chains into a single $parents[generations] variable.
            val = ParentPat.Replace(val, m => string.Format("$parents{0}.",
                                                                m.Groups["Index"].Captures.Cast<Capture>()
                                                                    .Sum(c => int.Parse(c.Value) - 1) +
                                                                m.Groups[1].Captures.Count));
            // Assign the appropriate data value from the stack.
            foreach (var m in from Match m in ParentsPat.Matches(val) select m.Groups[1].Value)
                engine.SetParameter("$parents" + m, _data.ElementAt(_data.Count - int.Parse(m)));
            #endregion

            // 1. Find non-js keyword members and prefix them with "$data."
            // 2. Capitalize the first letter after a dot or space to conform to C# naming conventions.
            val = Word.Replace(val, m => (ReservedKeywords.IsMatch(m.Groups["Word"].Value) || m.Groups[1].Value == "$")
                                         	? m.Value
                                         	: string.Concat(m.Groups[1].Value,
                                         	                DotOrDollar.IsMatch(m.Groups[1].Value) ? string.Empty : "$data.",
                                         	                m.Groups["c1"].Value.ToUpper(),
                                         	                m.Groups[2].Value));
            return engine.Run(val);
        }
Beispiel #23
0
        void worker_DoWork(object sender, DoWorkEventArgs e)
        {
            string script=textEditor1.Text;

            IsInNetDelegate IsInNet = PacExtensions.IsInNetAction;
            localHostOrDomainIsDelegate localHostOrDomainIs = PacExtensions.localHostOrDomainIs;
            myIpAddressDelegate myIpAddress = PacExtensions.myIpAddress;
            isResolvableDelegate isResolvable = PacExtensions.isResolvable;
            dateRangeDelegate dateRange = PacExtensions.dateRange;
            weekdayRangeDelegate weekdayRange = PacExtensions.weekdayRange;
            timeRangeDelegate timeRange = PacExtensions.timeRange;
            isPlainHostNameDelegate isPlainHostName = PacExtensions.isPlainHostName;
            dnsDomainIsDelegate dnsDomainIs = PacExtensions.dnsDomainIs;
            dnsResolveDelegate dnsResolve = PacExtensions.dnsResolve;
            alertDelegate alert = PacExtensions.alert;
            dnsDomainLevelsDelegate dnsDomainLevels = PacExtensions.dnsDomainLevels;
            shExpMatchDelegate shExpMatch = PacExtensions.shExpMatch;

            JintEngine jint = new JintEngine()
                .SetDebugMode(true)
                .SetFunction("isInNet", IsInNet)
                .SetFunction("localHostOrDomainIs", localHostOrDomainIs)
                .SetFunction("myIpAddress", myIpAddress)
                .SetFunction("isResolvable", isResolvable)
                .SetFunction("dateRange", dateRange)
                .SetFunction("weekdayRange", weekdayRange)
                .SetFunction("timeRange", timeRange)
                .SetFunction("isPlainHostName", isPlainHostName)
                .SetFunction("dnsDomainIs", dnsDomainIs)
                .SetFunction("dnsResolve", dnsResolve)
                .SetFunction("alert", alert)
                .SetFunction("dnsDomainLevels", dnsDomainLevels)
                .SetFunction("shExpMatch", shExpMatch);

            try
            {
                jint.Step += jint_Step;
                textEditor1.Text = script;

                var result = jint.Run(script);

                executionHistory.Clear();
                listBox1.Invoke(new Action(delegate
                {
                    listBox1.Items.Clear();
                }));

                Uri uri;

                if (!textBoxURL.Text.Contains("://"))
                {
                    this.Invoke(new Action(delegate
                        {
                            textBoxURL.Text = "http://" + textBoxURL.Text;
                        }));
                }
                if (!Uri.TryCreate(textBoxURL.Text, UriKind.Absolute, out uri))
                {
                    listView1.Invoke(new Action(delegate
                        {
                            listView1.Items.Add(string.Format("'{0}' is not a valid URL", textBoxURL.Text), 2);
                        }));
                }
                else
                {
                    PacExtensions.CounterReset();
                    result = jint.Run(string.Format("FindProxyForURL(\"{0}\",\"{1}\")", uri.ToString(), uri.Host));

                    Trace.WriteLine(result);
                    textBoxProxy.Invoke(new Action(delegate
                    {
                        listView1.Items.Add(string.Format("IsInNet Count: {0} Total Duration: {1} ms", PacExtensions.IsInNetCount, PacExtensions.IsInNetDuration.Milliseconds));
                        listView1.Items.Add(string.Format("DnsDomainIs Count: {0} Total Duration: {1} ms", PacExtensions.DnsDomainIsCount, PacExtensions.DnsDomainIsDuration.Milliseconds));

                        textBoxProxy.Text = result.ToString();
                        foreach (string s in PacExtensions.EvaluationHistory)
                        {
                            listView1.Items.Add(s, 0);
                        }
                    }));
                }



            }

            catch (Jint.Native.JsException ex)
            {
                listBox1.Invoke(new Action(delegate
                {
                    string msg = ex.Message.Replace("An unexpected error occurred while parsing the script. Jint.JintException: ", "");
                    listView1.Items.Add(msg, 2);
                }));


            }
            catch (System.NullReferenceException)
            {
                listBox1.Invoke(new Action(delegate
                {
                    string msg = "Null reference. Probably variable/function not defined, remember functions and variables are case sensitive.";
                    listView1.Items.Add(msg, 2);
                }));
            }
            catch (JintException ex)
            {
                listBox1.Invoke(new Action(delegate
                {
                    int i = ex.InnerException.ToString().IndexOf(":");

                    string msg = ex.InnerException.ToString();

                    if (msg.Contains("line"))
                    {
                        int x = msg.IndexOf("line");
                        int y = msg.IndexOf(":", x);
                        if (y > 0)
                        {
                            string lineNumber = msg.Substring(x + 5, y - x - 5);
                            int line;
                            if (Int32.TryParse(lineNumber, out line))
                            {
                                textEditor1.HighlightActiveLine = true;
                                textEditor1.GotoLine(line - 1);
                            }
                        }
                    }

                    if (i > 0)
                    {
                       msg= msg.Substring(i + 1);
                    }
                    msg = msg.Substring(0, msg.IndexOf("  at Jint."));

                    if (msg.Contains("Object reference not set to an instance of an object."))
                    {
                        msg = "Variable/Function not defined. Remember variables/functions are case sensitive.";
                    }

                    //.Replace("An unexpected error occurred while parsing the script. Jint.JintException: ", "");
                    listView1.Items.Add(msg, 2);

                    if (!msg.Contains("Variable/Function not defined."))
                    {

                        listBox1.Items.Add(string.Format("Fatal Error: {0}. {1}", ex.Message, ex.InnerException));
                    }
                }));
            }
            catch (Exception ex)
            {
                listBox1.Invoke(new Action(delegate
                {
                    listBox1.Items.Add(string.Format("Fatal Error: {0}", ex.Message));
                }));
            }
        }
Beispiel #24
0
		private void OutputLog(JintEngine engine)
		{
			var arr = engine.GetParameter("debug_outputs") as JsArray;
			if (arr == null)
				return;
			for (int i = 0; i < arr.Length; i++)
			{
				var o = arr.get(i);
				if (o == null)
					continue;
				Debug.Add(o.ToString());
			}
		}
Beispiel #25
0
		protected virtual void CustomizeEngine(JintEngine jintEngine)
		{
		}
Beispiel #26
0
		protected virtual void RemoveEngineCustomizations(JintEngine jintEngine)
		{
		}
Beispiel #27
0
		private static void AddScript(JintEngine jintEngine, string ravenDatabaseJsonMapJs)
		{
			jintEngine.Run(GetFromResources(ravenDatabaseJsonMapJs));
		}
Beispiel #28
0
			protected override void RemoveEngineCustomizations(JintEngine jintEngine)
			{
				jintEngine.RemoveParameter("documentId");
				jintEngine.RemoveParameter("sqlReplicate");
			}
Beispiel #29
0
		internal static JintEngine CreateEngine(ScriptedPatchRequest patch)
		{
			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)
				.SetDebugMode(false)
				.SetMaxRecursions(50)
				.SetMaxSteps(10*1000);


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

			jintEngine.Run(GetFromResources("Raven.Database.Json.lodash.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;
		}
Beispiel #30
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)
					});
				}));
			}
Beispiel #31
0
 public Jint()
 {
     JintEngine = new JintEngine();
 }
Beispiel #32
0
        public static void Load(JintEngine engine, Stream s)
        {
            ExecutionVisitor executionVisitor = (ExecutionVisitor) new BinaryFormatter().Deserialize(s);

            engine.visitor = executionVisitor;
        }