Beispiel #1
0
    public bool PosTest2()
    {
        bool         retVal      = true;
        const string c_TEST_DESC = "PosTest2: the parameter is empty ... ";
        const string c_TEST_ID   = "P002";

        string memberName = "";

        TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
        try
        {
            DefaultMemberAttribute dma = new DefaultMemberAttribute(memberName);
            if (dma == null)
            {
                string errorDesc = "the DefaultMemberAttribute ctor error occurred.)";
                errorDesc += "\n parameter is empty";
                TestLibrary.TestFramework.LogError("003" + " TestId-" + c_TEST_ID, errorDesc);
                retVal = false;
            }
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("004", "unexpected exception occurs :" + e);
            retVal = false;
        }

        return(retVal);
    }
        public override MemberInfo[] GetDefaultMembers()
        {
            // Get all of the custom attributes
            DefaultMemberAttribute attr = null;

            for (Type t = this; t != null; t = t.BaseType)
            {
                object[] attrs = GetCustomAttributes(typeof(DefaultMemberAttribute), false);
                if (attrs != null && attrs.Length > 0)
                {
                    attr = attrs[0] as DefaultMemberAttribute;
                }

                if (attr != null)
                {
                    break;
                }
            }

            if (attr == null)
            {
                return(new MemberInfo[0]);
            }

            String defaultMember = attr.MemberName;

            MemberInfo[] members = GetMember(defaultMember);
            if (members == null)
            {
                members = new MemberInfo[0];
            }
            return(members);
        }
Beispiel #3
0
        /// <summary>
        /// Returns the type of child object
        /// contained in a collection or list.
        /// </summary>
        /// <param name="listType">Type of the list.</param>
        public static Type GetChildItemType(Type listType)
        {
            Type result = null;

            if (listType.IsArray)
            {
                result = listType.GetElementType();
            }
            else
            {
#if NETFX_CORE
                DefaultMemberAttribute indexer =
                    (DefaultMemberAttribute)listType.GetCustomAttribute(typeof(DefaultMemberAttribute));
#else
                DefaultMemberAttribute indexer =
                    (DefaultMemberAttribute)Attribute.GetCustomAttribute(
                        listType, typeof(DefaultMemberAttribute));
#endif
                if (indexer != null)
                {
                    foreach (PropertyInfo prop in listType.GetProperties(
                                 BindingFlags.Public |
                                 BindingFlags.Instance |
                                 BindingFlags.FlattenHierarchy))
                    {
                        if (prop.Name == indexer.MemberName)
                        {
                            result = Utilities.GetPropertyType(prop.PropertyType);
                        }
                    }
                }
            }
            return(result);
        }
    public bool PosTest1()
    {
        bool retVal = true;
        string c_TEST_DESC = "PosTest1: Verfify property MemberName is random string ... ";
        string c_TEST_ID = "P001";
        string memberName = TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LEN, c_MAX_STRING_LEN);

        DefaultMemberAttribute dma = new DefaultMemberAttribute(memberName);

        TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
        try
        {
            if (dma.MemberName != memberName)
            {
                string errorDesc = "value is not " + memberName + " as expected: Actual is " + dma.MemberName;
                TestLibrary.TestFramework.LogError("001" + " TestId-" + c_TEST_ID, errorDesc);
                retVal = false;
            }


        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("002", "unexpected exception occurs :" + e);
            retVal = false;
        }

        return retVal;
    }
Beispiel #5
0
        public void WriteData(AMFWriter writer, object data)
        {
            NameObjectCollectionBase base2 = data as NameObjectCollectionBase;

            object[] customAttributes = base2.GetType().GetCustomAttributes(typeof(DefaultMemberAttribute), false);
            if ((customAttributes != null) && (customAttributes.Length > 0))
            {
                DefaultMemberAttribute attribute = customAttributes[0] as DefaultMemberAttribute;
                PropertyInfo           property  = base2.GetType().GetProperty(attribute.MemberName, new Type[] { typeof(string) });
                if (property != null)
                {
                    ASObject obj2 = new ASObject();
                    for (int i = 0; i < base2.Keys.Count; i++)
                    {
                        string key  = base2.Keys[i];
                        object obj3 = property.GetValue(base2, new object[] { key });
                        obj2.Add(key, obj3);
                    }
                    writer.WriteByte(10);
                    writer.WriteAMF3Object(obj2);
                    return;
                }
            }
            writer.WriteByte(10);
            writer.WriteAMF3Object(data);
        }
Beispiel #6
0
    public bool PosTest1()
    {
        bool         retVal      = true;
        const string c_TEST_DESC = "PosTest1: Verify the memberName is random string... ";
        const string c_TEST_ID   = "P001";

        string memberName = TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LEN, c_MAX_STRING_LEN);

        TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
        try
        {
            DefaultMemberAttribute dma = new DefaultMemberAttribute(memberName);
            if (dma == null)
            {
                string errorDesc = "the DefaultMemberAttribute ctor error occurred.)";
                errorDesc += "\n parameter is " + memberName;
                TestLibrary.TestFramework.LogError("001" + " TestId-" + c_TEST_ID, errorDesc);
                retVal = false;
            }
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("002", "unexpected exception occurs :" + e);
            retVal = false;
        }

        return(retVal);
    }
    public bool PosTest2()
    {
        bool retVal = true;
        string c_TEST_DESC = "PosTest2: Verfify the MemberName is empty ... ";
        string c_TEST_ID = "P002";
        string memberName = "";

        DefaultMemberAttribute dma = new DefaultMemberAttribute(memberName);

        TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
        try
        {
            if (dma.MemberName != memberName)
            {
                string errorDesc = "value is not " + memberName + " as expected: Actual is empty";
                TestLibrary.TestFramework.LogError("003" + " TestId-" + c_TEST_ID, errorDesc);
                retVal = false;
            }


        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("004", "Unexpected exception occurs :" + e);
            retVal = false;
        }

        return retVal;
    }
Beispiel #8
0
        // ----- SetProperty methods ------

        FBXResult SetIndexedProperty(object idx, fbxvariant value)
        {
            object convertedValue;

            DefaultMemberAttribute defaultMember = (DefaultMemberAttribute)Attribute.GetCustomAttribute(type, typeof(DefaultMemberAttribute));

            var property = (defaultMember != null) ? getProp(defaultMember.MemberName) : null;

            if (property != null)
            {
                FBXResult returnValue = Converter.ToNet(value, property.PropertyType.GetElementType(), out convertedValue);
                if (!returnValue.success)
                {
                    return(returnValue);
                }

                try
                {
                    property.SetValue(this.wrappedObject, value, new object[] { idx });
                }
                catch (Exception e)
                {
                    return(new FBXResult(false, e.ToString()));
                }
                return(FBXResult.successful);
            }

            return(new FBXResult(false, "Property '" + idx + "' not found"));
        }
    public bool PosTest1()
    {
        bool   retVal      = true;
        string c_TEST_DESC = "PosTest1: Verfify property MemberName is random string ... ";
        string c_TEST_ID   = "P001";
        string memberName  = TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LEN, c_MAX_STRING_LEN);

        DefaultMemberAttribute dma = new DefaultMemberAttribute(memberName);

        TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
        try
        {
            if (dma.MemberName != memberName)
            {
                string errorDesc = "value is not " + memberName + " as expected: Actual is " + dma.MemberName;
                TestLibrary.TestFramework.LogError("001" + " TestId-" + c_TEST_ID, errorDesc);
                retVal = false;
            }
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("002", "unexpected exception occurs :" + e);
            retVal = false;
        }

        return(retVal);
    }
        public static PropertyInfo GetProperty(Type baseType, string propertyName)
        {
            if (baseType == null)
            {
                throw new ArgumentNullException(nameof(baseType));
            }
            if (propertyName == null)
            {
                throw new ArgumentNullException(nameof(propertyName));
            }

            string[] parts = propertyName.Split('.');
            if (parts.Length > 1)
            {
                return(GetProperty(baseType.GetProperty(parts[0]).PropertyType, parts.Skip(1).Aggregate((a, i) => a + "." + i)));
            }

            Match match = Regex.Match(propertyName, @"(.*?)\[(.*?)\]");

            if (match.Success)
            {
                string collection = match.Groups[1].Value;
                string member     = match.Groups[2].Value;

                PropertyInfo           nestedProperty = baseType.GetProperty(collection);
                DefaultMemberAttribute defaultMember  = (DefaultMemberAttribute)Attribute.GetCustomAttribute(nestedProperty.PropertyType, typeof(DefaultMemberAttribute));
                PropertyInfo           nestedIndexer  = nestedProperty.PropertyType.GetProperty(defaultMember.MemberName);
                return(nestedIndexer);
            }

            return(baseType.GetProperty(propertyName));
        }
Beispiel #11
0
        private static string GenerateInstanceFields(Type classType)
        {
            var stringBuilder = new StringBuilder();

            var fields = classType.GetFields(BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance);

            DefaultMemberAttribute weirdAttr = (DefaultMemberAttribute)classType.GetCustomAttribute(typeof(DefaultMemberAttribute));

            foreach (var field in fields)
            {
                if (field.IsSpecialName)
                {
                    continue;              // Names that begin with or contain an underscore character (_), property accessors, and operator overloading methods
                }
                if (field.GetCustomAttribute(typeof(ObsoleteAttribute)) != null)
                {
                    Debug.Log("skipping obsolete " + field.Name);
                    continue;
                }

                if (weirdAttr != null && field.Name == weirdAttr.MemberName)
                {
                    Debug.Log("skipping weird DefaultMember attribute: " + field.Name);
                    continue; // ???
                }


                stringBuilder.AppendLine(FormatInstanceField(classType, field));
            }

            return(stringBuilder.ToString());
        }
    public bool PosTest2()
    {
        bool   retVal      = true;
        string c_TEST_DESC = "PosTest2: Verfify the MemberName is empty ... ";
        string c_TEST_ID   = "P002";
        string memberName  = "";

        DefaultMemberAttribute dma = new DefaultMemberAttribute(memberName);

        TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
        try
        {
            if (dma.MemberName != memberName)
            {
                string errorDesc = "value is not " + memberName + " as expected: Actual is empty";
                TestLibrary.TestFramework.LogError("003" + " TestId-" + c_TEST_ID, errorDesc);
                retVal = false;
            }
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("004", "Unexpected exception occurs :" + e);
            retVal = false;
        }

        return(retVal);
    }
    public bool PosTest2()
    {
        bool retVal = true;
        const string c_TEST_DESC = "PosTest2: the parameter is empty ... ";
        const string c_TEST_ID = "P002";

        string memberName = "";

        TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
        try
        {
            DefaultMemberAttribute dma = new DefaultMemberAttribute(memberName);
            if (dma == null)
            {
                string errorDesc = "the DefaultMemberAttribute ctor error occurred.)";
                errorDesc += "\n parameter is empty";
                TestLibrary.TestFramework.LogError("003" + " TestId-" + c_TEST_ID, errorDesc);
                retVal = false;
            }


        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("004", "unexpected exception occurs :" + e);
            retVal = false;
        }

        return retVal;
    }
    public bool PosTest1()
    {
        bool retVal = true;
        const string c_TEST_DESC = "PosTest1: Verify the memberName is random string... ";
        const string c_TEST_ID = "P001";

        string memberName = TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LEN, c_MAX_STRING_LEN);

        TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
        try
        {
            DefaultMemberAttribute dma = new DefaultMemberAttribute(memberName); 
            if (dma == null)
            {
                string errorDesc = "the DefaultMemberAttribute ctor error occurred.)";
                errorDesc += "\n parameter is " + memberName;
                TestLibrary.TestFramework.LogError("001" + " TestId-" + c_TEST_ID, errorDesc);
                retVal = false;
            }


        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("002", "unexpected exception occurs :" + e);
            retVal = false;
        }

        return retVal;
    }
Beispiel #15
0
        public void WriteData(AMFWriter writer, object data)
        {
            NameObjectCollectionBase collection = data as NameObjectCollectionBase;

            object[] attributes = collection.GetType().GetCustomAttributes(typeof(DefaultMemberAttribute), false);
            if (attributes != null && attributes.Length > 0)
            {
                DefaultMemberAttribute defaultMemberAttribute = attributes[0] as DefaultMemberAttribute;
                PropertyInfo           pi = collection.GetType().GetProperty(defaultMemberAttribute.MemberName, new Type[] { typeof(string) });
                if (pi != null)
                {
                    ASObject aso = new ASObject();

                    IEnumerator enumList = collection.Keys.GetEnumerator();

                    //为了兼容 webplayer 和手机 platform 而改掉的代码,原来的代码见后面的注释内容.
                    while (enumList.MoveNext())
                    {
                        string key   = enumList.Current as string;
                        object value = pi.GetValue(collection, new object[] { key });

                        aso.Add(key, value);
                    }
                    writer.WriteByte(AMF3TypeCode.Object);
                    writer.WriteAMF3Object(aso);
                    return;
                }
            }

            //We could not access an indexer so write out as it is.
            writer.WriteByte(AMF3TypeCode.Object);
            writer.WriteAMF3Object(data);
        }
Beispiel #16
0
        public void WriteData(AMFWriter writer, object data)
        {
            NameObjectCollectionBase collection = data as NameObjectCollectionBase;

            object[] attributes = collection.GetType().GetCustomAttributes(typeof(DefaultMemberAttribute), false);
            if (attributes != null && attributes.Length > 0)
            {
                DefaultMemberAttribute defaultMemberAttribute = attributes[0] as DefaultMemberAttribute;
                PropertyInfo           pi = collection.GetType().GetProperty(defaultMemberAttribute.MemberName, new Type[] { typeof(string) });
                if (pi != null)
                {
                    ASObject aso = new ASObject();
                    for (int i = 0; i < collection.Keys.Count; i++)
                    {
                        string key   = collection.Keys[i];
                        object value = pi.GetValue(collection, new object[] { key });
                        aso.Add(key, value);
                    }
                    writer.WriteByte(AMF3TypeCode.Object);
                    writer.WriteAMF3Object(aso);
                    return;
                }
            }

            //We could not access an indexer so write out as it is.
            writer.WriteByte(AMF3TypeCode.Object);
            writer.WriteAMF3Object(data);
        }
        public static void DefaultMemberAttribute_Test()
        {
            var attr1 = new DefaultMemberAttribute(null);

            Assert.Null(attr1.MemberName);

            var attr2 = new DefaultMemberAttribute("MyDefaultMember");

            Assert.Equal("MyDefaultMember", attr2.MemberName);
        }
 /// <summary>
 /// Gets the default member name that is used for an indexer (e.g. "Item").
 /// </summary>
 /// <param name="type">Type to check.</param>
 /// <returns>Default member name.</returns>
 private static string GetDefaultMemberName(this Type type)
 {
     object[] attributes = type.GetCustomAttributes(typeof(DefaultMemberAttribute), true);
     if (attributes != null && attributes.Length == 1)
     {
         DefaultMemberAttribute defaultMemberAttribute = attributes[0] as DefaultMemberAttribute;
         return(defaultMemberAttribute.MemberName);
     }
     else
     {
         return(null);
     }
 }
Beispiel #19
0
        AttributeCollection ICustomTypeDescriptor.GetAttributes()
        {
            object value = _staticAttributeCollection;

            if (value == null)
            {
                CLSCompliantAttribute  clsAttr    = new CLSCompliantAttribute(true);
                DefaultMemberAttribute defMemAttr = new DefaultMemberAttribute("Item");
                Attribute []           attrs      = { clsAttr, defMemAttr };
                value = new AttributeCollection(attrs);
            }
            System.Threading.Interlocked.CompareExchange(ref _staticAttributeCollection, value, null);
            return(_staticAttributeCollection as AttributeCollection);
        }
Beispiel #20
0
        // Get the default members within this type.
        public virtual MemberInfo[] GetDefaultMembers()
        {
            // Get the value of the "DefaultMember" attribute.
            DefaultMemberAttribute attr = (DefaultMemberAttribute)
                                          Attribute.GetCustomAttribute
                                              (this, typeof(DefaultMemberAttribute));

            if (attr == null)
            {
                return(new MemberInfo [0]);
            }

            // Find all members with the specified name.
            return(GetMember(attr.MemberName));
        }
Beispiel #21
0
    public static void GetDefMemberExample1()
    {
        // <snippet14>
        Type classType  = typeof(Class1);
        Type attribType = typeof(DefaultMemberAttribute);
        DefaultMemberAttribute defMem =
            (DefaultMemberAttribute)Attribute.GetCustomAttribute((MemberInfo)classType, attribType);

        MemberInfo[] memInfo = classType.GetMember(defMem.MemberName);
        // </snippet14>
        if (memInfo.Length > 0)
        {
            Console.WriteLine("Default Member: {0}", memInfo[0].Name);
        }
    }
Beispiel #22
0
    public static void GetDefMemberExample3()
    {
        // <snippet16>
        Type t = typeof(Class1);

        object[] customAttribs = t.GetCustomAttributes(typeof(DefaultMemberAttribute), false);
        if (customAttribs.Length > 0)
        {
            DefaultMemberAttribute defMem  = (DefaultMemberAttribute)customAttribs[0];
            MemberInfo[]           memInfo = t.GetMember(defMem.MemberName);
            if (memInfo.Length > 0)
            {
                Console.WriteLine("Default Member: {0}", memInfo[0].Name);
            }
        }
        // </snippet16>
    }
Beispiel #23
0
 public override DynamicMetaObject FallbackGetIndex(DynamicMetaObject target, DynamicMetaObject[] indexes, DynamicMetaObject errorSuggestion)
 {
     if (target.HasValue && !(from mo in indexes
                              where !mo.HasValue
                              select mo).Any <DynamicMetaObject>())
     {
         if ((!(target.Value is PSObject) || (PSObject.Base(target.Value) == target.Value)) && !(from mo in indexes
                                                                                                 where (mo.Value is PSObject) && (PSObject.Base(mo.Value) != mo.Value)
                                                                                                 select mo).Any <DynamicMetaObject>())
         {
             if (target.Value == null)
             {
                 return((errorSuggestion ?? target.ThrowRuntimeError(indexes, BindingRestrictions.Empty, "NullArray", ParserStrings.NullArray, new Expression[0])).WriteToDebugLog(this));
             }
             if (((indexes.Length == 1) && (indexes[0].Value == null)) && this._allowSlicing)
             {
                 return((errorSuggestion ?? target.ThrowRuntimeError(indexes, BindingRestrictions.Empty, "NullArrayIndex", ParserStrings.NullArrayIndex, new Expression[0])).WriteToDebugLog(this));
             }
             if (target.LimitType.IsArray)
             {
                 return(this.GetIndexArray(target, indexes, errorSuggestion).WriteToDebugLog(this));
             }
             foreach (Type type in target.LimitType.GetInterfaces())
             {
                 if (type.IsGenericType && (type.GetGenericTypeDefinition() == typeof(IDictionary <,>)))
                 {
                     DynamicMetaObject obj2 = this.GetIndexDictionary(target, indexes, type);
                     if (obj2 != null)
                     {
                         return(obj2.WriteToDebugLog(this));
                     }
                 }
             }
             DefaultMemberAttribute attribute = target.LimitType.GetCustomAttributes <DefaultMemberAttribute>(true).FirstOrDefault <DefaultMemberAttribute>();
             if (attribute != null)
             {
                 return(this.InvokeIndexer(target, indexes, errorSuggestion, attribute.MemberName).WriteToDebugLog(this));
             }
             return(errorSuggestion ?? this.CannotIndexTarget(target, indexes).WriteToDebugLog(this));
         }
         return(this.DeferForPSObject(indexes.Prepend <DynamicMetaObject>(target).ToArray <DynamicMetaObject>()).WriteToDebugLog(this));
     }
     return(base.Defer(indexes.Prepend <DynamicMetaObject>(target).ToArray <DynamicMetaObject>()).WriteToDebugLog(this));
 }
        internal override IEnumerable <PSTypeName> GetInferredType(CompletionContext context)
        {
            IEnumerable <PSTypeName> inferredType = this.Target.GetInferredType(context);

            foreach (PSTypeName iteratorVariable1 in inferredType)
            {
                Type type = iteratorVariable1.Type;
                if (type != null)
                {
                    Func <MethodInfo, bool> predicate = null;
                    if (type.IsArray)
                    {
                        yield return(new PSTypeName(type.GetElementType()));

                        continue;
                    }
                    foreach (Type iteratorVariable3 in type.GetInterfaces())
                    {
                        if (iteratorVariable3.IsGenericType && (iteratorVariable3.GetGenericTypeDefinition() == typeof(IDictionary <,>)))
                        {
                            Type iteratorVariable4 = iteratorVariable3.GetGenericArguments()[1];
                            if (!iteratorVariable4.ContainsGenericParameters)
                            {
                                yield return(new PSTypeName(iteratorVariable4));
                            }
                        }
                    }
                    DefaultMemberAttribute defaultMember = type.GetCustomAttributes <DefaultMemberAttribute>(true).FirstOrDefault <DefaultMemberAttribute>();
                    if (defaultMember != null)
                    {
                        if (predicate == null)
                        {
                            predicate = m => m.Name.Equals("get_" + defaultMember.MemberName);
                        }
                        IEnumerable <MethodInfo> iteratorVariable5 = type.GetMethods(BindingFlags.Public | BindingFlags.Instance).Where <MethodInfo>(predicate);
                        foreach (MethodInfo iteratorVariable6 in iteratorVariable5)
                        {
                            yield return(new PSTypeName(iteratorVariable6.ReturnType));
                        }
                    }
                }
                yield return(iteratorVariable1);
            }
        }
Beispiel #25
0
        // ----- GetProperty methods ------

        FBXResult GetIndexedProperty(object idx, fbxvariant value)
        {
            object obj;
            DefaultMemberAttribute defaultMember = (DefaultMemberAttribute)Attribute.GetCustomAttribute(type, typeof(DefaultMemberAttribute));

            var property = (defaultMember != null) ? getProp(defaultMember.MemberName) : null;

            if (property != null)
            {
                try
                {
                    obj = property.GetValue(this.wrappedObject, new object[] { idx });
                }
                catch (Exception e)
                {
                    return(new FBXResult(false, e.ToString()));
                }
                return(Converter.FromNet(obj, value));
            }
            // need to check if this.wrappedObject can be indexed directly?
            return(new FBXResult(false, "Property '" + idx + "' not found"));
        }
Beispiel #26
0
        static string GetBindingPath <TSource>(Expression <Func <TSource, object> > propertyGetter)
        {
            Expression expr = propertyGetter.Body;

            var unary = expr as UnaryExpression;

            if (unary != null)
            {
                expr = unary.Operand;
            }

            var builder = new StringBuilder();

            var indexed = false;

            var member = expr as MemberExpression;

            if (member == null)
            {
                var methodCall = expr as MethodCallExpression;
                if (methodCall != null)
                {
                    if (methodCall.Arguments.Count == 0)
                    {
                        throw new ArgumentException("Method calls are not allowed in binding expression");
                    }

                    var arguments = new List <string>(methodCall.Arguments.Count);
                    foreach (Expression arg in methodCall.Arguments)
                    {
                        if (arg.NodeType != ExpressionType.Constant)
                        {
                            throw new ArgumentException("Only constants can be used as indexer arguments");
                        }

                        object value = ((ConstantExpression)arg).Value;
                        arguments.Add(value != null ? value.ToString() : "null");
                    }

                    Type declarerType = methodCall.Method.DeclaringType;
                    DefaultMemberAttribute defaultMember = declarerType.GetTypeInfo().GetCustomAttributes(typeof(DefaultMemberAttribute), true).OfType <DefaultMemberAttribute>().FirstOrDefault();
                    string indexerName = defaultMember != null ? defaultMember.MemberName : "Item";

                    MethodInfo getterInfo =
                        declarerType.GetProperties().Where(pi => (pi.GetMethod != null) && pi.Name == indexerName && pi.CanRead && pi.GetMethod.IsPublic && !pi.GetMethod.IsStatic).Select(pi => pi.GetMethod).FirstOrDefault();
                    if (getterInfo != null)
                    {
                        if (getterInfo == methodCall.Method)
                        {
                            indexed = true;
                            builder.Append("[");

                            var first = true;
                            foreach (string argument in arguments)
                            {
                                if (!first)
                                {
                                    builder.Append(",");
                                }

                                builder.Append(argument);
                                first = false;
                            }

                            builder.Append("]");

                            member = methodCall.Object as MemberExpression;
                        }
                        else
                        {
                            throw new ArgumentException("Method calls are not allowed in binding expressions");
                        }
                    }
                    else
                    {
                        throw new ArgumentException("Public indexer not found");
                    }
                }
                else
                {
                    throw new ArgumentException("Invalid expression type");
                }
            }

            while (member != null)
            {
                var property = (PropertyInfo)member.Member;
                if (builder.Length != 0)
                {
                    if (!indexed)
                    {
                        builder.Insert(0, ".");
                    }
                    else
                    {
                        indexed = false;
                    }
                }

                builder.Insert(0, property.Name);

                //				member = member.Expression as MemberExpression ?? (member.Expression as UnaryExpression)?.Operand as MemberExpression;
                member = member.Expression as MemberExpression ?? (member.Expression is UnaryExpression ? (member.Expression as UnaryExpression).Operand as MemberExpression : null);
            }

            return(builder.ToString());
        }
Beispiel #27
0
        void SetupPart(TypeInfo sourceType, BindingExpressionPart part)
        {
            part.Arguments  = null;
            part.LastGetter = null;
            part.LastSetter = null;

            PropertyInfo property = null;

            if (part.IsIndexer)
            {
                if (sourceType.IsArray)
                {
                    int index;
                    if (!int.TryParse(part.Content, out index))
                    {
                        Log.Warning("Binding", "{0} could not be parsed as an index for a {1}", part.Content, sourceType);
                    }
                    else
                    {
                        part.Arguments = new object[] { index }
                    };

                    part.LastGetter = sourceType.GetDeclaredMethod("Get");
                    part.LastSetter = sourceType.GetDeclaredMethod("Set");
                    part.SetterType = sourceType.GetElementType();
                }

                DefaultMemberAttribute defaultMember = null;
                foreach (var attrib in sourceType.GetCustomAttributes(typeof(DefaultMemberAttribute), true))
                {
                    if (attrib is DefaultMemberAttribute d)
                    {
                        defaultMember = d;
                        break;
                    }
                }

                string indexerName = defaultMember != null ? defaultMember.MemberName : "Item";

                part.IndexerName = indexerName;

#if NETSTANDARD2_0
                try {
                    property = sourceType.GetDeclaredProperty(indexerName);
                }
                catch (AmbiguousMatchException) {
                    // Get most derived instance of property
                    foreach (var p in sourceType.GetProperties())
                    {
                        if (p.Name == indexerName && (property == null || property.DeclaringType.IsAssignableFrom(property.DeclaringType)))
                        {
                            property = p;
                        }
                    }
                }
#else
                property = sourceType.GetDeclaredProperty(indexerName);
#endif

                if (property == null)                 //is the indexer defined on the base class?
                {
                    property = sourceType.BaseType.GetProperty(indexerName);
                }
                if (property == null)                 //is the indexer defined on implemented interface ?
                {
                    foreach (var implementedInterface in sourceType.ImplementedInterfaces)
                    {
                        property = implementedInterface.GetProperty(indexerName);
                        if (property != null)
                        {
                            break;
                        }
                    }
                }

                if (property != null)
                {
                    ParameterInfo   parameter = null;
                    ParameterInfo[] array     = property.GetIndexParameters();
                    for (int i = 0; i < array.Length; i++)
                    {
                        parameter = array[i];
                        break;
                    }

                    if (parameter != null)
                    {
                        try
                        {
                            object arg = Convert.ChangeType(part.Content, parameter.ParameterType, CultureInfo.InvariantCulture);
                            part.Arguments = new[] { arg };
                        }
                        catch (FormatException)
                        {
                        }
                        catch (InvalidCastException)
                        {
                        }
                        catch (OverflowException)
                        {
                        }
                    }
                }
            }
            else
            {
                TypeInfo type = sourceType;
                while (type != null && property == null)
                {
                    property = type.GetDeclaredProperty(part.Content);
                    type     = type.BaseType?.GetTypeInfo();
                }
            }
            if (property != null)
            {
                if (property.CanRead && property.GetMethod.IsPublic && !property.GetMethod.IsStatic)
                {
                    part.LastGetter = property.GetMethod;
                }
                if (property.CanWrite && property.SetMethod.IsPublic && !property.SetMethod.IsStatic)
                {
                    part.LastSetter = property.SetMethod;
                    var lastSetterParameters = part.LastSetter.GetParameters();
                    part.SetterType = lastSetterParameters[lastSetterParameters.Length - 1].ParameterType;

                    if (Binding.AllowChaining)
                    {
                        FieldInfo bindablePropertyField = sourceType.GetDeclaredField(part.Content + "Property");
                        if (bindablePropertyField != null && bindablePropertyField.FieldType == typeof(BindableProperty) && sourceType.ImplementedInterfaces.Contains(typeof(IElementController)))
                        {
                            MethodInfo setValueMethod = null;
#if NETSTANDARD1_0
                            foreach (MethodInfo m in sourceType.AsType().GetRuntimeMethods())
                            {
                                if (m.Name.EndsWith("IElementController.SetValueFromRenderer"))
                                {
                                    ParameterInfo[] parameters = m.GetParameters();
                                    if (parameters.Length == 2 && parameters[0].ParameterType == typeof(BindableProperty))
                                    {
                                        setValueMethod = m;
                                        break;
                                    }
                                }
                            }
#else
                            setValueMethod = typeof(IElementController).GetMethod("SetValueFromRenderer", new[] { typeof(BindableProperty), typeof(object) });
#endif
                            if (setValueMethod != null)
                            {
                                part.LastSetter = setValueMethod;
                                part.IsBindablePropertySetter = true;
                                part.BindablePropertyField    = bindablePropertyField.GetValue(null);
                            }
                        }
                    }
                }
#if !NETSTANDARD1_0
                TupleElementNamesAttribute tupleEltNames;
                if (property != null &&
                    part.NextPart != null &&
                    property.PropertyType.IsGenericType &&
                    (property.PropertyType.GetGenericTypeDefinition() == typeof(ValueTuple <>) ||
                     property.PropertyType.GetGenericTypeDefinition() == typeof(ValueTuple <,>) ||
                     property.PropertyType.GetGenericTypeDefinition() == typeof(ValueTuple <, ,>) ||
                     property.PropertyType.GetGenericTypeDefinition() == typeof(ValueTuple <, , ,>) ||
                     property.PropertyType.GetGenericTypeDefinition() == typeof(ValueTuple <, , , ,>) ||
                     property.PropertyType.GetGenericTypeDefinition() == typeof(ValueTuple <, , , , ,>) ||
                     property.PropertyType.GetGenericTypeDefinition() == typeof(ValueTuple <, , , , , ,>) ||
                     property.PropertyType.GetGenericTypeDefinition() == typeof(ValueTuple <, , , , , , ,>)) &&
                    (tupleEltNames = property.GetCustomAttribute(typeof(TupleElementNamesAttribute)) as TupleElementNamesAttribute) != null)
                {
                    //modify the nextPart to access the tuple item via the ITuple indexer
                    var nextPart = part.NextPart;
                    var name     = nextPart.Content;
                    var index    = tupleEltNames.TransformNames.IndexOf(name);
                    if (index >= 0)
                    {
                        nextPart.IsIndexer = true;
                        nextPart.Content   = index.ToString();
                    }
                }
#endif
            }
        }
Beispiel #28
0
 public override DynamicMetaObject FallbackSetIndex(DynamicMetaObject target, DynamicMetaObject[] indexes, DynamicMetaObject value, DynamicMetaObject errorSuggestion)
 {
     if (target.HasValue)
     {
         DynamicMetaObject[] dynamicMetaObjectArray = indexes;
         if (!dynamicMetaObjectArray.Where <DynamicMetaObject>((DynamicMetaObject mo) => !mo.HasValue).Any <DynamicMetaObject>() && value.HasValue)
         {
             if (target.Value as PSObject == null || PSObject.Base(target.Value) == target.Value)
             {
                 DynamicMetaObject[] dynamicMetaObjectArray1 = indexes;
                 if (!dynamicMetaObjectArray1.Where <DynamicMetaObject>((DynamicMetaObject mo) =>
                 {
                     if ((mo.Value as PSObject == null))
                     {
                         return(false);
                     }
                     else
                     {
                         return(PSObject.Base(mo.Value) != mo.Value);
                     }
                 }
                                                                        ).Any <DynamicMetaObject>())
                 {
                     if (target.Value != null)
                     {
                         if ((int)indexes.Length != 1 || indexes[0].Value != null)
                         {
                             if (!target.LimitType.IsArray)
                             {
                                 DefaultMemberAttribute defaultMemberAttribute = target.LimitType.GetCustomAttributes <DefaultMemberAttribute>(true).FirstOrDefault <DefaultMemberAttribute>();
                                 if (defaultMemberAttribute == null)
                                 {
                                     DynamicMetaObject dynamicMetaObject = errorSuggestion;
                                     DynamicMetaObject debugLog          = dynamicMetaObject;
                                     if (dynamicMetaObject == null)
                                     {
                                         debugLog = this.CannotIndexTarget(target, indexes, value).WriteToDebugLog(this);
                                     }
                                     return(debugLog);
                                 }
                                 else
                                 {
                                     return(this.InvokeIndexer(target, indexes, value, errorSuggestion, defaultMemberAttribute.MemberName).WriteToDebugLog(this));
                                 }
                             }
                             else
                             {
                                 return(this.SetIndexArray(target, indexes, value, errorSuggestion).WriteToDebugLog(this));
                             }
                         }
                         else
                         {
                             DynamicMetaObject dynamicMetaObject1 = errorSuggestion;
                             DynamicMetaObject debugLog1          = dynamicMetaObject1;
                             if (dynamicMetaObject1 == null)
                             {
                                 debugLog1 = target.ThrowRuntimeError(indexes, BindingRestrictions.Empty, "NullArrayIndex", ParserStrings.NullArrayIndex, new Expression[0]).WriteToDebugLog(this);
                             }
                             return(debugLog1);
                         }
                     }
                     else
                     {
                         DynamicMetaObject dynamicMetaObject2 = errorSuggestion;
                         DynamicMetaObject dynamicMetaObject3 = dynamicMetaObject2;
                         if (dynamicMetaObject2 == null)
                         {
                             dynamicMetaObject3 = target.ThrowRuntimeError(indexes, BindingRestrictions.Empty, "NullArray", ParserStrings.NullArray, new Expression[0]);
                         }
                         return(dynamicMetaObject3.WriteToDebugLog(this));
                     }
                 }
             }
             return(this.DeferForPSObject(indexes.Prepend <DynamicMetaObject>(target).Append <DynamicMetaObject>(value).ToArray <DynamicMetaObject>()).WriteToDebugLog(this));
         }
     }
     return(base.Defer(indexes.Prepend <DynamicMetaObject>(target).Append <DynamicMetaObject>(value).ToArray <DynamicMetaObject>()).WriteToDebugLog(this));
 }
Beispiel #29
0
        public override object InvokeMember(string name, BindingFlags invokeAttr,
                                            Binder binder, object target, object[] args,
                                            ParameterModifier[] modifiers,
                                            CultureInfo culture, string[] namedParameters)
        {
            const string bindingflags_arg = "bindingFlags";


            if ((invokeAttr & BindingFlags.CreateInstance) != 0)
            {
                if ((invokeAttr & (BindingFlags.GetField |
                                   BindingFlags.GetField | BindingFlags.GetProperty |
                                   BindingFlags.SetProperty)) != 0)
                {
                    throw new ArgumentException(bindingflags_arg);
                }
            }
            else if (name == null)
            {
                throw new ArgumentNullException("name");
            }
            if ((invokeAttr & BindingFlags.GetField) != 0 && (invokeAttr & BindingFlags.SetField) != 0)
            {
                throw new ArgumentException("Cannot specify both Get and Set on a field.", bindingflags_arg);
            }
            if ((invokeAttr & BindingFlags.GetProperty) != 0 && (invokeAttr & BindingFlags.SetProperty) != 0)
            {
                throw new ArgumentException("Cannot specify both Get and Set on a property.", bindingflags_arg);
            }
            if ((invokeAttr & BindingFlags.InvokeMethod) != 0)
            {
                if ((invokeAttr & BindingFlags.SetField) != 0)
                {
                    throw new ArgumentException("Cannot specify Set on a field and Invoke on a method.", bindingflags_arg);
                }
                if ((invokeAttr & BindingFlags.SetProperty) != 0)
                {
                    throw new ArgumentException("Cannot specify Set on a property and Invoke on a method.", bindingflags_arg);
                }
            }
            if ((namedParameters != null) && ((args == null) || args.Length < namedParameters.Length))
            {
                throw new ArgumentException("namedParameters cannot be more than named arguments in number");
            }
            if ((invokeAttr & (BindingFlags.InvokeMethod | BindingFlags.CreateInstance | BindingFlags.GetField | BindingFlags.SetField | BindingFlags.GetProperty | BindingFlags.SetProperty)) == 0)
            {
                throw new ArgumentException("Must specify binding flags describing the invoke operation required.", bindingflags_arg);
            }

            /* set some defaults if none are provided :-( */
            if ((invokeAttr & (BindingFlags.Public | BindingFlags.NonPublic)) == 0)
            {
                invokeAttr |= BindingFlags.Public;
            }
            if ((invokeAttr & (BindingFlags.Static | BindingFlags.Instance)) == 0)
            {
                invokeAttr |= BindingFlags.Static | BindingFlags.Instance;
            }

            if (binder == null)
            {
                binder = Binder.DefaultBinder;
            }
            if ((invokeAttr & BindingFlags.CreateInstance) != 0)
            {
                /* the name is ignored */
                invokeAttr |= BindingFlags.DeclaredOnly;
                ConstructorInfo[] ctors = GetConstructors(invokeAttr);
                object            state = null;
                MethodBase        ctor  = binder.BindToMethod(invokeAttr, ctors, ref args, modifiers, culture, namedParameters, out state);
                if (ctor == null)
                {
                    if (this.IsValueType && args == null)
                    {
                        return(Activator.CreateInstanceInternal(this));
                    }

                    throw new MissingMethodException("Constructor on type '" + FullName + "' not found.");
                }
                object result = ctor.Invoke(target, invokeAttr, binder, args, culture);
                binder.ReorderArgumentArray(ref args, state);
                return(result);
            }
            if (name == String.Empty && Attribute.IsDefined(this, typeof(DefaultMemberAttribute)))
            {
                DefaultMemberAttribute attr = (DefaultMemberAttribute)Attribute.GetCustomAttribute(this, typeof(DefaultMemberAttribute));
                name = attr.MemberName;
            }
            bool   ignoreCase = (invokeAttr & BindingFlags.IgnoreCase) != 0;
            string throwMissingMethodDescription = null;
            bool   throwMissingFieldException    = false;

            if ((invokeAttr & BindingFlags.InvokeMethod) != 0)
            {
                MethodInfo[] methods = GetMethodsByName(name, invokeAttr, ignoreCase, this);
                object       state   = null;
                if (args == null)
                {
                    args = new object [0];
                }
                MethodBase m = binder.BindToMethod(invokeAttr, methods, ref args, modifiers, culture, namedParameters, out state);
                if (m == null)
                {
                    if (methods.Length > 0)
                    {
                        throwMissingMethodDescription = "The best match for method " + name + " has some invalid parameter.";
                    }
                    else
                    {
                        throwMissingMethodDescription = "Cannot find method " + name + ".";
                    }
                }
                else
                {
                    ParameterInfo[] parameters = m.GetParameters();
                    for (int i = 0; i < parameters.Length; ++i)
                    {
                        if (System.Reflection.Missing.Value == args [i] && (parameters [i].Attributes & ParameterAttributes.HasDefault) != ParameterAttributes.HasDefault)
                        {
                            throw new ArgumentException("Used Missing.Value for argument without default value", "parameters");
                        }
                    }
                    object result = m.Invoke(target, invokeAttr, binder, args, culture);
                    binder.ReorderArgumentArray(ref args, state);
                    return(result);
                }
            }
            if ((invokeAttr & BindingFlags.GetField) != 0)
            {
                FieldInfo f = GetField(name, invokeAttr);
                if (f != null)
                {
                    return(f.GetValue(target));
                }
                else if ((invokeAttr & BindingFlags.GetProperty) == 0)
                {
                    throwMissingFieldException = true;
                }
                /* try GetProperty */
            }
            else if ((invokeAttr & BindingFlags.SetField) != 0)
            {
                FieldInfo f = GetField(name, invokeAttr);
                if (f != null)
                {
                    if (args == null)
                    {
                        throw new ArgumentNullException("providedArgs");
                    }
                    if ((args == null) || args.Length != 1)
                    {
                        throw new ArgumentException("Only the field value can be specified to set a field value.", bindingflags_arg);
                    }
                    f.SetValue(target, args [0]);
                    return(null);
                }
                else if ((invokeAttr & BindingFlags.SetProperty) == 0)
                {
                    throwMissingFieldException = true;
                }
                /* try SetProperty */
            }
            if ((invokeAttr & BindingFlags.GetProperty) != 0)
            {
                PropertyInfo[] properties = GetPropertiesByName(name, invokeAttr, ignoreCase, this);
                object         state = null;
                int            i, count = 0;
                for (i = 0; i < properties.Length; ++i)
                {
                    if ((properties [i].GetGetMethod(true) != null))
                    {
                        count++;
                    }
                }
                MethodBase[] smethods = new MethodBase [count];
                count = 0;
                for (i = 0; i < properties.Length; ++i)
                {
                    MethodBase mb = properties [i].GetGetMethod(true);
                    if (mb != null)
                    {
                        smethods [count++] = mb;
                    }
                }
                MethodBase m = binder.BindToMethod(invokeAttr, smethods, ref args, modifiers, culture, namedParameters, out state);
                if (m == null)
                {
                    throwMissingFieldException = true;
                }
                else
                {
                    object result = m.Invoke(target, invokeAttr, binder, args, culture);
                    binder.ReorderArgumentArray(ref args, state);
                    return(result);
                }
            }
            else if ((invokeAttr & BindingFlags.SetProperty) != 0)
            {
                PropertyInfo[] properties = GetPropertiesByName(name, invokeAttr, ignoreCase, this);
                object         state = null;
                int            i, count = 0;
                for (i = 0; i < properties.Length; ++i)
                {
                    if (properties [i].GetSetMethod(true) != null)
                    {
                        count++;
                    }
                }
                MethodBase[] smethods = new MethodBase [count];
                count = 0;
                for (i = 0; i < properties.Length; ++i)
                {
                    MethodBase mb = properties [i].GetSetMethod(true);
                    if (mb != null)
                    {
                        smethods [count++] = mb;
                    }
                }
                MethodBase m = binder.BindToMethod(invokeAttr, smethods, ref args, modifiers, culture, namedParameters, out state);
                if (m == null)
                {
                    throwMissingFieldException = true;
                }
                else
                {
                    object result = m.Invoke(target, invokeAttr, binder, args, culture);
                    binder.ReorderArgumentArray(ref args, state);
                    return(result);
                }
            }
            if (throwMissingMethodDescription != null)
            {
                throw new MissingMethodException(throwMissingMethodDescription);
            }
            if (throwMissingFieldException)
            {
                throw new MissingFieldException("Cannot find variable " + name + ".");
            }

            return(null);
        }
		private void SetupPart(TypeInfo sourceType, BindingExpressionPart part)
		{
			part.Arguments = null;
			part.LastGetter = null;
			part.LastSetter = null;

			PropertyInfo property = null;
			if (part.IsIndexer)
			{
				if (sourceType.IsArray)
				{
					int index;
					if (!int.TryParse(part.Content, out index))
						Log.Warning("Binding", "{0} could not be parsed as an index for a {1}", part.Content, sourceType);
					else
						part.Arguments = new object[] { index };

					part.LastGetter = sourceType.GetDeclaredMethod("Get");
					part.LastSetter = sourceType.GetDeclaredMethod("Set");
					part.SetterType = sourceType.GetElementType();
				}

				DefaultMemberAttribute defaultMember = sourceType.GetCustomAttributes(typeof(DefaultMemberAttribute), true).OfType<DefaultMemberAttribute>().FirstOrDefault();
				string indexerName = defaultMember != null ? defaultMember.MemberName : "Item";

				part.IndexerName = indexerName;

				property = sourceType.GetDeclaredProperty(indexerName);
				if (property == null)
					property = sourceType.BaseType.GetProperty(indexerName);

				if (property != null)
				{
					ParameterInfo parameter = property.GetIndexParameters().FirstOrDefault();
					if (parameter != null)
					{
						try
						{
							object arg = Convert.ChangeType(part.Content, parameter.ParameterType, CultureInfo.InvariantCulture);
							part.Arguments = new[] { arg };
						}
						catch (FormatException)
						{
						}
						catch (InvalidCastException)
						{
						}
						catch (OverflowException)
						{
						}
					}
				}
			}
			else
			{
				property = sourceType.GetDeclaredProperty(part.Content);
				if (property == null)
					property = sourceType.BaseType.GetProperty(part.Content);
			}

			if (property != null)
			{
				if (property.CanRead && property.GetMethod.IsPublic && !property.GetMethod.IsStatic)
					part.LastGetter = property.GetMethod;
				if (property.CanWrite && property.SetMethod.IsPublic && !property.SetMethod.IsStatic)
				{
					part.LastSetter = property.SetMethod;
					part.SetterType = part.LastSetter.GetParameters().Last().ParameterType;

					if (Binding.AllowChaining)
					{
						FieldInfo bindablePropertyField = sourceType.GetDeclaredField(part.Content + "Property");
						if (bindablePropertyField != null && bindablePropertyField.FieldType == typeof(BindableProperty) && sourceType.ImplementedInterfaces.Contains(typeof(IElementController)))
						{
							MethodInfo setValueMethod = null;
							foreach (MethodInfo m in sourceType.AsType().GetRuntimeMethods())
							{
								if (m.Name.EndsWith("IElementController.SetValueFromRenderer"))
								{
									ParameterInfo[] parameters = m.GetParameters();
									if (parameters.Length == 2 && parameters[0].ParameterType == typeof(BindableProperty))
									{
										setValueMethod = m;
										break;
									}
								}
							}
							if (setValueMethod != null)
							{
								part.LastSetter = setValueMethod;
								part.IsBindablePropertySetter = true;
								part.BindablePropertyField = bindablePropertyField.GetValue(null);
							}
						}
					}
				}
			}
		}
Beispiel #31
0
        void SetupPart(TypeInfo sourceType, BindingExpressionPart part)
        {
            part.Arguments  = null;
            part.LastGetter = null;
            part.LastSetter = null;

            PropertyInfo property = null;

            if (part.IsIndexer)
            {
                if (sourceType.IsArray)
                {
                    int index;
                    if (!int.TryParse(part.Content, out index))
                    {
                        Log.Warning("Binding", "{0} could not be parsed as an index for a {1}", part.Content, sourceType);
                    }
                    else
                    {
                        part.Arguments = new object[] { index }
                    };

                    part.LastGetter = sourceType.GetDeclaredMethod("Get");
                    part.LastSetter = sourceType.GetDeclaredMethod("Set");
                    part.SetterType = sourceType.GetElementType();
                }

                DefaultMemberAttribute defaultMember = sourceType.GetCustomAttributes(typeof(DefaultMemberAttribute), true).OfType <DefaultMemberAttribute>().FirstOrDefault();
                string indexerName = defaultMember != null ? defaultMember.MemberName : "Item";

                part.IndexerName = indexerName;

                property = sourceType.GetDeclaredProperty(indexerName);
                if (property == null)                 //is the indexer defined on the base class?
                {
                    property = sourceType.BaseType.GetProperty(indexerName);
                }
                if (property == null)                 //is the indexer defined on implemented interface ?
                {
                    foreach (var implementedInterface in sourceType.ImplementedInterfaces)
                    {
                        property = implementedInterface.GetProperty(indexerName);
                        if (property != null)
                        {
                            break;
                        }
                    }
                }

                if (property != null)
                {
                    ParameterInfo parameter = property.GetIndexParameters().FirstOrDefault();
                    if (parameter != null)
                    {
                        try
                        {
                            object arg = Convert.ChangeType(part.Content, parameter.ParameterType, CultureInfo.InvariantCulture);
                            part.Arguments = new[] { arg };
                        }
                        catch (FormatException)
                        {
                        }
                        catch (InvalidCastException)
                        {
                        }
                        catch (OverflowException)
                        {
                        }
                    }
                }
            }
            else
            {
                property = sourceType.GetDeclaredProperty(part.Content) ?? sourceType.BaseType?.GetProperty(part.Content);
            }

            if (property != null)
            {
                if (property.CanRead && property.GetMethod.IsPublic && !property.GetMethod.IsStatic)
                {
                    part.LastGetter = property.GetMethod;
                }
                if (property.CanWrite && property.SetMethod.IsPublic && !property.SetMethod.IsStatic)
                {
                    part.LastSetter = property.SetMethod;
                    part.SetterType = part.LastSetter.GetParameters().Last().ParameterType;

                    if (Binding.AllowChaining)
                    {
                        FieldInfo bindablePropertyField = sourceType.GetDeclaredField(part.Content + "Property");
                        if (bindablePropertyField != null && bindablePropertyField.FieldType == typeof(BindableProperty) && sourceType.ImplementedInterfaces.Contains(typeof(IElementController)))
                        {
                            MethodInfo setValueMethod = typeof(IElementController).GetMethod("SetValueFromRenderer", new[] { typeof(BindableProperty), typeof(object) });
                            if (setValueMethod != null)
                            {
                                part.LastSetter = setValueMethod;
                                part.IsBindablePropertySetter = true;
                                part.BindablePropertyField    = bindablePropertyField.GetValue(null);
                            }
                        }
                    }
                }

                TupleElementNamesAttribute tupleEltNames;
                if (property != null &&
                    part.NextPart != null &&
                    property.PropertyType.IsGenericType &&
                    (property.PropertyType.GetGenericTypeDefinition() == typeof(ValueTuple <>) ||
                     property.PropertyType.GetGenericTypeDefinition() == typeof(ValueTuple <,>) ||
                     property.PropertyType.GetGenericTypeDefinition() == typeof(ValueTuple <, ,>) ||
                     property.PropertyType.GetGenericTypeDefinition() == typeof(ValueTuple <, , ,>) ||
                     property.PropertyType.GetGenericTypeDefinition() == typeof(ValueTuple <, , , ,>) ||
                     property.PropertyType.GetGenericTypeDefinition() == typeof(ValueTuple <, , , , ,>) ||
                     property.PropertyType.GetGenericTypeDefinition() == typeof(ValueTuple <, , , , , ,>) ||
                     property.PropertyType.GetGenericTypeDefinition() == typeof(ValueTuple <, , , , , , ,>)) &&
                    (tupleEltNames = property.GetCustomAttribute(typeof(TupleElementNamesAttribute)) as TupleElementNamesAttribute) != null)
                {
                    //modify the nextPart to access the tuple item via the ITuple indexer
                    var nextPart = part.NextPart;
                    var name     = nextPart.Content;
                    var index    = tupleEltNames.TransformNames.IndexOf(name);
                    if (index >= 0)
                    {
                        nextPart.IsIndexer = true;
                        nextPart.Content   = index.ToString();
                    }
                }
            }
        }
Beispiel #32
0
        /// <summary>
        /// Gets the default member name that is used for an indexer (e.g. "Item").
        /// </summary>
        /// <param name="type">Type to check.</param>
        /// <returns>Default member name.</returns>
        private static string GetDefaultMemberName(this Type type)
        {
            DefaultMemberAttribute defaultMemberAttribute = type.GetTypeInfo().GetCustomAttributes().OfType <DefaultMemberAttribute>().FirstOrDefault();

            return(defaultMemberAttribute == null ? null : defaultMemberAttribute.MemberName);
        }
Beispiel #33
0
        public static object ResolveReference(string reference, params Token[] tokens)
        {
            string[] references  = reference.Split('.');
            object   objectValue = null;

            for (int index = 0; index < references.Length; index++)
            {
                if (index == 0)
                {
                    objectValue = ResolveToken(references[index], tokens);
                }
                else
                {
                    int bracketIndex = references[index].IndexOf('[');
                    if (bracketIndex > 0)
                    {
                        if (references[index].IndexOf(']') != references[index].Length - 1)
                        {
                            throw new ArgumentException(String.Format("Indexer reference does not have a closing bracket: {0}", references[index]));
                        }
                        string memberName = references[index].Substring(0, bracketIndex);
                        objectValue = GetMemberValue(FindSimpleMember(objectValue.GetType(), memberName), objectValue);

                        string   referenceIndex = references[index].Substring(bracketIndex + 1, references[index].Length - 1 - (bracketIndex + 1));
                        string[] memberIndexes  = referenceIndex.Split(',');

                        if (objectValue.GetType().IsArray)
                        {
                            Array array             = (Array)objectValue;
                            int[] memberIndexValues = new int[memberIndexes.Length];
                            for (int memberIndex = 0; memberIndex < memberIndexes.Length; memberIndex++)
                            {
                                memberIndexValues[memberIndex] = Int32.Parse(memberIndexes[memberIndex]);
                            }

                            objectValue = array.GetValue(memberIndexValues);
                        }
                        else
                        {
                            DefaultMemberAttribute defaultMember = GetAttribute(objectValue.GetType(), typeof(DefaultMemberAttribute)) as DefaultMemberAttribute;
                            if (defaultMember == null)
                            {
                                throw new ArgumentException(String.Format("Member {0} does not have a default property.", memberName));
                            }

                            Type[]   memberIndexTypes  = new Type[memberIndexes.Length];
                            object[] memberIndexValues = new object[memberIndexes.Length];
                            for (int memberIndex = 0; memberIndex < memberIndexes.Length; memberIndex++)
                            {
                                int memberIndexInt;
                                if (Int32.TryParse(memberIndexes[memberIndex], out memberIndexInt))
                                {
                                    memberIndexTypes[memberIndex]  = typeof(Int32);
                                    memberIndexValues[memberIndex] = memberIndexInt;
                                }
                                else
                                {
                                    memberIndexTypes[memberIndex]  = typeof(String);
                                    memberIndexValues[memberIndex] = memberIndexes[memberIndex];
                                }
                            }

                            PropertyInfo info = objectValue.GetType().GetProperty(defaultMember.MemberName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.FlattenHierarchy, null, null, memberIndexTypes, null);
                            if (info == null)
                            {
                                throw new ArgumentException(String.Format("Could not resolve an indexer for member {0} with the reference list {1}.", memberName, referenceIndex));
                            }

                            objectValue = info.GetValue(objectValue, memberIndexValues);
                        }
                    }
                    else
                    {
                        objectValue = GetMemberValue(FindSimpleMember(objectValue.GetType(), references[index]), objectValue);
                    }
                }
            }

            return(objectValue);
        }
Beispiel #34
0
 public override object InvokeMember(string name, BindingFlags invokeAttr, Binder binder, object target, object[] args, ParameterModifier[] modifiers, CultureInfo culture, string[] namedParameters)
 {
     if ((invokeAttr & BindingFlags.CreateInstance) != BindingFlags.Default)
     {
         if ((invokeAttr & (BindingFlags.GetField | BindingFlags.GetProperty | BindingFlags.SetProperty)) != BindingFlags.Default)
         {
             throw new ArgumentException("bindingFlags");
         }
     }
     else if (name == null)
     {
         throw new ArgumentNullException("name");
     }
     if ((invokeAttr & BindingFlags.GetField) != BindingFlags.Default && (invokeAttr & BindingFlags.SetField) != BindingFlags.Default)
     {
         throw new ArgumentException("Cannot specify both Get and Set on a field.", "bindingFlags");
     }
     if ((invokeAttr & BindingFlags.GetProperty) != BindingFlags.Default && (invokeAttr & BindingFlags.SetProperty) != BindingFlags.Default)
     {
         throw new ArgumentException("Cannot specify both Get and Set on a property.", "bindingFlags");
     }
     if ((invokeAttr & BindingFlags.InvokeMethod) != BindingFlags.Default)
     {
         if ((invokeAttr & BindingFlags.SetField) != BindingFlags.Default)
         {
             throw new ArgumentException("Cannot specify Set on a field and Invoke on a method.", "bindingFlags");
         }
         if ((invokeAttr & BindingFlags.SetProperty) != BindingFlags.Default)
         {
             throw new ArgumentException("Cannot specify Set on a property and Invoke on a method.", "bindingFlags");
         }
     }
     if (namedParameters != null && (args == null || args.Length < namedParameters.Length))
     {
         throw new ArgumentException("namedParameters cannot be more than named arguments in number");
     }
     if ((invokeAttr & (BindingFlags.InvokeMethod | BindingFlags.CreateInstance | BindingFlags.GetField | BindingFlags.SetField | BindingFlags.GetProperty | BindingFlags.SetProperty)) == BindingFlags.Default)
     {
         throw new ArgumentException("Must specify binding flags describing the invoke operation required.", "bindingFlags");
     }
     if ((invokeAttr & (BindingFlags.Public | BindingFlags.NonPublic)) == BindingFlags.Default)
     {
         invokeAttr |= BindingFlags.Public;
     }
     if ((invokeAttr & (BindingFlags.Instance | BindingFlags.Static)) == BindingFlags.Default)
     {
         invokeAttr |= (BindingFlags.Instance | BindingFlags.Static);
     }
     if (binder == null)
     {
         binder = Binder.DefaultBinder;
     }
     if ((invokeAttr & BindingFlags.CreateInstance) != BindingFlags.Default)
     {
         invokeAttr |= BindingFlags.DeclaredOnly;
         ConstructorInfo[] constructors = this.GetConstructors(invokeAttr);
         object            state        = null;
         MethodBase        methodBase   = binder.BindToMethod(invokeAttr, constructors, ref args, modifiers, culture, namedParameters, out state);
         if (methodBase != null)
         {
             object result = methodBase.Invoke(target, invokeAttr, binder, args, culture);
             binder.ReorderArgumentArray(ref args, state);
             return(result);
         }
         if (this.IsValueType && args == null)
         {
             return(Activator.CreateInstanceInternal(this));
         }
         throw new MissingMethodException("Constructor on type '" + this.FullName + "' not found.");
     }
     else
     {
         if (name == string.Empty && Attribute.IsDefined(this, typeof(DefaultMemberAttribute)))
         {
             DefaultMemberAttribute defaultMemberAttribute = (DefaultMemberAttribute)Attribute.GetCustomAttribute(this, typeof(DefaultMemberAttribute));
             name = defaultMemberAttribute.MemberName;
         }
         bool   flag  = (invokeAttr & BindingFlags.IgnoreCase) != BindingFlags.Default;
         string text  = null;
         bool   flag2 = false;
         if ((invokeAttr & BindingFlags.InvokeMethod) != BindingFlags.Default)
         {
             MethodInfo[] methodsByName = this.GetMethodsByName(name, invokeAttr, flag, this);
             object       state2        = null;
             if (args == null)
             {
                 args = new object[0];
             }
             MethodBase methodBase2 = binder.BindToMethod(invokeAttr, methodsByName, ref args, modifiers, culture, namedParameters, out state2);
             if (methodBase2 != null)
             {
                 ParameterInfo[] parameters = methodBase2.GetParameters();
                 for (int i = 0; i < parameters.Length; i++)
                 {
                     if (System.Reflection.Missing.Value == args[i] && (parameters[i].Attributes & ParameterAttributes.HasDefault) != ParameterAttributes.HasDefault)
                     {
                         throw new ArgumentException("Used Missing.Value for argument without default value", "parameters");
                     }
                 }
                 bool flag3 = parameters.Length > 0 && Attribute.IsDefined(parameters[parameters.Length - 1], typeof(ParamArrayAttribute));
                 if (flag3)
                 {
                     this.ReorderParamArrayArguments(ref args, methodBase2);
                 }
                 object result2 = methodBase2.Invoke(target, invokeAttr, binder, args, culture);
                 binder.ReorderArgumentArray(ref args, state2);
                 return(result2);
             }
             if (methodsByName.Length > 0)
             {
                 text = "The best match for method " + name + " has some invalid parameter.";
             }
             else
             {
                 text = "Cannot find method " + name + ".";
             }
         }
         if ((invokeAttr & BindingFlags.GetField) != BindingFlags.Default)
         {
             FieldInfo field = this.GetField(name, invokeAttr);
             if (field != null)
             {
                 return(field.GetValue(target));
             }
             if ((invokeAttr & BindingFlags.GetProperty) == BindingFlags.Default)
             {
                 flag2 = true;
             }
         }
         else if ((invokeAttr & BindingFlags.SetField) != BindingFlags.Default)
         {
             FieldInfo field2 = this.GetField(name, invokeAttr);
             if (field2 != null)
             {
                 if (args == null)
                 {
                     throw new ArgumentNullException("providedArgs");
                 }
                 if (args == null || args.Length != 1)
                 {
                     throw new ArgumentException("Only the field value can be specified to set a field value.", "bindingFlags");
                 }
                 field2.SetValue(target, args[0]);
                 return(null);
             }
             else if ((invokeAttr & BindingFlags.SetProperty) == BindingFlags.Default)
             {
                 flag2 = true;
             }
         }
         if ((invokeAttr & BindingFlags.GetProperty) != BindingFlags.Default)
         {
             PropertyInfo[] propertiesByName = this.GetPropertiesByName(name, invokeAttr, flag, this);
             object         state3           = null;
             int            num = 0;
             for (int j = 0; j < propertiesByName.Length; j++)
             {
                 if (propertiesByName[j].GetGetMethod(true) != null)
                 {
                     num++;
                 }
             }
             MethodBase[] array = new MethodBase[num];
             num = 0;
             for (int j = 0; j < propertiesByName.Length; j++)
             {
                 MethodBase getMethod = propertiesByName[j].GetGetMethod(true);
                 if (getMethod != null)
                 {
                     array[num++] = getMethod;
                 }
             }
             MethodBase methodBase3 = binder.BindToMethod(invokeAttr, array, ref args, modifiers, culture, namedParameters, out state3);
             if (methodBase3 != null)
             {
                 ParameterInfo[] parameters2 = methodBase3.GetParameters();
                 bool            flag4       = parameters2.Length > 0 && Attribute.IsDefined(parameters2[parameters2.Length - 1], typeof(ParamArrayAttribute));
                 if (flag4)
                 {
                     this.ReorderParamArrayArguments(ref args, methodBase3);
                 }
                 object result3 = methodBase3.Invoke(target, invokeAttr, binder, args, culture);
                 binder.ReorderArgumentArray(ref args, state3);
                 return(result3);
             }
             flag2 = true;
         }
         else if ((invokeAttr & BindingFlags.SetProperty) != BindingFlags.Default)
         {
             PropertyInfo[] propertiesByName2 = this.GetPropertiesByName(name, invokeAttr, flag, this);
             object         state4            = null;
             int            num2 = 0;
             for (int k = 0; k < propertiesByName2.Length; k++)
             {
                 if (propertiesByName2[k].GetSetMethod(true) != null)
                 {
                     num2++;
                 }
             }
             MethodBase[] array2 = new MethodBase[num2];
             num2 = 0;
             for (int k = 0; k < propertiesByName2.Length; k++)
             {
                 MethodBase setMethod = propertiesByName2[k].GetSetMethod(true);
                 if (setMethod != null)
                 {
                     array2[num2++] = setMethod;
                 }
             }
             MethodBase methodBase4 = binder.BindToMethod(invokeAttr, array2, ref args, modifiers, culture, namedParameters, out state4);
             if (methodBase4 != null)
             {
                 ParameterInfo[] parameters3 = methodBase4.GetParameters();
                 bool            flag5       = parameters3.Length > 0 && Attribute.IsDefined(parameters3[parameters3.Length - 1], typeof(ParamArrayAttribute));
                 if (flag5)
                 {
                     this.ReorderParamArrayArguments(ref args, methodBase4);
                 }
                 object result4 = methodBase4.Invoke(target, invokeAttr, binder, args, culture);
                 binder.ReorderArgumentArray(ref args, state4);
                 return(result4);
             }
             flag2 = true;
         }
         if (text != null)
         {
             throw new MissingMethodException(text);
         }
         if (flag2)
         {
             throw new MissingFieldException("Cannot find variable " + name + ".");
         }
         return(null);
     }
 }