public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result) { var csharpBinder = binder.GetType().GetInterfaces().FirstOrDefault(s => s.Name == "Microsoft.CSharp.RuntimeBinder.ICSharpInvokeOrInvokeMemberBinder"); //var csharpBinder = binder.GetType().GetInterface("Microsoft.CSharp.RuntimeBinder.ICSharpInvokeOrInvokeMemberBinder"); if (csharpBinder == null) { throw new ArgumentException("is not csharp code"); } var typeArgs = (csharpBinder.GetProperty("TypeArguments").GetValue(binder, null) as IList <Type>).ToArray(); var parameterTypes = (binder.GetType().GetField("Cache", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(binder) as Dictionary <Type, object>) .First() .Key .GetGenericArguments() .Skip(2) .Take(args.Length) .ToArray(); var method = MatchMethod(binder.Name, args, typeArgs, parameterTypes); result = method.Invoke(target, args); return(true); }
public override bool TryInvokeMember(InvokeMemberBinder binder, object?[]?args, out object?result) { var csharpBinder = binder.GetType().GetInterface("Microsoft.CSharp.RuntimeBinder.ICSharpInvokeOrInvokeMemberBinder"); var typeArgs = csharpBinder !.GetProperty("TypeArguments")?.GetValue(binder, null) as IList <Type> ?? Array.Empty <Type>(); var jsObjectReferenceType = typeof(JSObjectReference); MethodInfo methodInfo; if (typeArgs.Any()) { var method = jsObjectReferenceType .GetMethods() .First(x => x.Name.Contains(nameof(Module.InvokeAsync))); // only support one generic methodInfo = method.MakeGenericMethod(typeArgs.First()); } else { methodInfo = jsObjectReferenceType .GetMethods() .First(x => x.Name.Contains(nameof(Module.InvokeVoidAsync))); } var task = methodInfo.Invoke(Module, new object[] { binder.Name, args }); result = task; return(true); }
private static Type GetGenericType(InvokeMemberBinder binder) { var csharpBinder = binder.GetType().GetInterface("Microsoft.CSharp.RuntimeBinder.ICSharpInvokeOrInvokeMemberBinder"); var typeArgs = (csharpBinder.GetProperty("TypeArguments").GetValue(binder, null) as IList <Type>); return(typeArgs.FirstOrDefault()); }
public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result) { if (binder == null) { throw new ArgumentNullException(nameof(binder)); } if (args == null) { throw new ArgumentNullException(nameof(args)); } for (int i = 0; i < args.Length; i++) { args[i] = Unwrap(args[i]); } var csharpBinder = binder.GetType().GetTypeInfo().GetInterface("Microsoft.CSharp.RuntimeBinder.ICSharpInvokeOrInvokeMemberBinder"); var typeArgs = (IList <Type>)csharpBinder.GetTypeInfo().GetProperty("TypeArguments").GetValue(binder, null); result = InvokeMethodOnType(TargetType, Instance, binder.Name, args, typeArgs); // Wrap the sub object if necessary. This allows nested anonymous objects to work. result = result.AsDynamic(); return(true); }
private static Type[] GetGenericMethodArguments(InvokeMemberBinder binder) { var csharpInvokeMemberBinderType = binder .GetType().GetTypeInfo() .GetInterface("Microsoft.CSharp.RuntimeBinder.ICSharpInvokeOrInvokeMemberBinder") .GetTypeInfo(); var typeArgsList = (IList <Type>)csharpInvokeMemberBinderType.GetProperty("TypeArguments").GetValue(binder, null); Type[] typeArgs; if (typeArgsList.Count == 0) { #if NET45 typeArgs = _emptyTypes; #else typeArgs = Array.Empty <Type>(); #endif } else { typeArgs = typeArgsList.ToArray(); } return(typeArgs); }
/// <summary>m /// Entry function for everything you can come up with.! /// </summary> /// <param name="binder"></param> /// <param name="args"></param> /// <param name="result"></param> /// <returns></returns> public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result) { //get the Type argument from the binder #if !__MonoCS__ var typeArgs = Impromptu.InvokeGet(binder, "Microsoft.CSharp.RuntimeBinder.ICSharpInvokeOrInvokeMemberBinder.TypeArguments") as IList <Type>; var typeArg = typeArgs == null ? null : typeArgs.FirstOrDefault(); #else var csharpBinder = binder.GetType().GetField("typeArguments", BindingFlags.NonPublic | BindingFlags.Instance); var typeArgs = csharpBinder.GetValue(binder) as IList <Type>; var typeArg = typeArgs == null ? null : typeArgs.FirstOrDefault(); #endif //Mangle the function name into nouns and verbs //var noun = Container.Resolve<INounResolver>().ResolveNoun (binder.Name); var verb = Container.Resolve <IVerbResolver>().ResolveVerb(binder.Name); var doCallParameters = GetDoCallParameters(typeArg, binder.Name, args); //dynamicly call a generic function var method = GetType().GetMethod("DoCall").MakeGenericMethod(doCallParameters.GenericTypeArgument); result = method.Invoke(this, new [] { verb, binder.Name, doCallParameters.QueryDict, doCallParameters.InputEditor, doCallParameters.UrlParameters, doCallParameters.Payload }); return(true); }
/// <summary> /// Gets the generic type parameters. /// </summary> /// <param name="binder">The binder.</param> /// <returns>Type[].</returns> internal static Type[] GetGenericTypeParameters(this InvokeMemberBinder binder) { var typeArgumentsProperty = binder.GetType() ?.GetInterface("Microsoft.CSharp.RuntimeBinder.ICSharpInvokeOrInvokeMemberBinder") ?.GetProperty("TypeArguments") ?? throw new NotSupportedException("Cannot find required internal type Microsoft.CSharp.RuntimeBinder.ICSharpInvokeOrInvokeMemberBinder"); var typeArgs = typeArgumentsProperty?.GetValue(binder, null) as IList <Type>; return(typeArgs?.ToArray() ?? Array.Empty <Type>()); }
private Type GetMethodReturnType(InvokeMemberBinder binder) { IList <Type> types = binder.GetType().GetField("m_typeArguments", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(binder) as IList <Type>; if ((types != null) && (types.Count > 0)) { return(types[0]); } return(null); }
public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result) { ParameterInfo[] parameters = null; if (binder.GetType().FullName.StartsWith("Microsoft.CSharp.", StringComparison.Ordinal)) { parameters = new StackFrame(1, false).GetMethod().GetParameters(); } return(TryWrappedInvokeOrInvokeMember(binder, parameters, args, out result)); }
public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result) { switch (binder.Name) { case nameof(GetName): case nameof(GetValue): { return(base.TryInvokeMember(binder, args, out result)); } default: { var name = NormalizeName(binder.Name); var match = Regex.Match(name, @"get([a-z0-9]+)list"); if (match.Success) { var childElementName = NormalizeName(match.Groups[1].Value); result = _root.Elements() .Where(x => NormalizeName(x.Name) == childElementName) .Select(CreateResult) //.ToImmutableArray(); .ToArray(); return(true); } var attribute = _root.Attributes().SingleOrDefault(x => NormalizeName(x.Name) == name); if (attribute != null) { var csharpBinder = binder.GetType().GetInterface("Microsoft.CSharp.RuntimeBinder.ICSharpInvokeOrInvokeMemberBinder"); if (csharpBinder.GetProperty("TypeArguments")?.GetValue(binder, null) is IList <Type> typeArgs && typeArgs.Count > 0) { result = ChangeType(attribute.Value, typeArgs[0]); } else { throw new InvalidOperationException("Output type is not specified, use property getter to get raw value."); } return(true); } result = null; return(true); } } }
/// <summary>Extension method allowing to easyly extract generic type arguments from <see cref="InvokeMemberBinder"/>.</summary> /// <param name="binder">Binder from which get type arguments.</param> /// <returns>List of types passed as generic parameters.</returns> public static IList <Type> GetGenericTypeArguments(this InvokeMemberBinder binder) { // First try to use delegate if exist if (_frameworkTypeArgumentsGetter != null) { return(_frameworkTypeArgumentsGetter(binder)); } if (_isMono) { // In mono this is trivial. // First we get field info. var field = binder.GetType().GetField("typeArguments", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static); // If this was a success get and return it's value if (field != null) { return(field.GetValue(binder) as IList <Type>); } } else { // In this case, we need more aerobic :D // First, get the interface var inter = binder.GetType().GetInterface("Microsoft.CSharp.RuntimeBinder.ICSharpInvokeOrInvokeMemberBinder"); if (inter != null) { // Now get property. var prop = inter.GetProperty("TypeArguments"); // If we have a property, return it's value if (prop != null) { return(prop.GetValue(binder, null) as IList <Type>); } } } // Sadly return null if failed. return(null); }
public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result) { var csharpBinder = binder.GetType().GetInterface("Microsoft.CSharp.RuntimeBinder.ICSharpInvokeOrInvokeMemberBinder"); if (csharpBinder == null) { throw new ArgumentException("is not generic csharp code"); } var typeArgs = (csharpBinder.GetProperty("TypeArguments").GetValue(binder, null) as IList <Type>).ToArray(); var method = MatchMethod(binder.Name, args, typeArgs); result = method.Invoke(target, args); return(true); }
public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result) { Guard.AgainstNullArgument(nameof(binder), binder); var csharpBinder = binder.GetType().GetInterface("Microsoft.CSharp.RuntimeBinder.ICSharpInvokeOrInvokeMemberBinder"); var genericTypeArgument = (csharpBinder.GetProperty("TypeArguments").GetValue(binder, null) as IList <Type>).FirstOrDefault(); if (!this.values.TryGetValue(binder.Name, out result)) { if (args != null && args.Any()) { if (!genericTypeArgument.IsInstanceOfType(args[0])) { throw new InvalidOperationException( Invariant($"The specified default is not an instance of '{genericTypeArgument.FullName}'.")); } result = args[0]; return(true); } throw new InvalidOperationException(Invariant($"'{binder.Name}' does not exist.")); } var castForRetreival = ((MethodCallExpression)castForRetreivalExample.Body) .Method.GetGenericMethodDefinition().MakeGenericMethod(genericTypeArgument); try { result = castForRetreival.Invoke(null, new object[] { result, binder.Name }); } catch (TargetInvocationException ex) { Exception actualException = ex; while (actualException is TargetInvocationException) { actualException = ex.InnerException; } ExceptionDispatchInfo.Capture(actualException).Throw(); } return(true); }
public static Type[] TryGetTypeArgumentsFromBinder(InvokeMemberBinder binder) { if (SecuredReflection.IsAvailable) { var csharpInvoke = binder.GetType().GetInterfaces() .FirstOrDefault(intf => intf.FullName == "Microsoft.CSharp.RuntimeBinder.ICSharpInvokeOrInvokeMemberBinder"); if (csharpInvoke != null) { var typeArgs = (ICollection <Type>)SecuredReflectionMethods.GetProperty(csharpInvoke.GetProperty("TypeArguments"), binder, null); if (typeArgs != null && typeArgs.Count > 0) { return(typeArgs.ToArray()); } } } return(null); }
public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result) { var method = binder.Name; var argumentNames = binder.CallInfo.ArgumentNames; // accept named args only if (argumentNames.Count != args.Length) { throw new InvalidOperationException("Please use named arguments. Example: myObject.MyMethod(myNamedParameter: 123);"); } //stuff parameters into case insensitive dictionary var parameters = new Dictionary <string, object>(StringComparer.OrdinalIgnoreCase); for (int i = 0; i < args.Length; i++) { parameters.Add(argumentNames[i], args[i]); } //the only way to determine if generic type parameters have been used is reflection var csharpBinder = binder.GetType().GetInterface("Microsoft.CSharp.RuntimeBinder.ICSharpInvokeOrInvokeMemberBinder"); var typeArgs = csharpBinder.GetProperty("TypeArguments").GetValue(binder, null) as IList <Type>; Type returnType = typeArgs.FirstOrDefault(); //if it exists, the first generic type parameter is our return type (e.g. myObject.MyMethod<int>(Id: 123); --> returnType would be typeof(int)) if (returnType != null) { MethodInfo methodInfo = typeof(JsonRPCHttpClient).GetMethod("ExecuteAndConvert"); MethodInfo genericMethodInfo = methodInfo.MakeGenericMethod(returnType); try { result = genericMethodInfo.Invoke(_client, new object[] { _serviceName, method, parameters }); } catch (TargetInvocationException tiex) { throw tiex.InnerException; } } else { result = _client.Execute(_serviceName, method, parameters); } return(true); }
public override bool TryInvokeMember(InvokeMemberBinder binder, object[] p_args, out object result) { var csharpBinder = binder.GetType().GetInterface("Microsoft.CSharp.RuntimeBinder.ICSharpInvokeOrInvokeMemberBinder"); var typeArgs = csharpBinder.GetProperty("TypeArguments").GetValue(binder, null) as IList <Type>; Type retrunType = null; if (typeArgs != null && typeArgs.Any()) { retrunType = typeArgs.First(); } var funcName = binder.Name; result = _native.Invoke(funcName, retrunType, p_args); return(true); }
/// <summary>Extension method allowing to easyly extract generic type arguments from <see cref="InvokeMemberBinder"/>.</summary> /// <param name="binder">Binder from which get type arguments.</param> /// <returns>List of types passed as generic parameters.</returns> public static IEnumerable <Type> GetGenericTypeArguments(this InvokeMemberBinder binder) { lock (_sync) { // if we haven't cached the private field of the base class do so now if (_typeArgumentsField == null) { // using reflection get the FieldInfo of the private typeArguments field // mono and MS .net use different naming for this field string fieldName = Type.GetType("Mono.Runtime") != null ? "typeArguments" : "m_typeArguments"; _typeArgumentsField = binder.GetType().GetTypeInfo().GetDeclaredField(fieldName); } } if (_typeArgumentsField != null) { return(_typeArgumentsField.GetValue(binder) as IEnumerable <Type> ?? new List <Type>()); } // if the field info is still null, something changed in how .net implements the dynamic binder Debug.Assert(false, "Retrieving the private collection of generic type arguments failed"); // Sadly return empty collection if failed. return(new List <Type>()); }
public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result) { int nargout = 1; var args1 = args; if (binder.CallInfo.ArgumentNames.Count != 0 && binder.CallInfo.ArgumentNames[binder.CallInfo.ArgumentNames.Count - 1].Equals("nargout", StringComparison.Ordinal)) { try { nargout = (int)args[args.Length - 1]; } catch (InvalidCastException) { throw new ArgumentException("Type of nargout argument must be Int32", "nargout"); } args1 = new object[args.Length - 1]; Array.Copy(args, 0, args1, 0, args1.Length); } else { if (_bInfo == null) { _bInfo = binder.GetType().GetInterface( "Microsoft.CSharp.RuntimeBinder.ICSharpInvokeOrInvokeMemberBinder") .GetProperty("ResultDiscarded"); } if ((bool)_bInfo.GetValue(binder, null)) { nargout = 0; } } var status = OctaveCore.Octave.Feval(binder.Name, args1, nargout, out result); switch (status) { case OctaveCore.Octave.FevalStatus.OK: return(true); case OctaveCore.Octave.FevalStatus.Error: throw new OctaveRuntimeException(OctaveCore.Octave.GetLastError()); case OctaveCore.Octave.FevalStatus.BadArgument: throw new ArgumentException("Unsupported argument type", "args"); case OctaveCore.Octave.FevalStatus.BadReturn: throw new ArgumentException("Unsupported return type", "ret"); case OctaveCore.Octave.FevalStatus.BadAlloc: throw new OutOfMemoryException("Octave failed to allocate the required memory"); case OctaveCore.Octave.FevalStatus.Interupted: throw new OctaveRuntimeException("Octave interpreter was interrupted"); default: return(false); } }
private dynamic generic_ndarray_function(IntPtr funcHandle, List <string> arguments, InvokeMemberBinder binder, object[] args) { var csharpBinder = binder.GetType().GetInterface("Microsoft.CSharp.RuntimeBinder.ICSharpInvokeOrInvokeMemberBinder"); var argumentInfos = ((IList <CSharpArgumentInfo>)csharpBinder.GetProperty("ArgumentInfo").GetValue(binder, null)).Skip(1).ToList(); var namedArgumentProperty = typeof(CSharpArgumentInfo).GetProperty("NamedArgument", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.GetProperty); var nametProperty = typeof(CSharpArgumentInfo).GetProperty("Name", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.GetProperty); Debug.Assert(argumentInfos != null, "argumentInfos != null"); var nonamarg = argumentInfos.Where(w => !(bool)namedArgumentProperty.GetValue(w, null)).ToList(); var namarg = argumentInfos.Select((x, i) => new { x, i }).Where(w => (bool)namedArgumentProperty.GetValue(w.x, null)) .ToDictionary(k => nametProperty.GetValue(k.x, null) as string, v => args[v.i]).ToList(); List <NDArrayHandle> nd_args = new List <NDArrayHandle>(); List <NDArrayHandle> output_vars = new List <NDArrayHandle>(); List <string> sparam_vals = new List <string>(); List <string> sparam_keys = new List <string>(); int pos_param_arg = 0; for (int i = 0; i < nonamarg.Count; i++) { if (args[i] is NdArray) { nd_args.Add(((NdArray)args[i]).Handle); } else { if (pos_param_arg >= arguments.Count) { throw new ArgumentException("Too many positional arguments"); } sparam_vals.Add(args[i].ToString()); sparam_keys.Add(arguments[pos_param_arg]); pos_param_arg = pos_param_arg + 1; } } dynamic original_output = null; foreach (var kviem in namarg) { if (kviem.Key == "out") { original_output = kviem.Value; if (kviem.Value is NdArray) { output_vars.Add(((NdArray)kviem.Value).Handle); } else { foreach (var v in (IEnumerable)kviem.Value) { if (!(v is NdArray)) { throw new ArgumentException("out need to be of type NDArray"); } output_vars.Add(((NdArray)v).Handle); } } } else { sparam_vals.Add(kviem.Value.ToString()); sparam_keys.Add(kviem.Key); } } int num_output = output_vars.Count; bool nooutput = num_output == 0; GCHandle?outputArrayGch = null; NDArrayHandle[] outputArray = null; IntPtr outputArrayPtr; if (nooutput) { outputArrayPtr = IntPtr.Zero; } else { outputArray = output_vars.ToArray(); outputArrayGch = GCHandle.Alloc(outputArray, GCHandleType.Pinned); outputArrayPtr = outputArrayGch.Value.AddrOfPinnedObject(); } NativeMethods.MXImperativeInvoke(funcHandle, nd_args.Count, nd_args.ToArray(), ref num_output, ref outputArrayPtr, sparam_keys.Count, sparam_keys.ToArray(), sparam_vals.ToArray()); if (!nooutput) { outputArrayGch.Value.Free(); } if (original_output != null) { return(original_output); } if (nooutput) { NDArrayHandle[] ndArrays = new NDArrayHandle[num_output]; Marshal.Copy(outputArrayPtr, ndArrays, 0, num_output); if (num_output == 1) { return(new NdArray(ndArrays[0])); } else { return((IList <NdArray>)ndArrays.Select(s => new NdArray(s)).ToList()); } } else { if (num_output == 1) { return(new NdArray(outputArray[0])); } else { return((IList <NdArray>)outputArray.Select(s => new NdArray(s)).ToList()); } } }
private Type[] TypeArguments(InvokeMemberBinder binder) { var csharpBinder = binder.GetType().GetInterface("Microsoft.CSharp.RuntimeBinder.ICSharpInvokeOrInvokeMemberBinder"); return((csharpBinder.GetProperty("TypeArguments").GetValue(binder, null) as IList <Type>).ToArray()); }
public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result) { //if the polling interval is zero (or less) run this request synchronously if (this._pollingIntervalMilliseconds <= 0) { return(this.ServiceBusClient.TryInvokeMember(binder, args, out result)); } result = null; var info = binder.CallInfo; var method = binder.Name; // accepting named args only... SKEET! if (info.ArgumentNames.Count != args.Length) { throw new InvalidOperationException("Please use named arguments."); } //stuff parameters into case insensitive dictionary var parameters = new Dictionary <string, object>(StringComparer.OrdinalIgnoreCase); for (int i = 0; i < args.Length; i++) { parameters.Add(info.ArgumentNames[i], args[i]); } var token = ServiceBusClient.AsyncProcess().ExecuteAsyncProcess(method, parameters); //the only way to determine if generic type parameters have been used is reflection var csharpBinder = binder.GetType().GetInterface("Microsoft.CSharp.RuntimeBinder.ICSharpInvokeOrInvokeMemberBinder"); var typeArgs = csharpBinder.GetProperty("TypeArguments").GetValue(binder, null) as IList <Type>; Type returnType = typeArgs.FirstOrDefault(); //if it exists, the first generic type parameter is our return type (e.g. myObject.MyMethod<int>(Id: 123); --> returnType would be typeof(int)) if (returnType != null) { MethodInfo genericMethodInfo = _asyncDynamicMethodInfo.MakeGenericMethod(returnType); try { var sw = Stopwatch.StartNew(); while (sw.ElapsedMilliseconds <= PollingTimeout.Value.TotalMilliseconds) { //async get result var asyncResult = genericMethodInfo.Invoke(ServiceBusClient.AsyncProcess(), new object[] { (string)token }); //examine result PropertyInfo statusPropertyInfo = asyncResult.GetType().GetProperty("Status"); Status asyncStatus = (Status)statusPropertyInfo.GetValue(asyncResult); if (asyncStatus == Status.Done) { PropertyInfo resultPropertyInfo = asyncResult.GetType().GetProperty("Result"); result = resultPropertyInfo.GetValue(asyncResult); return(true); } else if (asyncStatus == Status.NotFound) { //todo create a custom exception throw new AsyncNotFoundException(); } //wait our polling interval Thread.Sleep(_pollingIntervalMilliseconds); }//end while (not timed out) //if we've made it here... timed out throw new AsyncTimeoutException(); } catch (TargetInvocationException tiex) { throw tiex.InnerException; } } else { var sw = Stopwatch.StartNew(); while (sw.ElapsedMilliseconds <= PollingTimeout.Value.TotalMilliseconds) { //async get result AsyncResult asyncResult = ServiceBusClient.AsyncProcess().GetAsyncResult((string)token) as AsyncResult; //examine result if (asyncResult.Status == Status.Done) { result = asyncResult.Result; return(true); } else if (asyncResult.Status == Status.NotFound) { //todo create a custom exception throw new AsyncNotFoundException(); } //wait our polling interval Thread.Sleep(_pollingIntervalMilliseconds); }//end while (not timed out) //if we've made it here... timed out throw new AsyncTimeoutException(); } }