예제 #1
7
		public void ProcessMessage(object source, Message message)
		{
			string jsonScript = "var msg = " + JsonConvert.SerializeXmlNode(message.GetXmlDocument(), Formatting.Indented, true);

			Engine engine = new Engine();
			engine.SetValue("message", message);
			engine.Execute(jsonScript);
			engine.Execute(Script);
			engine.Execute("var jsonMsg = JSON.stringify(msg);");
			JsValue obj = engine.GetValue("jsonMsg");

			string jsonString = obj.AsString();
			var document = JsonConvert.DeserializeXNode(jsonString, "HL7Message");
			message.SetValueFrom(document);
		}
예제 #2
1
		private Engine CreateEngine(ScriptedPatchRequest patch)
		{
			var scriptWithProperLines = NormalizeLineEnding(patch.Script);
			// NOTE: we merged few first lines of wrapping script to make sure {0} is at line 0.
			// This will all us to show proper line number using user lines locations.
			var wrapperScript = String.Format(@"function ExecutePatchScript(docInner){{ (function(doc){{ {0} }}).apply(docInner); }};", scriptWithProperLines);

			var jintEngine = new Engine(cfg =>
			{
#if DEBUG
				cfg.AllowDebuggerStatement();
#else
				cfg.AllowDebuggerStatement(false);
#endif
				cfg.LimitRecursion(1024);
				cfg.MaxStatements(maxSteps);
			});

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

			jintEngine.Execute(wrapperScript, new ParserOptions
			{
				Source = "main.js"
			});

			return jintEngine;
		}
예제 #3
1
파일: KcAuth.cs 프로젝트: trhyfgh/OoiSharp
        private static Task UpdateKcInfo(double cacheHour = 1)
        {
            return Task.Run(() => {
                infoLock.EnterUpgradeableReadLock();
                if((DateTimeOffset.Now - lastUpdate).TotalHours < cacheHour) {
                    infoLock.ExitUpgradeableReadLock();
                    return;
                }
                infoLock.EnterWriteLock();
                try {
                    if((DateTimeOffset.Now - lastUpdate).TotalHours < cacheHour) {
                        return;
                    }

                    Engine interpreter = new Engine(cfg => cfg
                        .LocalTimeZone(TimeZoneInfo.FindSystemTimeZoneById("Tokyo Standard Time"))
                        .Culture(System.Globalization.CultureInfo.GetCultureInfo("ja-JP"))
                        .MaxStatements(100)
                        .LimitRecursion(2));

                    var hwr = Forwarder.CreateRequest(KcsConstantsJs);
                    hwr.Method = "GET";
                    using(var resp = hwr.GetResponse())
                    using(var jsRdr = new StreamReader(resp.GetResponseStream()))
                        interpreter.Execute(jsRdr.ReadToEnd());

                    var urlInfo = interpreter.GetValue("ConstURLInfo");
                    kcLoginUrl = interpreter.GetValue(urlInfo, "LoginURL").AsString();
                    //kcTokenUrl = interpreter.GetValue(urlInfo, "GetTokenURL").AsString();
                    kcWorldUrl = interpreter.GetValue(urlInfo, "GetUserWorldURL").AsString();

                    var maintenanceInfo = interpreter.GetValue("MaintenanceInfo");
                    maintenanceOngoing = interpreter.GetValue(maintenanceInfo, "IsDoing").AsNumber() != 0;
                    maintenanceStart = UnixTimestamp.MillisecondTimestampToDateTimeOffset(interpreter.GetValue(maintenanceInfo, "StartDateTime").AsNumber());
                    maintenanceEnd = UnixTimestamp.MillisecondTimestampToDateTimeOffset(interpreter.GetValue(maintenanceInfo, "EndDateTime").AsNumber());

                    servers.Clear();
                    var serverInfo = interpreter.GetValue("ConstServerInfo");
                    foreach(var kv in serverInfo.AsObject().GetOwnProperties()) {
                        if(kv.Value.Value?.IsString() != true) continue;
                        servers.Add(kv.Key, kv.Value.Value.Value.AsString());
                    }

                    lastUpdate = DateTimeOffset.UtcNow;
                } finally {
                    infoLock.ExitWriteLock();
                    infoLock.ExitUpgradeableReadLock();
                }
            });
        }
        protected override object InnerEvaluate(string expression, string documentName)
        {
            object result;
            string uniqueDocumentName           = _documentNameManager.GetUniqueName(documentName);
            OriginalParserOptions parserOptions = CreateParserOptions(uniqueDocumentName);

            lock (_executionSynchronizer)
            {
                OriginalValue resultValue;

                try
                {
                    resultValue = _jsEngine.Execute(expression, parserOptions).GetCompletionValue();
                }
                catch (OriginalParserException e)
                {
                    throw WrapParserException(e);
                }
                catch (OriginalRuntimeException e)
                {
                    throw WrapRuntimeException(e);
                }
                catch (TimeoutException e)
                {
                    throw WrapTimeoutException(e);
                }

                result = MapToHostType(resultValue);
            }

            return(result);
        }
예제 #5
0
파일: JistEngine.cs 프로젝트: wwa171/Jist
        protected void ExecuteHardCodedScripts()
        {
            lock (syncRoot)
                jsEngine.Execute(@"dump = function(o) {
    var s = '';

    if (typeof(o) == 'undefined') return 'undefined';

    if (typeof o.valueOf == 'undefined') return ""'valueOf()' is missing on '"" + (typeof o) + ""' - if you are inheriting from V8ManagedObject, make sure you are not blocking the property."";

    if (typeof o.toString == 'undefined') return ""'toString()' is missing on '"" + o.valueOf() + ""' - if you are inheriting from V8ManagedObject, make sure you are not blocking the property."";

    for (var p in o) {
        var ov = '',
            pv = '';

        try {
            ov = o.valueOf();
        } catch (e) {
            ov = '{error: ' + e.message + ': ' + dump(o) + '}';
        }

        try {
            pv = o[p];
        } catch (e) {
            pv = e.message;
        }

        s += '* ' + ov + '.' + p + ' = (' + pv + ')\r\n';
    }

    return s;
}");
        }
예제 #6
0
        protected override void InnerExecute(string code, string documentName)
        {
            string uniqueDocumentName           = _documentNameManager.GetUniqueName(documentName);
            OriginalParserOptions parserOptions = CreateParserOptions(uniqueDocumentName);

            lock (_executionSynchronizer)
            {
                try
                {
                    _jsEngine.Execute(code, parserOptions);
                }
                catch (OriginalParserException e)
                {
                    throw WrapParserException(e);
                }
                catch (OriginalRuntimeException e)
                {
                    throw WrapRuntimeException(e);
                }
                catch (TimeoutException e)
                {
                    throw WrapTimeoutException(e);
                }
            }
        }
예제 #7
0
        protected override void OnCommonUpdate()
        {
            base.OnCommonUpdate();

            try
            {
                engine.Execute("Update();");
            }
            catch (Jint.Parser.ParserException E)
            {
                DebugError.Value = "Update() Line " + E.LineNumber + " : " + E.Description;
            }
            catch (Exception) { }
            if (impulseRun.Value)
            {
                try
                {
                    engine.Execute("Run();");
                }
                catch (Jint.Parser.ParserException E)
                {
                    DebugError.Value = "Run() Line " + E.LineNumber + " : " + E.Description;
                }
                catch (Exception)
                {
                }
                impulseRun.Value = false;
            }
        }
예제 #8
0
        public void Test4()
        {
            Jint.Engine engine       = new Jint.Engine();
            IDocument   htmlDocument = new Document();

            htmlDocument.HtmlDocument = new AngleSharp.Html.Parser.HtmlParser().ParseDocument(htmlContent);

            Window.Window window1 = new Window.Window(engine);
            window1.document = htmlDocument.HtmlDocument;

            window1.InitializeEngine();
            var jquery = System.IO.File.ReadAllText(@"../../../../BrowseSharpPlayground/jquery.js");

            //engine.Execute("window.document.readyState = \"Loading\";");
            engine.Execute(jquery);

            engine.Execute("var $ = window.jQuery;");
            var script = "$(document).ready(function() {$('#content').text('hello there it worked');})";
            //var cleanedScript = new Regex();
            Regex regex = new Regex(@"(\$\([^document]*document[^)]*\)[^.]*.ready[^(]*\([^function]*function[^(]*\([^)]*\)[^{]*{)([^a|a]*)(}\))");

            engine.Execute(regex.Match(script).Groups[2].Value);
            //engine.Execute("window.document.readyState = 'complete'");
            //engine.Execute("$(document).trigger('ready',window.document)");
            //engine.Execute("$(document).trigger('ready')");
            Assert.AreEqual("hello there it worked", window1.document.GetElementById("content").TextContent);
        }
예제 #9
0
파일: CDSCode.cs 프로젝트: Threadnaught/CDS
 static Engine PrepareEngine(string code)
 {
     Engine e = new Engine(f => f.AllowClr(typeof(CDSData).Assembly));
     e.SetValue("Log", new Action<Object>(Console.WriteLine)); //change to write data to a node rather than to console later
     e.Execute("var CDSCommon = importNamespace('CDS.Common');");
     e.Execute(code);
     return e;
 }
예제 #10
0
        /// <summary>
        /// Initializes a new instance of the CoffeeScriptPluginLoader class
        /// </summary>
        /// <param name="engine"></param>
        public CoffeeScriptPluginLoader(Engine engine)
        {
            JavaScriptEngine = engine;

            using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(compilerResourcePath))
                using (var reader = new StreamReader(stream))
                    engine.Execute(reader.ReadToEnd(), new ParserOptions { Source = "CoffeeScriptCompiler" });
            engine.Execute("function __CompileScript(name){return CoffeeScript.compile(name+\"=\\n\"+__CoffeeSource.replace(/^/gm, '  '),{bare: true})}");
        }
예제 #11
0
        public async Task jQueryClickTest()
        {
            string script = "var numClicks = 0;\n" +
                            "$('#btn').click(function() {\n" +
                            "$('#message').text(\"hello there you clicked the button \" + numClicks + \" times\");\n" +
                            "});";
            string html = @"<!DOCTYPE html>\n<html>
	<head>
		
	</head>
	<body>
		<div id='message'>empty</div>
        <input type='button' id='btn'>Click me please</input>
	</body>
</html>";

            Jint.Engine engine   = new Jint.Engine();
            IDocument   document = new Document();
            var         parser   = new AngleSharp.Html.Parser.HtmlParser(new AngleSharp.Html.Parser.HtmlParserOptions()
            {
                IsScripting = true
            });

            bool waitForScripts = true;

            //parser.AddEventListener(AngleSharp.Dom.EventNames.Parsing, (target,ev) => { document.HtmlDocument = (IHtmlDocument)target; while (waitForScripts) { Thread.Sleep(250); } });
            //CancellationToken parserCanellationToken = new CancellationToken();

            /*Task<IHtmlDocument> parseTask = Task.Run(() => { return parser.ParseDocumentAsync(html, parserCanellationToken); });
             *
             *  Thread.Sleep(500);
             *  while(document.HtmlDocument == null)
             * {
             *
             * }*/
            Window.Window window1 = new Window.Window(engine);
            window1.document = parser.ParseDocument(html);

            window1.InitializeEngine();
            var jquery = System.IO.File.ReadAllText(@"../../../../BrowseSharpPlayground/jquery.js");

            //engine.Execute("window.document.readyState = \"Loading\";");
            engine.Execute(jquery);
            engine.Execute("var $ = window.jQuery;");

            engine.Execute(script);
            waitForScripts = false;;
            CheckMessage(engine, document, "empty");

            engine.Execute("$('#btn').trigger('click');");
            CheckMessage(engine, document, "hello there you clicked the button 1 times");
        }
예제 #12
0
        private void CheckMessage(Jint.Engine engine, IDocument document, string message)
        {
            string messageContentJintJqueryInitial = engine.Execute("$('#message').text();").GetCompletionValue().AsString();

            Assert.AreEqual(message, messageContentJintJqueryInitial);

            string messageContentJintVanillaInitial = engine.Execute("document.getElementById('message').textContent;").GetCompletionValue().AsString();

            Assert.AreEqual(message, messageContentJintVanillaInitial);

            string messageContentAngleSharpInitial = engine.Execute("document.getElementById('message').textContent;").GetCompletionValue().AsString();

            Assert.AreEqual(message, document.HtmlDocument.GetElementById("message").TextContent);
        }
예제 #13
0
        public void TestJint()
        {
            var ngfmPrototype = new NGFMPrototype();

            Jint.Engine JintEngine = new Jint.Engine();
            JintEngine.Execute(System.IO.File.ReadAllText(ngfmPrototype.underscore_js));
            JintEngine.Execute(System.IO.File.ReadAllText(ngfmPrototype.grammar_ast_js));

            string strCDL = "Contract Declarations Subject is Loss to Acme by HU Inception is 5 Jun 2014 Expiration is 4 Jun 2015 PolicyNum is A5059-3 Covers 100% share of 10M Sublimits 10000 by Wind";

            strCDL = strCDL.Replace(System.Environment.NewLine, "     ");

            Dictionary <string, object> IR =
                (Dictionary <string, object>)(AsPOJO(JintEngine.Execute("grammarAst.parse('" + strCDL + "')").GetCompletionValue()));
        }
예제 #14
0
        static void Main(string[] args)
        {
            string datePattern      = @"([0-2]?[0-9]|3[0-1])/(0?[0-9]|1[0-2])/([0-9][0-9])?[0-9][0-9]|([0-9][0-9])?[0-9][0-9]/(0?[0-9]|1[0-2])/([0-2]?[0-9]|3[0-1])";
            string equationInString = "12/12/2018 - 11/11/2017";

            MatchCollection dateMatcher  = Regex.Matches(equationInString, datePattern);
            List <DateTime> dateTimeList = new List <DateTime>();

            if (dateMatcher.Count > 0)
            {
                foreach (Match match in dateMatcher)
                {
                    Console.WriteLine(match.Value);
                }
            }

            Jint.Engine scriptEngine = new Jint.Engine();
            Console.WriteLine("this: " + scriptEngine.Execute("\'this is good\'>= \'what is this\'").GetCompletionValue());
            //TestClass.Testing_for_ALL_Node_Lines_and_features_10();

            //TestClass.Testing_Whole_Features_Of_ValueConclusionLine_ComparisonLine_and_ExprConclusionLine_9();

            //TestClass.Testing_Whole_Features_Of_ValueConclusionLIne_and_ComparisonLine_8();
            //TestClass.Tesing_Full_ValueConclusion_Comparison_7();
            //TestClass.Testing_ValueConclusionLine_6();
            //TestClass.Testing_Inference_For_NotKnownManOpPo_5();
            //TestClass.Testing_For_Reading_NotKnownMandatoryPossiblyAndOptionally_4();
            //TestClass.WeddingPlanner_Inference_Test_3();
            //TestClass.TopoSortingTest_2();
            //TestClass.Testing();
        }
예제 #15
0
        public void Initialize(string javascript)
        {
            lock (_sync) {
                try {
                    // Define the aggregator
                    mng = _engine.Execute(javascript).GetCompletionValue().AsObject();
                } catch (Exception ex) {
                    var details = string.Format(@"Error, unable to execute initial script:
Javascript
------
{0}
------
Message: {1}
In: {2}

The script needs to follow the pattern: 

E.g. `(function () { return this; })();`
",
                                                javascript,
                                                ex.Message,
                                                _errorMessageContext + ":" + "Initialize"
                                                );
                    throw new JavascriptException(details, ex);
                }
            }
        }
예제 #16
0
 public void loop()
 {
     string loopscript = File.ReadAllText("scripts/loop.js");
     Jint.Engine jsint = new Jint.Engine();
     jsint.SetValue("debuglog", new Action<object>(Console.WriteLine));
     jsint.Execute(loopscript);
 }
예제 #17
0
        public void FuncTest()
        {
            var engine = new Engine()
                .SetValue("hello", (Func<string, string>)(a => a));
            engine.Execute(@"
      function getWord(word) { 
        return hello(word);
      };

      getWord('Hello World');");
            var value = engine.GetCompletionValue().ToObject();
            Assert.AreEqual("Hello World", value);
            engine.Execute("getWord('worldbye')");
            value = engine.GetCompletionValue().ToObject();
            Assert.AreEqual("worldbye", value);
        }
예제 #18
0
 public void Construct(params string[] JavascriptSourceFiles)
 {
     JintEngine = new Jint.Engine();
     foreach (string JavascriptSourceFile in JavascriptSourceFiles)
     {
         JintEngine.Execute(System.IO.File.ReadAllText(JavascriptSourceFile));
     }
 }
        protected override object InnerEvaluate(string expression, string documentName)
        {
            object result;
            string uniqueDocumentName           = _documentNameManager.GetUniqueName(documentName);
            OriginalParserOptions parserOptions = CreateParserOptions(uniqueDocumentName);

            lock (_executionSynchronizer)
            {
                OriginalValue resultValue;

                try
                {
                    resultValue = _jsEngine.Execute(expression, parserOptions).GetCompletionValue();
                }
                catch (OriginalParserException e)
                {
                    throw WrapParserException(e);
                }
                catch (OriginalJavaScriptException e)
                {
                    throw WrapJavaScriptException(e);
                }
                catch (OriginalMemoryLimitExceededException e)
                {
                    throw WrapMemoryLimitExceededException(e);
                }
                catch (OriginalRecursionDepthOverflowException e)
                {
                    throw WrapRecursionDepthOverflowException(e);
                }
                catch (OriginalStatementsCountOverflowException e)
                {
                    throw WrapStatementsCountOverflowException(e);
                }
                catch (TimeoutException e)
                {
                    throw WrapTimeoutException(e);
                }

                result = MapToHostType(resultValue);
            }

            return(result);
        }
예제 #20
0
        public void Import(string path)
        {
            // TODO: IO Manager
            string folderPath = PackageManager.GetAssetsFolder(gameMetadata);
            string fullPath   = Path.Combine(folderPath, path);

            string jsCode = File.ReadAllText(fullPath);

            engine.Execute(jsCode);
        }
예제 #21
0
        public void Test3()
        {
            Jint.Engine engine       = new Jint.Engine();
            IDocument   htmlDocument = new Document();

            htmlDocument.HtmlDocument = new AngleSharp.Html.Parser.HtmlParser().ParseDocument(htmlContent);

            Window.Window window1 = new Window.Window(engine);
            window1.document = htmlDocument.HtmlDocument;

            window1.InitializeEngine();
            var jquery = System.IO.File.ReadAllText(@"../../../../BrowseSharpPlayground/jquery.js");

            engine.Execute(jquery);
            engine.Execute("var $ = window.jQuery;");
            engine.Execute("$('#content').text('hello there it worked');");
            //engine.Execute("$(document).trigger('ready')");
            Assert.AreEqual("hello there it worked", window1.document.GetElementById("content").TextContent);
        }
예제 #22
0
        public static void DefinedDotNetApi()
        {
            var engine = new Jint.Engine();

            engine.SetValue("demoJSApi", new DemoJavascriptApi());

            var result = engine.Execute("demoJSApi.helloWorldFromDotNet('TestTest')").GetCompletionValue();

            Console.WriteLine(result);
        }
예제 #23
0
        public void TestToDateStrings()
        {
            var testDates = new[] { new DateTime(2000,1,1), new DateTime(2000, 1, 1, 0, 15, 15, 15), new DateTime(1900, 1, 1, 0, 15, 15, 15), new DateTime(1999, 6, 1, 0, 15, 15, 15) };
            foreach(var tzId in new[] { "Pacific Standard Time", "New Zealand Standard Time", "India Standard Time" })
            {
                Debug.WriteLine(tzId);
                TimeZoneInfo tzi = TimeZoneInfo.FindSystemTimeZoneById(tzId); 
                var engine = new Engine(ctx => ctx.LocalTimeZone(tzi));
                foreach (var d in testDates)
                {
                    var td = new DateTimeOffset(d, tzi.GetUtcOffset(d));
                    engine.Execute(
                        string.Format("var d = new Date({0},{1},{2},{3},{4},{5},{6});", td.Year, td.Month - 1, td.Day, td.Hour, td.Minute, td.Second, td.Millisecond));
                    
                    Assert.AreEqual(td.ToString("ddd MMM dd yyyy HH:mm:ss 'GMT'zzz"), engine.Execute("d.toString();").GetCompletionValue().ToString());

                    Assert.AreEqual(td.UtcDateTime.ToString("yyyy-MM-dd'T'HH:mm:ss.fff'Z'"), engine.Execute("d.toISOString();").GetCompletionValue().ToString());
                }
            }
        }
예제 #24
0
파일: Script.cs 프로젝트: DemonRem/ivmp
 public void Execute()
 {
     try
     {
         Engine.Execute(Code);
     }
     catch (Exception e)
     {
         Console.WriteLine(e + " in script " + Name);
     }
 }
예제 #25
0
        private void Initialize()
        {
            _engine.Execute($"function exit() {{ setManagedExit(true); throw \"{StopExecutionIdentifier}\";}}", EsprimaOptions);
            _engine.Execute("var exports = {};", EsprimaOptions);


            void SetManagedExit(bool value)
            {
                managedExit = value;
            }

            _engine.SetValue("setManagedExit", new Action <bool>(SetManagedExit));
            _engine.SetValue("NewObject", new Func <string, object[], object?>(TypeHelper.CreateObject));
            managedExit = false;
            _engine.SetValue("managedExit", managedExit);
            //_engine.Global.FastAddProperty("middler", new NamespaceReference(_engine, "middler"), false, false, false );
            //_engine.Execute("var middler = importNamespace('middler')");
            _engine.DebugHandler.Step += EngineOnStep;
            _engine.SetValue("require", new Func <string, JsValue>(Require));
        }
예제 #26
0
        public static void Repl()
        {
            var engine = new Jint.Engine();

            while (true)
            {
                Console.Write("> ");
                var statement = Console.ReadLine();
                var result    = engine.Execute(statement).GetCompletionValue();
                Console.WriteLine(result);
            }
        }
예제 #27
0
        private static void InitJsEngine(Jint.Engine engine)
        {
            StringBuilder sb = new StringBuilder();

            foreach (string strFunc in listFunc)
            {
                sb.Append(strFunc);
            }
            engine.Execute(sb.ToString());
            engine.SetValue("colorFromName", new Func <string, System.Drawing.Color>(System.Drawing.Color.FromName));
            engine.SetValue("colorFromArgb", new Func <int, int, int, int, System.Drawing.Color>(System.Drawing.Color.FromArgb));
        }
예제 #28
0
		public bool Evaluate(object source, Message message)
		{
			Engine engine = new Engine();
			engine.SetValue("message", message);
			engine.Execute(Script);

			if (!engine.GetCompletionValue().IsBoolean())
			{
				return false;
			}

			return engine.GetCompletionValue().AsBoolean();
		}
예제 #29
0
        internal string GetAssignScriptResult(string script, string field, Dictionary <string, string> answers)
        {
            var engine = new Jint.Engine();

            foreach (var variable in answers)
            {
                engine.SetValue(variable.Key, variable.Value);
            }
            engine.Execute(script);
            var result = engine.GetCompletionValue();

            return(result.IsNull() ? null : result.ToString());
        }
예제 #30
0
        public bool GetCondResult(string condCode, Dictionary <string, string> variables)
        {
            condCode = condCode.Replace("&amp;", "&");
            var engine = new Jint.Engine();

            foreach (var variable in variables)
            {
                engine.SetValue(variable.Key, variable.Value);
            }
            engine.Execute(condCode);
            var result = engine.GetCompletionValue().AsBoolean();

            return(result);
        }
예제 #31
0
        public static void Handlebars()
        {
            var engine = new Jint.Engine();

            engine.Execute(File.ReadAllText("handlebars-v4.0.11.js"));

            engine.SetValue("context", new
            {
                cats = new[]
                {
                    new { name = "Feivel" },
                    new { name = "Lilly" }
                }
            });

            engine.SetValue("source", "{{#each cats}} {{name}} says meow!!!\n{{/each}}");

            engine.Execute("var template = Handlebars.compile(source);");

            var result = engine.Execute("template(context)").GetCompletionValue();

            Console.WriteLine(result);
        }
예제 #32
0
        public void ActionTest()
        {
            var engine = new Engine()
        .SetValue("log", new Action<object>(Console.WriteLine))
        ;

            engine.Execute(@"
              function hello() { 
                log('Hello World');
              };

              hello();
            ");
        }
예제 #33
0
        public async Task vanillaJsClickTest()
        {
            string script = "var numClicks = 0; function onClickBtn(){numClicks += 1; document.getElementById('message').textContent = \"hello there you clicked the button \" + numClicks + \" times\";}; ";
            string html   = @"
<!DOCTYPE html>
<html>
	<head>
		
	</head>
	<body>
		<div id='message'>empty</div>
        <button id='btn' onclick='onClickBtn();'>Click me please</button>
	</body>
</html>";

            //var context = BrowsingContext.New(new Configuration.Default.WithJavaScript());

            Jint.Engine engine       = new Jint.Engine();
            IDocument   htmlDocument = new Document();

            Window.Window window1 = new Window.Window(engine);
            window1.document = htmlDocument.HtmlDocument;

            window1.InitializeEngine();
            var jquery = System.IO.File.ReadAllText(@"../../../../BrowseSharpPlayground/jquery.js");

            //engine.Execute("window.document.readyState = \"Loading\";");
            engine.Execute(jquery);

            engine.Execute("var $ = window.jQuery;");
            engine.Execute(script);

            CheckMessage(engine, htmlDocument, "empty");

            ((AngleSharp.Html.Dom.IHtmlElement)window1.document.GetElementById("btn")).DoClick();
            CheckMessage(engine, htmlDocument, "hello there you clicked the button 1 times");
        }
        public MapDelegate CompileMap(string source, string language)
        {
            if(!language.Equals("javascript")) {
                return null;
            }

            source = source.Replace("function", "function _f1");

            return (doc, emit) =>
            {
                var engine = new Engine().SetValue("log", new Action<object>((line) => Log.I("JSViewCompiler", line.ToString())));
                engine.SetValue("emit", emit);
                engine.Execute(source).Invoke("_f1", doc);
            };
        }
예제 #35
0
		public void Initialize(SmugglerDatabaseOptions databaseOptions)
		{
			if (databaseOptions == null || string.IsNullOrEmpty(databaseOptions.TransformScript))
				return;

			jint = new Engine(cfg =>
			{
				cfg.AllowDebuggerStatement(false);
				cfg.MaxStatements(databaseOptions.MaxStepsForTransformScript);
			});

			jint.Execute(string.Format(@"
					function Transform(docInner){{
						return ({0}).apply(this, [docInner]);
					}};", databaseOptions.TransformScript));
		}
예제 #36
0
        object IScriptingProvider.Execute(string script, ScriptExecutionOptions options)
        {
            ScriptContext context = new ScriptContext(options);

            Engine eng = new Engine(_ => _.Strict());
            eng.SetValue("context", context);

            object v = eng.Execute(script);

            if (context.ret != null)
            {
                return context.ret;
            }

            return v;
        }
예제 #37
0
        /// <summary>
        /// 自定义公式运算
        /// </summary>
        /// <param name="strFormulas">自定义的算式字符串</param>
        /// <returns>运算结果</returns>
        public string Computing(string strFormulas)
        {
            string strResult = "";

            try
            {
                //////////临时处理//////////
                strFormulas = strFormulas.Replace("-*", "*");
                strResult   = js.Execute(strFormulas).Invoke("jsfun").ToString();
            }
            catch (Exception ex)
            {
                ex.Message.ToString();
            }

            return(strResult);
        }
예제 #38
0
파일: Template.cs 프로젝트: yonglehou/docfx
        private object ProcessWithJint(string model, object attrs)
        {
            var engine = new Engine();

            // engine.SetValue("model", stream.ToString());
            engine.SetValue("console", new
            {
                log = new Action<object>(Logger.Log)
            });

            // throw exception when execution fails
            engine.Execute(_script);
            var value = engine.Invoke("transform", model, JsonUtility.Serialize(attrs)).ToObject();

            // var value = engine.GetValue("model").ToObject();
            // The results generated
            return value;
        }
        private void ValidateCustomFunctions(RavenJObject document)
        {
            var engine = new Engine(cfg =>
            {
                cfg.AllowDebuggerStatement();
                cfg.MaxStatements(1000);
            });

            engine.Execute(string.Format(@"
var customFunctions = function() {{ 
	var exports = {{ }};
	{0};
	return exports;
}}();
for(var customFunction in customFunctions) {{
	this[customFunction] = customFunctions[customFunction];
}};", document.Value<string>("Functions")));

        }
예제 #40
0
        public string Initialize(string metadata, string metadataRootfolder, string jsCode)
        {
            hData = new HandlerData();

            engine = new Jint.Engine();

            gameMetadata = JsonConvert.DeserializeObject <GameHandlerMetadata>(metadata);
            gameMetadata.RootDirectory = metadataRootfolder;

            engine.SetValue("SaveType", TypeReference.CreateTypeReference(engine, typeof(SaveType)));
            engine.SetValue("DPIHandling", TypeReference.CreateTypeReference(engine, typeof(DPIHandling)));
            engine.SetValue("Folder", TypeReference.CreateTypeReference(engine, typeof(Folder)));
            engine.SetValue("SaveType", TypeReference.CreateTypeReference(engine, typeof(SaveType)));

            engine.SetValue("Game", hData);
            engine.SetValue("Import", (Action <string>)Import);

            engine.Execute(jsCode);

            return(JsonConvert.SerializeObject(hData));
        }
예제 #41
0
        private static void Transform(JintPluginsStore plugins)
        {
            var engine = new Engine();
            engine.UsePlugins("ais", plugins);

            engine.Execute(@"
                function hello() {

                return ais.TestPlugin.Test('dsadsa');
                };
            ");

            try
            {
                var hello = engine.Invoke("hello");
                Console.WriteLine(hello);
            }
            catch (TargetInvocationException e)
            {
                ExceptionDispatchInfo.Capture(e.InnerException).Throw();
            }
        }
예제 #42
0
        public static void calculate(string resPonse)
        {
            var JSEngine = new Jint.Engine();

            challenge      = Regex.Match(resPonse, "name=\"jschl_vc\" value=\"(\\w+)\"").Groups[1].Value;
            challenge_pass = Regex.Match(resPonse, "name=\"pass\" value=\"(.+?)\"").Groups[1].Value;

            builder = Regex.Match(resPonse, "setTimeout\\(function\\(\\){\\s+(var s,t,o,p,b,r,e,a,k,i,n,g,f.+?\r?\n[\\s\\S]+?a\\.value =.+?)\r?\n").Groups[1].Value;


            builder = Regex.Replace(builder, @"a\.value =(.+?) \+ .+?;", "$1");
            builder = Regex.Replace(builder, @"\s{3,}[a-z](?: = |\.).+", "");
            builder = Regex.Replace(builder, @"[\n\\']", "");
            builder = Regex.Replace(builder, @"(parseInt\((.*?)\,\s\d{1,10}\)\s\;\s\d{1,10})", "");

            //Console.WriteLine(builder);
            var test = @"var s,t,o,p,b,r,e,a,k,i,n,g,f, tDZRQkc={""Gkre"":+((!+[]+!![]+[])+(!+[]+!![]))};        ;tDZRQkc.Gkre-=+((+!![]+[])+(!+[]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]));tDZRQkc.Gkre+=+((!+[]+!![]+!![]+!![]+!![]+[])+(+[]));tDZRQkc.Gkre+=+!![];tDZRQkc.Gkre*=+((!+[]+!![]+!![]+!![]+[])+(+[]));tDZRQkc.Gkre+=+((!+[]+!![]+!![]+!![]+[])+(!+[]+!![]+!![]+!![]+!![]+!![]+!![]));tDZRQkc.Gkre-=+((!+[]+!![]+[])+(!+[]+!![]+!![]+!![]+!![]+!![]+!![]+!![]));tDZRQkc.Gkre+=+((!+[]+!![]+!![]+!![]+[])+(!+[]+!![]+!![]+!![]+!![]+!![]+!![]));tDZRQkc.Gkre+=+((!+[]+!![]+[])+(!+[]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]));tDZRQkc.Gkre+=+((!+[]+!![]+[])+(!+[]+!![]+!![]+!![]));tDZRQkc.Gkre*=+((!+[]+!![]+!![]+!![]+[])+(!+[]+!![]+!![]+!![]+!![]+!![]+!![]+!![]));";

            solved  = long.Parse(JSEngine.Execute(builder).GetCompletionValue().ToObject().ToString());
            solved += ("account.leagueoflegends.com").Length;
            Console.WriteLine(solved);
        }
예제 #43
0
		private Engine CreateEngine(ScriptedPatchRequest patch)
		{
			var scriptWithProperLines = NormalizeLineEnding(patch.Script);
			var wrapperScript = String.Format(@"
function ExecutePatchScript(docInner){{
  (function(doc){{
	{0}
  }}).apply(docInner);
}};
", scriptWithProperLines);

			var jintEngine = new Engine(cfg =>
			{
#if DEBUG
				cfg.AllowDebuggerStatement();
#else
				cfg.AllowDebuggerStatement(false);
#endif
				cfg.MaxStatements(maxSteps);
			});

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

            jintEngine.Execute(wrapperScript);

			return jintEngine;
		}
예제 #44
0
        void ActivateScript()
        {
            string code = adventure.rooms[roomX, roomY].code;
            if (code != null)
            {
                jintEngine = ActivateEngine(code);

                jintEngine.Execute("onLoad()");
            }
            else
                jintEngine = null;
        }
예제 #45
0
        private static void Run(string[] args)
        {
            var engine = new Engine(cfg => cfg.AllowClr())
                .SetValue("print", new Action<object>(Print))
                .SetValue("ac", _acDomain);

            var filename = args.Length > 0 ? args[0] : "";
            if (!String.IsNullOrEmpty(filename))
            {
                if (!File.Exists(filename))
                {
                    Console.WriteLine(@"Could not find file: {0}", filename);
                }

                var script = File.ReadAllText(filename);
                var result = engine.GetValue(engine.Execute(script).GetCompletionValue());
                return;
            }

            Welcome();

            var defaultColor = Console.ForegroundColor;
            while (true)
            {
                Console.ForegroundColor = defaultColor;
                Console.Write(@"anycmd> ");
                var input = Console.ReadLine();
                if (input == "exit")
                {
                    return;
                }
                if (input == "clear")
                {
                    Console.Clear();
                    Welcome();
                    continue;
                }

                try
                {
                    var result = engine.GetValue(engine.Execute(string.Format("print({0})", input)).GetCompletionValue());
                    if (result.Type != Types.None && result.Type != Types.Null && result.Type != Types.Undefined)
                    {
                        var str = TypeConverter.ToString(engine.Json.Stringify(engine.Json, Arguments.From(result, Undefined.Instance, "  ")));
                        Console.WriteLine(@"=> {0}", str);
                    }
                }
                catch (JavaScriptException je)
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine(je.ToString());
                }
                catch (Exception e)
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine(e.Message);
                }
            }
        }
예제 #46
0
        private async Task<Tuple<string, string>> GetChallengeAndSaltAsync()
        {
            Uri loginUri = new Uri(this.endpoint.ToString() + LoginPath);
            using (var webClient = new WebClient())
            {
                webClient.Headers.Add("X-FBX-FREEBOX0S", "1");
                string jsonString = await webClient.DownloadStringTaskAsync(loginUri);
                dynamic jsonObject = JObject.Parse(jsonString);

                if (jsonObject.success != true)
                {
                    throw new Exception("Failed to fetch challenge. Response: " + jsonString);
                }

                string salt = jsonObject.result.password_salt;
                string challenge = string.Empty;

                // The challenge is an array of javacript code.
                // The code in each cell is executed an the results concatenated.
                try
                {
                    foreach (var challengeEntry in jsonObject.result.challenge)
                    {
                        var engine = new Engine();
                        engine.SetValue("challengeEntry", challengeEntry.ToString());
                        engine.SetValue("result", "");
                        engine.SetValue("unescape", (StringTranform)delegate(string s) { return HttpUtility.UrlDecode(s); });
                        string script = @"
                            result = eval(challengeEntry)";
                        engine.Execute(script);
                        challenge += engine.GetValue("result").AsString();
                    }

                    return new Tuple<string, string>(challenge, salt);
                }
                catch (Exception exception)
                {
                    return null;
                }
            }
        }
예제 #47
0
        public void ExecuteScript(string fullPath, Dictionary<string, string> urlParameters,
            ClientHttpResponse response, string extension, string mimeType, HTTPMethod method, string postData,
            string documentRoot, dynamic serverHandle, ScriptExecutionParameters executionParameters)
        {
            //Prepare JSScript
            var scriptContents = File.ReadAllText(fullPath);
            var scriptDir = Path.GetDirectoryName(fullPath);
            var jsEngine = new Engine(cfg => cfg.AllowClr());

            var undefined = Undefined.Instance;

            //Inject variables
            if (method == HTTPMethod.Get)
            {
                jsEngine.SetValue("_GET", urlParameters);
                jsEngine.SetValue("_SERVER", response.RequestHttpHeaders);
                jsEngine.SetValue("_POST", undefined);
            }
            if (method == HTTPMethod.Post)
            {
                jsEngine.SetValue("_GET", undefined);
                jsEngine.SetValue("_SERVER", response.RequestHttpHeaders);
                jsEngine.SetValue("_POST", urlParameters);
                jsEngine.SetValue("POST_DATA", postData);
            }

            //Globals
            jsEngine.SetValue("DocumentRoot", documentRoot);
            jsEngine.SetValue("__dirname__", scriptDir);

            switch (extension)
            {
                case ".jscx": //Fully-controlled script
                {
                    try
                    {
                        //Manipulate Scope
                        jsEngine.SetValue("response", response);
                        jsEngine.SetValue("FireHTTPServer", serverHandle);
                        jsEngine.SetValue("_mimeTypeMappings", CommonVariables.MimeTypeMappings);
                        jsEngine.SetValue("dirSep", _dirSep);
                        DefineScriptingApi(jsEngine);
                        jsEngine.Execute(scriptContents);
                        break;
                    }
                    catch (DeadRequestException)
                    {
                        throw; //Don't catch these.
                    }
                    catch (Exception ex)
                    {
                        var level = (int) jsEngine.GetValue("__error_reporting_level").AsNumber();
                        if (level > 0)
                        {
                            if (!response.HasFinishedSendingHeaders)
                            {
                                //If headers not sent, send default headers.
                                response.SendHeader("HTTP/1.1 200 OK");
                                response.SendHeader("Content-Type: text/plain");
                                response.SendEndHeaders();
                            }
                            response.OutputStream.WriteLine("Error in script execution. Stack trace:");
                            response.OutputStream.WriteLine(ex.ToString());
                            break;
                        }
                        throw;
                    }
                }
            }
        }
예제 #48
0
        internal MethodRunResult EvaluateCondition()
        {
            MethodRunResult result = null;

            switch (codeType.ToLower())
            {
            case "python":
                string       pythonScript = this.ScriptCondition;
                ScriptEngine pythonEngine = (scriptEngine as ScriptEngine);
                result = new MethodRunResult();
                try
                {
                    pythonEngine.Execute(pythonScript, scriptScope);
                    result.ReturnValue = (scriptScope as dynamic).hg.executeCodeToRun;
                }
                catch (Exception e)
                {
                    result.Exception = e;
                }
                break;

            case "ruby":
                string       rubyScript = this.ScriptCondition;
                ScriptEngine rubyEngine = (scriptEngine as ScriptEngine);
                result = new MethodRunResult();
                try
                {
                    rubyEngine.Execute(rubyScript, scriptScope);
                    result.ReturnValue = (scriptScope as dynamic).hg.executeCodeToRun;
                }
                catch (Exception e)
                {
                    result.Exception = e;
                }
                break;

            case "javascript":
                string      jsScript = this.ScriptCondition;
                Jint.Engine engine   = (scriptEngine as Jint.Engine);
                result = new MethodRunResult();
                try
                {
                    engine.Execute(jsScript);
                    result.ReturnValue = (engine.GetValue("hg").ToObject() as ScriptingHost).executeCodeToRun;
                }
                catch (Exception e)
                {
                    result.Exception = e;
                }
                break;

            case "csharp":
                if (appAssembly != null && CheckAppInstance())
                {
                    result = (MethodRunResult)methodEvaluateCondition.Invoke(assembly, null);
                }
                break;
            }
            //
            return(result);
        }
예제 #49
0
		private static void AddScript(Engine jintEngine, string ravenDatabaseJsonMapJs)
		{
			jintEngine.Execute(GetFromResources(ravenDatabaseJsonMapJs));
		}
예제 #50
0
        internal MethodRunResult Run(string options)
        {
            MethodRunResult result = null;

            switch (codeType.ToLower())
            {
            case "python":
                string       pythonScript = this.ScriptSource;
                ScriptEngine pythonEngine = (scriptEngine as ScriptEngine);
                result = new MethodRunResult();
                try
                {
                    pythonEngine.Execute(pythonScript, scriptScope);
                }
                catch (Exception e)
                {
                    result.Exception = e;
                }
                break;

            case "ruby":
                string       rubyScript = this.ScriptSource;
                ScriptEngine rubyEngine = (scriptEngine as ScriptEngine);
                result = new MethodRunResult();
                try
                {
                    rubyEngine.Execute(rubyScript, scriptScope);
                }
                catch (Exception e)
                {
                    result.Exception = e;
                }
                break;

            case "javascript":
                string      jsScript = this.ScriptSource;
                Jint.Engine engine   = (scriptEngine as Jint.Engine);
                //engine.Options.AllowClr(false);
                result = new MethodRunResult();
                try
                {
                    engine.Execute(jsScript);
                }
                catch (Exception e)
                {
                    result.Exception = e;
                }
                break;

            case "csharp":
                if (appAssembly != null && CheckAppInstance())
                {
                    result = (MethodRunResult)methodRun.Invoke(assembly, new object[1] {
                        options
                    });
                }
                break;
            }
            //
            return(result);
        }
예제 #51
0
        private void doChat()
        {
            int requestCount = 0;
            int buffSize = 10 * 1024;
            byte[] bytesFrom = new byte[buffSize];
            string dataFromClient = null;
            Byte[] sendBytes = null;
            string serverResponse = null;
            string rCount = null;
            requestCount = 0;

            NetworkStream networkStream = clientSocket.GetStream();
            networkStream.ReadTimeout = 50;
            serverResponse = "ACK:(" + clNo + ")." + rCount + "\0";
            sendBytes = Encoding.ASCII.GetBytes(serverResponse);
            networkStream.Write(sendBytes, 0, sendBytes.Length);
            networkStream.Flush();

            //var engine = new Engine().SetValue("log", new Action<object>(getString));
            var engine = new Engine(cfg => cfg.AllowClr());
            engine.SetValue("log", new Action<object>(getString));
            engine.SetValue("Color", new System.Drawing.Color());
            indy ui = new indy();
            engine.SetValue("ui", ui);
            running = true;
            while (running)
            {
                try
                {
                    requestCount = requestCount + 1;

                    networkStream.Read(bytesFrom, 0, bytesFrom.Length);
                    dataFromClient = Encoding.ASCII.GetString(bytesFrom);
                    dataFromClient = dataFromClient.Substring(0, dataFromClient.IndexOf('\0'));
                    messageDisplay.displayStatusText("Received code from client No. " + clNo);

                    rCount = Convert.ToString(requestCount);
                    outputMessage = "ok_tx\n";
                    try
                    {
                        engine.Execute(dataFromClient);
                    }
                    catch (Exception e)
                    {
                        outputMessage = e.ToString();
                    }
                    sendBytes = Encoding.ASCII.GetBytes(outputMessage);
                    networkStream.Write(sendBytes, 0, sendBytes.Length);
                    messageDisplay.displayStatusText("Output sent to client No. " + clNo);
                    messageDisplay.displayOutgoingText(outputMessage);
                }
                catch (System.IO.IOException ex)
                {
                    // expected time out
                }
                catch (Exception ex)
                {
                    Console.WriteLine(" >> " + ex.ToString());
                    running = false;
                }
            }
            clientSocket.Close();
        }
예제 #52
0
        private Engine CreateEngine(StringBuilder output)
        {
            var engine = new Engine();

            engine.SetValue("write", new Action<object>(s =>
            {
                if (s is TemplateParameter)
                    engine.Execute((string)((TemplateParameter)s).Value);
                else
                    output.Append(s);
            }));

            if (PrepareEngine != null)
                PrepareEngine(engine);

            return engine;
        }
예제 #53
0
 public object Execute(string FunctionInvocation)
 {
     return(JintEngine.Execute(FunctionInvocation).GetCompletionValue());
 }
예제 #54
0
        private void loadJS()
        {
            var js = Script.GetElement(0).Value;

            for (int i = 1; i < Script.Count; i++)
            {
                js += "\n" + Script.GetElement(i).Value;
            }

            ContentOut.Value = js;

            engine = new Jint.Engine();

            //Output Types
            engine.SetValue("OutputBool", new Action <int, bool>(OutputValue <bool>));
            engine.SetValue("OutputString", new Action <int, string>(OutputValue <string>));
            engine.SetValue("OutputInt", new Action <int, int>(OutputValue <int>));
            engine.SetValue("OutputFloat", new Action <int, float>(OutputValue <float>));
            engine.SetValue("OutputFloat3", new Action <int, float3>(OutputValue <float3>));
            engine.SetValue("OutputColor", new Action <int, color>(OutputValue <color>));
            engine.SetValue("OutputFloatQ", new Action <int, floatQ>(OutputValue <floatQ>));

            //Input Types
            engine.SetValue("InputBool", new Func <int, bool>(InputValue <bool>));
            engine.SetValue("InputString", new Func <int, string>(InputValue <string>));
            engine.SetValue("InputInt", new Func <int, int>(InputValue <int>));
            engine.SetValue("InputFloat", new Func <int, float>(InputValue <float>));
            engine.SetValue("InputFloat3", new Func <int, float3>(InputValue <float3>));
            engine.SetValue("InputColor", new Func <int, color>(InputValue <color>));
            engine.SetValue("InputFloatQ", new Func <int, floatQ>(InputValue <floatQ>));


            //Output Types
            engine.SetValue("SetBool", new Action <int, bool>(PutValue <bool>));
            engine.SetValue("SetString", new Action <int, string>(PutValue <string>));
            engine.SetValue("SetInt", new Action <int, int>(PutValue <int>));
            engine.SetValue("SetFloat", new Action <int, float>(PutValue <float>));
            engine.SetValue("SetFloat3", new Action <int, float3>(PutValue <float3>));
            engine.SetValue("SetColor", new Action <int, color>(PutValue <color>));
            engine.SetValue("SetFloatQ", new Action <int, floatQ>(PutValue <floatQ>));

            //Input Types
            engine.SetValue("GetBool", new Func <int, bool>(GetValue <bool>));
            engine.SetValue("GetString", new Func <int, string>(GetValue <string>));
            engine.SetValue("GetInt", new Func <int, int>(GetValue <int>));
            engine.SetValue("GetFloat", new Func <int, float>(GetValue <float>));
            engine.SetValue("GetFloat3", new Func <int, float3>(GetValue <float3>));
            engine.SetValue("GetColor", new Func <int, color>(GetValue <color>));
            engine.SetValue("GetFloatQ", new Func <int, floatQ>(GetValue <floatQ>));

            //Function
            engine.SetValue("Log", new Action <object, bool>(Debug.Log));
            engine.SetValue("AddIn", new Action <string>(AddInput));
            engine.SetValue("AddOut", new Action <string>(AddOutput));
            engine.SetValue("AddSync", new Action <string>(AddSync));

            //Objects
            engine.SetValue("Time", base.Time);
            engine.SetValue("MySlot", base.Slot);
            engine.SetValue("World", base.World);

            //Types
            engine.SetValue("string", typeof(string));
            engine.SetValue("int", typeof(int));
            engine.SetValue("float", typeof(float));
            engine.SetValue("float3", typeof(float3));
            engine.SetValue("color", typeof(color));
            engine.SetValue("slot", typeof(Slot));
            engine.SetValue("floatQ", typeof(floatQ));

            try
            {
                engine.Execute(js);
            }
            catch (Jint.Parser.ParserException E)
            {
                DebugError.Value = "Line " + E.LineNumber + " : " + E.Description;
                Debug.Log("Line " + E.LineNumber + " : " + E.Description);
            }
            catch (Exception E)
            {
                Debug.Log("NeosJint Error: " + E.Message);
            }
        }
예제 #55
0
		protected virtual void RemoveEngineCustomizations(Engine engine, ScriptedJsonPatcherOperationScope scope)
		{
			RavenJToken functions;
			if (scope.CustomFunctions == null || scope.CustomFunctions.DataAsJson.TryGetValue("Functions", out functions) == false)
				return;

			engine.Execute(@"
if(customFunctions) { 
	for(var customFunction in customFunctions) { 
		delete this[customFunction]; 
	}; 
};");
			engine.SetValue("customFunctions", JsValue.Undefined);
		}
예제 #56
0
		protected virtual void CustomizeEngine(Engine engine, ScriptedJsonPatcherOperationScope scope)
		{
			RavenJToken functions;
			if (scope.CustomFunctions == null || scope.CustomFunctions.DataAsJson.TryGetValue("Functions", out functions) == false)
				return;

			engine.Execute(string.Format(@"var customFunctions = function() {{  var exports = {{ }}; {0};
	return exports;
}}();
for(var customFunction in customFunctions) {{
	this[customFunction] = customFunctions[customFunction];
}};", functions), new ParserOptions { Source = "customFunctions.js"});
		}
예제 #57
0
        private static void startGame(GameManager gameManager)
        {
            Engine engine = new Engine();
            var promise = getFile(@"./js/promise.js");
            var sevens = getFile(@"./js/sevens.js");

            var dataClass = new DataClass(gameManager);
            engine.SetValue("shuff", dataClass);
            engine.SetValue("exports", new { });
            engine.SetValue("require", new Func<string, JsValue>((file) =>
             {
                 var txt = getFile($@"./js/{file}.js");
                 engine.SetValue("shuff", dataClass);
                 engine.Execute("var exports={};" + txt);
                 return engine.GetValue("exports");
             }));

            engine.Execute(promise + "; " + sevens);
            engine.Execute("Main.run()");
        }
예제 #58
0
파일: Template.cs 프로젝트: ansyral/docfx
        private static Engine CreateEngine(string script)
        {
            if (string.IsNullOrEmpty(script)) return null;
            var engine = new Engine();

            engine.SetValue("console", new
            {
                log = new Action<object>(Logger.Log)
            });

            // throw exception when execution fails
            engine.Execute(script);
            return engine;
        }
예제 #59
0
		private static void AddScript(Engine jintEngine, string ravenDatabaseJsonMapJs)
		{
			jintEngine.Execute(GetFromResources(ravenDatabaseJsonMapJs), new ParserOptions
			{
				Source = ravenDatabaseJsonMapJs
			});
		}