public static DomEventHandler ToListener(this FunctionInstance function, EngineInstance engine) { return((obj, ev) => { function.Call(obj.ToJsValue(engine), new [] { ev.ToJsValue(engine) }); }); }
public IEnumerable IndexingFunction(IEnumerable <object> items) { try { foreach (var item in items) { _engine.ResetCallStack(); _engine.ResetStatementsCount(); _engine.ResetTimeoutTicks(); if (JavaScriptIndexUtils.GetValue(_engine, item, out JsValue jsItem) == false) { continue; } { _oneItemArray[0] = jsItem; try { jsItem = MapFunc.Call(JsValue.Null, _oneItemArray); }catch (JavaScriptException jse) { var(message, success) = JavaScriptIndexFuncException.PrepareErrorMessageForJavaScriptIndexFuncException(MapString, jse); if (success == false) { throw new JavaScriptIndexFuncException($"Failed to execute {MapString}", jse); } throw new JavaScriptIndexFuncException($"Failed to execute map script, {message}", jse); } catch (Exception e) { throw new JavaScriptIndexFuncException($"Failed to execute {MapString}", e); } if (jsItem.IsArray()) { var array = jsItem.AsArray(); foreach (var(prop, val) in array.GetOwnProperties()) { if (prop == "length") { continue; } yield return(val.Value); } } else if (jsItem.IsObject()) { yield return(jsItem.AsObject()); } // we ignore everything else by design, we support only // objects and arrays, anything else is discarded } _resolver.ExplodeArgsOn(null, null); } } finally { _oneItemArray[0] = null; } }
public static DomEventHandler ToListener(this FunctionInstance function, EngineInstance engine) => (obj, ev) => { var objAsJs = obj.ToJsValue(engine); var evAsJs = ev.ToJsValue(engine); try { function.Call(objAsJs, new[] { evAsJs }); } catch (JavaScriptException jsException) { var window = (IWindow)engine.Window.Value; window.Fire <ErrorEvent>(e => e.Init(null, jsException.LineNumber, jsException.Column, jsException)); } };
public object CallAsUser(string applicationId, FunctionInstance function, object thisObj, params object[] arguments) { if (thisObj == null || thisObj == Null.Value || thisObj == Undefined.Value) { thisObj = this.Engine.Global; } object result = null; ImpersonationHelper.InvokeAsUser(applicationId, new Action(() => { result = function.Call(thisObj, arguments); })); return(result); }
private async void SetTimeout(ManticoreEngine engine, FunctionInstance callback, int timeout) { await Task.Delay(TimeSpan.FromMilliseconds(timeout)); engine.Js(() => { try { callback.Call(JsValue.Null, new JsValue[] { }); } catch (Exception x) { Debug.WriteLine(x); } }); }
public DeferredInstance Construct(FunctionInstance function, params object[] parameters) { var state = new DeferredState { This = this.Engine.Evaluate("this;"), Parameters = parameters, }; var task = new Task <object>(s => { var localState = s as DeferredState; return(localState == null ? null : function.Call(localState.This, localState.Parameters)); }, state); task.Start(); return(new DeferredInstance(this.InstancePrototype, task)); }
void Xhr(ObjectInstance href, ObjectInstance type, FunctionInstance callback, FunctionInstance errorCallback) { var filename = href.ToString(); var referencingFile = currentFiles.Peek(); try { var file = referencingFile.Directory.GetFile(filename); var content = file.OpenRead().ReadToEnd(); callback.Call(Null.Value, content, DateTime.MinValue); } catch (FileNotFoundException ex) { throw FileNotFoundExceptionWithSourceFilename(referencingFile, ex); } catch (DirectoryNotFoundException ex) { throw DirectoryNotFoundExceptionWithSourceFilename(referencingFile, ex); } }
private void SetTimeout(ManticoreEngine engine, FunctionInstance callback, int timeout) { System.Timers.Timer timer = new System.Timers.Timer(); // TODO not sure there may be a better way to emulate NextTick timer.Interval = Math.Max(1, timeout); timer.AutoReset = false; timer.Elapsed += (obj, args) => { engine.Js(() => { try { callback.Call(JsValue.Null, new JsValue[] { }); } catch (Exception x) { // TODO perhaps throw this error INTO JS? Log("error", x.ToString(), JsValue.Null); } }); }; timer.Start(); }
public int setTimeout(double msTimeout, ObjectInstance callback) { if (callback == null) { return(-1); } StringInstance strInst = callback as StringInstance; FunctionInstance funcInst = callback as FunctionInstance; if (funcInst == null && strInst == null) { return(-1); } int id = Interlocked.Increment(ref _timeoutId); Timer timer = new Timer(msTimeout); timer.AutoReset = false; _timers.Add(id, timer); timer.Elapsed += (sender, e) => { if (funcInst != null) { funcInst.Call(null); } else { _engine.Evaluate(strInst.ToString()); } timer.Dispose(); }; timer.Start(); return(id); }
public bool Download(FunctionInstance callback) { if (callback == null) { return(false); } try { var request = (HttpWebRequest)HttpWebRequest.Create(uri); request.CachePolicy = new RequestCachePolicy(RequestCacheLevel.Reload); request.Method = method.ToUpper(); foreach (object obj in Headers.Items) { string str = obj.ToString(); if (str.StartsWith("host")) { request.Host = str.Substring(str.IndexOf(':') + 1).Trim(); } else if (str.StartsWith("content-type")) { request.ContentType = str.Substring(str.IndexOf(':') + 1).Trim(); } else if (str.StartsWith("content-length")) { if (Int32.TryParse(str.Substring(str.IndexOf(':') + 1), out int length)) { request.ContentLength = length; } } else if (str.StartsWith("connection")) { request.Connection = str.Substring(str.IndexOf(':') + 1).Trim(); } else if (str.StartsWith("date")) { DateTime date = DateTime.MinValue; if (DateTime.TryParse(str.Substring(str.IndexOf(':') + 1), out date)) { request.Date = date; } } else if (str.StartsWith("expect")) { request.Expect = str.Substring(str.IndexOf(':') + 1).Trim(); } else if (str.StartsWith("accept")) { request.Accept = str.Substring(str.IndexOf(':') + 1).Trim(); } else if (str.StartsWith("user-agent")) { request.UserAgent = str.Substring(str.IndexOf(':') + 1).Trim(); } else if (str.StartsWith("referer")) { request.Referer = str.Substring(str.IndexOf(':') + 1).Trim(); } else if (str.StartsWith("TE")) { request.TransferEncoding = str.Substring(str.IndexOf(':') + 1).Trim(); } else if (str.StartsWith("if-modified-since")) { DateTime date = DateTime.MinValue; if (DateTime.TryParse(str.Substring(str.IndexOf(':') + 1), out date)) { request.IfModifiedSince = date; } } else { request.Headers.Add(str); } } if (request.Method == "POST") { if (!String.IsNullOrEmpty(PostContent)) { byte[] buffer = System.Text.Encoding.UTF8.GetBytes(PostContent); request.ContentLength = buffer.Length; var stream = request.GetRequestStream(); stream.Write(buffer, 0, buffer.Length); } else { request.ContentLength = 0; } } request.BeginGetResponse((IAsyncResult ar) => { try { var response = request.EndGetResponse(ar); var stream = response.GetResponseStream(); var reader = new StreamReader(stream, System.Text.Encoding.UTF8); string page = reader.ReadToEnd(); callback.Call(this, page); } catch (JavaScriptException jex) { JurassicPlugin.Self.OnError(jex); } catch (Exception ex) { JurassicPlugin.Self.OnError(new JavaScriptException(Engine, ErrorType.Error, ex.Message, ex)); } }, null); return(true); } catch (Exception e) { JurassicPlugin.Self.OnError(new JavaScriptException(Engine, ErrorType.Error, e.Message, e)); } return(false); }
public Delegate ConvertToClr(FunctionInstance func, Type targetType, JsValue jsThis, bool expandArrayArgs = false) { if (func == null) { return(null); } if (typeof(Delegate).IsAssignableFrom(targetType)) { var jsThisInst = jsThis == JsValue.Undefined ? Engine.Global : jsThis; //we have to pin 'this' to the handler. if (_jsToClrDelegatesMap.TryGetValue(new Tuple <FunctionInstance, JsValue>(func, jsThisInst), out var del)) { return(del); } if (targetType == typeof(System.Action)) { var expressionBody = Expression.Call( Expression.Constant(func, typeof(FunctionInstance)), nameof(FunctionInstance.Call), new Type[0], Expression.Constant(jsThis), Expression.Constant(new JsValue[0])); var lambda = Expression.Lambda <Action>(expressionBody); var compiled = lambda.Compile(); RegisterMap(compiled, func, jsThisInst); return(compiled); } else { var generic = targetType.IsGenericTypeDefinition ? targetType : targetType.IsGenericType ? targetType.GetGenericTypeDefinition() : null; if (generic != null) { if (targetType == typeof(Action <object[]>) && expandArrayArgs) { //special case Action <object[]> handler = args => { var jsArgs = args != null? args.Select(ConvertToJs).ToArray() : new JsValue[0]; func.Call(jsThis, jsArgs); }; RegisterMap(handler, func, jsThisInst); return(handler); } else if (generic == typeof(System.Action <>) || generic == typeof(Func <,>)) { var genArgs = targetType.GetGenericArguments(); var parameterExpression = Expression.Parameter(genArgs[0], "arg1"); var argumentsArrayInit = Expression.NewArrayInit(typeof(JsValue), Expression.Call( Expression.Constant(this), nameof(ConvertToJs), new Type[0], Expression.Convert(parameterExpression, typeof(object)) ) ); var callJsFuncExpr = (Expression)Expression.Call( Expression.Constant(func, func.GetType()), nameof(func.Call), new Type[0], Expression.Constant(jsThis), argumentsArrayInit); //for Func we have to convert jsValue to the target type. var funcReturnType = targetType.GetGenericArguments().Last(); if (generic == typeof(Func <,>)) { callJsFuncExpr = CreateConverterExpr( funcReturnType, callJsFuncExpr, Expression.Constant(jsThis)); } var lambda = Expression.Lambda(targetType, callJsFuncExpr, parameterExpression); var compiled = lambda.Compile(); RegisterMap(compiled, func, jsThisInst); return(compiled); } else if (generic == typeof(System.Action <,>)) //todo: two and more arguments callback { throw new NotImplementedException("Support of callback with multiple arguments not implemented"); } } } throw new NotImplementedException(); } throw new InvalidOperationException($"The FunctionInstance can not be converted to the target type: {targetType.Name}"); }
protected override string Compile(string code) => _compiler.Call(_engine.Global, code)?.ToString();