Пример #1
0
        private string GetDisplayName(object value, Type enumType)
        {
            FieldInfo[] fields;
            if (!_typeCache.TryGetValue(enumType, out fields))
            {
                fields = enumType.GetRuntimeFields()
                                   .Where(f => f.IsPublic && f.IsStatic)
                                   .ToArray();
                _typeCache[enumType] = fields;
            }

            var matchingField = fields.FirstOrDefault(
                f => Equals(f.GetValue(null), value));
            if (matchingField == null)
            {
                throw new MissingMemberException(String.Format("No matching field in the Enum '{0}' for value '{1}'", enumType.FullName, value));
            }
            string displayName = matchingField.Name;
            DisplayNameAttribute attr = matchingField.GetCustomAttribute<DisplayNameAttribute>();
            if (attr != null)
            {
                displayName = attr.Name;
            }
            return displayName;
        }
Пример #2
0
        private static IEnumerable<DependencyProperty> GetDependencyProperties(Type type)
        {
            List<DependencyProperty> propertyList = null;

            if (!DataBindingHelper.DependenciesPropertyCache.TryGetValue(type, out propertyList))
            {
                propertyList = new List<DependencyProperty>();

                while (type != null && type != typeof(DependencyObject))
                {
                    foreach (FieldInfo fieldInfo in type.GetRuntimeFields())
                    {
                        if (fieldInfo.IsPublic && fieldInfo.FieldType == typeof(DependencyProperty))
                        {
                            DependencyProperty property = fieldInfo.GetValue(null) as DependencyProperty;
                            if (property != null)
                            {
                                propertyList.Add(property);
                            }
                        }
                    }

                    type = type.GetTypeInfo().BaseType;
                }

                DataBindingHelper.DependenciesPropertyCache[type] = propertyList;
            }

            return propertyList;
        }
 public static void InjectIntoResxGeneratedApplicationResourcesClass(Type resxGeneratedApplicationResourcesClass)
 {
     resxGeneratedApplicationResourcesClass.GetRuntimeFields()
         .First(m => m.Name == "resourceMan")
         .SetValue(null, new WindowsRuntimeResourceManager(resxGeneratedApplicationResourcesClass.FullName,
             resxGeneratedApplicationResourcesClass.GetTypeInfo().Assembly));
 }
Пример #4
0
        private static string FormatCompledValue(object value, int depth, Type type)
        {
            if (depth == MAX_DEPTH)
                return String.Format("{0} {{ ... }}", type.Name);

            var fields = type.GetRuntimeFields()
                             .Where(f => f.IsPublic && !f.IsStatic)
                             .Select(f => new { name = f.Name, value = WrapAndGetFormattedValue(() => f.GetValue(value), depth) });
            var properties = type.GetRuntimeProperties()
                                 .Where(p => p.GetMethod != null && p.GetMethod.IsPublic && !p.GetMethod.IsStatic)
                                 .Select(p => new { name = p.Name, value = WrapAndGetFormattedValue(() => p.GetValue(value), depth) });
            var parameters = fields.Concat(properties)
                                   .OrderBy(p => p.name)
                                   .Take(MAX_OBJECT_PARAMETER_COUNT + 1)
                                   .ToList();

            if (parameters.Count == 0)
                return String.Format("{0} {{ }}", type.Name);

            var formattedParameters = String.Join(", ", parameters.Take(MAX_OBJECT_PARAMETER_COUNT)
                                                                  .Select(p => String.Format("{0} = {1}", p.name, p.value)));

            if (parameters.Count > MAX_OBJECT_PARAMETER_COUNT)
                formattedParameters += ", ...";

            return String.Format("{0} {{ {1} }}", type.Name, formattedParameters);
        }
        /// <summary>
        /// Describes the Guid  by looking for a FieldDescription attribute on the specified class
        /// </summary>
        public static string Describe(Type t, Guid guid)
        {
            // when we go to .NET 3.5, use LINQ for this
            foreach (var f in t
#if NETFX_CORE
                .GetRuntimeFields())
#else
                .GetFields(BindingFlags.Static | BindingFlags.Public))
#endif
            {
                if (f.IsPublic && f.IsStatic && f.FieldType == typeof (Guid) && (Guid) f.GetValue(null) == guid)
                {
                    foreach (var a in f.GetCustomAttributes(false))
                    {
                        var d = a as FieldDescriptionAttribute;
                        if (d != null)
                        {
                            return d.Description;
                        }
                    }
                    // no attribute, return the name
                    return f.Name;
                }
            }
            return guid.ToString();
        }
Пример #6
0
 public static string[] GetPrimaryKey(Type type) {
     return new MemberInfo[0]
         .Concat(type.GetRuntimeProperties())
         .Concat(type.GetRuntimeFields())
         .Where(m => m.GetCustomAttributes(true).Any(i => i.GetType().Name == "KeyAttribute"))
         .Select(m => m.Name)
         .OrderBy(i => i)
         .ToArray();
 }
Пример #7
0
 public LocalizationService(Context context, Type stringType)
 {
     _strings = stringType.GetRuntimeFields()
                         .Where(field => field.IsLiteral)
                         .ToDictionary(
                             field => field.Name,
                             field => context.GetString((int)field.GetRawConstantValue())
                         );
 }
Пример #8
0
        private static List<IConfigurationItem> GetItems(DroneConfiguration configuration, object section, Type type)
        {
            List<IConfigurationItem> configurationItems = new List<IConfigurationItem>();

            var configItems = type.GetRuntimeFields()
                .Where(field => field.GetValue(section) is IConfigurationItem);

            foreach (var configItem in configItems)
            {
                configurationItems.Add((IConfigurationItem)configItem.GetValue(section));
            }

            return configurationItems;
        }
        public static string FindSortableMember(Type entityType) {
            var candidates = Enumerable.Concat(
                entityType.GetRuntimeProperties()
                    .Where(i => i.CanRead && i.CanWrite && i.GetGetMethod(true).IsPublic && i.GetSetMethod(true).IsPublic)
                    .Select(i => new Candidate(i, i.PropertyType)),
                entityType.GetRuntimeFields()
                    .Where(i => i.IsPublic)
                    .Select(i => new Candidate(i, i.FieldType))
            );

            var codeFirstId = candidates.FirstOrDefault(IsEFCodeFirstConventionalKey);
            if(codeFirstId != null)
                return codeFirstId.Member.Name;

            return ORDERED_SORTABLE_TYPES.SelectMany(type => candidates.Where(c => c.Type == type)).FirstOrDefault()?.Member.Name;
        }
Пример #10
0
            public TypeInfo(Type t)
            {
                //discover properties
                IEnumerable<PropertyInfo> properties = t.GetRuntimeProperties();
                foreach (PropertyInfo pi in properties)
                {
                   string name = pi.Name;

                   if(pi.GetMethod != null)
                   {
                  _propNameToGetter[name] = _ => pi.GetMethod.Invoke(_, null);
                   }
                }

                //discover fields
                IEnumerable<FieldInfo> fields = t.GetRuntimeFields();
                foreach(FieldInfo fi in fields)
                {
                   string name = fi.Name;

                   _propNameToGetter[name] = _ => fi.GetValue(_);
                }
            }
Пример #11
0
 private static IEnumerable<DependencyProperty> GetDependencyProperties(Type type)
 {
     List<DependencyProperty> list = null;
     if (!DataBindingHelper.DependenciesPropertyCache.TryGetValue(type, out list))
     {
         list = new List<DependencyProperty>();
         while (type != null && type != typeof(DependencyObject))
         {
             foreach (FieldInfo current in type.GetRuntimeFields())
                 if (current.IsPublic && current.FieldType == typeof(DependencyProperty))
                 {
                     DependencyProperty dependencyProperty = current.GetValue(null) as DependencyProperty;
                     if (dependencyProperty != null)
                     {
                         list.Add(dependencyProperty);
                     }
                 }
         }
         type = type.GetTypeInfo().BaseType;
     }
     DataBindingHelper.DependenciesPropertyCache[type] = list;
     return list;
 }
Пример #12
0
 public static FieldInfo GetField(this Type type, string fieldName)
 {
     return(type.GetRuntimeFields().First(field => field.Name == fieldName));
 }
Пример #13
0
 private static FieldInfo GetField(Type type, string name)
 {
     return type.GetRuntimeFields().FirstOrDefault(m => !m.IsStatic && m.Name == name);
 }
		private static IEnumerable<SerializingMember> GetTargetMembers( Type type )
		{
#if DEBUG && !UNITY
			Contract.Assert( type != null, "type != null" );
#endif // DEBUG && !UNITY
#if !NETFX_CORE
			var members =
				type.FindMembers(
					MemberTypes.Field | MemberTypes.Property,
					BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance,
					null,
					null
				);
#else
			var members =
				type.GetRuntimeFields().Where( f => !f.IsStatic ).OfType<MemberInfo>()
					.Concat( type.GetRuntimeProperties().Where( p => p.GetMethod != null && !p.GetMethod.IsStatic ) )
					.ToArray();
#endif
			var filtered = members.Where( item => item.IsDefined( typeof( MessagePackMemberAttribute ) ) ).ToArray();

			if ( filtered.Length > 0 )
			{
				return GetAnnotatedMembersWithDuplicationDetection( type, filtered );
			}

			if ( type.GetCustomAttributesData().Any( attr =>
				attr.GetAttributeType().FullName == "System.Runtime.Serialization.DataContractAttribute" ) )
			{
				return GetSystemRuntimeSerializationCompatibleMembers( members );
			}

			return GetPublicUnpreventedMembers( members );
		}
Пример #15
0
 /// <summary>
 /// Gets the dependency properties from <paramref name="type"/>.
 /// </summary>
 /// <param name="type">The type to inspect.</param>
 /// <returns>The dependency properties.</returns>
 public static IEnumerable<DependencyProperty> GetDependencyProperties(Type type)
 {
     List<DependencyProperty> properties;
     if (!DependencyPropertyCache.TryGetValue(type, out properties))
     {
         properties = new List<DependencyProperty>();
         for (; type != null && type != typeof (DependencyObject); type = type.GetTypeInfo().BaseType)
         {
             foreach (var fieldInfo in type.GetRuntimeFields())
             {
                 if (fieldInfo.IsPublic && fieldInfo.FieldType == typeof (DependencyProperty))
                 {
                     var dependencyProperty = fieldInfo.GetValue(null) as DependencyProperty;
                     if (dependencyProperty != null)
                         properties.Add(dependencyProperty);
                 }
             }
         }
         DependencyPropertyCache[type] = properties;
     }
     return properties;
 }
Пример #16
0
 public static FieldInfo[] GetFields(this Type t)
 {
     return(t.GetRuntimeFields().ToArray <FieldInfo>());
 }
Пример #17
0
 public IEnumerable<FieldInfo> GetFields( Type type )
 {
     return type.GetRuntimeFields().Where( f => f.IsPublic );
 }
 public static IEnumerable <FieldInfo> GetFields(this Type type)
 {
     return(type.GetRuntimeFields());
 }
Пример #19
0
 /// <summary>
 /// Find field corresponding to object's runtime fields.
 /// </summary>
 public static FieldInfo LookupRuntimeFields(Type target)
 {
     return target.GetRuntimeFields().FirstOrDefault(ReflectionUtils.IsRuntimeFields);
 }
Пример #20
0
        /// <summary>
        /// Create an instance of <paramref name="type"/> using empty constructor.
        /// </summary>
        /// <param name="type">Type of object to create.</param>
        /// <returns>An instance of <paramref name="type"/>. If <paramref name="type"/> is value type or array type then same instance is returned every call.</returns>
        public static object CreateInstance(Type type)
#endif
        {
            if (type == null)
            {
                throw new ArgumentNullException("type");
            }

            var constructorFn = default(Func <object>);

            lock (DefaultConstructorCache)
            {
                if (DefaultConstructorCache.TryGetValue(type, out constructorFn) == false)
                {
#if !NETSTANDARD
                    var typeInfo                = type;
                    var constructors            = typeInfo.GetConstructors(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
                    var publicEmptyConstructor  = constructors.SingleOrDefault(c => c.GetParameters().Length == 0 && c.IsPublic && c.IsStatic == false);
                    var privateEmptyConstructor = constructors.SingleOrDefault(c => c.GetParameters().Length == 0 && !c.IsPublic && c.IsStatic == false);
                    var instanceField           = type.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static).FirstOrDefault(f =>
                                                                                                                                                    ConstructorSubstitutionMembers.Contains(f.Name) &&
                                                                                                                                                    type.IsAssignableFrom(f.FieldType)
                                                                                                                                                    );
                    var instanceProperty = type.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static).FirstOrDefault(p =>
                                                                                                                                                 ConstructorSubstitutionMembers.Contains(p.Name) &&
                                                                                                                                                 type.IsAssignableFrom(p.PropertyType) &&
                                                                                                                                                 p.CanRead && p.GetIndexParameters().Length == 0
                                                                                                                                                 );
#else
                    var typeInfo                = type.GetTypeInfo();
                    var constructors            = typeInfo.DeclaredConstructors.ToList();
                    var publicEmptyConstructor  = constructors.SingleOrDefault(c => c.GetParameters().Length == 0 && c.IsPublic && c.IsStatic == false);
                    var privateEmptyConstructor = constructors.SingleOrDefault(c => c.GetParameters().Length == 0 && c.IsPublic == false && c.IsStatic == false);
                    var instanceField           = type.GetRuntimeFields().FirstOrDefault(f =>
                                                                                         f.IsStatic &&
                                                                                         ConstructorSubstitutionMembers.Contains(f.Name) &&
                                                                                         IsAssignableFrom(type, f.FieldType)
                                                                                         );
                    var instanceProperty = type.GetRuntimeProperties().FirstOrDefault(p =>
                                                                                      p.GetMethod != null &&
                                                                                      p.GetMethod.IsStatic &&
                                                                                      ConstructorSubstitutionMembers.Contains(p.Name) &&
                                                                                      IsAssignableFrom(type, p.PropertyType) &&
                                                                                      p.GetIndexParameters().Length == 0
                                                                                      );
#endif

                    if (publicEmptyConstructor != null)
                    {
                        var createNewObjectExpr = Expression.Lambda <Func <object> >
                                                  (
                            Expression.Convert
                            (
                                Expression.New(publicEmptyConstructor),
                                typeof(object)
                            )
                                                  );

                        constructorFn = createNewObjectExpr.Compile();
                    }
                    else if (instanceField != null)
                    {
                        var getInstanceFieldExpr = Expression.Lambda <Func <object> >
                                                   (
                            Expression.Convert
                            (
                                Expression.Field(null, instanceField),
                                typeof(object)
                            )
                                                   );
                        constructorFn = getInstanceFieldExpr.Compile();
                    }
                    else if (instanceProperty != null)
                    {
                        var getInstancePropertyExpr = Expression.Lambda <Func <object> >
                                                      (
                            Expression.Convert
                            (
                                Expression.Property(null, instanceProperty),
                                typeof(object)
                            )
                                                      );
                        constructorFn = getInstancePropertyExpr.Compile();
                    }
                    else if (privateEmptyConstructor != null)
                    {
                        var createNewObjectExpr = Expression.Lambda <Func <object> >
                                                  (
                            Expression.Convert
                            (
                                Expression.New(privateEmptyConstructor),
                                typeof(object)
                            )
                                                  );

                        constructorFn = createNewObjectExpr.Compile();
                    }
                    else if (type.IsArray && type.GetArrayRank() == 1)
                    {
                        var elementType = type.GetElementType();
                        Debug.Assert(elementType != null, "elementType != null");
                        var createNewArrayExpr = Expression.Lambda <Func <object> >
                                                 (
                            Expression.Convert
                            (
                                Expression.Constant(Array.CreateInstance(elementType, 0)),
                                typeof(object)
                            )
                                                 );

                        constructorFn = createNewArrayExpr.Compile();
                    }
                    else if (typeInfo.IsValueType)
                    {
                        var createNewValueTypeExpr = Expression.Lambda <Func <object> >
                                                     (
                            Expression.Constant
                            (
                                Activator.CreateInstance(type),
                                typeof(object)
                            )
                                                     );

                        constructorFn = createNewValueTypeExpr.Compile();
                    }

                    DefaultConstructorCache[type] = constructorFn;
                }
            }

#if !NETSTANDARD
            if (constructorFn == null && forceCreate)
            {
                return(Runtime.Serialization.FormatterServices.GetSafeUninitializedObject(type));
            }
#endif
            if (constructorFn == null)
            {
                throw new ArgumentException(string.Format("Type '{0}' does not contains default empty constructor.", type), "type");
            }
            else
            {
                return(constructorFn());
            }
        }
Пример #21
0
		private static void GetObjectValues(Type objType, object obj, SerializationInfo graph) {
#if PCL
			var fields =
				objType.GetRuntimeFields()
					.Where(x => !x.IsStatic && !x.IsDefined(typeof (NonSerializedAttribute)) && !x.Name.EndsWith("_BackingField"));
			var properties = objType.GetRuntimeProperties()
				.Where(x => !x.IsStatic() && x.CanWrite && !x.IsDefined(typeof (NonSerializedAttribute)));
#else
			var fields = objType.GetFields(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public)
				.Where(x => !x.IsDefined(typeof (NonSerializedAttribute), false) && !x.Name.EndsWith("_BackingField"));
			var properties = objType.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)
				.Where(x => !x.IsDefined(typeof (NonSerializedAttribute), false) && x.CanRead);
#endif

			var members = new List<MemberInfo>();
			members.AddRange(fields.Cast<MemberInfo>());
			members.AddRange(properties.Cast<MemberInfo>());

			foreach (var member in members) {
				var memberName = member.Name;
				Type memberType;

				object value;
				if (member is FieldInfo) {
					value = ((FieldInfo) member).GetValue(obj);
					memberType = ((FieldInfo) member).FieldType;
				} else if (member is PropertyInfo) {
					value = ((PropertyInfo) member).GetValue(obj, null);
					memberType = ((PropertyInfo) member).PropertyType;
				} else {
					throw new NotSupportedException();
				}

				graph.AddValue(memberName, value, memberType);
			}
		}
Пример #22
0
 /// <summary>
 /// Gets all fields of a given type.
 /// </summary>
 /// <param name="type">Type of properties.</param>
 /// <returns>List of propertyies</returns>
 public IEnumerable<FieldInfo> GetFields(Type type)
 {
     return type.GetRuntimeFields();
 }
Пример #23
0
 public virtual FieldInfo FindField(Type modelType, string expression)
 {
     return 
         modelType.GetRuntimeFields()
             .FirstOrDefault(p => p.Name.Equals(expression, StringComparison.OrdinalIgnoreCase));
 }
Пример #24
0
        internal static TType GetFromField(Type type)
        {
            while (type != null)
            {
                foreach (FieldInfo field in type.GetRuntimeFields())
                    if (field.IsStatic && field.Name == "TYPE")
                        if (field.FieldType == typeof(TType) || field.FieldType == typeof(org.objectfabric.TType))
                            return (TType) field.GetValue(null);

                type = type.GetTypeInfo().BaseType;
            }

            return null;
        }
        internal void  buildFieldList(StorageImpl storage, Type cls, ArrayList list)
        {
#if WINRT_NET_FRAMEWORK
           Type superclass = cls.GetTypeInfo().BaseType;
#else
           Type superclass = cls.BaseType;
#endif
            if (superclass != null
#if !SILVERLIGHT
                && superclass != typeof(MarshalByRefObject)
#endif
                )
            {
                buildFieldList(storage, superclass, list);
            }
#if !COMPACT_NET_FRAMEWORK && !SILVERLIGHT
            bool isWrapper = typeof(PersistentWrapper).IsAssignableFrom(cls);
            bool hasTransparentAttribute = cls.GetCustomAttributes(typeof(TransparentPersistenceAttribute), true).Length != 0;
#else
            bool hasTransparentAttribute = false;
#endif
#if WINRT_NET_FRAMEWORK
            bool serializeProperties = cls.GetTypeInfo().GetCustomAttributes(typeof(SerializePropertiesAttribute), true).GetEnumerator().MoveNext();
#else
            bool serializeProperties = cls.GetCustomAttributes(typeof(SerializePropertiesAttribute), true).Length != 0;
#endif
            if (serializeProperties)
            {
#if WINRT_NET_FRAMEWORK
                PropertyInfo[] props = Enumerable.ToArray<PropertyInfo>(cls.GetRuntimeProperties());
#else
                PropertyInfo[] props = cls.GetProperties(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.DeclaredOnly);
#endif
                Array.Sort(props, 0, props.Length, fieldComparator);
                for (int i = 0; i < props.Length; i++)
                {
                    PropertyInfo prop = props[i];
#if WINRT_NET_FRAMEWORK
                    if (prop.GetCustomAttributes(typeof(NonSerializedAttribute), true).GetEnumerator().MoveNext()
                        || prop.GetCustomAttributes(typeof(TransientAttribute), true).GetEnumerator().MoveNext())
#else
                        if (prop.GetCustomAttributes(typeof(NonSerializedAttribute), true).Length != 0
                        || prop.GetCustomAttributes(typeof(TransientAttribute), true).Length != 0)
#endif
                    {
                        continue;
                    }
                    FieldDescriptor fd = new FieldDescriptor();
                    fd.property = prop;
                    fd.fieldName = prop.Name;
                    fd.className = getTypeName(cls);
                    Type fieldType = prop.PropertyType;
                    FieldType type = getTypeCode(fieldType);
                    switch (type) 
                    {
#if USE_GENERICS
                        case FieldType.tpArrayOfOid:
                            fd.constructor = GetConstructor(fieldType, "ConstructArray");
                            hasReferences = true;
                            break;
                        case FieldType.tpLink:
                            fd.constructor = GetConstructor(fieldType, "ConstructLink");
                            hasReferences = true;
                            break;
#else
                        case FieldType.tpArrayOfOid:
                        case FieldType.tpLink:
#endif
                        case FieldType.tpArrayOfObject:
                        case FieldType.tpObject:
                            hasReferences = true;
                            if (hasTransparentAttribute && isPerstInternalType(fieldType))
                            {
                                fd.recursiveLoading = true; 
                            }
                            break;
                        case FieldType.tpValue:
                        case FieldType.tpNullableValue:
                            fd.valueDesc = storage.getClassDescriptor(fieldType);
                            hasReferences |= fd.valueDesc.hasReferences;
                            break;
                        case FieldType.tpArrayOfValue:
                            fd.valueDesc = storage.getClassDescriptor(fieldType.GetElementType());
                            hasReferences |= fd.valueDesc.hasReferences;
                            break;
                    }
                    fd.type = type;
                    list.Add(fd);
                }
            }   
            else  
            {            
#if WINRT_NET_FRAMEWORK
                FieldInfo[] flds = Enumerable.ToArray<FieldInfo>(cls.GetRuntimeFields());
#else
                FieldInfo[] flds = cls.GetFields(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.DeclaredOnly);
#endif
                Array.Sort(flds, 0, flds.Length, fieldComparator);
                for (int i = 0; i < flds.Length; i++)
                {
                    FieldInfo f = flds[i];
#if WINRT_NET_FRAMEWORK
                    if (!f.IsStatic && !typeof(Delegate).GetTypeInfo().IsAssignableFrom(f.FieldType.GetTypeInfo()))
#else
                    if (!f.IsNotSerialized && !f.IsStatic && !typeof(Delegate).IsAssignableFrom(f.FieldType))
#endif
                    {
#if WINRT_NET_FRAMEWORK
                        if (f.GetCustomAttributes(typeof(NonSerializedAttribute), true).GetEnumerator().MoveNext()
                            || f.GetCustomAttributes(typeof(TransientAttribute), true).GetEnumerator().MoveNext())
#else
                            if (f.GetCustomAttributes(typeof(NonSerializedAttribute), true).Length != 0
                            || f.GetCustomAttributes(typeof(TransientAttribute), true).Length != 0)
#endif
                        {
                            continue;
                        }
                        FieldDescriptor fd = new FieldDescriptor();
                        fd.field = f;
                        fd.fieldName = f.Name;
                        fd.className = getTypeName(cls);
                        Type fieldType = f.FieldType;
                        FieldType type = getTypeCode(fieldType);
                        switch (type) 
                        {
#if !COMPACT_NET_FRAMEWORK && !SILVERLIGHT
                            case FieldType.tpInt:
                                if (isWrapper && isObjectProperty(cls, f)) 
                                {
                                    hasReferences = true;
                                    type = FieldType.tpOid;
                                } 
                                break;
#endif
#if USE_GENERICS
                            case FieldType.tpArrayOfOid:
                                fd.constructor = GetConstructor(fieldType, "ConstructArray");
                                hasReferences = true;
                                break;
                            case FieldType.tpLink:
                                fd.constructor = GetConstructor(fieldType, "ConstructLink");
                                hasReferences = true;
                                break;
#else
                            case FieldType.tpArrayOfOid:
                            case FieldType.tpLink:
#endif
                            case FieldType.tpArrayOfObject:
                            case FieldType.tpObject:
                                hasReferences = true;
                                if (hasTransparentAttribute && isPerstInternalType(fieldType))
                                {
                                    fd.recursiveLoading = true; 
                                }
                                break;
                            case FieldType.tpValue:
                            case FieldType.tpNullableValue:
                                fd.valueDesc = storage.getClassDescriptor(fieldType);
                                hasReferences |= fd.valueDesc.hasReferences;
                                break;
                            case FieldType.tpArrayOfValue:
                                fd.valueDesc = storage.getClassDescriptor(fieldType.GetElementType());
                                hasReferences |= fd.valueDesc.hasReferences;
                                break;
                        }
                        fd.type = type;
                        list.Add(fd);
                    }
                }
            }
        }
Пример #26
0
		// internal for testing
		internal static IEnumerable<SerializingMember> GetTargetMembers( Type type )
		{
#if DEBUG && !UNITY
			Contract.Assert( type != null );
#endif // DEBUG && !UNITY
#if !NETFX_CORE
			var members =
				type.FindMembers(
					MemberTypes.Field | MemberTypes.Property,
					BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance,
					( member, criteria ) => CheckTargetEligibility( member ),
					null
				);
			var filtered = members.Where( item => Attribute.IsDefined( item, typeof( MessagePackMemberAttribute ) ) ).ToArray();
#else
			var members =
				type.GetRuntimeFields().Where( f => !f.IsStatic ).OfType<MemberInfo>()
					.Concat( type.GetRuntimeProperties().Where( p => p.GetMethod != null && !p.GetMethod.IsStatic ) )
					.Where( CheckTargetEligibility );
			var filtered = members.Where( item => item.IsDefined( typeof( MessagePackMemberAttribute ) ) ).ToArray();
#endif

			if ( filtered.Length > 0 )
			{
				return
					filtered.Select( member =>
						new SerializingMember(
							member,
							new DataMemberContract( member, member.GetCustomAttribute<MessagePackMemberAttribute>() )
						)
					);
			}

			if ( type.GetCustomAttributesData().Any( attr =>
				attr.GetAttributeType().FullName == "System.Runtime.Serialization.DataContractAttribute" ) )
			{
				return
					members.Select(
						item =>
						new
						{
							member = item,
							data = item.GetCustomAttributesData()
								.FirstOrDefault(
									data => data.GetAttributeType().FullName == "System.Runtime.Serialization.DataMemberAttribute" )
						}
					).Where( item => item.data != null )
					.Select(
						item =>
						{
							var name = item.data.GetNamedArguments()
								.Where( arg => arg.GetMemberName() == "Name" )
								.Select( arg => ( string )arg.GetTypedValue().Value )
								.FirstOrDefault();
							var id = item.data.GetNamedArguments()
								.Where( arg => arg.GetMemberName() == "Order" )
								.Select( arg => ( int? ) arg.GetTypedValue().Value )
								.FirstOrDefault();
#if SILVERLIGHT
							if ( id == -1 )
							{
								// Shim for Silverlight returns -1 because GetNamedArguments() extension method cannot recognize whether the argument was actually specified or not.
								id = null;
							}
#endif // SILVERLIGHT

							return
								new SerializingMember(
									item.member,
									new DataMemberContract( item.member, name, NilImplication.MemberDefault, id )
								);
						}
					);
			}
#if SILVERLIGHT || NETFX_CORE
			return members.Where( member => member.GetIsPublic() ).Select( member => new SerializingMember( member, new DataMemberContract( member ) ) );
#else
			return
				members.Where( item => item.GetIsPublic() && !Attribute.IsDefined( item, typeof( NonSerializedAttribute ) ) )
				.Select( member => new SerializingMember( member, new DataMemberContract( member ) ) );
#endif
		}
Пример #27
0
		private object DeserializeType(BinaryReader reader, Type graphType) {
			object obj;

#if !PCL
			if (graphType.IsValueType) {
#else
			if (graphType.IsValueType()) {
#endif
				obj = Activator.CreateInstance(graphType);
			} else {
				var ctor = GetDefaultConstructor(graphType);
				if (ctor == null)
					throw new NotSupportedException(String.Format("The type '{0}' does not specify any default empty constructor.", graphType));

				obj = ctor.Invoke(new object[0]);
			}

#if PCL
			var fields = graphType.GetRuntimeFields().Where(x => !x.IsStatic && !x.IsDefined(typeof(NonSerializedAttribute)));
			var properties =
				graphType.GetRuntimeProperties()
					.Where(x => !x.IsStatic() && x.CanWrite && !x.IsDefined(typeof (NonSerializedAttribute)));
#else
			var fields = graphType.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)
				.Where(member => !member.IsDefined(typeof (NonSerializedAttribute), false));
			var properties = graphType.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)
				.Where(member => member.CanWrite && !member.IsDefined(typeof (NonSerializedAttribute), false));
#endif

			var members = new List<MemberInfo>();
			members.AddRange(fields.Cast<MemberInfo>());
			members.AddRange(properties.Cast<MemberInfo>());

			var values = new Dictionary<string, object>();
			ReadValues(reader, Encoding, values);

			foreach (var member in members) {
				var memberName = member.Name;
				object value;

				if (values.TryGetValue(memberName, out value)) {
					// TODO: convert the source value to the destination value...

					if (member is PropertyInfo) {
						var property = (PropertyInfo) member;
						property.SetValue(obj, value, null);
					} else if (member is FieldInfo) {
						var field = (FieldInfo) member;
						field.SetValue(obj, value);
					}
				}
			}

			return obj;
		}

		private ConstructorInfo GetDefaultConstructor(Type type) {
#if PCL
			return type.GetConstructorOrNull(true);
#else
			var ctors = type.GetConstructors(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
			foreach (var ctor in ctors) {
				if (ctor.GetParameters().Length == 0)
					return ctor;
			}

			return null;
#endif
		}
Пример #28
0
        private void InitializePrimitives()
        {
            this.primitiveMap = new Dictionary <long, SyncPrimitive>();
            this.primitives   = new List <SyncPrimitive>();

            // Scan the type of object this is a look for the SyncDataAttribute
            System.Type baseType = this.GetType();

#if USE_WINRT
            var typeFields = baseType.GetRuntimeFields();
#else
            var typeFields = baseType.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
#endif

            foreach (FieldInfo typeField in typeFields)
            {
                SyncDataAttribute attribute = null;

#if USE_WINRT
                attribute = typeField.GetCustomAttribute <SyncDataAttribute>(true);
#else
                object[] customAttributes = typeField.GetCustomAttributes(typeof(SyncDataAttribute), true);
                if (customAttributes.Length > 0)
                {
                    attribute = customAttributes[0] as SyncDataAttribute;
                }
#endif

                if (attribute != null)
                {
                    System.Type fieldType  = typeField.FieldType;
                    string      memberName = typeField.Name;

                    // Override the member name if provided
                    if (!string.IsNullOrEmpty(attribute.CustomFieldName))
                    {
                        memberName = attribute.CustomFieldName;
                    }

                    // Auto instantiate the primitive if it doesn't already exist
                    SyncPrimitive dataPrimitive = typeField.GetValue(this) as SyncPrimitive;
                    if (dataPrimitive == null)
                    {
                        try
                        {
                            // Constructors are not inherited, as per Section 1.6.7.1 of the C# Language Specification.
                            // This means that if a class subclasses Object or Primitive, they must either declare a constructor
                            // that takes the "memberName" property or use the default (parameter less constructor).

                            // First check if there is a constructor that takes the member name and if so call it
                            bool hasConstructor = fieldType.GetConstructor(new Type[] { typeof(string) }) != null;
                            if (hasConstructor)
                            {
                                dataPrimitive = (SyncPrimitive)Activator.CreateInstance(fieldType, new object[] { memberName });
                            }
                            else
                            {
                                // Fallback on using the default constructor and manually assign the member name
                                dataPrimitive           = (SyncPrimitive)Activator.CreateInstance(fieldType, null);
                                dataPrimitive.FieldName = memberName;
                            }

                            typeField.SetValue(this, dataPrimitive);
                        }
                        catch (Exception ex)
                        {
                            Debug.LogWarningFormat("Unable to create SyncPrimitive of type {0}.  Exception: {1}", memberName, ex);
                        }
                    }

                    if (dataPrimitive != null)
                    {
                        // Register the child
                        AddChild(dataPrimitive);
                    }
                }
            }
        }
Пример #29
0
        // Debug
        internal override bool shallowEquals(object a, object b, Type c, string[] exceptions)
        {
            if (!Debug.ENABLED)
                throw new Exception();

            if (a.GetType() != b.GetType())
                return false;

            if (c.IsArray)
            {
                Object[] x = (Object[]) a;
                Object[] y = (Object[]) b;

                if (x.Length != y.Length)
                    return false;

                for (int i = 0; i < x.Length; i++)
                    if (!referenceLevelEquals(c.GetElementType(), x[i], y[i]))
                        return false;
            }

            List<FieldInfo> exceptionFields = new List<FieldInfo>();

            // BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static
            foreach (FieldInfo field in c.GetRuntimeFields())
                if (Array.IndexOf(exceptions, field.Name) >= 0)
                    exceptionFields.Add(field);

            Debug.assertion(exceptionFields.Count == exceptions.Length);

            foreach (FieldInfo field in c.GetRuntimeFields())
            {
                if (Array.IndexOf(exceptions, field.Name) < 0)
                {
                    if (!field.IsStatic)
                    {
                        if (!field.IsInitOnly)
                        {
                            Object x = field.GetValue(a);
                            Object y = field.GetValue(b);

                            if (!referenceLevelEquals(field.FieldType, x, y))
                                return false;
                        }
                    }
                }
            }

            return true;
        }