Esempio n. 1
0
        public override DynamicMetaObject/*!*/ BindInvokeMember(InvokeMemberBinder/*!*/ action, DynamicMetaObject/*!*/[]/*!*/ args) {
            DynamicMetaObject errorSuggestion = null;
            if (_baseMetaObject != null) {
                errorSuggestion = _baseMetaObject.BindInvokeMember(action, args);
            }
            
            CodeContext context = BinderState.GetBinderState(action).Context;
            IPythonObject sdo = Value;
            PythonTypeSlot foundSlot;

            if (TryGetGetAttribute(context, sdo.PythonType, out foundSlot)) {
                // we'll always fetch the value, go ahead and invoke afterwards.
                return BindingHelpers.GenericCall(action, this, args);
            }

            bool isOldStyle;
            bool systemTypeResolution;
            foundSlot = FindSlot(context, action.Name, sdo, out isOldStyle, out systemTypeResolution);
            if (foundSlot != null && !systemTypeResolution) {
                // we found the member in the type dictionary, not a .NET type, go ahead and
                // do the get & invoke.
                return BindingHelpers.GenericCall(action, this, args);
            }

            // it's a normal .NET member, let the calling language handle it how it usually does
            return action.FallbackInvokeMember(this, args, errorSuggestion);
        }
        public override DynamicMetaObject BindInvokeMember(InvokeMemberBinder binder, DynamicMetaObject[] args) {
            ContractUtils.RequiresNotNull(binder, "binder");

            ComMethodDesc method;
            if (_self.TryGetMemberMethod(binder.Name, out method) ||
                _self.TryGetMemberMethodExplicit(binder.Name, out method)) {

                bool[] isByRef = ComBinderHelpers.ProcessArgumentsForCom(ref args);
                return BindComInvoke(args, method, binder.CallInfo, isByRef);
            }

            return base.BindInvokeMember(binder, args);
        }
Esempio n. 3
0
        public override DynamicMetaObject/*!*/ BindInvokeMember(InvokeMemberBinder/*!*/ action, DynamicMetaObject/*!*/[]/*!*/ args) {
            foreach (PythonType pt in Value.ResolutionOrder) {
                PythonTypeSlot dummy;
                if (pt.IsSystemType) {
                    return action.FallbackInvokeMember(this, args);
                } else if (
                    pt.TryResolveSlot(DefaultContext.DefaultCLS, action.Name, out dummy) ||
                    pt.IsOldClass) {
                    break;
                }
            }

            return BindingHelpers.GenericInvokeMember(action, null, this, args);
        }
        public static DynamicMetaObject TryBind(RubyContext/*!*/ context, InvokeMemberBinder/*!*/ binder, DynamicMetaObject/*!*/ target, DynamicMetaObject/*!*/[]/*!*/ args) {
            Assert.NotNull(context, target);

            var metaBuilder = new MetaObjectBuilder();
            
            RubyCallAction.Bind(metaBuilder, binder.Name,
                new CallArguments(
                    new DynamicMetaObject(AstUtils.Constant(context), BindingRestrictions.Empty, context),
                    target, 
                    args, 
                    RubyCallSignature.Simple(binder.CallInfo.ArgumentCount)
                )
            );

            // TODO: we should return null if we fail, we need to throw exception for now:
            return metaBuilder.CreateMetaObject(binder, DynamicMetaObject.EmptyMetaObjects);
        }
        public override DynamicMetaObject/*!*/ BindInvokeMember(InvokeMemberBinder/*!*/ action, DynamicMetaObject/*!*/[]/*!*/ args) {
            ParameterExpression tmp = Expression.Parameter(typeof(object));

            // first get the default binder value
            DynamicMetaObject fallback = action.FallbackInvokeMember(this, args);

            // then fallback w/ an error suggestion that does a late bound lookup.
            return action.FallbackInvokeMember(
                this,
                args,
                new DynamicMetaObject(
                    Ast.Block(
                        new[] { tmp },
                        Ast.Condition(
                            Ast.NotEqual(
                                Ast.Assign(
                                    tmp,
                                    Ast.Call(
                                        typeof(PythonOps).GetMethod("PythonFunctionGetMember"),
                                        AstUtils.Convert(
                                            Expression,
                                            typeof(PythonFunction)
                                        ),
                                        Expression.Constant(action.Name)
                                    )
                                ),
                                Ast.Constant(OperationFailed.Value)
                            ),
                            action.FallbackInvoke(
                                new DynamicMetaObject(tmp, BindingRestrictions.Empty),
                                args,
                                null
                            ).Expression,
                            AstUtils.Convert(fallback.Expression, typeof(object))
                        )
                    ),
                    BindingRestrictions.GetTypeRestriction(Expression, typeof(PythonFunction)).Merge(fallback.Restrictions)
                )
            );
        }
Esempio n. 6
0
 public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result)
 {
     result = "Invoke Member " + binder.Name;
     return(true);
 }
Esempio n. 7
0
        // Because we don't ComboBind over several MOs and operations, and no one
        // is falling back to this function with MOs that have no values, we
        // don't need to check HasValue.  If we did check, and HasValue == False,
        // then would defer to new InvokeMemberBinder.Defer().
        //
        public override DynamicMetaObject BindInvokeMember(
            InvokeMemberBinder binder, DynamicMetaObject[] args)
        {
            var flags = BindingFlags.IgnoreCase | BindingFlags.Static |
                        BindingFlags.Public;
            var members = ReflType.GetMember(binder.Name, flags);

            if ((members.Length == 1) && (members[0] is PropertyInfo ||
                                          members[0] is FieldInfo))
            {
                // NEED TO TEST, should check for delegate value too
                var mem = members[0];
                throw new NotImplementedException();
                //return new DynamicMetaObject(
                //    Expression.Dynamic(
                //        new SymplInvokeBinder(new CallInfo(args.Length)),
                //        typeof(object),
                //        args.Select(a => a.Expression).AddFirst(
                //               Expression.MakeMemberAccess(this.Expression, mem)));

                // Don't test for eventinfos since we do nothing with them now.
            }
            else
            {
                // Get MethodInfos with right arg counts.
                var mi_mems = members.
                              Select(m => m as MethodInfo).
                              Where(m => m is MethodInfo &&
                                    ((MethodInfo)m).GetParameters().Length ==
                                    args.Length);
                // Get MethodInfos with param types that work for args.  This works
                // for except for value args that need to pass to reftype params.
                // We could detect that to be smarter and then explicitly StrongBox
                // the args.
                List <MethodInfo> res = new List <MethodInfo>();
                foreach (var mem in mi_mems)
                {
                    if (RuntimeHelpers.ParametersMatchArguments(
                            mem.GetParameters(), args))
                    {
                        res.Add(mem);
                    }
                }
                if (res.Count == 0)
                {
                    // Sometimes when binding members on TypeModels the member
                    // is an intance member since the Type is an instance of Type.
                    // We fallback to the binder with the Type instance to see if
                    // it binds.  The SymplInvokeMemberBinder does handle this.
                    var typeMO = RuntimeHelpers.GetRuntimeTypeMoFromModel(this);
                    var result = binder.FallbackInvokeMember(typeMO, args, null);
                    return(result);
                }
                // True below means generate an instance restriction on the MO.
                // We are only looking at the members defined in this Type instance.
                var restrictions = RuntimeHelpers.GetTargetArgsRestrictions(
                    this, args, true);
                // restrictions and conversion must be done consistently.
                var callArgs =
                    RuntimeHelpers.ConvertArguments(
                        args, res[0].GetParameters());
                return(new DynamicMetaObject(
                           RuntimeHelpers.EnsureObjectResult(
                               Expression.Call(res[0], callArgs)),
                           restrictions));
                // Could hve tried just letting Expr.Call factory do the work,
                // but if there is more than one applicable method using just
                // assignablefrom, Expr.Call throws.  It does not pick a "most
                // applicable" method or any method.
            }
        }
Esempio n. 8
0
 public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result) => base.TryInvokeMember(binder, args, out result);
 /// <summary>
 /// Performs the binding of the dynamic invoke member operation.
 /// </summary>
 /// <param name="binder">An instance of the <see cref="InvokeMemberBinder"/> that represents the details of the dynamic operation.</param>
 /// <param name="args">An array of <see cref="DynamicMetaObject"/> instances - arguments to the invoke member operation.</param>
 /// <returns>The new <see cref="DynamicMetaObject"/> representing the result of the binding.</returns>
 public virtual DynamicMetaObject BindInvokeMember(InvokeMemberBinder binder, DynamicMetaObject[] args) {
     ContractUtils.RequiresNotNull(binder, "binder");
     return binder.FallbackInvokeMember(this, args);
 }
Esempio n. 10
0
        /// <summary>
        /// Transforms an invoke member into a Python GetMember/Invoke.  The caller should
        /// verify that the given attribute is not resolved against a normal .NET class
        /// before calling this.  If it is a normal .NET member then a fallback InvokeMember
        /// is preferred.
        /// </summary>
        internal static DynamicMetaObject/*!*/ GenericInvokeMember(InvokeMemberBinder/*!*/ action, ValidationInfo valInfo, DynamicMetaObject target, DynamicMetaObject/*!*/[]/*!*/ args) {
            if (target.NeedsDeferral()) {
                return action.Defer(args);
            }

            return AddDynamicTestAndDefer(action, 
                action.FallbackInvoke(
                    new DynamicMetaObject(
                        Binders.Get(
                            BinderState.GetCodeContext(action),
                            BinderState.GetBinderState(action),
                            typeof(object),
                            action.Name,
                            target.Expression
                        ),
                        BindingRestrictionsHelpers.GetRuntimeTypeRestriction(target)
                    ),
                    args,
                    null
                ),
                args,
                valInfo
            );
        }
Esempio n. 11
0
        /// <summary>
        /// Transforms a call into a Python GetMember/Invoke.  This isn't quite the correct semantic as
        /// we shouldn't be returning Python members (e.g. object.__repr__) to non-Python callers.  This
        /// can go away as soon as all of the classes implement the full fidelity of the protocol
        /// </summary>
        internal static DynamicMetaObject/*!*/ GenericCall(InvokeMemberBinder/*!*/ action, DynamicMetaObject target, DynamicMetaObject/*!*/[]/*!*/ args) {
            if (target.NeedsDeferral()) {
                return action.Defer(args);
            }

            return new DynamicMetaObject(
                Invoke(
                    BinderState.GetCodeContext(action),
                    BinderState.GetBinderState(action),
                    typeof(object),
                    GetCallSignature(action),
                    ArrayUtils.Insert(
                        Binders.Get(
                            BinderState.GetCodeContext(action),
                            BinderState.GetBinderState(action),
                            typeof(object),
                            action.Name,
                            target.Expression
                        ),
                        DynamicUtils.GetExpressions(args)
                    )
                ),
                BindingRestrictions.Combine(args).Merge(target.Restrict(target.GetLimitType()).Restrictions)
            );
        }
Esempio n. 12
0
 public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result)
 {
     return(TryInvokeMember(binder.Name, args, out result));
 }
            public override DynamicMetaObject BindInvokeMember(InvokeMemberBinder binder, DynamicMetaObject[] args) {
                if (IsOverridden("TryInvokeMember")) {
                    return CallMethodWithResult("TryInvokeMember", binder, GetArgArray(args), (e) => binder.FallbackInvokeMember(this, args, e));
                } else if (IsOverridden("TryGetMember")) {
                    // Generate a tree like:
                    //
                    // {
                    //   object result;
                    //   TryGetMember(payload, out result) ? FallbackInvoke(result) : fallbackResult
                    // }
                    //
                    // Then it calls FallbackInvokeMember with this tree as the
                    // "error", giving the language the option of using this
                    // tree or doing .NET binding.
                    //
                    return CallMethodWithResult(
                        "TryGetMember", new GetBinderAdapter(binder), NoArgs,
                        (e) => binder.FallbackInvokeMember(this, args, e),
                        (e) => binder.FallbackInvoke(e, args, null)
                    );
                }

                return base.BindInvokeMember(binder, args);
            }
        // 为动态类型动态添加方法;
        public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result)
        {
            // 可以通过调用方法的手段添加属性,AddProperty方法一共有三个参数;
            // 参数1:属性的名称;
            // 参数2:属性的实例值;
            // 参数3:列名称与属性之间建立关系;
            if (binder.Name == "AddProperty" && binder.CallInfo.ArgumentCount == 3)
            {
                string name = args[0] as string;
                if (name == null)
                {
                    //throw new ArgumentException("name");
                    result = null;
                    return(false);
                }
                // 向属性列表添加属性及其值;
                object value = args[1];
                Properties.Add(name, value);

                // 添加列名与属性列表的映射关系;
                string column_name = args[2] as string;
                ColName_Property.Add(column_name, name);

                PropertyList.Add(new Tuple <string, string, object>(name, column_name, value));

                result = value;
                return(true);
            }

            if (binder.Name == "GetProperty" && binder.CallInfo.ArgumentCount == 1)
            {
                string columnname = args[0] as string;
                if (columnname == null)
                {
                    result = null;
                    return(false);
                }

                // 在当前列名于属性列表中查找,看是否有匹配项;
                if (ColName_Property.ContainsKey(columnname))
                {
                    string key = ColName_Property[columnname];
                    if (Properties.ContainsKey(key))
                    {
                        object property = Properties[key];
                        result = property;
                        return(true);
                    }
                }
                else
                {
                    Console.WriteLine("Can not find the right property");
                    result = null;
                    return(false);
                }
            }

            // 判断单元格是否正在被编辑;
            if (binder.Name == "JudgePropertyName_StartEditing" && binder.CallInfo.ArgumentCount == 1)
            {
                string columnname = args[0] as string;
                if (columnname == null)
                {
                    result = null;
                    return(false);
                }

                // 在当前列名于属性列表中查找,看是否有匹配项;
                if (ColName_Property.ContainsKey(columnname))
                {
                    string key = ColName_Property[columnname];
                    if (Properties.ContainsKey(key))
                    {
                        object property = Properties[key];
                        (property as AbsDataGridCell).EditingCallback();
                        result = property;
                        return(true);
                    }
                }
                else
                {
                    Console.WriteLine("Can not find the right property");
                    result = null;
                    return(false);
                }
            }

            return(base.TryInvokeMember(binder, args, out result));
        }
Esempio n. 15
0
 public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result)
 {
     throw new InvalidOperationException("成员不能当作函数使用,成员不能被调用");
 }
Esempio n. 16
0
        /// <summary>
        /// A helpful query tool
        /// </summary>
        public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result)
        {
            //parse the method
            var constraints = new List <string>();
            var counter     = 0;
            var info        = binder.CallInfo;

            // accepting named args only... SKEET!
            if (info.ArgumentNames.Count != args.Length)
            {
                throw new InvalidOperationException("Please use named arguments for this type of query - the column name, orderby, columns, etc");
            }
            //first should be "FindBy, Last, Single, First"
            var    op      = binder.Name;
            var    columns = " * ";
            string orderBy = string.Format(" ORDER BY {0}", PrimaryKeyField);
            string sql     = "";

            string where = "";
            var whereArgs = new List <object>();

            //loop the named args - see if we have order, columns and constraints
            if (info.ArgumentNames.Count > 0)
            {
                for (int i = 0; i < args.Length; i++)
                {
                    var name = info.ArgumentNames[i].ToLower();
                    switch (name)
                    {
                    case "orderby":
                        orderBy = " ORDER BY " + args[i];
                        break;

                    case "columns":
                        columns = args[i].ToString();
                        break;

                    default:
                        constraints.Add(string.Format(" {0} = @{1}", name, counter));
                        whereArgs.Add(args[i]);
                        counter++;
                        break;
                    }
                }
            }

            //Build the WHERE bits
            if (constraints.Count > 0)
            {
                where = " WHERE " + string.Join(" AND ", constraints.ToArray());
            }
            //probably a bit much here but... yeah this whole thing needs to be refactored...
            if (op.ToLower() == "count")
            {
                result = Scalar("SELECT COUNT(*) FROM " + TableName + where, whereArgs.ToArray());
            }
            else if (op.ToLower() == "sum")
            {
                result = Scalar("SELECT SUM(" + columns + ") FROM " + TableName + where, whereArgs.ToArray());
            }
            else if (op.ToLower() == "max")
            {
                result = Scalar("SELECT MAX(" + columns + ") FROM " + TableName + where, whereArgs.ToArray());
            }
            else if (op.ToLower() == "min")
            {
                result = Scalar("SELECT MIN(" + columns + ") FROM " + TableName + where, whereArgs.ToArray());
            }
            else if (op.ToLower() == "avg")
            {
                result = Scalar("SELECT AVG(" + columns + ") FROM " + TableName + where, whereArgs.ToArray());
            }
            else
            {
                //build the SQL
                sql = "SELECT TOP 1 " + columns + " FROM " + TableName + where;
                var justOne = op.StartsWith("First") || op.StartsWith("Last") || op.StartsWith("Get") || op.StartsWith("Single");

                //Be sure to sort by DESC on the PK (PK Sort is the default)
                if (op.StartsWith("Last"))
                {
                    orderBy = orderBy + " DESC ";
                }
                else
                {
                    //default to multiple
                    sql = "SELECT " + columns + " FROM " + TableName + where;
                }

                if (justOne)
                {
                    //return a single record
                    result = Query(sql + orderBy, whereArgs.ToArray()).FirstOrDefault();
                }
                else
                {
                    //return lots
                    result = Query(sql + orderBy, whereArgs.ToArray());
                }
            }
            return(true);
        }
Esempio n. 17
0
 public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result)
 {
     result = Invoke(binder.Name, args);
     return true;
 }
Esempio n. 18
0
        public static bool TryBindInvokeMember(InvokeMemberBinder binder, DynamicMetaObject instance, DynamicMetaObject[] args, out DynamicMetaObject result) {
            ContractUtils.RequiresNotNull(binder, "binder");
            ContractUtils.RequiresNotNull(instance, "instance");
            ContractUtils.RequiresNotNull(args, "args");

            if (TryGetMetaObject(ref instance)) {
                //
                // Demand Full Trust to proceed with the binding.
                //

                new PermissionSet(PermissionState.Unrestricted).Demand();

                result = instance.BindInvokeMember(binder, args);
                return true;
            } else {
                result = null;
                return false;
            }
        }
Esempio n. 19
0
 public override DynamicMetaObject BindInvokeMember(InvokeMemberBinder binder, DynamicMetaObject[] args)
 {
     Requires.NotNull(binder, nameof(binder));
     return(binder.FallbackInvokeMember(UnwrapSelf(), args));
 }
Esempio n. 20
0
 public override bool TryInvokeMember(InvokeMemberBinder binder, object?[]?args, out object?result)
 {
     result = _clientProxy.SendCoreAsync(binder.Name, args !);
     return(true);
 }
Esempio n. 21
0
 public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result)
 {
     result = null;
     return(false);
 }
Esempio n. 22
0
 public virtual Object InvokeMember(InvokeMemberBinder binder, Object[] args)
 {
     throw Fallback();
 }
 public virtual bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result) {
     result = null;
     return false;
 }
Esempio n. 24
0
 ///<remarks>Needed for Visual basic dynamic support</remarks>
 public override DynamicMetaObject BindInvokeMember(InvokeMemberBinder binder, DynamicMetaObject[] args)
 {
     return(CallMethod(GetValue, new Expression[] { Expression.Constant(binder.Name) }));
 }
Esempio n. 25
0
 public override DynamicMetaObject/*!*/ BindInvokeMember(InvokeMemberBinder/*!*/ action, DynamicMetaObject/*!*/[]/*!*/ args) {
     return BindingHelpers.GenericInvokeMember(action, null, this, args);
 }
Esempio n. 26
0
 public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result)
 {
     result = Invoke(binder.Name, Arguments.From(args, binder.CallInfo.ArgumentNames));
     return(true);
 }
Esempio n. 27
0
            public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result)
            {
                if (binder.Name.Equals(
                    "Power", binder.IgnoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal)
                    && args.Length == 2)
                {
                    int x;
                    int y;
                    try
                    {
                        x = Convert.ToInt32(args[0]);
                        y = Convert.ToInt32(args[1]);
                    }
                    catch (Exception)
                    {
                        result = null;
                        return false;
                    }

                    result = checked((int)Math.Pow(x, y));
                    return true;
                }

                result = null;
                return false;
            }
Esempio n. 28
0
            /// <summary>
            /// A helpful query tool
            /// </summary>
            public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result)
            {
                //parse the method
                var constraints = new List<string>();
                var counter = 0;
                var info = binder.CallInfo;
                // accepting named args only... SKEET!
                if (info.ArgumentNames.Count != args.Length)
                {
                    throw new InvalidOperationException("Please use named arguments for this type of query - the column name, orderby, columns, etc");
                }
                //first should be "FindBy, Last, Single, First"
                var op = binder.Name;
                var columns = " * ";
                string orderBy = string.Format(" ORDER BY {0}", PrimaryKeyField);
                string sql = "";
                string where = "";
                var whereArgs = new List<object>();

                //loop the named args - see if we have order, columns and constraints
                if (info.ArgumentNames.Count > 0)
                {

                    for (int i = 0; i < args.Length; i++)
                    {
                        var name = info.ArgumentNames[i].ToLower();
                        switch (name)
                        {
                            case "orderby":
                                orderBy = " ORDER BY " + args[i];
                                break;
                            case "columns":
                                columns = args[i].ToString();
                                break;
                            default:
                                constraints.Add(string.Format(" {0} = @{1}", name, counter));
                                whereArgs.Add(args[i]);
                                counter++;
                                break;
                        }
                    }
                }

                //Build the WHERE bits
                if (constraints.Count > 0)
                {
                    where = " WHERE " + string.Join(" AND ", constraints.ToArray());
                }
                //probably a bit much here but... yeah this whole thing needs to be refactored...
                if (op.ToLower() == "count")
                {
                    result = Scalar("SELECT COUNT(*) FROM " + TableName + where, whereArgs.ToArray());
                }
                else if (op.ToLower() == "sum")
                {
                    result = Scalar("SELECT SUM(" + columns + ") FROM " + TableName + where, whereArgs.ToArray());
                }
                else if (op.ToLower() == "max")
                {
                    result = Scalar("SELECT MAX(" + columns + ") FROM " + TableName + where, whereArgs.ToArray());
                }
                else if (op.ToLower() == "min")
                {
                    result = Scalar("SELECT MIN(" + columns + ") FROM " + TableName + where, whereArgs.ToArray());
                }
                else if (op.ToLower() == "avg")
                {
                    result = Scalar("SELECT AVG(" + columns + ") FROM " + TableName + where, whereArgs.ToArray());
                }
                else
                {

                    //build the SQL
                    sql = "SELECT TOP 1 " + columns + " FROM " + TableName + where;
                    var justOne = op.StartsWith("First") || op.StartsWith("Last") || op.StartsWith("Get") || op.StartsWith("Single");

                    //Be sure to sort by DESC on the PK (PK Sort is the default)
                    if (op.StartsWith("Last"))
                    {
                        orderBy = orderBy + " DESC ";
                    }
                    else
                    {
                        //default to multiple
                        sql = "SELECT " + columns + " FROM " + TableName + where;
                    }

                    if (justOne)
                    {
                        //return a single record
                        result = Query(sql + orderBy, whereArgs.ToArray()).FirstOrDefault();
                    }
                    else
                    {
                        //return lots
                        result = Query(sql + orderBy, whereArgs.ToArray());
                    }
                }
                return true;
            }
Esempio n. 29
0
 public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result)
 {
     Console.WriteLine("Invoke Method \"{0}\"", binder.Name);
     result = new RichDynamo();
     return(true);
 }
 public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result)
 {
     throw new ArgumentException("Arguments not allowed");
 }
Esempio n. 31
0
 /// <summary>
 /// Tries to perform binding of the dynamic invoke member operation.
 /// </summary>
 /// <remarks>
 /// Always return false in CoreCLR.
 /// </remarks>
 public static bool TryBindInvokeMember(InvokeMemberBinder binder, bool isSetProperty, DynamicMetaObject instance, DynamicMetaObject[] args, out DynamicMetaObject result)
 {
     result = null;
     return(false);
 }
Esempio n. 32
0
 public override DynamicMetaObject BindInvokeMember(InvokeMemberBinder binder, DynamicMetaObject[] args)
 {
     ContractUtils.RequiresNotNull(binder, nameof(binder));
     return(binder.Defer(args.AddFirst(WrapSelf())));
 }
 internal GetBinderAdapter(InvokeMemberBinder binder) :
     base(binder.Name, binder.IgnoreCase)
 {
 }
Esempio n. 34
0
 public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result)
 {
     result = Activator.CreateInstance(binder.ReturnType);
     return(true);
 }
Esempio n. 35
0
 public override DynamicMetaObject /*!*/ BindInvokeMember(InvokeMemberBinder /*!*/ action, DynamicMetaObject /*!*/[] /*!*/ args)
 {
     return(BindingHelpers.GenericInvokeMember(action, null, this, args));
 }
 public override bool TryInvokeMember
     (InvokeMemberBinder binder, object[] args, out object result)
 {
     Console.WriteLine("Calling: " + binder.Name);
     return(base.TryInvokeMember(binder, args, out result));
 }
Esempio n. 37
0
 public override DynamicMetaObject BindInvokeMember(InvokeMemberBinder binder, DynamicMetaObject[] args)
 {
     return(scriptItem.PostProcessBindResult(metaDynamic.BindInvokeMember(binder, args)));
 }
Esempio n. 38
0
        public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result)
        {
            if (base.TryInvokeMember(binder, args, out result))
            {
                return(true);
            }
            if (binder.Name.StartsWith("order", StringComparison.OrdinalIgnoreCase))
            {
                if (args.Length != 0)
                {
                    throw new ArgumentException("OrderByColumn form does not accept parameters");
                }
                result = ParseOrderBy(binder.Name);
                return(true);
            }
            if (binder.Name.StartsWith("then", StringComparison.OrdinalIgnoreCase))
            {
                if (args.Length != 0)
                {
                    throw new ArgumentException("ThenByColumn form does not accept parameters");
                }
                result = ParseThenBy(binder.Name);
                return(true);
            }
            if (binder.Name.Equals("join", StringComparison.OrdinalIgnoreCase))
            {
                result = args.Length == 1 ? Join(ObjectAsObjectReference(args[0]), JoinType.Inner) : ParseJoin(binder, args);
                return(true);
            }
            if (binder.Name.Equals("leftjoin", StringComparison.OrdinalIgnoreCase) || binder.Name.Equals("outerjoin", StringComparison.OrdinalIgnoreCase))
            {
                result = args.Length == 1 ? Join(ObjectAsObjectReference(args[0]), JoinType.Outer) : ParseJoin(binder, args);
                return(true);
            }
            if (binder.Name.Equals("on", StringComparison.OrdinalIgnoreCase))
            {
                result = ParseOn(binder, args);
                return(true);
            }
            if (binder.Name.Equals("having", StringComparison.OrdinalIgnoreCase))
            {
                SimpleExpression expression;
                try
                {
                    expression = args.SingleOrDefault() as SimpleExpression;
                }
                catch (InvalidOperationException)
                {
                    throw new ArgumentException("Having requires an expression");
                }
                if (expression != null)
                {
                    result = new SimpleQuery(this, _clauses.Append(new HavingClause(expression)));
                    return(true);
                }
                throw new ArgumentException("Having requires an expression");
            }
            if (binder.Name.StartsWith("with", StringComparison.OrdinalIgnoreCase) && !binder.Name.Equals("WithTotalCount", StringComparison.OrdinalIgnoreCase))
            {
                result = ParseWith(binder, args);
                return(true);
            }
            if (binder.Name.Equals("select", StringComparison.OrdinalIgnoreCase))
            {
                result = Select(args.OfType <SimpleReference>());
                return(true);
            }

            var command = Commands.CommandFactory.GetCommandFor(binder.Name) as IQueryCompatibleCommand;

            if (command != null)
            {
                try
                {
                    result = command.Execute(_dataStrategy, this, binder, args);
                    return(true);
                }
                catch (NotImplementedException)
                {
                }
            }
            try
            {
                var methodInfo = typeof(SimpleQuery).GetMethod(binder.Name, args.Select(a => (a ?? new object()).GetType()).ToArray());
                if (methodInfo != null)
                {
                    methodInfo.Invoke(this, args);
                }
            }
            catch (AmbiguousMatchException)
            {
            }

            if (binder.Name.Equals("where", StringComparison.InvariantCultureIgnoreCase) || binder.Name.Equals("replacewhere", StringComparison.InvariantCultureIgnoreCase))
            {
                throw new BadExpressionException("Where methods require a single criteria expression.");
            }

            return(false);
        }
Esempio n. 39
0
 public virtual bool TryInvokeMember(T instance, InvokeMemberBinder binder, object[] args, out object result)
 {
     result = null;
     return(false);
 }
Esempio n. 40
0
        /// <summary>
        /// Provides the implementation for operations that invoke a member. Classes derived from the <see cref="T:System.Dynamic.DynamicObject" /> class can override this method to specify dynamic behavior for operations such as calling a method.
        /// </summary>
        /// <param name="binder">Provides information about the dynamic operation. The binder.Name property provides the name of the member on which the dynamic operation is performed. For example, for the statement sampleObject.SampleMethod(100), where sampleObject is an instance of the class derived from the <see cref="T:System.Dynamic.DynamicObject" /> class, binder.Name returns "SampleMethod". The binder.IgnoreCase property specifies whether the member name is case-sensitive.</param>
        /// <param name="args">The arguments that are passed to the object member during the invoke operation. For example, for the statement sampleObject.SampleMethod(100), where sampleObject is derived from the <see cref="T:System.Dynamic.DynamicObject" /> class, <paramref name="args" /> is equal to 100.</param>
        /// <param name="result">The result of the member invocation.</param>
        /// <returns>true if the operation is successful; otherwise, false. If this method returns false, the run-time binder of the language determines the behavior. (In most cases, a language-specific run-time exception is thrown.)</returns>
        public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result)
        {
            string method = binder.Name;

            bool hasArg = args.Length == 1;

            result = null;

            switch (method)
            {
            case "First":
                result = hasArg ? _collection.First((Func <T, bool>)args[0]) : _collection.First();

                break;

            case "Last":
                result = hasArg ? _collection.Last((Func <T, bool>)args[0]) : _collection.Last();
                break;

            case "FirstOrDefault":
                result = hasArg ? _collection.FirstOrDefault((Func <T, bool>)args[0]) : _collection.FirstOrDefault();
                break;

            case "LastOrDefault":
                result = hasArg ? _collection.LastOrDefault((Func <T, bool>)args[0]) : _collection.LastOrDefault();
                break;

            case "Count":
                result = _collection.Count;
                break;

            case "ElementAt":
                result = _collection.ElementAt((int)args[0]);
                break;

            case "Where":
                var arrayWhere = _collection.Where((Func <T, bool>)args[0]).Select(x => x as T);
                result = new DynamicCollection <T>(arrayWhere);
                break;

            case "Any":
                result = hasArg ? _collection.Any((Func <T, bool>)args[0]) : _collection.Any();
                break;

            case "All":
                result = _collection.All((Func <T, bool>)args[0]);
                break;

            case "Select":
                var type     = args[0].GetType();
                var generic2 = type.GetGenericArguments()[1];

                var enumGeneric = typeof(DynamicCollection <>);
                var enumType    = enumGeneric.MakeGenericType(generic2);

                var list = Activator.CreateInstance(enumType);

                foreach (var item in _collection)
                {
                    var newItem = type.InvokeMember("Invoke", BindingFlags.DeclaredOnly |
                                                    BindingFlags.Public | BindingFlags.NonPublic |
                                                    BindingFlags.Instance | BindingFlags.InvokeMethod, null, args[0], new object[] { item });

                    enumType.InvokeMember("Add", BindingFlags.DeclaredOnly |
                                          BindingFlags.Public | BindingFlags.NonPublic |
                                          BindingFlags.Instance | BindingFlags.InvokeMethod, null, list, new object[] { newItem });
                }
                result = list;
                break;
            }

            return(true);
        }
 internal GetBinderAdapter(InvokeMemberBinder binder)
     : base(binder.Name, binder.IgnoreCase) {
 }
Esempio n. 42
0
            /// <summary>
            /// Provides the implementation for operations that invoke a member.
            /// Classes derived from the <see cref="T:System.Dynamic.DynamicObject"/> class can
            /// override this method to specify dynamic behavior for operations such as calling a method.
            /// This method should not be called directly, it is  called through dynamic method calls.
            /// </summary>
            /// <param name="binder">
            /// Provides information about the dynamic operation.
            /// The binder.Name property provides the name of the member on which the dynamic operation is performed.
            /// For example, for the statement sampleObject.SampleMethod(100), where sampleObject is an instance of the
            /// class derived from the <see cref="T:System.Dynamic.DynamicObject"/> class, binder.Name returns "SampleMethod".
            /// The binder.IgnoreCase property specifies whether the member name is case-sensitive.
            /// </param>
            /// <param name="args">
            /// The arguments that are passed to the object member during the invoke operation. For example,
            /// for the statement sampleObject.SampleMethod(100), where sampleObject is derived from the
            /// <see cref="T:System.Dynamic.DynamicObject"/> class, the first argument to <paramref name="args"/> is equal to 100.
            /// </param>
            /// <param name="result">The result of the member invocation.</param>
            /// <returns>
            /// true if the operation is successful; otherwise, false. If this method returns false, the run-time
            /// binder of the language determines the behavior. (In most cases, a language-specific run-time exception is thrown.)
            /// </returns>
            /// <exception cref="InvalidOperationException">
            /// Dynamic method is called with non-named argument.
            /// All parameters must be passed as name arguments to API calls.
            /// - or -
            /// The dynamic method name was not in the correct format.
            /// All API function calls must be in the format 'FunctionName###' where the optional ###'s represent a version number.
            /// </exception>
            /// <exception cref="ArgumentException">
            /// The reserved named parameter 'secure' was not a boolean value.
            /// This parameter is used when requests must go through the secure API.
            /// </exception>
            /// <exception cref="ArgumentOutOfRangeException">
            /// The function version number specified was out of range.
            /// </exception>
            public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result)
            {
                if (binder.CallInfo.ArgumentNames.Count != args.Length)
                {
                    throw new InvalidOperationException("Argument mismatch in API call. All parameters must be passed as named arguments.");
                }

                var apiArgs = new Dictionary <string, string>();

                string requestMethod = WebRequestMethods.Http.Get;
                bool   secure        = false;

                // convert named arguments into key value pairs
                for (int x = 0; x < args.Length; x++)
                {
                    string argName  = binder.CallInfo.ArgumentNames[x];
                    object argValue = args[x];

                    // method is a reserved param for selecting the http request method
                    if (argName.Equals("method", StringComparison.OrdinalIgnoreCase))
                    {
                        requestMethod = argValue.ToString();
                        continue;
                    }
                    // secure is another reserved param for selecting the http or https apis
                    else if (argName.Equals("secure", StringComparison.OrdinalIgnoreCase))
                    {
                        try
                        {
                            secure = ( bool )argValue;
                        }
                        catch (InvalidCastException)
                        {
                            throw new ArgumentException("The parameter 'secure' is a reserved parameter that must be of type bool.");
                        }

                        continue;
                    }
                    // flatten lists
                    else if (argValue is IEnumerable && !(argValue is string))
                    {
                        int         index      = 0;
                        IEnumerable enumerable = argValue as IEnumerable;

                        foreach (object value in enumerable)
                        {
                            apiArgs.Add(String.Format("{0}[{1}]", argName, index++), value.ToString());
                        }

                        continue;
                    }


                    apiArgs.Add(argName, argValue.ToString());
                }

                Match match = funcNameRegex.Match(binder.Name);

                if (!match.Success)
                {
                    throw new InvalidOperationException(
                              "The called API function was invalid. It must be in the form of 'FunctionName###' where the optional ### represent the function version."
                              );
                }

                string functionName = match.Groups["name"].Value;

                int    version       = 1; // assume version 1 unless specified
                string versionString = match.Groups["version"].Value;

                if (!string.IsNullOrEmpty(versionString))
                {
                    // the regex matches digits, but we should check for absurdly large numbers
                    if (!int.TryParse(versionString, out version))
                    {
                        throw new ArgumentOutOfRangeException("version", "The function version number supplied was invalid or out of range.");
                    }
                }

                result = Call(functionName, version, apiArgs, requestMethod, secure);

                return(true);
            }
Esempio n. 43
0
 public override DynamicMetaObject BindInvokeMember(InvokeMemberBinder binder, DynamicMetaObject[] args) {
     ContractUtils.RequiresNotNull(binder, "binder");
     return binder.Defer(args.AddFirst(WrapSelf()));
 }
Esempio n. 44
0
 public override DynamicMetaObject/*!*/ BindInvokeMember(InvokeMemberBinder/*!*/ action, DynamicMetaObject/*!*/[]/*!*/ args) {
     return MakeMemberAccess(action, action.Name, MemberAccess.Invoke, args);
 }
Esempio n. 45
0
 public override DynamicMetaObject/*!*/ BindInvokeMember(InvokeMemberBinder/*!*/ action, DynamicMetaObject/*!*/[]/*!*/ args) {
     return new InvokeBinderHelper(this, action, args, PythonContext.GetCodeContextMO(action)).Bind(PythonContext.GetPythonContext(action).SharedContext, action.Name);
 }
Esempio n. 46
0
		public override DynamicMetaObject BindInvokeMember( InvokeMemberBinder binder, DynamicMetaObject[] args )
		{
			DEBUG.IndentLine( "\n-- BindInvokeMember: {0}{1}", binder.Name, TypeHelper.ToString( MetaList2List( args ), "()" ) );

			var obj = (DynamicNode)this.Value;
			var node = new DynamicNode.Method( obj, binder.Name, MetaList2List( args ) ) { _Parser = obj._Parser };
			obj._Parser._LastNode = node;

			var par = Expression.Variable( typeof( DynamicNode ), "ret" );
			var exp = Expression.Block(
				new ParameterExpression[] { par },
				Expression.Assign( par, Expression.Constant( node ) )
				);

			DEBUG.Unindent();
			return new DynamicMetaNode( exp, this.Restrictions, node );
		}
 public override DynamicMetaObject BindInvokeMember(InvokeMemberBinder binder, DynamicMetaObject[] args) {
     ContractUtils.RequiresNotNull(binder, "binder");
     return binder.FallbackInvokeMember(UnwrapSelf(), args);
 }
Esempio n. 48
0
 public static DynamicMetaObject /*!*/ Bind(DynamicMetaObject /*!*/ context, InvokeMemberBinder /*!*/ binder, DynamicMetaObject /*!*/ target,
                                            DynamicMetaObject /*!*/[] /*!*/ args, Func <DynamicMetaObject, DynamicMetaObject[], DynamicMetaObject> /*!*/ fallback)
 {
     return(Bind(context, binder.Name, binder.CallInfo, binder, target, args, fallback));
 }
Esempio n. 49
0
 public Func <object[], object> CreateDelegate(DataStrategy dataStrategy, DynamicTable table, InvokeMemberBinder binder, object[] args)
 {
     throw new NotImplementedException();
 }
Esempio n. 50
0
 public override DynamicMetaObject/*!*/ BindInvokeMember(InvokeMemberBinder/*!*/ action, DynamicMetaObject/*!*/[]/*!*/ args) {
     return new InvokeBinderHelper(this, action, args, BinderState.GetCodeContext(action)).Bind(BinderState.GetBinderState(action).Context, action.Name);
 }
Esempio n. 51
0
 public override DynamicMetaObject BindInvokeMember(InvokeMemberBinder binder, DynamicMetaObject[] args) {
     return DynamicTryGetValue(binder.Name, binder.IgnoreCase, 
         binder.FallbackInvokeMember(this, args).Expression,
         (tmp) => binder.FallbackInvoke(new DynamicMetaObject(tmp, BindingRestrictions.Empty), args, null).Expression
     );
 }
Esempio n. 52
0
 private static object InsertDictionary(InvokeMemberBinder binder, object[] args, DataStrategy dataStrategy, string tableName)
 {
     return(dataStrategy.Insert(tableName, binder.NamedArgumentsToDictionary(args), !binder.IsResultDiscarded()));
 }