Run() public method

Runs a set of JavaScript statements and optionally returns a value if return is called
public Run ( Program program ) : object
program Program The expression tree to execute
return object
 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;
 }
Ejemplo n.º 2
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);
        }
Ejemplo n.º 3
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);
    }
Ejemplo n.º 4
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();
        }
Ejemplo n.º 5
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);
        }
Ejemplo n.º 6
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));
		}
Ejemplo n.º 7
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 { }
        }
Ejemplo n.º 8
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>();
		}
Ejemplo n.º 9
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);
        }
Ejemplo n.º 10
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;
		}
Ejemplo n.º 11
0
		private static void AddScript(JintEngine jintEngine, string ravenDatabaseJsonMapJs)
		{
			jintEngine.Run(GetFromResources(ravenDatabaseJsonMapJs));
		}
Ejemplo n.º 12
0
        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);
        }
Ejemplo n.º 13
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;
		}
Ejemplo n.º 14
0
        /// <summary>
        /// 获取待运行活动
        /// </summary>
        /// <param name="processDefID"></param>
        /// <param name="srcActInst"></param>
        /// <returns></returns>
        public IList<Activity> GetActivateActivities(string processDefID, ActivityInst srcActInst)
        {
            IList<Definition.Transition> transitions = Persistence.GetOutTransitions(processDefID, srcActInst.ActivityDefID);
            Activity srcActDef = Persistence.GetActivity(processDefID, srcActInst.ActivityDefID);

            IList<Activity> activateActivities = new List<Activity>();
            Activity defaultActivity = null;
            foreach (var transition in transitions)
            {
                //IDictionary<string, object> parameters = new Dictionary<string, object>();
                //parameters.SafeAdd("money", 1000);
                //parameters.SafeAdd("number", 4);
                //Context.Parameters = parameters;
                ////engine.SetParameter(":money", 1000);
                //transition.Expression = "return @money-100>0&&@number<10;";
                //new Regex(@"[^@@](?<p>@\w+)");对@@value,不表示变量;Regex(@"@\w*")以@开头的表示变量。
                string expression = transition.Expression;
                try
                {
                    bool expressionResult = string.IsNullOrWhiteSpace(expression);
                    if (!expressionResult)
                    {
                        var prefix = WFUtil.ExpressionVariablePrefix;
                        Regex regex = new Regex(string.Format(@"{0}\w*", prefix));
                        MatchCollection matches = regex.Matches(expression.Replace(string.Format("{0}{0}", prefix), "###"));
                        JintEngine engine = new JintEngine();

                        if (matches != null && Context.Parameters != null)
                        {
                            foreach (Match match in matches)
                            {
                                string variable = match.Value.TrimStart(prefix);
                                if (Context.Parameters.ContainsKey(variable))
                                    engine.SetParameter(variable, Context.Parameters[variable]);
                            }
                        }
                        expression = expression.Replace(string.Format("{0}{0}", prefix), "###").Replace(prefix.ToString(), "").Replace("###", prefix.ToString());
                        expressionResult = (bool)engine.Run(expression);
                    }

                    Activity destActivity = Persistence.GetActivity(processDefID, transition.DestActivity);
                    //记住默认活动
                    if (transition.IsDefault) defaultActivity = destActivity;

                    if (expressionResult && CanActivateActiviy(srcActInst.ProcessInstID, destActivity))
                    {
                        activateActivities.SafeAdd(destActivity);
                    }
                }
                catch (Exception ex)
                {
                    WFUtil.HandleException(new WFException(typeof(ProcessRuntime).FullName, string.Format("计算表达式{0}出错", expression), ex));
                    throw;
                }

            }

            if (activateActivities.Count == 0 && defaultActivity != null && CanActivateActiviy(srcActInst.ProcessInstID, defaultActivity))
            {
                activateActivities.Add(defaultActivity);
            }

            return activateActivities;
        }
Ejemplo n.º 15
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);
        }
Ejemplo n.º 16
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));
                }));
            }
        }
Ejemplo n.º 17
0
 private void LoadJavascriptCode(String javascript)
 {
     _engine = new JintEngine();
     _engine.EnableSecurity();
     _engine.AllowClr = true;
     _engine.Run(javascript);
 }