コード例 #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
0
ファイル: WebUtils.cs プロジェクト: CookieEaters/FireHTTP
 internal void InstallProvider_WebUtils(Engine scriptScope)
 {
     InitializeScope_WebUtils(scriptScope);
     scriptScope.SetValue("echo", new Func<object, int>(s => Echo(scriptScope, s)));
     scriptScope.SetValue("header", new Func<string, int>(s => Header(scriptScope, s)));
     scriptScope.SetValue("endheaders", new Action(() => EndHeaders(scriptScope)));
     scriptScope.SetValue("die", new Action(() => Die(scriptScope)));
     scriptScope.SetValue("error_reporting", new Func<int, int>(s => error_reporting(scriptScope, s)));
 }
コード例 #3
0
ファイル: EGCMDJsEngine.cs プロジェクト: jingjiajie/WMSClient
        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));
        }
コード例 #4
0
        public string Play(string contextData, string playerInfo)
        {
            HandlerContext context = JsonConvert.DeserializeObject <HandlerContext>(contextData);
            PlayerInfo     player  = JsonConvert.DeserializeObject <PlayerInfo>(playerInfo);

            engine.SetValue("Context", context);
            engine.SetValue("Player", player);
            engine.SetValue("Game", hData);

            hData.OnPlay.Invoke();

            return(JsonConvert.SerializeObject(context));
        }
コード例 #5
0
		protected override void CustomizeEngine(Engine jintEngine, ScriptedJsonPatcherOperationScope scope)
		{
			jintEngine.SetValue("documentId", docId);
			jintEngine.SetValue("replicateTo", new Action<string,object>(ReplicateToFunction));
			foreach (var sqlReplicationTable in config.SqlReplicationTables)
			{
				var current = sqlReplicationTable;
				jintEngine.SetValue("replicateTo" + sqlReplicationTable.TableName, (Action<object>)(cols =>
				{
					var tableName = current.TableName;
					ReplicateToFunction(tableName, cols);
				}));
			}
		}
コード例 #6
0
        public bool Initialize(UserGameInfo game, GameProfile profile)
        {
            this.userGame = game;
            this.profile = profile;

            // see if we have any save game to backup
            gen = game.Game as GenericGameInfo;
            if (gen == null)
            {
                // you f****d up
                return false;
            }

            engine = new Engine();
            engine.SetValue("Options", profile.Options);

            data = new Dictionary<string, string>();
            data.Add(NucleusFolderEnum.GameFolder.ToString(), Path.GetDirectoryName(game.ExePath));

            if (gen.SaveType == GenericGameSaveType.None)
            {
                return true;
            }

            string saveFile = ProcessPath(gen.SavePath);
            GameManager.Instance.BeginBackup(game.Game);
            GameManager.Instance.BackupFile(game.Game, saveFile);

            return true;
        }
コード例 #7
0
ファイル: Javascript.cs プロジェクト: gitter-badger/RevEngine
 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);
 }
コード例 #8
0
        protected override void InnerSetVariableValue(string variableName, object value)
        {
            lock (_executionSynchronizer)
            {
                OriginalValue processedValue = MapToScriptType(value);

                try
                {
                    _jsEngine.SetValue(variableName, processedValue);
                }
                catch (OriginalRuntimeException e)
                {
                    throw WrapRuntimeException(e);
                }
            }
        }
コード例 #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
        public EngineInstance(IWindow window, IDictionary<String, Object> assignments)
        {
            _objects = new Dictionary<Object, DomNodeInstance>();
            _engine = new Engine();
            _engine.SetValue("console", new ConsoleInstance(_engine));

            foreach (var assignment in assignments)
                _engine.SetValue(assignment.Key, assignment.Value);

            _window = GetDomNode(window);
            _lexicals = LexicalEnvironment.NewObjectEnvironment(_engine, _window, _engine.ExecutionContext.LexicalEnvironment, true);
            _variables = LexicalEnvironment.NewObjectEnvironment(_engine, _engine.Global, null, false);
            _constructors = new DomConstructors(this);
            _constructors.Configure();

            this.AddConstructors(_window, typeof(INode));
            this.AddConstructors(_window, this.GetType());
        }
コード例 #11
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);
        }
        private Engine SetupScriptEngine()
        {
            var engine = new Engine(cfg => cfg.TimeoutInterval(TimeSpan.FromMinutes(1)));

            foreach (var objectProvider in _objectProviders)
            {
                foreach (var tuple in objectProvider.GetObjects())
                {
                    engine.SetValue(tuple.Item1, tuple.Item2);
                }

                foreach (var tuple in objectProvider.GetDelegates())
                {
                    engine.SetValue(tuple.Item1, tuple.Item2);
                }
            }

            return engine;
        }
コード例 #13
0
		protected override void CustomizeEngine(Engine engine, ScriptedJsonPatcherOperationScope scope)
		{
			base.CustomizeEngine(engine, scope);

			engine.SetValue("documentId", docId);
			engine.SetValue("replicateTo", new Action<string,object>(ReplicateToFunction));
			foreach (var sqlReplicationTable in config.SqlReplicationTables)
			{
				var current = sqlReplicationTable;
				engine.SetValue("replicateTo" + sqlReplicationTable.TableName, (Action<object>)(cols =>
				{
					var tableName = current.TableName;
					ReplicateToFunction(tableName, cols);
				}));
			}

            engine.SetValue("toVarchar", (Func<string, int,ValueTypLengthTriple>)(ToVarchar));
            engine.SetValue("toNVarchar", (Func<string, int, ValueTypLengthTriple>)(ToNVarchar));
		}
コード例 #14
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));
        }
コード例 #15
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());
        }
コード例 #16
0
ファイル: Script.cs プロジェクト: DemonRem/ivmp
        public Script()
        {
            ConsoleNatives = new Scripting.Natives.Console();
            Engine         = new Engine(cfg => cfg.AllowClr(typeof(Vector2).Assembly,
                                                            typeof(Vector3).Assembly,
                                                            typeof(Vector4).Assembly,
                                                            typeof(Quaternion).Assembly));
#if SERVER
            Engine.SetValue("Vector2", new Func <float, float, Vector2>((X, Y) => { return(new Vector2(X, Y)); }));
            Engine.SetValue("Vector3", new Func <float, float, float, Vector3>((X, Y, Z) => { return(new Vector3(X, Y, Z)); }));
            Engine.SetValue("Vector4", new Func <float, float, float, float, Vector4>((X, Y, Z, W) => { return(new Vector4(X, Y, Z, W)); }));
            Engine.SetValue("Quaternion", new Func <float, float, float, float, Quaternion>((X, Y, Z, W) => { return(new Quaternion(X, Y, Z, W)); }));
#endif
#if CLIENT
            Engine.SetValue("Vector2", new Func <float, float, GTA.Vector2>((X, Y) => { return(new GTA.Vector2(X, Y)); }));
            Engine.SetValue("Vector3", new Func <float, float, float, GTA.Vector3>((X, Y, Z) => { return(new GTA.Vector3(X, Y, Z)); }));
            Engine.SetValue("Vector4", new Func <float, float, float, float, GTA.Vector4>((X, Y, Z, W) => { return(new GTA.Vector4(X, Y, Z, W)); }));
            Engine.SetValue("Quaternion", new Func <float, float, float, float, GTA.Quaternion>((X, Y, Z, W) => { return(new GTA.Quaternion(X, Y, Z, W)); }));
#endif
            Engine.SetValue("Console", ConsoleNatives);
            Engine.SetValue("Event", new Func <string, Scripting.Natives.EventNatives>((Name) => { return(new Scripting.Natives.EventNatives(Name)); }));
        }
コード例 #17
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();
		}
コード例 #18
0
ファイル: Script.cs プロジェクト: Neproify/ivmp
        public Script()
        {
            ConsoleNatives = new Scripting.Natives.Console();
            Engine = new Engine(cfg => cfg.AllowClr(typeof(Vector2).Assembly,
                typeof(Vector3).Assembly,
                typeof(Vector4).Assembly,
                typeof(Quaternion).Assembly));
#if SERVER
            Engine.SetValue("Vector2", new Func<float, float, Vector2>((X, Y) => { return new Vector2(X, Y); }));
            Engine.SetValue("Vector3", new Func<float, float, float, Vector3>((X, Y, Z) => { return new Vector3(X, Y, Z); }));
            Engine.SetValue("Vector4", new Func<float, float, float, float, Vector4>((X, Y, Z, W) => { return new Vector4(X, Y, Z, W); }));
            Engine.SetValue("Quaternion", new Func<float, float, float, float, Quaternion>((X, Y, Z, W) => { return new Quaternion(X, Y, Z, W); }));
#endif
#if CLIENT
            Engine.SetValue("Vector2", new Func<float, float, GTA.Vector2>((X, Y) => { return new GTA.Vector2(X, Y); }));
            Engine.SetValue("Vector3", new Func<float, float, float, GTA.Vector3>((X, Y, Z) => { return new GTA.Vector3(X, Y, Z); }));
            Engine.SetValue("Vector4", new Func<float, float, float, float, GTA.Vector4>((X, Y, Z, W) => { return new GTA.Vector4(X, Y, Z, W); }));
            Engine.SetValue("Quaternion", new Func<float, float, float, float, GTA.Quaternion>((X, Y, Z, W) => { return new GTA.Quaternion(X, Y, Z, W); }));
#endif
            Engine.SetValue("Console", ConsoleNatives);
            Engine.SetValue("Event", new Func<string, Scripting.Natives.EventNatives>((Name) => { return new Scripting.Natives.EventNatives(Name); }));
        }
コード例 #19
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);
        }
コード例 #20
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);
        }
コード例 #21
0
ファイル: JavascriptEngine.cs プロジェクト: jetzfly/HomeGenie
        public bool Load()
        {
            Unload();

            if (homegenie == null)
                return false;

            scriptEngine = new Engine();

            hgScriptingHost = new ScriptingHost();
            hgScriptingHost.SetHost(homegenie, programBlock.Address);
            scriptEngine.SetValue("hg", hgScriptingHost);

            return true;
        }
        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);
            };
        }
コード例 #23
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;
        }
コード例 #24
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;
        }
コード例 #25
0
 private void SetupScriptingScope()
 {
     hgScriptingHost = new ScriptingHost();
     hgScriptingHost.SetHost(homegenie, this.Address);
     if (scriptEngine.GetType() == typeof(ScriptEngine))
     {
         // IronPyton and IronRuby engines
         ScriptEngine currentEngine = (scriptEngine as ScriptEngine);
         dynamic      scope         = scriptScope = currentEngine.CreateScope();
         scope.hg = hgScriptingHost;
     }
     else if (scriptEngine.GetType() == typeof(Jint.Engine))
     {
         // Jint Javascript engine
         Jint.Engine javascriptEngine = (scriptEngine as Jint.Engine);
         javascriptEngine.SetValue("hg", hgScriptingHost);
     }
 }
コード例 #26
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));
        }
コード例 #27
0
ファイル: NeosJint.cs プロジェクト: wel97459/NeosJint
        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);
            }
        }
コード例 #28
0
		private void PrepareEngine(ScriptedPatchRequest patch, string docId, int size, ScriptedJsonPatcherOperationScope scope, Engine jintEngine)
		{
			jintEngine.Global.Delete("PutDocument", false);
			jintEngine.Global.Delete("LoadDocument", false);
			jintEngine.Global.Delete("DeleteDocument", false);

			CustomizeEngine(jintEngine, scope);

			jintEngine.SetValue("PutDocument", (Action<string, object, object>)((key, document, metadata) => scope.PutDocument(key, document, metadata, jintEngine)));
			jintEngine.SetValue("LoadDocument", (Func<string, JsValue>)(key => scope.LoadDocument(key, jintEngine)));
			jintEngine.SetValue("DeleteDocument", (Action<string>)(scope.DeleteDocument));
			jintEngine.SetValue("__document_id", docId);

			foreach (var kvp in patch.Values)
			{
				var token = kvp.Value as RavenJToken;
				if (token != null)
				{
					jintEngine.SetValue(kvp.Key, scope.ToJsInstance(jintEngine, token));
				}
				else
				{
					var rjt = RavenJToken.FromObject(kvp.Value);
					var jsInstance = scope.ToJsInstance(jintEngine, rjt);
					jintEngine.SetValue(kvp.Key, jsInstance);
				}
			}

			jintEngine.ResetStatementsCount();
			if (size != 0)
				jintEngine.Options.MaxStatements(maxSteps + (size * additionalStepsPerSize));
		}
コード例 #29
0
ファイル: TypescriptEngine.cs プロジェクト: doob-at/Scripter
        private string CompileScriptInternal(string sourceCode)
        {
            if (String.IsNullOrWhiteSpace(sourceCode))
            {
                return("");
            }


            Regex regex = new Regex(@"new\s(?<typeName>[a-zA-Z0-9_\.\s<>\[\]$,]+)\((?<parameters>[a-zA-Z0-9_\.,\s<>\[\]$'""]+)?\)(;)?(?<ignore>//ignore)?");

            //var match = regex.Match(sourceCode);

            var matches = regex.Matches(sourceCode);

            if (matches.Count > 0)
            {
                foreach (Match match in matches)
                {
                    if (match.Groups["ignore"].Success)
                    {
                        continue;
                    }

                    var typeName = match.Groups["typeName"].Value;

                    var type = TypeHelper.FindConstructorReplaceType(typeName);
                    if (type != null)
                    {
                        var parameters = match.Groups["parameters"].Value;

                        var constuctorParameters = "";
                        if (!String.IsNullOrWhiteSpace(parameters))
                        {
                            constuctorParameters = $", [{parameters}]";
                        }

                        var replaceText = $"NewObject('{typeName}'{constuctorParameters})";

                        sourceCode = sourceCode.Replace(match.Value, replaceText);
                    }
                }
            }

            if (TypeScriptScript == null)
            {
                var tsLib  = GetFromResources("typescript.min.js");
                var parser = new JavaScriptParser(tsLib, EsprimaOptions);

                TypeScriptScript = parser.ParseScript();
            }



            var _engine = new Jint.Engine();

            _engine.Execute(TypeScriptScript);



            _engine.SetValue("src", sourceCode);


            var transpileOtions = "{\"compilerOptions\": {\"target\":\"ES5\"}}";

            var output = _engine.Execute($"ts.transpileModule(src, {transpileOtions})", EsprimaOptions).GetCompletionValue().AsObject();

            return(output.Get("outputText").AsString());
        }
コード例 #30
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);
		}
コード例 #31
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;
                    }
                }
            }
        }
コード例 #32
0
ファイル: TemplateService.cs プロジェクト: npenin/templater
 private void SetParameters(Engine engine, IEnumerable<TemplateParameter> parameters)
 {
     if (parameters != null)
     {
         foreach (TemplateParameter parameter in parameters)
         {
             if (parameter.IsFunction && parameter.Value != null)
             {
                 if (parameter.IsScript)
                     engine.SetValue(parameter.Name, engine.Function.CreateFunctionObject(new Jint.Parser.Ast.FunctionDeclaration
                     {
                         Body = new Jint.Parser.Ast.BlockStatement
                         {
                             Body = new Jint.Parser.JavaScriptParser().Parse(parameter.Value.ToString()).Body
                         }
                     }));
                 else
                     engine.SetValue(parameter.Name, (Delegate)parameter.Value);
             }
             else if (parameter.IsScript && parameter.Value != null)
             {
                 parameter.Value = GenerateScriptTemplate(parameter.Value.ToString());
                 engine.SetValue(parameter.Name, parameter);
             }
             else
                 engine.SetValue(parameter.Name, parameter.Value);
         }
     }
 }
コード例 #33
0
ファイル: TemplateService.cs プロジェクト: npenin/templater
        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;
        }
コード例 #34
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();
        }
コード例 #35
0
        public virtual void Execute(object controller, Dictionary <string, Parameter> parameters, View view, Dictionary <string, object> values, DataRow prevRow, string pk, string connectionString, int currentUsetId, string currentUserRole, IDbCommand command, IDbCommand sysCommand, string actionName, Durados.TriggerDataAction dataAction)
        {
            if (pk != null && (prevRow == null || dataAction == TriggerDataAction.AfterCreate || dataAction == TriggerDataAction.AfterEdit || dataAction == TriggerDataAction.AfterCreateBeforeCommit || dataAction == TriggerDataAction.AfterEditBeforeCommit) && controller is Durados.Data.IData)
            {
                try
                {
                    if (((Durados.Data.IData)controller).DataHandler != null)
                    {
                        prevRow = ((Durados.Data.IData)controller).DataHandler.GetDataRow(view, pk, command);
                    }
                }
                catch { }
            }

            var guid = Guid.NewGuid();

            //if (System.Web.HttpContext.Current != null && System.Web.HttpContext.Current.Request.QueryString[GuidKey] != null)
            //{
            //    guid = new Guid(System.Web.HttpContext.Current.Request.QueryString[GuidKey]);
            //}
            SetCacheInCurrentRequest("js" + guid, new Dictionary <string, object>()
            {
                { "controller", controller }, { "connectionString", connectionString }, { "currentUsetId", currentUsetId }, { "currentUserRole", currentUserRole }, { "command", command }, { "sysCommand", sysCommand }, { "actionName", actionName }, { "dataAction", dataAction }
            });


            SetCacheInCurrentRequest(ConnectionStringKey, view.Database.SysDbConnectionString);
            SetCacheInCurrentRequest(GuidKey, guid);

            if (!parameters.ContainsKey("code"))
            {
                throw new DuradosException("code was not supplied");
            }

            string code = parameters["code"].Value.Replace(Engine.AsToken(values), ((Durados.Workflow.INotifier)controller).GetTableViewer(), view);

            string currentUsername = view.Database.GetCurrentUsername();

            try
            {
                code = code.Replace(Durados.Database.UserPlaceHolder, currentUsetId.ToString(), false).Replace(Durados.Database.SysUserPlaceHolder.AsToken(), currentUsetId.ToString(), false)
                       .Replace(Durados.Database.UsernamePlaceHolder, currentUsername, false).Replace(Durados.Database.SysUsernamePlaceHolder.AsToken(), currentUsername)
                       .Replace(Durados.Database.RolePlaceHolder, currentUserRole, false).Replace(Durados.Database.SysRolePlaceHolder.AsToken(), currentUserRole)
                       .ReplaceConfig(view);
            }
            catch { }

            Dictionary <string, object> clientParameters = new Dictionary <string, object>();
            Dictionary <string, object> newRow           = new Dictionary <string, object>();
            Dictionary <string, object> oldRow           = new Dictionary <string, object>();
            Dictionary <string, object> userProfile      = new Dictionary <string, object>();

            bool debug = false;

            if (IsDebug())
            {
                debug = true;
            }

            if (values != null)
            {
                foreach (string key in values.Keys)
                {
                    if (key == "$$debug$$" || key == "$$debug$$".AsToken())
                    {
                        debug = true;
                    }
                    else
                    {
                        string keyWithoutToken = key.TrimStart("{{".ToCharArray()).TrimEnd("}}".ToCharArray());

                        if (key.StartsWith("{{"))
                        {
                            if (!clientParameters.ContainsKey(keyWithoutToken))
                            {
                                clientParameters.Add(keyWithoutToken, values[key]);
                            }
                        }

                        if (view.GetFieldsByJsonName(keyWithoutToken) == null || view.GetFieldsByJsonName(keyWithoutToken).Length == 0)
                        {
                            if (view.Fields.ContainsKey(keyWithoutToken))
                            {
                                string jsonName = view.Fields[keyWithoutToken].JsonName;

                                if (!newRow.ContainsKey(jsonName))
                                {
                                    newRow.Add(jsonName, values[key]);
                                }
                            }
                            else
                            {
                                if (!clientParameters.ContainsKey(keyWithoutToken))
                                {
                                    clientParameters.Add(keyWithoutToken, values[key]);
                                }
                            }
                        }
                        else
                        {
                            if (!newRow.ContainsKey(keyWithoutToken))
                            {
                                newRow.Add(keyWithoutToken, values[key]);
                            }
                        }
                    }
                }
            }
            SetCacheInCurrentRequest(Debug, debug);

            if (prevRow != null)
            {
                foreach (Field field in view.Fields.Values)
                {
                    if (!oldRow.ContainsKey(field.JsonName))
                    {
                        if (field.FieldType == FieldType.Column && field.IsDate)
                        {
                            oldRow.Add(field.JsonName, prevRow[((ColumnField)field).DataColumn.ColumnName]);
                        }
                        else
                        {
                            oldRow.Add(field.JsonName, field.GetValue(prevRow));
                        }
                    }
                }
                //var shallowRow = view.RowToShallowDictionary(prevRow, pk);
                //foreach (Field field in view.Fields.Values)
                //{
                //    if (oldRow.ContainsKey(field.JsonName) && shallowRow.ContainsKey(field.JsonName))
                //    {
                //        if (field.FieldType == FieldType.Column && (field.IsBoolean || field.IsPoint || field.IsNumeric))
                //        {
                //            oldRow[field.JsonName] = shallowRow[field.JsonName];
                //        }
                //    }
                //}
            }

            userProfile.Add("username", view.Database.GetCurrentUsername());
            userProfile.Add("role", currentUserRole);
            userProfile.Add("app", view.Database.GetCurrentAppName());
            userProfile.Add("userId", view.Database.GetCurrentUserId());
            userProfile.Add("token", GetUserProfileAuthToken(view));
            userProfile.Add("anonymousToken", view.Database.GetAnonymousToken().ToString());
            userProfile.Add("info", GetUserProfileInfo(view));


            if (!clientParameters.ContainsKey(FILEDATA))
            {
                int parametersLimit = (int)view.Database.GetLimit(Limits.ActionParametersKbSize);

                HandleParametersSizeLimit(parametersLimit, clientParameters);
                userProfile.Add("request", GetRequest());
            }



            var CONSTS = new Dictionary <string, object>()
            {
                { "apiUrl", System.Web.HttpContext.Current.Request.Url.Scheme + "://" + System.Web.HttpContext.Current.Request.Url.Host + ":" + System.Web.HttpContext.Current.Request.Url.Port + System.Web.HttpContext.Current.Request.ApplicationPath }, { "actionGuid", System.Web.HttpContext.Current.Request.QueryString[GuidKey] ?? (System.Web.HttpContext.Current.Items[GuidKey] ?? guid.ToString()) }
            };

            //Newtonsoft.Json.JsonConvert.SerializeObject

            var theJavaScriptSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();

            theJavaScriptSerializer.MaxJsonLength = int.MaxValue;

            var parser = new Jint.Native.Json.JsonParser(call2);
            //var userInput = parser.Parse(theJavaScriptSerializer.Serialize(newRow));
            //Object clientParametersToSend = null;
            //if (!clientParameters.ContainsKey("filedata"))
            //{
            //    clientParametersToSend = parser.Parse(theJavaScriptSerializer.Serialize(clientParameters));
            //}
            //else
            //{
            //    System.Web.HttpContext.Current.Items["file_stream"] = clientParameters["filedata"];
            //    clientParameters["filedata"] = "file_stream";
            //    clientParametersToSend = clientParameters;
            //}
            //var dbRow = parser.Parse(theJavaScriptSerializer.Serialize(oldRow));
            //var userProfile2 = parser.Parse(theJavaScriptSerializer.Serialize(userProfile));
            //var CONSTS2 = parser.Parse(theJavaScriptSerializer.Serialize(CONSTS));


            //var Config = view.Database.GetConfigDictionary();
            //var Config2 = parser.Parse(theJavaScriptSerializer.Serialize(Config));
            var    userInput = parser.Parse(Newtonsoft.Json.JsonConvert.SerializeObject(newRow));
            Object clientParametersToSend = null;

            bool upload = false;

            if (!clientParameters.ContainsKey(FILEDATA))
            {
                clientParametersToSend = parser.Parse(Newtonsoft.Json.JsonConvert.SerializeObject(clientParameters));
            }
            else
            {
                upload = true;
                System.Web.HttpContext.Current.Items["file_stream"] = clientParameters[FILEDATA];
                clientParameters[FILEDATA] = "file_stream";
                clientParametersToSend     = clientParameters;
            }

            if (clientParameters.ContainsKey(FILEDATA) || clientParameters.ContainsKey(FILENAME))
            {
                System.Web.HttpContext.Current.Items[StorageAccountsKey] = view.Database.CloudStorages;
            }

            var dbRow        = parser.Parse(Newtonsoft.Json.JsonConvert.SerializeObject(oldRow));
            var userProfile2 = parser.Parse(Newtonsoft.Json.JsonConvert.SerializeObject(userProfile));
            var CONSTS2      = parser.Parse(Newtonsoft.Json.JsonConvert.SerializeObject(CONSTS));


            var Config  = view.Database.GetConfigDictionary();
            var Config2 = parser.Parse(Newtonsoft.Json.JsonConvert.SerializeObject(Config));

            var Environment  = view.Database.GetEnvironmentDictionary();
            var Environment2 = parser.Parse(Newtonsoft.Json.JsonConvert.SerializeObject(Environment));


            Limits limit = Limits.ActionTimeMSec;

            if (upload)
            {
                limit = Limits.UploadTimeMSec;
            }

            object actionTimeMSecObject = view.Database.GetLimit(limit);
            int    actionTimeMSec       = -1;

            if (!Int32.TryParse(actionTimeMSecObject.ToString(), out actionTimeMSec))
            {
                throw new DuradosException("actionTimeMSecLimit in web.config is not numeric or too long");
            }

            TimeSpan?timeoutInterval = new TimeSpan(0, 0, 0, 0, actionTimeMSec);

            if (actionTimeMSec == 0)
            {
                timeoutInterval = null;
            }

            string actionId = Guid.NewGuid().ToString();

            string startMessage = theJavaScriptSerializer.Serialize(new { objectName = view.JsonName, actionName = actionName, id = actionId, @event = "started", time = GetSequence(view), data = new { userInput = newRow, dbRow = oldRow, parameters = clientParameters, userProfile = userProfile } });

            Backand.Logger.Log(startMessage, 502);

            var call = new Jint.Engine(cfg => cfg.AllowClr(typeof(Backand.XMLHttpRequest).Assembly), timeoutInterval, GetLineStart(), new ActionPath()
            {
                @object = view.JsonName, action = actionName
            });

            try
            {
                call.SetValue("userInput", userInput)
                .SetValue("btoa", new btoaHandler(Backand.Convert.btoa))
                .SetValue("dbRow", dbRow)
                .SetValue("parameters", clientParametersToSend)
                .SetValue("userProfile", userProfile2)
                .SetValue("CONSTS", CONSTS2)
                .SetValue("Config", Config2)
                .SetValue("Environment", Environment2)
                .Execute(GetXhrWrapper() + code + "; function call(){return backandCallback(userInput, dbRow, parameters, userProfile);}");
            }
            catch (TimeoutException exception)
            {
                Handle503(theJavaScriptSerializer, view.JsonName, actionName, actionId, exception.Message, view);
                string errorMessage = "Timeout: The operation took longer than " + actionTimeMSec + " milliseconds limit. at (" + view.JsonName + "/" + actionName + ")";
                if (!IsSubAction())
                {
                    Backand.Logger.Log(exception.Message, 501);
                    if (IsDebug())
                    {
                        throw new MainActionInDebugJavaScriptException(errorMessage, exception);
                    }
                    else
                    {
                        throw new MainActionJavaScriptException(errorMessage, exception);
                    }
                }
                else
                {
                    throw new SubActionJavaScriptException(errorMessage, exception);
                }
            }
            catch (Exception exception)
            {
                Handle503(theJavaScriptSerializer, view.JsonName, actionName, actionId, exception.Message, view);
                string errorMessage = "Syntax error: " + HandleLineCodes(exception.Message, view.JsonName, actionName, view, IsDebug());
                if (!IsSubAction())
                {
                    Backand.Logger.Log(exception.Message, 501);
                    if (IsDebug())
                    {
                        throw new MainActionInDebugJavaScriptException(errorMessage, exception);
                    }
                    else
                    {
                        throw new MainActionJavaScriptException(errorMessage, exception);
                    }
                }
                else
                {
                    throw new SubActionJavaScriptException(errorMessage, exception);
                }
            }
            object r = null;

            try
            {
                var r2 = call.GetValue("call").Invoke();
                if (!r2.IsNull())
                {
                    r = r2.ToObject();
                }

                string endMessage = null;
                try
                {
                    endMessage = theJavaScriptSerializer.Serialize(new { objectName = view.JsonName, actionName = actionName, id = actionId, @event = "ended", time = GetSequence(view), data = r });
                }
                catch (Exception exception)
                {
                    if (exception.Message.StartsWith("A circular reference was detected while serializing an object"))
                    {
                        object oNull = null;
                        endMessage = theJavaScriptSerializer.Serialize(new { objectName = view.JsonName, actionName = actionName, id = actionId, @event = "ended", time = GetSequence(view), data = oNull });
                    }
                    else
                    {
                        endMessage = "Failed to serialize response";
                        if (!IsSubAction())
                        {
                            Backand.Logger.Log(endMessage, 501);
                            //if (IsDebug())
                            //{
                            //    values[ReturnedValueKey] = message;
                            //    return;
                            //}
                            //else
                            if (IsDebug())
                            {
                                throw new MainActionInDebugJavaScriptException(endMessage, exception);
                            }
                            else
                            {
                                throw new MainActionJavaScriptException(endMessage, exception);
                            }
                        }
                        else
                        {
                            throw new SubActionJavaScriptException(endMessage, exception);
                        }
                    }
                }

                Backand.Logger.Log(endMessage, 503);
            }
            catch (TimeoutException exception)
            {
                string message = "Timeout: The operation took longer than " + actionTimeMSec + " milliseconds limit. at (" + view.JsonName + "/" + actionName + ")";
                Handle503(theJavaScriptSerializer, view.JsonName, actionName, actionId, message, view);
                if (!IsSubAction())
                {
                    Backand.Logger.Log(message, 501);
                    if (IsDebug())
                    {
                        throw new MainActionInDebugJavaScriptException(message, exception);
                    }
                    else
                    {
                        throw new MainActionJavaScriptException(message, exception);
                    }
                }
                else
                {
                    throw new SubActionJavaScriptException(message, exception);
                }
            }
            catch (Exception exception)
            {
                string message = (exception.InnerException == null) ? exception.Message : exception.InnerException.Message;
                string trace   = message;
                if (exception is Jint.Runtime.JavaScriptException)
                {
                    trace = ((Jint.Runtime.JavaScriptException)exception).GetTrace();
                }
                trace = HandleLineCodes(trace, view.JsonName, actionName, view, IsDebug());
                Handle503(theJavaScriptSerializer, view.JsonName, actionName, actionId, trace, view);
                if (!IsSubAction())
                {
                    IMainActionJavaScriptException mainActionJavaScriptException;
                    Backand.Logger.Log(trace, 501);
                    if (IsDebug())
                    {
                        mainActionJavaScriptException = new MainActionInDebugJavaScriptException(message, exception);
                    }
                    else
                    {
                        mainActionJavaScriptException = new MainActionJavaScriptException(message, exception);
                    }

                    mainActionJavaScriptException.JintTrace = trace;
                    throw (Exception)mainActionJavaScriptException;
                }
                else
                {
                    throw new SubActionJavaScriptException(message, exception);
                }
            }

            var v = call.GetValue("userInput").ToObject();

            if (v != null && v is System.Dynamic.ExpandoObject)
            {
                IDictionary <string, object> newValues = v as IDictionary <string, object>;
                foreach (string key in newValues.Keys)
                {
                    if (values.ContainsKey(key))
                    {
                        object  val    = newValues[key];
                        Field[] fields = view.GetFieldsByJsonName(key);
                        val         = DateConversion(view, val, fields);
                        values[key] = val;
                    }
                    else
                    {
                        Field[] fields = view.GetFieldsByJsonName(key);
                        if (fields.Length > 0)
                        {
                            string fieldName = fields[0].Name;
                            object val       = newValues[key];
                            val = DateConversion(view, val, fields);
                            if (values.ContainsKey(fieldName))
                            {
                                values[fieldName] = val;
                            }
                            else
                            {
                                values.Add(fieldName, val);
                            }
                        }
                        else
                        {
                            values.Add(key, newValues[key]);
                        }
                    }
                }
            }

            if (r != null && values != null && dataAction == TriggerDataAction.OnDemand)
            {
                if (!values.ContainsKey(ReturnedValueKey))
                {
                    values.Add(ReturnedValueKey, r);
                }
                else
                {
                    values[ReturnedValueKey] = r;
                }
            }
        }
コード例 #36
0
ファイル: Session.cs プロジェクト: CookieEaters/FireHTTP
 private void _session_createSession(Engine scriptScope)
 {
     var response = (ClientHttpResponse) scriptScope.GetValue("response").ToObject();
     var sessionId = Guid.NewGuid().ToString("N");
     response.SendHeader("HTTP/1.1 200 OK");
     response.SendHeader("Set-Cookie: " + SessionIdVarName + "=" + sessionId + ";path=/");
     var currentSessionDict = new SessionData();
     _sessions.Add(sessionId, currentSessionDict); //Add a new session dictionary
     scriptScope.SetValue("_SESSION", currentSessionDict);
     _session_dumpSession(sessionId, currentSessionDict);
 }
コード例 #37
0
        private Engine GetEngine()
        {
            if (_engine == null)
            {
                _engine = new Engine().SetValue(RequireSystemFunctionName, new Func<string, dynamic>(Require));

                foreach (var extension in _packages.SelectMany(package => package.GetExtensions()))
                {
                    _engine.SetValue(extension.Key, extension.Value);
                }
            }

            return _engine;
        }
コード例 #38
0
        private void PrepareEngine(ScriptedPatchRequest patch, string docId, int size, ScriptedJsonPatcherOperationScope scope, Engine jintEngine)
        {
            scope.AdditionalStepsPerSize = additionalStepsPerSize;
            scope.MaxSteps = maxSteps;


            if (size != 0)
            {
                totalScriptSteps = maxSteps + (size * additionalStepsPerSize);
                jintEngine.Options.MaxStatements(TotalScriptSteps);
            }

            jintEngine.Global.Delete("PutDocument", false);
            jintEngine.Global.Delete("LoadDocument", false);
            jintEngine.Global.Delete("DeleteDocument", false);
            jintEngine.Global.Delete("IncreaseNumberOfAllowedStepsBy", false);

            CustomizeEngine(jintEngine, scope);

            jintEngine.SetValue("PutDocument", (Func<string, object, object, string>)((key, document, metadata) => scope.PutDocument(key, document, metadata, jintEngine)));
            jintEngine.SetValue("LoadDocument", (Func<string, JsValue>)(key => scope.LoadDocument(key, jintEngine, ref totalScriptSteps)));
            jintEngine.SetValue("DeleteDocument", (Action<string>)(scope.DeleteDocument));
            jintEngine.SetValue("__document_id", docId);

            jintEngine.SetValue("IncreaseNumberOfAllowedStepsBy", (Action<int>)(number =>
            {
                if (database != null && database.Configuration.AllowScriptsToAdjustNumberOfSteps)
                {
                    scope.MaxSteps += number;
                    jintEngine.Options.MaxStatements(totalScriptSteps + number);

                    return;
                }

                throw new InvalidOperationException("Cannot use 'IncreaseNumberOfAllowedStepsBy' method, because `Raven/AllowScriptsToAdjustNumberOfSteps` is set to false.");
            }));

            foreach (var kvp in patch.Values)
            {
                var token = kvp.Value as RavenJToken;
                if (token != null)
                {
                    jintEngine.SetValue(kvp.Key, scope.ToJsInstance(jintEngine, token));
                }
                else
                {
                    var rjt = RavenJToken.FromObject(kvp.Value);
                    var jsInstance = scope.ToJsInstance(jintEngine, rjt);
                    jintEngine.SetValue(kvp.Key, jsInstance);
                }
            }

            jintEngine.ResetStatementsCount();
        }
コード例 #39
0
ファイル: Session.cs プロジェクト: CookieEaters/FireHTTP
 internal void InstallProvider_Session(Engine scriptScope)
 {
     scriptScope.SetValue("session_start", new Action(() => session_start(scriptScope)));
     scriptScope.SetValue("session_destroy", new Action(() => session_destroy(scriptScope)));
 }
コード例 #40
0
        private Engine CreateDefaultEngine()
        {
            var engine = new Engine();

            engine.SetValue(ExportsVariableName, engine.Object.Construct(Jint.Runtime.Arguments.Empty));
            engine.SetValue(ConsoleVariableName, ConsoleObject);
            engine.SetValue(UtilityVariableName, _utilityObject);

            return engine;
        }
コード例 #41
0
ファイル: Session.cs プロジェクト: CookieEaters/FireHTTP
 internal void session_start(Engine scriptScope)
 {
     var response = (ClientHttpResponse) scriptScope.GetValue("response").ToObject();
     _session_initSession(scriptScope);
     //Check if a session exists for user:
     if (response.RequestHttpHeaders.ContainsKey("Cookie"))
     {
         var cookieString = response.RequestHttpHeaders["Cookie"];
         var hostString = response.RequestHttpHeaders["Host"];
         var currentClientcookies = GetAllCookiesFromHeader(cookieString, hostString);
         var existingSession = currentClientcookies[SessionIdVarName];
         if (existingSession != null)
         {
             var existingSessionId = existingSession.Value;
             //Cookie exists
             if (_session_hasSessionOnDisk(existingSessionId))
             {
                 //Session exists
                 response.SendHeader("HTTP/1.1 200 OK"); //Send OK like the other code path
                 if (_sessions.ContainsKey(existingSessionId))
                     scriptScope.SetValue("_SESSION", _sessions[existingSessionId]); //Assign _SESSION variable
                 else
                     _session_createSession(scriptScope);
             }
             else
             {
                 //Have to recreate
                 _session_createSession(scriptScope);
             }
         }
         else
         {
             _session_createSession(scriptScope);
         }
     }
     else
     {
         _session_createSession(scriptScope);
     }
 }
コード例 #42
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()");
        }
コード例 #43
0
ファイル: JistEngine.cs プロジェクト: wwa171/Jist
        /// <summary>
        /// Creates Javascript function delegates for the type specified, and
        /// optionally by the object instance.
        ///
        /// Instance may be null, however only static methods will be regarded
        /// in this manner, since there is no 'this' pointer.
        /// </summary>
        public void CreateScriptFunctions(Type type, object instance)
        {
            Delegate functionDelegate  = null;
            Type     delegateSignature = null;
            string   functionName      = null;
            JavascriptFunctionAttribute jsAttribute = null;

            /*
             * If the class provides functionality for scripts,
             * add it into the providedpackages array.
             */
            foreach (JavascriptProvidesAttribute attrib in type.GetCustomAttributes(true).OfType <JavascriptProvidesAttribute>())
            {
                if (!providedPackages.Contains(attrib.PackageName))
                {
                    providedPackages.Add(attrib.PackageName);
                }
            }

            /*
             * look for JS methods in the type
             */
            foreach (var jsFunction in type.GetMethods().Where(i => i.GetCustomAttributes(true).OfType <JavascriptFunctionAttribute>().Any()))
            {
                if (instance == null && jsFunction.IsStatic == false ||
                    (jsAttribute = jsFunction.GetCustomAttributes(true).OfType <JavascriptFunctionAttribute>().FirstOrDefault()) == null)
                {
                    continue;
                }

                foreach (string func in jsAttribute.FunctionNames)
                {
                    functionName = func ?? jsFunction.Name;

                    try
                    {
                        /*
                         * A delegate signature type matching every single parameter type,
                         * and the return type must be appended as the very last item
                         * in the array.
                         */
                        delegateSignature = Expression.GetDelegateType(jsFunction.GetParameters().Select(i => i.ParameterType)
                                                                       .Concat(new[] { jsFunction.ReturnType }).ToArray());

                        if (instance != null)
                        {
                            functionDelegate = Delegate.CreateDelegate(delegateSignature, instance, jsFunction);
                        }
                        else
                        {
                            functionDelegate = Delegate.CreateDelegate(delegateSignature, jsFunction);
                        }

                        lock (syncRoot)
                            jsEngine.SetValue(functionName, functionDelegate);
                    }
                    catch (Exception ex)
                    {
                        ScriptLog.ErrorFormat("engine", "Error whilst creating javascript function for {0}: {1}",
                                              functionName, ex.ToString());
                        continue;
                    }
                }
            }
        }
コード例 #44
0
ファイル: FreeboxOS.cs プロジェクト: JRBANCEL/FreeboxLogin
        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;
                }
            }
        }
コード例 #45
0
 Engine ActivateEngine(Engine engine)
 {
     return engine
         .SetValue("setDimensions", new Action<int, int>(SetDimensions))
         .SetValue("overrideSettings", new Action<bool, bool>(OverrideSettings))
         .SetValue("move", new Action<int, int>(CommandMove))
         .SetValue("hurtPlayer", new Action(parent.player.Hurt))
         .SetValue("die", new Action(Die))
         .SetValue("questionBox", new Action<string, string, string>(QuestionBox))
         .SetValue("setLocation", new Action<int, int>(SetLocation))
         .SetValue("setWander", new Action<bool>(SetWander))
         .SetValue("setColor", new Action<int, int, int, int>(SetColor))
         .SetValue("becomeEnemy", new Action<int, bool>(BecomeEnemy))
         .SetValue("spawnShooter", new Action<int, int, bool>(SpawnShooter))
         .SetValue("changeFace", new Action<int>(ChangeFace))
         .SetValue("changeDirection", new Action<int>(ChangeDirection))
         .SetValue("getThisX", new Func<int>(GetThisX))
         .SetValue("getThisY", new Func<int>(GetThisY))
         .SetValue("explode", new Action<bool>(Explode))
         .SetValue("hookDeath", new Action<string>(HookDeath))
         .Execute("onLoad()");
 }