Exemplo n.º 1
0
 internal fsMetaProperty(PropertyInfo property) {
     _memberInfo = property;
     StorageType = property.PropertyType;
     JsonName = GetJsonName(property);
     MemberName = property.Name;
     IsPublic = (property.GetGetMethod() != null && property.GetGetMethod().IsPublic) && (property.GetSetMethod() != null && property.GetSetMethod().IsPublic);
     CanRead = property.CanRead;
     CanWrite = property.CanWrite;
 }
Exemplo n.º 2
0
		public static void LoadPropertyValue(this ILGenerator il, PropertyInfo property, LocalBuilder target) {
			if (target.LocalType.IsValueType || target.LocalType.IsNullable()) {
				il.LoadLocalAddress(target);
				il.Call(property.GetGetMethod());
			} else {
				il.LoadLocal(target);
				il.CallVirt(property.GetGetMethod());
			}
		}
Exemplo n.º 3
0
        internal fsMetaProperty(PropertyInfo property) {
            _memberInfo = property;
            StorageType = property.PropertyType;
            MemberName = property.Name;
            IsPublic = (property.GetGetMethod() != null && property.GetGetMethod().IsPublic) &&
                       (property.GetSetMethod() != null && property.GetSetMethod().IsPublic);
            CanRead = property.CanRead;
            CanWrite = property.CanWrite;

            CommonInitialize();
        }
Exemplo n.º 4
0
 public PropertyObject(PropertyInfo md)
     : base()
 {
     getter = md.GetGetMethod(true);
     setter = md.GetSetMethod(true);
     info = md;
 }
Exemplo n.º 5
0
		private static DynamicGetter CreateGetMethod(PropertyInfo propertyInfo, Type type)
		{
			var getMethod = propertyInfo.GetGetMethod();

			if (getMethod == null)
				throw new InvalidOperationException(string.Format("Could not retrieve GetMethod for the {0} property of {1} type", propertyInfo.Name, type.FullName));

			var arguments = new Type[1]
			{
				typeof (object)
			};

			var getterMethod = new DynamicMethod(string.Concat("_Get", propertyInfo.Name, "_"), typeof(object), arguments, propertyInfo.DeclaringType);
			var generator = getterMethod.GetILGenerator();

			generator.DeclareLocal(typeof(object));
			generator.Emit(OpCodes.Ldarg_0);
			generator.Emit(OpCodes.Castclass, propertyInfo.DeclaringType);
			generator.EmitCall(OpCodes.Callvirt, getMethod, null);

			if (propertyInfo.PropertyType.IsClass == false)
				generator.Emit(OpCodes.Box, propertyInfo.PropertyType);

			generator.Emit(OpCodes.Ret);

			return (DynamicGetter) getterMethod.CreateDelegate(typeof (DynamicGetter));
		}
		private IProperty GetProperty(PropertyInfo propertyInfo, ElasticsearchPropertyAttributeBase attribute)
		{
			var property = _visitor.Visit(propertyInfo, attribute);
			if (property != null)
				return property;

			if (propertyInfo.GetGetMethod().IsStatic)
				return null;

			if (attribute != null)
				property = attribute;
			else
				property = InferProperty(propertyInfo.PropertyType);

			var objectProperty = property as IObjectProperty;
			if (objectProperty != null)
			{
				var type = GetUnderlyingType(propertyInfo.PropertyType);
				var seenTypes = new ConcurrentDictionary<Type, int>(_seenTypes);
				seenTypes.AddOrUpdate(type, 0, (t, i) => ++i);
				var walker = new PropertyWalker(type, _visitor, _maxRecursion, seenTypes);
				objectProperty.Properties = walker.GetProperties(seenTypes, _maxRecursion);
			}

			_visitor.Visit(property, propertyInfo, attribute);

			return property;
		}
Exemplo n.º 7
0
        internal static GenericGetter CreateGetMethod(Type type, PropertyInfo propertyInfo)
        {
            MethodInfo getMethod = propertyInfo.GetGetMethod();
            if (getMethod == null)
                return null;

            DynamicMethod getter = new DynamicMethod("_", typeof(object), new Type[] { typeof(object) }, type);

            ILGenerator il = getter.GetILGenerator();

            if (!type.IsClass) // structs
            {
                var lv = il.DeclareLocal(type);
                il.Emit(OpCodes.Ldarg_0);
                il.Emit(OpCodes.Unbox_Any, type);
                il.Emit(OpCodes.Stloc_0);
                il.Emit(OpCodes.Ldloca_S, lv);
                il.EmitCall(OpCodes.Call, getMethod, null);
                if (propertyInfo.PropertyType.IsValueType)
                    il.Emit(OpCodes.Box, propertyInfo.PropertyType);
            }
            else
            {
                il.Emit(OpCodes.Ldarg_0);
                il.Emit(OpCodes.Castclass, propertyInfo.DeclaringType);
                il.EmitCall(OpCodes.Callvirt, getMethod, null);
                if (propertyInfo.PropertyType.IsValueType)
                    il.Emit(OpCodes.Box, propertyInfo.PropertyType);
            }

            il.Emit(OpCodes.Ret);

            return (GenericGetter)getter.CreateDelegate(typeof(GenericGetter));
        }
Exemplo n.º 8
0
        private void InitializeGet(PropertyInfo propertyInfo)
        {
            if (!propertyInfo.CanRead) return;

            // Target: (Object)(((TInstance)instance).Property)

            // preparing parameter, Object type
            ParameterExpression instance = Expression.Parameter(typeof (Object), "instance");

            // non-instance for static method, or ((TInstance)instance)
            UnaryExpression instanceCast = propertyInfo.GetGetMethod(true).IsStatic
                                               ? null
                                               : Expression.Convert(instance, propertyInfo.ReflectedType);

            // ((TInstance)instance).Property
            MemberExpression propertyAccess = Expression.Property(instanceCast, propertyInfo);

            // (Object)(((TInstance)instance).Property)
            UnaryExpression castPropertyValue = Expression.Convert(propertyAccess, typeof (Object));

            // Lambda expression
            Expression<Func<object, object>> lambda = Expression.Lambda<Func<Object, Object>>(castPropertyValue,
                                                                                              instance);

            getter = lambda.Compile();
        }
Exemplo n.º 9
0
 //Supports getters of the form `return field;`
 private static FieldInfo GetBackingFieldInternal(PropertyInfo property)
 {
     if (property == null)
         throw new ArgumentNullException("property");
     MethodInfo getter = property.GetGetMethod(true);
     if (getter == null)
         return null;
     byte[] il = getter.GetMethodBody().GetILAsByteArray();
     if (il.Length != 7
        || il[0] != 0x02//ldarg.0
        || il[1] != 0x7b//ldfld <field>
        || il[6] != 0x2a//ret
        )
         return null;
     int metadataToken = il[2] | il[3] << 8 | il[4] << 16 | il[5] << 24;
     Type type = property.ReflectedType;
     do
     {
         foreach (FieldInfo fi in type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic))
         {
             if (fi.MetadataToken == metadataToken)
                 return fi;
         }
         type = type.BaseType;
     } while (type != null);
     throw new Exception("Field not found");
 }
Exemplo n.º 10
0
        /// <summary>
        /// Creates a dynamic getter for the property
        /// </summary>
        /// <param name="propertyInfo"></param>
        /// <returns></returns>
        public static GenericGetter CreateGetMethod(PropertyInfo propertyInfo)
        {
            /*
             * If there's no getter return null
             */
            MethodInfo getMethod = propertyInfo.GetGetMethod();
            if (getMethod == null)
                return null;

            /*
             * Create the dynamic method
             */
            Type[] arguments = new Type[1];
            arguments[0] = typeof(object);

            DynamicMethod getter = new DynamicMethod(
                String.Concat("_Get", propertyInfo.Name, "_"),
                typeof(object), arguments, propertyInfo.DeclaringType,false);

            ILGenerator generator = getter.GetILGenerator();
            generator.DeclareLocal(typeof(object));
            generator.Emit(OpCodes.Ldarg_0);
            generator.Emit(OpCodes.Castclass, propertyInfo.DeclaringType);
            generator.EmitCall(OpCodes.Callvirt, getMethod, null);

            if (!propertyInfo.PropertyType.IsClass)
                generator.Emit(OpCodes.Box, propertyInfo.PropertyType);

            generator.Emit(OpCodes.Ret);

            /*
             * Create the delegate and return it
             */
            return (GenericGetter)getter.CreateDelegate(typeof(GenericGetter));
        }
Exemplo n.º 11
0
        private static bool IsMatch(PropertyInfo propertyInfo, BindingFlags flags)
        {
            // this methods is heavily used during reflection, so we have traded
            // readablility for performance.

            var mainMethod = propertyInfo.GetGetMethod() ?? propertyInfo.GetSetMethod();
            if (mainMethod == null)
                return false;

            if (flags == Type.BindFlags.AllMembers || flags == Type.BindFlags.DeclaredMembers)
                return true;

            bool incStatic   = (flags & BindingFlags.Static) == BindingFlags.Static;
            bool incInstance = (flags & BindingFlags.Instance) == BindingFlags.Instance;

            if (incInstance == incStatic && !incInstance)
                return false;

            if (incInstance != incStatic)
            {
                bool isStatic = mainMethod.IsStatic;

                if (!((incStatic && isStatic) || (incInstance && !isStatic)))
                    return false;
            }

            bool incPublic    = (flags & BindingFlags.Public) == BindingFlags.Public;
            bool incNonPublic = (flags & BindingFlags.NonPublic) == BindingFlags.NonPublic;

            if (incPublic == incNonPublic)
                return incPublic;

            bool isPublic = mainMethod.IsPublic;
            return (incPublic && isPublic) || (incNonPublic && !isPublic);
        }
        public PocoFeatureAttributeDefinition(PropertyInfo propertyInfo, FeatureAttributeAttribute att)
        {
            AttributeName = propertyInfo.Name;
            if (!string.IsNullOrEmpty(att.AttributeName)) AttributeName = att.AttributeName;

            AttributeDescription = att.AttributeDescription;
            
            AttributeType = propertyInfo.PropertyType;
            if (propertyInfo.CanRead)
            {
                _getMethod = propertyInfo.GetGetMethod();
                _static = _getMethod.IsStatic;
            }
            if (propertyInfo.CanWrite)
            {
                _setMethod = propertyInfo.GetSetMethod();
            }
            else
            {
                _readonly = true;
            }
            
            /*
            var att = propertyInfo.GetCustomAttributes(typeof (FeatureAttributeAttribute), true);
            if (att.Length > 0) CorrectByAttribute((FeatureAttributeAttribute)att[0]);
             */

            CorrectByAttribute(att);
        }
        private PropertyFormat ConvertToPropertyFormat(PropertyInfo property)
        {
            var getMethod = property.GetGetMethod(false);
            if (getMethod == null) return null;
            var format = property.GetCustomAttribute<FormatInfoAttribute>(true);
            PropertyFormat result = null;

            if (formatInfoProvider != null)
                result = formatInfoProvider.GetFormat(property);

            if (result == null) result = new PropertyFormat();

            if (string.IsNullOrEmpty(result.Title)) result.Title = property.Name;
            if (string.IsNullOrEmpty(result.Format)) result.Format = "{0}";
            if (result.Order <= 0) result.Order = int.MaxValue;
            if (!Enum.IsDefined(typeof(PropertyDisplay), result.Display)) result.Display = PropertyDisplay.Inline;

            if (format != null)
            {
                if (!string.IsNullOrEmpty(format.Title)) result.Title = format.Title;
                if (!string.IsNullOrEmpty(format.Format)) result.Format = format.Format;
                if (format.Order > 0) result.Order = format.Order;
                if (Enum.IsDefined(typeof(PropertyDisplay), format.Display)) result.Display = format.Display;
            }
            result.Get = getMethod;
            return result;
        }
Exemplo n.º 14
0
 public StepArgument(PropertyInfo member, object declaringObject)
 {
     Name = member.Name;
     _get = () => member.GetGetMethod(true).Invoke(declaringObject, null);
     _set = o => member.GetSetMethod(true).Invoke(declaringObject, new[] { o });
     ArgumentType = member.PropertyType;
 }
Exemplo n.º 15
0
 public string SourceFor(PropertyInfo property)
 {
     return string.Format("{0} {1} {2} {{ get; set; }}",
                          property.GetGetMethod().IsPublic ? "public" : "internal",
                          property.PropertyType.Name,
                          property.Name);
 }
Exemplo n.º 16
0
        bool IsAReadWriteProperty(PropertyInfo propertyInfo)
        {
            if (!propertyInfo.GetSetMethod(true).IsPublic || !propertyInfo.GetGetMethod(true).IsPublic)
                throw new InvalidOperationException("Tweakable property {" + propertyInfo.ReflectedType + "." + propertyInfo.Name + "} is of the wrong type (should be public read/write)");

            return true;
        }
 public void SetConfiguration( PropertyInfo p, ServiceLogMethodOptions option )
 {
     MethodInfo mG = p.GetGetMethod();
     if( mG != null ) SetConfiguration( mG, option );
     MethodInfo mS = p.GetSetMethod();
     if( mS != null ) SetConfiguration( mS, option );
 }
Exemplo n.º 18
0
 /// <summary>
 /// Initialize the structure for a Property
 /// </summary>
 /// <param name="property">Property to import</param>
 public PropertyInfo(System.Reflection.PropertyInfo property)
     : base(property)
 {
     CanRead   = property.CanRead;
     GetMethod = (CanRead ? property.GetGetMethod(true) : null);
     SetMethod = (CanWrite ? property.GetSetMethod(true) : null);
 }
Exemplo n.º 19
0
 /// <summary>
 /// Initialize the structure for a Property
 /// </summary>
 /// <param name="reflectedProperty">Property to import</param>
 public Property(System.Reflection.PropertyInfo reflectedProperty)
     : base(reflectedProperty)
 {
     CanRead   = reflectedProperty.CanRead;
     GetMethod = (CanRead ? reflectedProperty.GetGetMethod(true) : null);
     SetMethod = (CanWrite ? reflectedProperty.GetSetMethod(true) : null);
 }
Exemplo n.º 20
0
        /// <summary>
        /// Initializes a new instance of the <see cref="CachedPropertyInfo"/> class.
        /// </summary>
        /// <param name="propertyInfo">The property information.</param>
        public CachedPropertyInfo(PropertyInfo propertyInfo)
        {
            Argument.IsNotNull("propertyInfo", propertyInfo);

            PropertyInfo = propertyInfo;

            _publicGetter = new Lazy<bool>(() =>
            {
#if NETFX_CORE || PCL
                var getMethod = propertyInfo.GetMethod;
#else
                var getMethod = propertyInfo.GetGetMethod(false);
#endif

                return getMethod != null && getMethod.IsPublic;
            });

            _publicSetter = new Lazy<bool>(() =>
            {
#if NETFX_CORE || PCL
                var setMethod = propertyInfo.SetMethod;
#else
                var setMethod = propertyInfo.GetSetMethod(false);
#endif

                return setMethod != null && setMethod.IsPublic;
            });
        }
Exemplo n.º 21
0
        public PropertyBoundCommand(CommandExecute execute, INotifyPropertyChanged boundTo, string propertyName)
        {
            if (execute == null)
                throw new ArgumentNullException("execute");
            this.execute = execute;

            if (boundTo == null)
                throw new ArgumentNullException("boundTo");
            this.boundTo = boundTo;

            property = boundTo.GetType().GetProperty(propertyName);
            if (property == null)
                throw new ArgumentException("Bad propertyName");

            if (property.PropertyType != typeof(bool))
                throw new ArgumentException("Bad property type");

            propertyGetMethod = property.GetGetMethod();
            if (propertyGetMethod == null)
                throw new ArgumentException("No public get-method found.");

            this.propertyName = propertyName;

            boundTo.PropertyChanged += new PropertyChangedEventHandler(boundTo_PropertyChanged);
        }
Exemplo n.º 22
0
 internal static bool IsInteresting(PropertyInfo pi)
 {
     MethodInfo getter, setter;
     return pi.CanRead && pi.CanWrite &&
         (getter = pi.GetGetMethod()) != null && getter.IsVirtual &&
         (setter = pi.GetSetMethod()) != null && setter.IsVirtual;
 }
 static Func<object, object> CreateGetter(Type t, PropertyInfo property)
 {
     var arg = Expression.Parameter(typeof(object), "obj");
     var target = Expression.Convert(arg, t);
     var getProp = Expression.Convert(Expression.Call(target, property.GetGetMethod(true)), typeof (object));
     return Expression.Lambda<Func<object, object>>(getProp, arg).Compile();
 }
Exemplo n.º 24
0
 /// <summary> 表示一个可以获取或者设置其内容的对象属性
 /// </summary>
 /// <param name="property">属性信息</param>
 public ObjectProperty(PropertyInfo property)
 {
     Field = false;
     MemberInfo = property; //属性信息
     OriginalType = property.PropertyType;
     var get = property.GetGetMethod(true); //获取属性get方法,不论是否公开
     var set = property.GetSetMethod(true); //获取属性set方法,不论是否公开
     if (set != null) //set方法不为空
     {
         CanWrite = true; //属性可写
         Static = set.IsStatic; //属性是否为静态属性
         IsPublic = set.IsPublic;
     }
     if (get != null) //get方法不为空
     {
         CanRead = true; //属性可读
         Static = get.IsStatic; //get.set只要有一个静态就是静态
         IsPublic = IsPublic || get.IsPublic;
     }
     ID = System.Threading.Interlocked.Increment(ref Literacy.Sequence);
     UID = Guid.NewGuid();
     Init();
     TypeCodes = TypeInfo.TypeCodes;
     Attributes = new AttributeCollection(MemberInfo);
     var mapping = Attributes.First<IMemberMappingAttribute>();
     if (mapping != null)
     {
         MappingName = mapping.Name;
     }
 }
Exemplo n.º 25
0
        /// <summary>
        /// �����¶���
        /// </summary>
        /// <param name="colAttr">����������</param>
        /// <param name="prop">��֮������������Ϣ</param>
        public PropertyColumn(ColumnMappingAttribute colAttr, PropertyInfo prop)
            : base(colAttr)
        {
            if (prop == null)
            {
                throw new ArgumentNullException();
            }

            this.prop = prop;

            getter = prop.GetGetMethod();
            setter = prop.GetSetMethod();

            if (colAttr.Name == null || colAttr.Name == string.Empty)
                this.Name = prop.Name;
            else
                this.Name = colAttr.Name;

            if (this.DataType == typeof(object))
            {
                throw new OrmLogicException("Not Allowed to declare Object type as basic column");
            }

            if (colAttr.DbType == System.Data.DbType.Object)
            {
                //������������
                this.DbType = DbFunction.BuildDbType(this.DataType);
            }
        }
Exemplo n.º 26
0
        public static void CargarControles(Control[] unaListaControles, object unObjeto)
        {
            Control unControl = null;
            object  valor     = null;

            for (int i = 0; i < unaListaControles.Count(); i++)
            {
                Application.DoEvents();
                unControl = unaListaControles[i];

                Type tipo = unControl.GetType();
                if (tipo.Name == "DgvPlus" || tipo.Name == "TextBoxX" || tipo.Name == "PictureBox" || tipo.Name == "ComboBoxEx" || tipo.Name == "DateTimeInput" || tipo.Name == "CheckBox")
                {
                    object nombre = ExtraeNombre(unControl);

                    System.Reflection.PropertyInfo item = unObjeto.GetType().GetProperty(nombre.ToString());
                    if (item != null)
                    {
                        if (item.GetGetMethod() != null)
                        {
                            valor = item.GetValue(unObjeto, null);
                        }

                        switch (tipo.Name)
                        {
                        case "TextBoxX":
                            unControl.Text = valor == null ? "" : valor.ToString();
                            break;

                        case "PictureBox":
                            ((PictureBox)unControl).Image = null;
                            ((PictureBox)unControl).Image = (Image)valor;
                            break;

                        case "ComboBoxEx":
                            ((ComboBox)unControl).SelectedIndex = -1;
                            ((ComboBox)unControl).SelectedValue = valor;
                            break;

                        case "DateTimeInput":
                            ((DevComponents.Editors.DateTimeAdv.DateTimeInput)unControl).Value = (DateTime)valor;
                            break;

                        case "CheckBox":
                            ((CheckBox)unControl).Checked = (bool)valor;
                            break;

                        case "DgvPlus":
                            //((DataGridView)unControl).DataSource = SoporteList<DetalleOrdenPedido>.ToBindingList(((IEnumerable<DetalleOrdenPedido>)valor).ToList());
                            break;
                        }
                    }
                    else
                    {
                        General.Mensaje("Propiedad '" + nombre.ToString() + "' no definida");
                    }
                }
            }
        }
Exemplo n.º 27
0
 public PropertyGetter(PropertyInfo propertyInfo)
 {
     _propertyInfo = propertyInfo;
     _name = _propertyInfo.Name;
     _memberType = _propertyInfo.PropertyType;
     if (_propertyInfo.GetGetMethod(true) != null)
         _lateBoundPropertyGet = DelegateFactory.CreateGet(propertyInfo);
 }
Exemplo n.º 28
0
 public PropertyInterceptionArgs(object instance, PropertyInfo property, object value)
     : base(instance, property, value)
 {
     var getter = property.GetGetMethod(nonPublic: true);
     if (getter != null) _getter = DelegateFactory.CreateGetter(instance, getter);
     var setter = property.GetSetMethod(nonPublic: true);
     if (setter != null) _setter = DelegateFactory.CreateSetter(instance, setter);
 }
Exemplo n.º 29
0
 public ClassAccessor(PropertyInfo property)
 {
     this.Name = property.Name;
     this.PropertyType = property.PropertyType;
     this.IsPrimaryKey = false;
     this.getter = createGetter(property.GetGetMethod());
     this.setter = createSetter(property.GetSetMethod());
 }
Exemplo n.º 30
0
		void EmitPropertyAccess (EmitContext ec, PropertyInfo property)
		{
			var getter = property.GetGetMethod (true);
			if (!getter.IsStatic)
				ec.EmitLoadSubject (expression);

			ec.EmitCall (getter);
		}
Exemplo n.º 31
0
 public EnumPropertyField(object instance, string name)
 {
     this.instance = instance;
     this.name     = name;
     System.Reflection.PropertyInfo info = instance.GetType().GetProperty(name);
     setter = info.GetSetMethod();
     getter = info.GetGetMethod();
 }
		public static UserDefinedTypeExporter.GetterDelegate CreateGetter(Type type, PropertyInfo property)
		{
			return (object value, Exporter exporter) =>
			{
				object propertyValue = property.GetGetMethod().Invoke(value, new object[]{});
				exporter.Export(propertyValue);
			};
		}
 public override void Process(IReflector reflector, PropertyInfo property, IMethodRemover methodRemover, ISpecificationBuilder specification) {
     if ((property.PropertyType.IsPrimitive || TypeUtils.IsEnum(property.PropertyType)) && property.GetCustomAttribute<OptionallyAttribute>() != null) {
         Log.Warn("Ignoring Optionally annotation on primitive or un-readable parameter on " + property.ReflectedType + "." + property.Name);
         return;
     }
     if (property.GetGetMethod() != null && !property.PropertyType.IsPrimitive) {
         Process(property, specification);
     }
 }
Exemplo n.º 34
0
 private static Vector3 SnapSettingsMove()
 {
     if (Invoke_SnapSettingsMove == null)
     {
         System.Reflection.PropertyInfo p = typeof(EditorUtility).Assembly.GetType("UnityEditor.SnapSettings").GetProperty("move", (System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public));
         System.Reflection.MethodInfo   m = p.GetGetMethod();
         Invoke_SnapSettingsMove = (System.Func <Vector3>)System.Delegate.CreateDelegate(typeof(System.Func <Vector3>), m);
     }
     return(Invoke_SnapSettingsMove());
 }
Exemplo n.º 35
0
        public static System.Func <TSource, TRet> CreateGetter <TSource, TRet>(System.Reflection.PropertyInfo propertyInfo, bool nonPublic)
        {
            if (propertyInfo == null)
            {
                throw new System.ArgumentNullException(nameof(propertyInfo));
            }

            if (propertyInfo.GetIndexParameters().Length > 0)
            {
                //throw new System.ArgumentException("Cannot create a dynamic getter for anindexed property.", "propertyInfo");
                return(null);
            }

            if (typeof(TSource) != typeof(object) &&
                !propertyInfo.DeclaringType.IsAssignableFrom(typeof(TSource)))
            {
                //throw new System.ArgumentException("The declaring type of the property is not assignable from the type of the instance.", "propertyInfo");
                return(null);
            }

            if (!typeof(TRet).IsAssignableFrom(propertyInfo.PropertyType))
            {
                //throw new System.ArgumentException("The type of the return value is not assignable from the type of the property.", "propertyInfo");
                return(null);
            }

            //the method call of the get accessor method fails in runtime
            //if the declaring type of the property is an interface and TSource is a value type,
            //in this case, we should find the property from TSource whose DeclaringType is TSource itself

            if (typeof(TSource).GetTypeInfo().IsValueType&& propertyInfo.DeclaringType.GetTypeInfo().IsInterface)
            {
                propertyInfo = typeof(TSource).GetProperty(propertyInfo.Name);
            }

            var getMethod = propertyInfo.GetGetMethod(nonPublic);

            if (getMethod == null)
            {
                //if (nonPublic)
                //{
                //    throw new System.ArgumentException("The property does not have a get method.", "propertyInfo");
                //}

                //throw new System.ArgumentException("The property does not have a public get method.", "propertyInfo");

                return(null);
            }

            return(EmitPropertyGetter <TSource, TRet>(propertyInfo, getMethod));
        }
Exemplo n.º 36
0
            Property LoadProperty(System.Reflection.PropertyInfo refProperty)
            {
                bool isStatic =
                    (refProperty.CanRead && refProperty.GetGetMethod().IsStatic) ||
                    (refProperty.CanRead && refProperty.GetGetMethod().IsStatic);

                System.Reflection.MethodInfo getMethod =
                    (refProperty.CanRead ? refProperty.GetGetMethod(false) : null);
                System.Reflection.MethodInfo setMethod =
                    (refProperty.CanWrite ? refProperty.GetSetMethod(false) : null);
                Property property = new Property
                {
                    Name         = refProperty.Name,
                    IsStatic     = isStatic,
                    PropertyType = GetTypeFullName(refProperty.PropertyType),
                    GetMethod    = (getMethod != null ? LoadMethod(getMethod) : null),
                    SetMethod    = (setMethod != null ? LoadMethod(setMethod) : null),
                    Attributes   = refProperty.Attributes,
                };

                property.IndexParameters = refProperty.GetIndexParameters().Select(p => LoadParameter(p)).ToList();
                return(property);
            }
        static StackObject *GetGetMethod_0(ILIntepreter __intp, StackObject *__esp, IList <object> __mStack, CLRMethod __method, bool isNewObj)
        {
            ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain;
            StackObject *ptr_of_this_method;
            StackObject *__ret = ILIntepreter.Minus(__esp, 1);

            ptr_of_this_method = ILIntepreter.Minus(__esp, 1);
            System.Reflection.PropertyInfo instance_of_this_method = (System.Reflection.PropertyInfo) typeof(System.Reflection.PropertyInfo).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack), (CLR.Utils.Extensions.TypeFlags) 0);
            __intp.Free(ptr_of_this_method);

            var result_of_this_method = instance_of_this_method.GetGetMethod();

            return(ILIntepreter.PushObject(__ret, __mStack, result_of_this_method));
        }
Exemplo n.º 38
0
    public static string GetGACDir()
    {
        System.Reflection.PropertyInfo gac = typeof(System.Environment).GetProperty("GacPath", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic);
        if (gac == null)
        {
            Console.WriteLine("Can't find the GAC!");
            Environment.Exit(1);
        }

        System.Reflection.MethodInfo get_gac = gac.GetGetMethod(true);
        string sGACDir = (string)get_gac.Invoke(null, null);

        return(sGACDir);
    }
Exemplo n.º 39
0
    //묻지도 따지지도 않고 프로퍼티 Get을 호출해 ReturnType형으로 리턴.
    //어떤 체크도 하지 않음.
    static public ReturnType GetPropertyValue <ReturnType>(
        object obj, string propName, object[] index
        )
    {
        System.Type type = obj.GetType();
        System.Reflection.PropertyInfo pi = type.GetProperty(propName);
        if (pi == null)
        {
            Debug.LogError("invalid state : " + propName);
            return(default(ReturnType));
        }
        object value = pi.GetGetMethod().Invoke(obj, index);

        return((ReturnType)value);
    }
Exemplo n.º 40
0
 private static System.Reflection.PropertyInfo GetDefaultIndexer(System.Type type)
 {
     System.Reflection.PropertyInfo result;
     if (typeof(System.Collections.IDictionary).IsAssignableFrom(type))
     {
         result = null;
     }
     else
     {
         System.Reflection.MemberInfo[] defaultMembers = type.GetDefaultMembers();
         System.Reflection.PropertyInfo propertyInfo   = null;
         if (defaultMembers != null && defaultMembers.Length > 0)
         {
             System.Type type2 = type;
             while (type2 != null)
             {
                 for (int i = 0; i < defaultMembers.Length; i++)
                 {
                     if (defaultMembers[i] is System.Reflection.PropertyInfo)
                     {
                         System.Reflection.PropertyInfo propertyInfo2 = (System.Reflection.PropertyInfo)defaultMembers[i];
                         if (propertyInfo2.DeclaringType == type2 && propertyInfo2.CanRead)
                         {
                             System.Reflection.ParameterInfo[] parameters = propertyInfo2.GetGetMethod().GetParameters();
                             if (parameters.Length == 1 && parameters[0].ParameterType == typeof(int))
                             {
                                 propertyInfo = propertyInfo2;
                                 break;
                             }
                         }
                     }
                 }
                 if (propertyInfo != null)
                 {
                     break;
                 }
                 type2 = type2.BaseType;
             }
         }
         if (propertyInfo == null)
         {
             throw new System.InvalidOperationException(string.Format("You must implement a default accessor on {0} because it inherits from ICollection.", type.FullName));
         }
         result = propertyInfo;
     }
     return(result);
 }
Exemplo n.º 41
0
        public static Func <object, object> CreatePropertyGetter(System.Reflection.PropertyInfo propertyInfo)
        {
            var getMethod = propertyInfo.GetGetMethod();

            if (getMethod == null)
            {
                return(x => propertyInfo.GetValue(x, null));
            }

            var type = propertyInfo.DeclaringType;

            var instance      = Expression.Parameter(typeof(object));
            var typedInstance = Expression.Convert(instance, type);
            var res           = Expression.Call(typedInstance, getMethod);
            var result        = Expression.Convert(res, typeof(object));

            var lambda = Expression.Lambda <Func <object, object> >(result, instance);

            return(lambda.Compile());
        }
Exemplo n.º 42
0
        static StackObject *GetGetMethod_0(ILIntepreter __intp, StackObject *__esp, IList <object> __mStack, CLRMethod __method, bool isNewObj)
        {
            ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain;
            StackObject *ptr_of_this_method;
            StackObject *__ret = ILIntepreter.Minus(__esp, 1);

            ptr_of_this_method = ILIntepreter.Minus(__esp, 1);
            System.Reflection.PropertyInfo instance_of_this_method = (System.Reflection.PropertyInfo) typeof(System.Reflection.PropertyInfo).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
            __intp.Free(ptr_of_this_method);

            var result_of_this_method = instance_of_this_method.GetGetMethod();

            object obj_result_of_this_method = result_of_this_method;

            if (obj_result_of_this_method is CrossBindingAdaptorType)
            {
                return(ILIntepreter.PushObject(__ret, __mStack, ((CrossBindingAdaptorType)obj_result_of_this_method).ILInstance));
            }
            return(ILIntepreter.PushObject(__ret, __mStack, result_of_this_method));
        }
Exemplo n.º 43
0
    /// <summary>
    /// src가 가진 프로퍼티이름과 같은 프로퍼티를 dest에서 찾아 값을 복사해준다.
    /// 단순 복사이므로 주의. 찾는 이름이 없으면 무시된다.
    /// 필드가 아닌 프로퍼티만을 사용한다.
    /// </summary>
    /// <param name="src">원본 오브젝트</param>
    /// <param name="dest">복사 대상 오브젝트</param>
    static public void CopyToSameNameProperties(object src, object dest)
    {
        if (src == null || dest == null)
        {
            return;
        }
        System.Reflection.PropertyInfo[] srcPiList =
            src.GetType().GetProperties();
        System.Type destType = dest.GetType();
        for (int idx = 0; idx < srcPiList.Length; ++idx)
        {
            System.Reflection.PropertyInfo srcProp  = srcPiList[idx];
            System.Reflection.PropertyInfo destProp =
                destType.GetProperty(srcProp.Name);

            if (destProp == null || srcProp.PropertyType != destProp.PropertyType)
            {
                Debug.LogWarning("not found prop : " + srcProp.Name);
                continue;
            }
            destProp.SetValue(dest, srcProp.GetGetMethod().Invoke(src, null), null);
        }
    }
Exemplo n.º 44
0
        public static PropsAttribute GetProps(this System.Reflection.PropertyInfo i)
        {
            var attribute = i.GetCustomAttribute <PropsAttribute>();

            if (attribute == null && i.GetGetMethod().IsVirtual)
            {
                return(null);
            }
            var            foregnKey    = i.GetCustomAttribute <ForeignKeyAttribute>();
            var            stringLength = i.GetCustomAttribute <StringLengthAttribute>();
            var            require      = i.GetCustomAttribute <RequiredAttribute>();
            PropsAttribute attr;

            if (attribute == null)
            {
                attr = new PropsAttribute(i.Name);
            }
            else
            {
                attr = attribute;
            }

            if (foregnKey != null)
            {
                attr.ForeignTable = attr.ForeignTable ?? foregnKey.Name;
            }
            if (stringLength != null)
            {
                attr.MaxLength = stringLength.MaximumLength;
                attr.MinLength = stringLength.MinimumLength;
            }
            if (require != null)
            {
                attr.Required = true;
            }
            return(attr);
        }
        /// <summary>
        /// A property is serializable if:
        /// - it's not marked with any of the 'DontSerializeMember' attributes
        /// - it's an auto-property
        /// - has a public getter or setter, otherwise must be annotated with any of the 'SerializeMember' attributes
        /// - its type is serializable
        /// - static properties that meet the previous requirements are always serialized in Better[Behaviour|ScriptableObject],
        ///   and in System.Objects if the serializer of use supports it (FullSerialier doesn't)
        /// </summary>
        public override bool IsSerializableProperty(System.Reflection.PropertyInfo property)
        {
            foreach (System.Type v_type in DontSerializeMember)
            {
                if (property.IsDefined(v_type, false))
                {
                    return(false);
                }
            }

            if (!property.IsAutoProperty())
            {
                return(false);
            }

            bool v_isSerializableDefined = false;

            foreach (System.Type v_type in SerializeMember)
            {
                if (property.IsDefined(v_type, false))
                {
                    v_isSerializableDefined = true;
                    break;
                }
            }

            if (!(property.GetGetMethod(true).IsPublic ||
                  property.GetSetMethod(true).IsPublic ||
                  v_isSerializableDefined))
            {
                return(false);
            }

            bool serializable = IsSerializableType(property.PropertyType);

            return(serializable);
        }
Exemplo n.º 46
0
        private static void ConsoleCleaner()
        {
            // Il2CppSystem.Console.SetOut(new Il2CppSystem.IO.StreamWriter(Il2CppSystem.IO.Stream.Null));
            try
            {
                Il2Cppmscorlib = Assembly.Load("Il2Cppmscorlib");
                if (Il2Cppmscorlib == null)
                {
                    throw new Exception("Unable to Find Assembly Il2Cppmscorlib!");
                }

                streamType = Il2Cppmscorlib.GetType("Il2CppSystem.IO.Stream");
                if (streamType == null)
                {
                    throw new Exception("Unable to Find Type Il2CppSystem.IO.Stream!");
                }

                System.Reflection.PropertyInfo propertyInfo = streamType.GetProperty("Null", BindingFlags.Static | BindingFlags.Public);
                if (propertyInfo == null)
                {
                    throw new Exception("Unable to Find Property Il2CppSystem.IO.Stream.Null!");
                }

                MethodInfo nullStreamField = propertyInfo.GetGetMethod();
                if (nullStreamField == null)
                {
                    throw new Exception("Unable to Find Get Method of Property Il2CppSystem.IO.Stream.Null!");
                }

                object nullStream = nullStreamField.Invoke(null, new object[0]);
                if (nullStream == null)
                {
                    throw new Exception("Unable to Get Value of Property Il2CppSystem.IO.Stream.Null!");
                }

                Type streamWriterType = Il2Cppmscorlib.GetType("Il2CppSystem.IO.StreamWriter");
                if (streamWriterType == null)
                {
                    throw new Exception("Unable to Find Type Il2CppSystem.IO.StreamWriter!");
                }

                ConstructorInfo streamWriterCtor = streamWriterType.GetConstructor(new[] { streamType });
                if (streamWriterCtor == null)
                {
                    throw new Exception("Unable to Find Constructor of Type Il2CppSystem.IO.StreamWriter!");
                }

                object nullStreamWriter = streamWriterCtor.Invoke(new[] { nullStream });
                if (nullStreamWriter == null)
                {
                    throw new Exception("Unable to Invoke Constructor of Type Il2CppSystem.IO.StreamWriter!");
                }

                Type consoleType = Il2Cppmscorlib.GetType("Il2CppSystem.Console");
                if (consoleType == null)
                {
                    throw new Exception("Unable to Find Type Il2CppSystem.Console!");
                }

                MethodInfo setOutMethod = consoleType.GetMethod("SetOut", BindingFlags.Static | BindingFlags.Public);
                if (setOutMethod == null)
                {
                    throw new Exception("Unable to Find Method Il2CppSystem.Console.SetOut!");
                }

                setOutMethod.Invoke(null, new[] { nullStreamWriter });
            }
            catch (Exception ex) { MelonLogger.Warning($"Console Cleaner Failed: {ex}"); }
        }
Exemplo n.º 47
0
 public static bool IsPublic(this PropertyInfo propertyInfo)
 {
     return((propertyInfo?.GetGetMethod(true)?.IsPublic ?? false) ||
            (propertyInfo?.GetSetMethod(true)?.IsPublic ?? false));
 }
Exemplo n.º 48
0
 private void EmitPropertyLoad(System.Reflection.PropertyInfo pi, FleeILGenerator ilg)
 {
     System.Reflection.MethodInfo getter = pi.GetGetMethod(true);
     base.EmitMethodCall(getter, ilg);
 }
Exemplo n.º 49
0
            /// <summary>
            /// Enumerates sorted object members to display.
            /// </summary>
            private void FormatObjectMembersRecursive(List <FormattedMember> result, object obj, bool includeNonPublic, ref int lengthLimit)
            {
                Debug.Assert(obj != null);

                var type       = obj.GetType();
                var fields     = type.GetFields(Ref.BindingFlags.Instance | Ref.BindingFlags.Public | Ref.BindingFlags.NonPublic);
                var properties = type.GetProperties(Ref.BindingFlags.Instance | Ref.BindingFlags.Public | Ref.BindingFlags.NonPublic);
                var members    = new List <Ref.MemberInfo>(fields.Length + properties.Length);

                members.AddRange(fields);
                members.AddRange(properties);

                // kirillo: need case-sensitive comparison here so that the order of members is
                // always well-defined (members can differ by case only). And we don't want to
                // depend on that order. TODO (tomat): sort by visibility.
                members.Sort(new Comparison <Ref.MemberInfo>((x, y) =>
                {
                    int comparisonResult = StringComparer.OrdinalIgnoreCase.Compare(x.Name, y.Name);
                    if (comparisonResult == 0)
                    {
                        comparisonResult = StringComparer.Ordinal.Compare(x.Name, y.Name);
                    }

                    return(comparisonResult);
                }));

                foreach (var member in members)
                {
                    if (_language.IsHiddenMember(member))
                    {
                        continue;
                    }

                    bool rootHidden = false, ignoreVisibility = false;
                    var  browsable = (DebuggerBrowsableAttribute)member.GetCustomAttributes(typeof(DebuggerBrowsableAttribute), false).FirstOrDefault();
                    if (browsable != null)
                    {
                        if (browsable.State == DebuggerBrowsableState.Never)
                        {
                            continue;
                        }

                        ignoreVisibility = true;
                        rootHidden       = browsable.State == DebuggerBrowsableState.RootHidden;
                    }

                    Ref.FieldInfo field = member as Ref.FieldInfo;
                    if (field != null)
                    {
                        if (!(includeNonPublic || ignoreVisibility || field.IsPublic || field.IsFamily || field.IsFamilyOrAssembly))
                        {
                            continue;
                        }
                    }
                    else
                    {
                        Ref.PropertyInfo property = (Ref.PropertyInfo)member;

                        var getter = property.GetGetMethod(nonPublic: true);
                        var setter = property.GetSetMethod(nonPublic: true);

                        if (!(includeNonPublic || ignoreVisibility ||
                              getter != null && (getter.IsPublic || getter.IsFamily || getter.IsFamilyOrAssembly) ||
                              setter != null && (setter.IsPublic || setter.IsFamily || setter.IsFamilyOrAssembly)))
                        {
                            continue;
                        }

                        if (getter.GetParameters().Length > 0)
                        {
                            continue;
                        }
                    }

                    var debuggerDisplay = GetApplicableDebuggerDisplayAttribute(member);
                    if (debuggerDisplay != null)
                    {
                        string k = FormatWithEmbeddedExpressions(lengthLimit, debuggerDisplay.Name, obj) ?? _language.FormatMemberName(member);
                        string v = FormatWithEmbeddedExpressions(lengthLimit, debuggerDisplay.Value, obj) ?? String.Empty; // TODO: ?
                        if (!AddMember(result, new FormattedMember(-1, k, v), ref lengthLimit))
                        {
                            return;
                        }

                        continue;
                    }

                    Exception exception;
                    object    value = GetMemberValue(member, obj, out exception);
                    if (exception != null)
                    {
                        var memberValueBuilder = MakeMemberBuilder(lengthLimit);
                        FormatException(memberValueBuilder, exception);
                        if (!AddMember(result, new FormattedMember(-1, _language.FormatMemberName(member), memberValueBuilder.ToString()), ref lengthLimit))
                        {
                            return;
                        }

                        continue;
                    }

                    if (rootHidden)
                    {
                        if (value != null && !VisitedObjects.Contains(value))
                        {
                            Array array;
                            if ((array = value as Array) != null)  // TODO (tomat): n-dim arrays
                            {
                                int i = 0;
                                foreach (object item in array)
                                {
                                    string  name;
                                    Builder valueBuilder = MakeMemberBuilder(lengthLimit);
                                    FormatObjectRecursive(valueBuilder, item, _options.QuoteStrings, MemberDisplayFormat.InlineValue, out name);

                                    if (!String.IsNullOrEmpty(name))
                                    {
                                        name = FormatWithEmbeddedExpressions(MakeMemberBuilder(lengthLimit), name, item).ToString();
                                    }

                                    if (!AddMember(result, new FormattedMember(i, name, valueBuilder.ToString()), ref lengthLimit))
                                    {
                                        return;
                                    }

                                    i++;
                                }
                            }
                            else if (_language.FormatPrimitive(value, _options.QuoteStrings, _options.IncludeCodePoints, _options.UseHexadecimalNumbers) == null && VisitedObjects.Add(value))
                            {
                                FormatObjectMembersRecursive(result, value, includeNonPublic, ref lengthLimit);
                                VisitedObjects.Remove(value);
                            }
                        }
                    }
                    else
                    {
                        string  name;
                        Builder valueBuilder = MakeMemberBuilder(lengthLimit);
                        FormatObjectRecursive(valueBuilder, value, _options.QuoteStrings, MemberDisplayFormat.InlineValue, out name);

                        if (String.IsNullOrEmpty(name))
                        {
                            name = _language.FormatMemberName(member);
                        }
                        else
                        {
                            name = FormatWithEmbeddedExpressions(MakeMemberBuilder(lengthLimit), name, value).ToString();
                        }

                        if (!AddMember(result, new FormattedMember(-1, name, valueBuilder.ToString()), ref lengthLimit))
                        {
                            return;
                        }
                    }
                }
            }
Exemplo n.º 50
0
 public static MethodInfo?GetGetMethod(this PropertyInfo property, bool nonPublic)
 {
     Requires.NotNull(property, nameof(property));
     return(property.GetGetMethod(nonPublic));
 }
Exemplo n.º 51
0
        public static void WriteProperty(ILGenerator methodIL, System.Reflection.PropertyInfo propertyInfo, ref bool isFirst, DateTimeFormat dateTimeFormat)
        {
            //不解析静态属性和未设置Get的属性。
            if (propertyInfo.GetGetMethod() == null || propertyInfo.GetGetMethod().IsStatic == true)
            {
                return;
            }
            Type propertyType = propertyInfo.PropertyType;
            bool isNullable   = false;

            if (propertyInfo.PropertyType
#if (NET40 || NET451 || NET461)
                .IsGenericType
#endif
#if NETCORE
                .GetTypeInfo().IsGenericType
#endif
                && propertyInfo.PropertyType.GetGenericTypeDefinition() == typeof(Nullable <>))
            {
                isNullable   = true;
                propertyType = propertyInfo.PropertyType.GetGenericArguments()[0];
            }
            if (propertyType == typeof(System.String))
            {
                #region
                var elseCase = methodIL.DefineLabel();
                var endCase  = methodIL.DefineLabel();
                WriteComma(methodIL, ref isFirst);
                WriteString(methodIL, "\"" + propertyInfo.Name + "\"");
                //model
                methodIL.Emit(OpCodes.Ldarg_0);
                //model.property
                methodIL.Emit(OpCodes.Callvirt, propertyInfo.GetGetMethod());
                //model.property,null
                methodIL.Emit(OpCodes.Ldnull);
                //bool
                methodIL.Emit(OpCodes.Ceq);
                //
                methodIL.Emit(OpCodes.Brfalse_S, elseCase);
                WriteString(methodIL, "null");
                methodIL.Emit(OpCodes.Br_S, endCase);
                methodIL.MarkLabel(elseCase);
                WriteString(methodIL, "\"");
                //writer,model
                methodIL.Emit(OpCodes.Ldarg_1);
                //writer,model
                methodIL.Emit(OpCodes.Ldarg_0);
                //writer,model.property
                methodIL.Emit(OpCodes.Callvirt, propertyInfo.GetGetMethod());
                //
                methodIL.Emit(OpCodes.Call, WriteJsonReverseStringMethodInfo);
                WriteString(methodIL, "\"");
                methodIL.MarkLabel(endCase);
                #endregion
            }
            else if (propertyType == typeof(System.Byte[]))
            {
                var elseCase = methodIL.DefineLabel();
                var endCase  = methodIL.DefineLabel();
                WriteComma(methodIL, ref isFirst);
                WriteString(methodIL, "\"" + propertyInfo.Name + "\":");
                methodIL.Emit(OpCodes.Ldarg_0);
                methodIL.Emit(OpCodes.Callvirt, propertyInfo.GetGetMethod());
                methodIL.Emit(OpCodes.Ldnull);
                methodIL.Emit(OpCodes.Ceq);
                methodIL.Emit(OpCodes.Brfalse_S, elseCase);
                WriteString(methodIL, "null");
                methodIL.Emit(OpCodes.Br_S, endCase);
                methodIL.MarkLabel(elseCase);
                WriteString(methodIL, "\"");
                methodIL.Emit(OpCodes.Ldarg_1);
                methodIL.Emit(OpCodes.Ldarg_0);
                methodIL.Emit(OpCodes.Callvirt, propertyInfo.GetGetMethod());
                methodIL.Emit(OpCodes.Call, toBase64StringMethodInfo);
                methodIL.Emit(OpCodes.Callvirt, writeMethodInfo);
                WriteString(methodIL, "\"");
                methodIL.MarkLabel(endCase);
            }
            else if (propertyType == typeof(System.Char) ||
                     propertyType == typeof(System.Guid))
            {
                #region
                if (isNullable)
                {
                    var elseCase = methodIL.DefineLabel();
                    var endCase  = methodIL.DefineLabel();
                    var temp1    = methodIL.DeclareLocal(propertyInfo.PropertyType);
                    var temp     = methodIL.DeclareLocal(propertyType);
                    WriteComma(methodIL, ref isFirst);
                    WriteString(methodIL, "\"" + propertyInfo.Name + "\":");
                    methodIL.Emit(OpCodes.Ldarg_0);
                    methodIL.Emit(OpCodes.Callvirt, propertyInfo.GetGetMethod());
                    methodIL.Emit(OpCodes.Stloc_S, temp1);
                    methodIL.Emit(OpCodes.Ldloca_S, temp1);
                    methodIL.Emit(OpCodes.Call, propertyInfo.PropertyType.GetMethod("get_HasValue", Type.EmptyTypes));
                    methodIL.Emit(OpCodes.Ldc_I4_0);
                    methodIL.Emit(OpCodes.Ceq);
                    methodIL.Emit(OpCodes.Brfalse_S, elseCase);
                    WriteString(methodIL, "null");
                    methodIL.Emit(OpCodes.Br_S, endCase);
                    methodIL.MarkLabel(elseCase);
                    WriteString(methodIL, "\"");
                    methodIL.Emit(OpCodes.Ldarg_1);
                    methodIL.Emit(OpCodes.Ldarg_0);
                    methodIL.Emit(OpCodes.Callvirt, propertyInfo.GetGetMethod());
                    methodIL.Emit(OpCodes.Stloc_S, temp1);
                    methodIL.Emit(OpCodes.Ldloca_S, temp1);
                    methodIL.Emit(OpCodes.Call, propertyInfo.PropertyType.GetMethod("get_Value", Type.EmptyTypes));
                    methodIL.Emit(OpCodes.Stloc, temp);
                    methodIL.Emit(OpCodes.Ldloca_S, temp);
                    methodIL.Emit(OpCodes.Call, propertyType.GetMethod("ToString", Type.EmptyTypes));
                    methodIL.Emit(OpCodes.Callvirt, writeMethodInfo);
                    WriteString(methodIL, "\"");
                    methodIL.MarkLabel(endCase);
                }
                else
                {
                    var temp = methodIL.DeclareLocal(propertyType);
                    WriteComma(methodIL, ref isFirst);
                    WriteString(methodIL, "\"" + propertyInfo.Name + "\":");
                    WriteString(methodIL, "\"");
                    methodIL.Emit(OpCodes.Ldarg_1);
                    methodIL.Emit(OpCodes.Ldarg_0);
                    methodIL.Emit(OpCodes.Callvirt, propertyInfo.GetGetMethod());
                    methodIL.Emit(OpCodes.Stloc, temp);
                    methodIL.Emit(OpCodes.Ldloca_S, temp);
                    methodIL.Emit(OpCodes.Call, propertyType.GetMethod("ToString", Type.EmptyTypes));
                    methodIL.Emit(OpCodes.Callvirt, writeMethodInfo);
                    WriteString(methodIL, "\"");
                }
                #endregion
            }
            else if (propertyType == typeof(System.Int32) ||
                     propertyType == typeof(System.Int16) ||
                     propertyType == typeof(System.Int64) ||
                     propertyType == typeof(System.UInt32) ||
                     propertyType == typeof(System.UInt16) ||
                     propertyType == typeof(System.UInt64) ||
                     propertyType == typeof(System.Byte) ||
                     propertyType == typeof(System.SByte) ||
                     propertyType == typeof(System.Single) ||
                     propertyType == typeof(System.Double) ||
                     propertyType == typeof(System.Decimal))
            {
                #region
                if (isNullable)
                {
                    var elseCase = methodIL.DefineLabel();
                    var endCase  = methodIL.DefineLabel();
                    var temp     = methodIL.DeclareLocal(propertyType);
                    var temp1    = methodIL.DeclareLocal(propertyInfo.PropertyType);
                    WriteComma(methodIL, ref isFirst);
                    WriteString(methodIL, "\"" + propertyInfo.Name + "\":");
                    methodIL.Emit(OpCodes.Ldarg_0);
                    methodIL.Emit(OpCodes.Call, propertyInfo.GetGetMethod());
                    methodIL.Emit(OpCodes.Stloc, temp1);
                    methodIL.Emit(OpCodes.Ldloca_S, temp1);
                    methodIL.Emit(OpCodes.Call, propertyInfo.PropertyType.GetMethod("get_HasValue", Type.EmptyTypes));
                    methodIL.Emit(OpCodes.Ldc_I4_0);
                    methodIL.Emit(OpCodes.Ceq);
                    methodIL.Emit(OpCodes.Brfalse_S, elseCase);
                    WriteString(methodIL, "null");
                    methodIL.Emit(OpCodes.Br_S, endCase);
                    methodIL.MarkLabel(elseCase);
                    methodIL.Emit(OpCodes.Ldarg_1);
                    methodIL.Emit(OpCodes.Ldarg_0);
                    methodIL.Emit(OpCodes.Callvirt, propertyInfo.GetGetMethod());
                    methodIL.Emit(OpCodes.Stloc, temp1);
                    methodIL.Emit(OpCodes.Ldloca_S, temp1);
                    methodIL.Emit(OpCodes.Call, propertyInfo.PropertyType.GetMethod("get_Value", Type.EmptyTypes));
                    methodIL.Emit(OpCodes.Stloc, temp);
                    methodIL.Emit(OpCodes.Ldloca_S, temp);
                    methodIL.Emit(OpCodes.Call, propertyType.GetMethod("ToString", Type.EmptyTypes));
                    methodIL.Emit(OpCodes.Callvirt, writeMethodInfo);
                    methodIL.MarkLabel(endCase);
                }
                else
                {
                    var temp = methodIL.DeclareLocal(propertyInfo.PropertyType);
                    WriteComma(methodIL, ref isFirst);
                    WriteString(methodIL, "\"" + propertyInfo.Name + "\":");
                    methodIL.Emit(OpCodes.Ldarg_1);
                    methodIL.Emit(OpCodes.Ldarg_0);
                    methodIL.Emit(OpCodes.Callvirt, propertyInfo.GetGetMethod());
                    methodIL.Emit(OpCodes.Stloc, temp);
                    methodIL.Emit(OpCodes.Ldloca_S, temp);
                    methodIL.Emit(OpCodes.Call, propertyType.GetMethod("ToString", Type.EmptyTypes));
                    methodIL.Emit(OpCodes.Callvirt, writeMethodInfo);
                }
                #endregion
            }
            else if (propertyType == typeof(System.DateTime)
                     )
            {
                #region
                if (isNullable)
                {
                    var elseCase = methodIL.DefineLabel();
                    var endCase  = methodIL.DefineLabel();
                    var longTime = methodIL.DeclareLocal(typeof(System.Int64));
                    var temp     = methodIL.DeclareLocal(propertyType);
                    var temp1    = methodIL.DeclareLocal(propertyInfo.PropertyType);
                    WriteComma(methodIL, ref isFirst);
                    WriteString(methodIL, "\"" + propertyInfo.Name + "\":");
                    methodIL.Emit(OpCodes.Ldarg_0);
                    methodIL.Emit(OpCodes.Callvirt, propertyInfo.GetGetMethod());
                    methodIL.Emit(OpCodes.Stloc, temp1);
                    methodIL.Emit(OpCodes.Ldloca_S, temp1);
                    methodIL.Emit(OpCodes.Call, propertyInfo.PropertyType.GetMethod("get_HasValue", Type.EmptyTypes));
                    methodIL.Emit(OpCodes.Ldc_I4_0);
                    methodIL.Emit(OpCodes.Ceq);
                    methodIL.Emit(OpCodes.Brfalse_S, elseCase);
                    WriteString(methodIL, "null");
                    methodIL.Emit(OpCodes.Br_S, endCase);
                    methodIL.MarkLabel(elseCase);

                    if (dateTimeFormat == DateTimeFormat.LocalTimeNumber)
                    {
                        methodIL.Emit(OpCodes.Ldarg_1);
                        methodIL.Emit(OpCodes.Ldarg_0);
                        methodIL.Emit(OpCodes.Callvirt, propertyInfo.GetGetMethod());
                        methodIL.Emit(OpCodes.Stloc, temp1);
                        methodIL.Emit(OpCodes.Ldloca_S, temp1);
                        methodIL.Emit(OpCodes.Call, propertyInfo.PropertyType.GetMethod("get_Value", Type.EmptyTypes));
                        methodIL.Emit(OpCodes.Call, GetLocalTimeNumberMethodInfo);
                        methodIL.Emit(OpCodes.Stloc, longTime);
                        methodIL.Emit(OpCodes.Ldloca_S, longTime);
                        methodIL.Emit(OpCodes.Call, typeof(System.Int64).GetMethod("ToString", Type.EmptyTypes));
                        methodIL.Emit(OpCodes.Callvirt, writeMethodInfo);
                    }
                    else if (dateTimeFormat == DateTimeFormat.UTCTimeNumber)
                    {
                        methodIL.Emit(OpCodes.Ldarg_1);
                        methodIL.Emit(OpCodes.Ldarg_0);
                        methodIL.Emit(OpCodes.Callvirt, propertyInfo.GetGetMethod());
                        methodIL.Emit(OpCodes.Stloc, temp1);
                        methodIL.Emit(OpCodes.Ldloca_S, temp1);
                        methodIL.Emit(OpCodes.Call, propertyInfo.PropertyType.GetMethod("get_Value", Type.EmptyTypes));
                        methodIL.Emit(OpCodes.Call, GetUTCTimeNumberMethodInfo);
                        methodIL.Emit(OpCodes.Stloc, longTime);
                        methodIL.Emit(OpCodes.Ldloca_S, longTime);
                        methodIL.Emit(OpCodes.Call, typeof(System.Int64).GetMethod("ToString", Type.EmptyTypes));
                        methodIL.Emit(OpCodes.Callvirt, writeMethodInfo);
                    }
                    else if (dateTimeFormat == DateTimeFormat.LocalTimeString)
                    {
                        WriteString(methodIL, "\"");
                        methodIL.Emit(OpCodes.Ldarg_1);
                        methodIL.Emit(OpCodes.Ldarg_0);
                        methodIL.Emit(OpCodes.Callvirt, propertyInfo.GetGetMethod());
                        methodIL.Emit(OpCodes.Stloc, temp1);
                        methodIL.Emit(OpCodes.Ldloca_S, temp1);
                        methodIL.Emit(OpCodes.Call, propertyInfo.PropertyType.GetMethod("get_Value", Type.EmptyTypes));
                        methodIL.Emit(OpCodes.Call, GetLocalTimeStringMethodInfo);
                        methodIL.Emit(OpCodes.Callvirt, writeMethodInfo);
                        WriteString(methodIL, "\"");
                    }
                    else if (dateTimeFormat == DateTimeFormat.UTCTimeString)
                    {
                        WriteString(methodIL, "\"");
                        methodIL.Emit(OpCodes.Ldarg_1);
                        methodIL.Emit(OpCodes.Ldarg_0);
                        methodIL.Emit(OpCodes.Callvirt, propertyInfo.GetGetMethod());
                        methodIL.Emit(OpCodes.Stloc, temp1);
                        methodIL.Emit(OpCodes.Ldloca_S, temp1);
                        methodIL.Emit(OpCodes.Call, propertyInfo.PropertyType.GetMethod("get_Value", Type.EmptyTypes));
                        methodIL.Emit(OpCodes.Call, GetUTCTimeStringMethodInfo);
                        methodIL.Emit(OpCodes.Callvirt, writeMethodInfo);
                        WriteString(methodIL, "\"");
                    }
                    methodIL.MarkLabel(endCase);
                }
                else
                {
                    var longTime = methodIL.DeclareLocal(typeof(System.Int64));
                    WriteComma(methodIL, ref isFirst);
                    WriteString(methodIL, "\"" + propertyInfo.Name + "\":");

                    if (dateTimeFormat == DateTimeFormat.LocalTimeNumber)
                    {
                        methodIL.Emit(OpCodes.Ldarg_1);
                        methodIL.Emit(OpCodes.Ldarg_0);
                        methodIL.Emit(OpCodes.Callvirt, propertyInfo.GetGetMethod());
                        methodIL.Emit(OpCodes.Call, GetLocalTimeNumberMethodInfo);
                        methodIL.Emit(OpCodes.Stloc_S, longTime);
                        methodIL.Emit(OpCodes.Ldloca_S, longTime);
                        methodIL.Emit(OpCodes.Call, typeof(System.Int64).GetMethod("ToString", Type.EmptyTypes));
                        methodIL.Emit(OpCodes.Callvirt, writeMethodInfo);
                    }
                    else if (dateTimeFormat == DateTimeFormat.UTCTimeNumber)
                    {
                        methodIL.Emit(OpCodes.Ldarg_1);
                        methodIL.Emit(OpCodes.Ldarg_0);
                        methodIL.Emit(OpCodes.Callvirt, propertyInfo.GetGetMethod());
                        methodIL.Emit(OpCodes.Call, GetUTCTimeNumberMethodInfo);
                        methodIL.Emit(OpCodes.Stloc_S, longTime);
                        methodIL.Emit(OpCodes.Ldloca_S, longTime);
                        methodIL.Emit(OpCodes.Call, typeof(System.Int64).GetMethod("ToString", Type.EmptyTypes));
                        methodIL.Emit(OpCodes.Callvirt, writeMethodInfo);
                    }
                    else if (dateTimeFormat == DateTimeFormat.LocalTimeString)
                    {
                        WriteString(methodIL, "\"");
                        methodIL.Emit(OpCodes.Ldarg_1);
                        methodIL.Emit(OpCodes.Ldarg_0);
                        methodIL.Emit(OpCodes.Callvirt, propertyInfo.GetGetMethod());
                        methodIL.Emit(OpCodes.Call, GetLocalTimeStringMethodInfo);
                        methodIL.Emit(OpCodes.Callvirt, writeMethodInfo);
                        WriteString(methodIL, "\"");
                    }
                    else if (dateTimeFormat == DateTimeFormat.UTCTimeString)
                    {
                        WriteString(methodIL, "\"");
                        methodIL.Emit(OpCodes.Ldarg_1);
                        methodIL.Emit(OpCodes.Ldarg_0);
                        methodIL.Emit(OpCodes.Callvirt, propertyInfo.GetGetMethod());
                        methodIL.Emit(OpCodes.Call, GetUTCTimeStringMethodInfo);
                        methodIL.Emit(OpCodes.Callvirt, writeMethodInfo);
                        WriteString(methodIL, "\"");
                    }
                }
                #endregion
            }
            else if (propertyType == typeof(System.Boolean))
            {
                var temp = methodIL.DeclareLocal(propertyInfo.PropertyType);
                WriteComma(methodIL, ref isFirst);
                WriteString(methodIL, "\"" + propertyInfo.Name + "\":");
                if (isNullable)
                {
                    var isNullElseCase = methodIL.DefineLabel();
                    var isNullEndCase  = methodIL.DefineLabel();
                    methodIL.Emit(OpCodes.Ldarg_0);
                    methodIL.Emit(OpCodes.Callvirt, propertyInfo.GetGetMethod());
                    methodIL.Emit(OpCodes.Stloc_S, temp);
                    methodIL.Emit(OpCodes.Ldloca_S, temp);
                    methodIL.Emit(OpCodes.Call, propertyInfo.PropertyType.GetMethod("get_HasValue", Type.EmptyTypes));
                    methodIL.Emit(OpCodes.Ldc_I4_0);
                    methodIL.Emit(OpCodes.Ceq);
                    methodIL.Emit(OpCodes.Brfalse_S, isNullElseCase);
                    {
                        WriteString(methodIL, "null");
                    }
                    methodIL.Emit(OpCodes.Br_S, isNullEndCase);
                    methodIL.MarkLabel(isNullElseCase);
                    {
                        var elseCase = methodIL.DefineLabel();
                        var endCase  = methodIL.DefineLabel();
                        methodIL.Emit(OpCodes.Ldarg_1);
                        methodIL.Emit(OpCodes.Ldarg_0);
                        methodIL.Emit(OpCodes.Callvirt, propertyInfo.GetGetMethod());
                        methodIL.Emit(OpCodes.Stloc_S, temp);
                        methodIL.Emit(OpCodes.Ldloca_S, temp);
                        methodIL.Emit(OpCodes.Call, propertyInfo.PropertyType.GetMethod("get_Value", Type.EmptyTypes));
                        methodIL.Emit(OpCodes.Brtrue_S, elseCase);
                        {
                            methodIL.Emit(OpCodes.Ldstr, "false");
                        }
                        methodIL.Emit(OpCodes.Br_S, endCase);
                        methodIL.MarkLabel(elseCase);
                        {
                            methodIL.Emit(OpCodes.Ldstr, "true");
                        }
                        methodIL.MarkLabel(endCase);
                        methodIL.Emit(OpCodes.Callvirt, writeMethodInfo);
                    }
                    methodIL.MarkLabel(isNullEndCase);
                }
                else
                {
                    var elseCase = methodIL.DefineLabel();
                    var endCase  = methodIL.DefineLabel();
                    methodIL.Emit(OpCodes.Ldarg_1);
                    methodIL.Emit(OpCodes.Ldarg_0);
                    methodIL.Emit(OpCodes.Callvirt, propertyInfo.GetGetMethod());
                    methodIL.Emit(OpCodes.Brtrue_S, elseCase);
                    methodIL.Emit(OpCodes.Ldstr, "false");
                    methodIL.Emit(OpCodes.Br_S, endCase);
                    methodIL.MarkLabel(elseCase);
                    methodIL.Emit(OpCodes.Ldstr, "true");
                    methodIL.MarkLabel(endCase);
                    methodIL.Emit(OpCodes.Callvirt, writeMethodInfo);
                }
            }
        }
Exemplo n.º 52
0
 public static object GetValue(this PropertyInfo pi, object obj)
 {
     return(pi.GetGetMethod().Invoke(obj, Constants.EmptyObjectArray));
 }
Exemplo n.º 53
0
 public override bool SetupPropertyDelegates()
 {
     if (!base.SetupPropertyDelegates())
     {
         return(false);
     }
     try{
         System.Reflection.PropertyInfo info = DriveTarget.GetType().GetProperty(TargetProperty);
         this.GetTargetProp = (System.Func <U>)System.Delegate.CreateDelegate(typeof(System.Func <U>), DriveTarget, info.GetGetMethod());
     }
     catch {
         Debug.Log("Failed to retrieve getter for property:" + TargetProperty + ". Make sure that the property exists and is type " + typeof(T).Name, this);
     }
     return(true);
 }
Exemplo n.º 54
0
 public object InvokeGet(object target)
 {
     return(_property.GetGetMethod().Invoke(target, null));
 }
Exemplo n.º 55
0
        /// <summary>
        /// Recursively prints objects property names and values, as well as child objects
        /// </summary>
        /// <param name="prop">PropertyInfo object</param>
        /// <param name="o">The object it belongs to</param>
        /// <param name="linecount">How many lines we've printed since the last "...more"</param>
        /// <param name="more">How many lines to print before stopping and writing "...more"</param>
        /// <param name="prefix">Prefix for indentation of nested properties</param>
        /// <returns>Int - the current line counter</returns>
        public static int DumpConfigObject(System.Reflection.PropertyInfo prop, Object o, int linecount, int more, string prefix = null)
        {
            //don't print empty/null properties
            if (!String.IsNullOrEmpty(Convert.ToString(prop.GetValue(o, null))))
            {
                //some nice color highlighting of the names/values just to make the output more readable
                ConsoleColor propColor  = ConsoleColor.Gray;
                ConsoleColor nameColor  = ConsoleColor.Green;
                ConsoleColor valueColor = ConsoleColor.Yellow;
                Console.ForegroundColor = propColor;

                //prefix for indenting nested properties
                if (prefix != null)
                {
                    //use Cyan for nested properties names to break up the monotony
                    nameColor = ConsoleColor.Cyan;
                    Console.Write(prefix + "Property: ");
                }
                else
                {
                    Console.Write("Property: ");
                }

                Console.ForegroundColor = nameColor;
                Console.Write(prop.Name);
                Console.ForegroundColor = propColor;
                Console.Write(" = ");
                Console.ForegroundColor = valueColor;
                //write the property's value and retrieve current line count
                linecount = WriteLine(Convert.ToString(prop.GetValue(o, null)), linecount, more);

                //get the type of the property's value
                Type type = prop.GetValue(o, null).GetType();

                //for "primitive" types (or enums, strings) we are done. for anything else they can have nested objects
                //so we go through those and recurseively print them. arrays need to be handled somewhat specially because
                //they can
                if (!(type.IsPrimitive || type.Equals(typeof(string)) || type.BaseType.Equals(typeof(Enum))))
                {
                    var getMethod = prop.GetGetMethod();
                    if (prop.GetValue(o, null) is IEnumerable)
                    {
                        prefix = ((prefix != null) ? prefix : "") + "    ";
                        IEnumerable enumerableObject = (IEnumerable)getMethod.Invoke(o, null);
                        if (enumerableObject != null)
                        {
                            foreach (object element in enumerableObject)
                            {
                                Type elemType = element.GetType();
                                //if it's an array of primitives, just print each element. otherwise we need the recursive call
                                if (elemType.IsPrimitive || elemType.Equals(typeof(string)) || elemType.BaseType.Equals(typeof(Enum)))
                                {
                                    Console.ForegroundColor = propColor;
                                    Console.Write(prefix + "Element = ");
                                    Console.ForegroundColor = valueColor;
                                    linecount = WriteLine(Convert.ToString(element), linecount, more);
                                }
                                else
                                {
                                    //recursive call for arrays of objects
                                    foreach (PropertyInfo p in element.GetType().GetProperties())
                                    {
                                        linecount = DumpConfigObject(p, element, linecount, more, prefix);
                                    }
                                }
                            }
                        }
                    }
                    else
                    {
                        //this handles other types of objects that aren't arrays such as tables.table[x].columnList
                        prefix = ((prefix != null) ? prefix : "") + "    ";
                        foreach (PropertyInfo p in prop.GetValue(o, null).GetType().GetProperties())
                        {
                            linecount = DumpConfigObject(p, prop.GetValue(o, null), linecount, more, prefix);
                        }
                    }
                }
            }
            return(linecount);
        }
Exemplo n.º 56
0
        protected PropertyInfo[] GetProperties_impl(BindingFlags bf, Type reftype)
        {
            ArrayList        l = new ArrayList();
            bool             match;
            MethodAttributes mattrs;
            MethodInfo       accessor;

            initialize();

            PropertyInfo[] properties = GetProperties_internal(reftype);

            for (int i = 0; i < properties.Length; i++)
            {
                PropertyInfo c = properties [i];

                match    = false;
                accessor = c.GetGetMethod(true);
                if (accessor == null)
                {
                    accessor = c.GetSetMethod(true);
                }
                if (accessor == null)
                {
                    continue;
                }
                mattrs = accessor.Attributes;
                if ((mattrs & MethodAttributes.MemberAccessMask) == MethodAttributes.Public)
                {
                    if ((bf & BindingFlags.Public) != 0)
                    {
                        match = true;
                    }
                }
                else
                {
                    if ((bf & BindingFlags.NonPublic) != 0)
                    {
                        match = true;
                    }
                }
                if (!match)
                {
                    continue;
                }
                match = false;
                if ((mattrs & MethodAttributes.Static) != 0)
                {
                    if ((bf & BindingFlags.Static) != 0)
                    {
                        match = true;
                    }
                }
                else
                {
                    if ((bf & BindingFlags.Instance) != 0)
                    {
                        match = true;
                    }
                }
                if (!match)
                {
                    continue;
                }
                l.Add(c);
            }
            PropertyInfo[] result = new PropertyInfo [l.Count];
            l.CopyTo(result);
            return(result);
        }
Exemplo n.º 57
0
            internal ResourcePropertyInfo(System.Reflection.PropertyInfo propertyInfo)
            {
                ParameterExpression expression;

                this.PropertyInfo   = propertyInfo;
                this.PropertyGetter = (Func <object, object>)Expression.Lambda(Expression.Convert(Expression.Call(Expression.Convert(expression = Expression.Parameter(typeof(object), "instance"), propertyInfo.DeclaringType), propertyInfo.GetGetMethod()), typeof(object)), new ParameterExpression[] { expression }).Compile();
            }
Exemplo n.º 58
0
        private void FillPropertiesInformation()
        {
            MemberInfo[] tmpElements   = _emptyChildNodeInfos;
            MemberInfo[] tmpAttributes = _emptyChildNodeInfos;

            if (IsSimpleType)
            {
                return;
            }

            ArrayList elements   = new ArrayList();
            ArrayList attributes = new ArrayList();

            _attributesNamed = new HybridDictionary();
            int elementIndex   = 0;
            int attributeIndex = 0;

            R.MemberInfo[] members = _type.FindMembers(MemberTypes.Property | MemberTypes.Field, BindingFlags.Instance | BindingFlags.Public, null, null);
            SortMembersArray(members);
            foreach (R.MemberInfo mi in members)
            {
                // Create member info
                R.PropertyInfo pi          = mi as R.PropertyInfo;
                R.MethodInfo   piGetMethod = null;
                MemberInfo     nodeInfo    = null;
                if (pi != null)
                {
                    piGetMethod = pi.GetGetMethod();
                    if (piGetMethod != null && piGetMethod.GetParameters().Length == 0)
                    {
                        nodeInfo = new PropertyInfo(pi);
                    }
                    else
                    {
                        // This is not a property without arguments.
                        continue;
                    }
                }
                else
                {
                    R.FieldInfo fi = (R.FieldInfo)mi;
                    nodeInfo = new FieldInfo(fi);
                }

                nodeInfo._nodeName = mi.Name;

                // Get decorations for the original MemberInfo
                nodeInfo.GetDecorations(mi);

                if (pi != null)
                {
                    // Check for interface's attributes if the member is property
                    foreach (Type iface in _type.GetInterfaces())
                    {
                        int accessorIndex    = -1;
                        InterfaceMapping map = _type.GetInterfaceMap(iface);
                        for (int i = 0; i < map.TargetMethods.Length; i++)
                        {
                            if (map.TargetMethods[i] == piGetMethod)
                            {
                                accessorIndex = i;
                                break;
                            }
                        }
                        if (accessorIndex != -1)
                        {
                            R.MethodInfo ifaceMember = map.InterfaceMethods[accessorIndex];
                            foreach (R.PropertyInfo ifaceProperty in iface.GetProperties())
                            {
                                if (ifaceProperty.GetGetMethod() == ifaceMember)
                                {
                                    nodeInfo.GetDecorations(ifaceProperty);
                                    break;
                                }
                            }
                            break;
                        }
                    }
                }

                // Check for XmlIgnore attribute
                if (nodeInfo.XmlIgnore != null)
                {
                    continue;
                }

                nodeInfo.ProcessDecorations();

                TypeInfo declTypeInfo = TypeInfoCache.Instance.GetTypeInfo(mi.DeclaringType);
                string   declSchemaNs = declTypeInfo.Namespace;
                if (declTypeInfo.XmlType != null && declTypeInfo.XmlType.Namespace != null)
                {
                    declSchemaNs = declTypeInfo.XmlType.Namespace;
                }

                // Add member to the collection
                switch (nodeInfo.NodeType)
                {
                case XPathNodeType.Element:
                {
                    if ((nodeInfo.Form == XmlSchemaForm.None ||
                         nodeInfo.Form == XmlSchemaForm.Qualified) &&
                        nodeInfo._namespace == null)
                    {
                        // Take NS from declaring type
                        nodeInfo._namespace = declSchemaNs;
                    }

                    goto case XPathNodeType.Text;
                }

                case XPathNodeType.Text:
                {
                    // Add to array of elements
                    nodeInfo.Index = elementIndex++;
                    elements.Add(nodeInfo);
                    break;
                }

                default:                         // Attribute
                {
                    if (nodeInfo.Form == XmlSchemaForm.None)
                    {
                        if (nodeInfo._namespace == declSchemaNs)
                        {
                            nodeInfo._namespace = null;
                        }
                    }
                    else if (nodeInfo.Form == XmlSchemaForm.Qualified &&
                             nodeInfo._namespace == null)
                    {
                        // Take NS from declaring type
                        nodeInfo._namespace = declSchemaNs;
                    }


                    // Add to array of attributes
                    nodeInfo.Index = attributeIndex++;
                    attributes.Add(nodeInfo);
                    _attributesNamed.Add(new XmlQualifiedName(nodeInfo.Name, nodeInfo.Namespace), nodeInfo);
                    break;
                }
                }
            }

            if (elements.Count > 0)
            {
                tmpElements = (MemberInfo[])elements.ToArray(typeof(MemberInfo));
            }

            if (attributes.Count > 0)
            {
                tmpAttributes = (MemberInfo[])attributes.ToArray(typeof(MemberInfo));
            }

            _elements   = tmpElements;
            _attributes = tmpAttributes;
        }
Exemplo n.º 59
0
 public PropertyInfo(R.PropertyInfo pi)
 {
     _pi = pi;
     _getValueDelegate = GeneratePropertyGetter(_pi.GetGetMethod());
 }
        public GetSetGeneric(PropertyInfo info)
        {
            Name = info.Name;
            Info = info;
            CollectionType = Info.PropertyType.GetInterface ("IEnumerable", true) != null;
            var getMethod = info.GetGetMethod (true);
            var setMethod = info.GetSetMethod (true);
            if(getMethod == null)
            {

                Get = (o)=> {
                    return info.GetValue(o, null);
                };
                Set = (o,v) => {
                    info.SetValue(o, v, null);
                };
                return;
            }
            Get = (o) => {
                    return getMethod.Invoke (o, null);
            };
            Set = (o,v) => {
                try {
                    setMethod.Invoke (o, new [] {v});
                } catch (Exception e) {
                    Radical.LogWarning (string.Format("When setting {0} to {1} found {2}:", o.ToString(), v.ToString(), e.ToString ()));
                }
            };
        }