/// <summary>
        /// Gets the serializable members for the type.
        /// </summary>
        /// <param name="objectType">The type to get serializable members for.</param>
        /// <returns>The serializable members for the type.</returns>
        protected virtual List <MemberInfo> GetSerializableMembers(Type objectType)
        {
#if !PocketPC
            DataContractAttribute dataContractAttribute = JsonTypeReflector.GetDataContractAttribute(objectType);
#endif

            List <MemberInfo> defaultMembers = ReflectionUtils.GetFieldsAndProperties(objectType, DefaultMembersSearchFlags);
            List <MemberInfo> allMembers     = ReflectionUtils.GetFieldsAndProperties(objectType, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static);

            List <MemberInfo> serializableMembers = new List <MemberInfo>();
            foreach (MemberInfo member in allMembers)
            {
                if (defaultMembers.Contains(member))
                {
                    serializableMembers.Add(member);
                }
                else
                {
                    if (JsonTypeReflector.GetAttribute <JsonPropertyAttribute>(member) != null)
                    {
                        serializableMembers.Add(member);
                    }
#if !PocketPC
                    else if (dataContractAttribute != null && JsonTypeReflector.GetAttribute <DataMemberAttribute>(member) != null)
                    {
                        serializableMembers.Add(member);
                    }
#endif
                }
            }

            return(serializableMembers);
        }
示例#2
0
        private static string CheckType(Type type)
        {
            bool   flag = false;
            string txt  = "";

            txt += string.Format("检查类型:{0}\n", type);
            DataContractAttribute attribute = type.GetCustomAttribute <DataContractAttribute>();

            if (attribute == null)
            {
                txt += string.Format("没有 DataContract !!\n");
                flag = true;
            }

            foreach (PropertyInfo propertyInfo in type.GetProperties())
            {
                DataMemberAttribute attribute2 = propertyInfo.GetCustomAttribute <DataMemberAttribute>();
                if (attribute2 == null)
                {
                    txt += string.Format("没有DataMember:{0}\n", propertyInfo);
                    flag = true;
                }
            }

            txt += string.Format("\n");
            if (flag)
            {
                return(txt);
            }
            return("");
        }
示例#3
0
        internal void GetStableName(DataContractAttribute dataContractAttribute, out string name, out string ns)
        {
            name = null;
            ns   = null;
            if (dataContractAttribute == null)
            {
                GetDefaultStableName(this.UnderlyingType, out name, out ns);
            }
            else
            {
                if (dataContractAttribute.Name == null || dataContractAttribute.Name.Length == 0)
                {
                    GetDefaultStableName(this.UnderlyingType, out name, out ns);
                }
                else
                {
                    name = dataContractAttribute.Name;
                }

                if (dataContractAttribute.Namespace == null)
                {
                    //TODO,sowmys: Use DataContractNamespaceAttribute if one is provided
                    if (ns == null)
                    {
                        string defName;

                        GetDefaultStableName(this.UnderlyingType, out defName, out ns);
                    }
                }
                else
                {
                    ns = dataContractAttribute.Namespace;
                }
            }
        }
示例#4
0
        /// <summary>
        /// Creates a <see cref="CodeAttributeDeclaration"/> for a <see cref="DataContractAttribute"/>
        /// </summary>
        /// <param name="sourceType">The type to which the attribute will be applied (to use as a reference)</param>
        /// <param name="codeGenerator">The client proxy generator</param>
        /// <param name="referencingType">The type referencing this declaration</param>
        /// <returns>The new attribute declaration</returns>
        internal static CodeAttributeDeclaration CreateDataContractAttributeDeclaration(Type sourceType, CodeDomClientCodeGenerator codeGenerator, CodeTypeDeclaration referencingType)
        {
            CodeAttributeDeclaration dataContractAttrib = CodeGenUtilities.CreateAttributeDeclaration(typeof(System.Runtime.Serialization.DataContractAttribute), codeGenerator, referencingType);

            string dataContractNamespace = CodeGenUtilities.GetContractNamespace(sourceType);
            string dataContractName      = null;

            // If the user specified a DataContract, we should copy the namespace and name.
            DataContractAttribute sourceDataContractAttrib = (DataContractAttribute)Attribute.GetCustomAttribute(sourceType, typeof(DataContractAttribute));

            if (sourceDataContractAttrib != null)
            {
                if (sourceDataContractAttrib.Namespace != null)
                {
                    dataContractNamespace = sourceDataContractAttrib.Namespace;
                }
                if (sourceDataContractAttrib.Name != null)
                {
                    dataContractName = sourceDataContractAttrib.Name;
                }
            }

            dataContractAttrib.Arguments.Add(new CodeAttributeArgument("Namespace", new CodePrimitiveExpression(dataContractNamespace)));
            if (dataContractName != null)
            {
                dataContractAttrib.Arguments.Add(new CodeAttributeArgument("Name", new CodePrimitiveExpression(dataContractName)));
            }
            return(dataContractAttrib);
        }
示例#5
0
        public static MemberSerialization GetObjectMemberSerialization(Type objectType, bool ignoreSerializableAttribute)
        {
            JsonObjectAttribute objectAttribute = GetCachedAttribute <JsonObjectAttribute>(objectType);

            if (objectAttribute != null)
            {
                return(objectAttribute.MemberSerialization);
            }

            DataContractAttribute dataContractAttribute = GetDataContractAttribute(objectType);

            if (dataContractAttribute != null)
            {
                return(MemberSerialization.OptIn);
            }

            if (!ignoreSerializableAttribute)
            {
                SerializableAttribute serializableAttribute = GetCachedAttribute <SerializableAttribute>(objectType);
                if (serializableAttribute != null)
                {
                    return(MemberSerialization.Fields);
                }
            }

            // the default
            return(MemberSerialization.OptOut);
        }
示例#6
0
        public static MemberSerialization GetObjectMemberSerialization(Type objectType, bool ignoreSerializableAttribute)
        {
            JsonObjectAttribute objectAttribute = GetJsonObjectAttribute(objectType);

            if (objectAttribute != null)
            {
                return(objectAttribute.MemberSerialization);
            }

#if !PocketPC && !NET20
            DataContractAttribute dataContractAttribute = GetDataContractAttribute(objectType);
            if (dataContractAttribute != null)
            {
                return(MemberSerialization.OptIn);
            }
#endif

#if !(SILVERLIGHT || NETFX_CORE || PORTABLE)
            if (!ignoreSerializableAttribute)
            {
                SerializableAttribute serializableAttribute = GetSerializableAttribute(objectType);
                if (serializableAttribute != null)
                {
                    return(MemberSerialization.Fields);
                }
            }
#endif

            // the default
            return(MemberSerialization.OptOut);
        }
        protected virtual List <MemberInfo> GetSerializableMembers(Type objectType)
        {
            DataContractAttribute dataContractAttribute = JsonTypeReflector.GetDataContractAttribute(objectType);
            List <MemberInfo>     list = (from m in ReflectionUtils.GetFieldsAndProperties(objectType, DefaultMembersSearchFlags)
                                          where !ReflectionUtils.IsIndexedProperty(m)
                                          select m).ToList();
            List <MemberInfo> list2 = (from m in ReflectionUtils.GetFieldsAndProperties(objectType, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic)
                                       where !ReflectionUtils.IsIndexedProperty(m)
                                       select m).ToList();
            List <MemberInfo> list3 = new List <MemberInfo>();

            foreach (MemberInfo item in list2)
            {
                if (SerializeCompilerGeneratedMembers || !item.IsDefined(typeof(CompilerGeneratedAttribute), inherit: true))
                {
                    if (list.Contains(item))
                    {
                        list3.Add(item);
                    }
                    else if (JsonTypeReflector.GetAttribute <JsonPropertyAttribute>(item) != null)
                    {
                        list3.Add(item);
                    }
                    else if (dataContractAttribute != null && JsonTypeReflector.GetAttribute <DataMemberAttribute>(item) != null)
                    {
                        list3.Add(item);
                    }
                }
            }
            if (objectType.AssignableToTypeName("System.Data.Objects.DataClasses.EntityObject", out Type _))
            {
                list3 = list3.Where(ShouldSerializeEntityMember).ToList();
            }
            return(list3);
        }
示例#8
0
 /// <summary>
 /// Gets the namespace from an attribute marked on the type's definition
 /// </summary>
 /// <param name="type"></param>
 /// <returns>Namespace of type</returns>
 public static string GetNamespace(Type type)
 {
     Attribute[] attrs = (Attribute[])type.GetCustomAttributes(typeof(DataContractAttribute), true);
     if (attrs.Length > 0)
     {
         DataContractAttribute dcAttr = (DataContractAttribute)attrs[0];
         return(dcAttr.Namespace);
     }
     attrs = (Attribute[])type.GetCustomAttributes(typeof(XmlRootAttribute), true);
     if (attrs.Length > 0)
     {
         XmlRootAttribute xmlAttr = (XmlRootAttribute)attrs[0];
         return(xmlAttr.Namespace);
     }
     attrs = (Attribute[])type.GetCustomAttributes(typeof(XmlTypeAttribute), true);
     if (attrs.Length > 0)
     {
         XmlTypeAttribute xmlAttr = (XmlTypeAttribute)attrs[0];
         return(xmlAttr.Namespace);
     }
     attrs = (Attribute[])type.GetCustomAttributes(typeof(XmlElementAttribute), true);
     if (attrs.Length > 0)
     {
         XmlElementAttribute xmlAttr = (XmlElementAttribute)attrs[0];
         return(xmlAttr.Namespace);
     }
     return(null);
 }
示例#9
0
        public static MemberSerialization GetObjectMemberSerialization(Type objectType, bool ignoreSerializableAttribute)
        {
            JsonObjectAttribute objectAttribute = GetCachedAttribute <JsonObjectAttribute>(objectType);

            if (objectAttribute != null)
            {
                return(objectAttribute.MemberSerialization);
            }

#if HAVE_DATA_CONTRACTS
            DataContractAttribute dataContractAttribute = GetDataContractAttribute(objectType);
            if (dataContractAttribute != null)
            {
                return(MemberSerialization.OptIn);
            }
#endif

#if HAVE_BINARY_SERIALIZATION
            if (!ignoreSerializableAttribute && IsSerializable(objectType))
            {
                return(MemberSerialization.Fields);
            }
#endif

            // the default
            return(MemberSerialization.OptOut);
        }
示例#10
0
        private static string GetAndCacheContractIdFromAttribute(Type contractType)
        {
            string contractId;
            DataContractAttribute contract = contractType
                                             .GetCustomAttributes(false).Where(attr => attr is DataContractAttribute)
                                             .SingleOrDefault() as DataContractAttribute;

            if (contract == null || String.IsNullOrEmpty(contract.Name))
            {
                if (typeof(IProjection).IsAssignableFrom(contractType) ||
                    typeof(IPort).IsAssignableFrom(contractType) ||
                    typeof(IAggregateRootApplicationService).IsAssignableFrom(contractType))
                {
                    contractId = contractType.GetHashCode().ToString();
                }
                else
                {
                    throw new Exception(String.Format(@"The message type '{0}' is missing a DataContract attribute. Example: [DataContract(""00000000-0000-0000-0000-000000000000"")]", contractType.FullName));
                }
            }
            else
            {
                contractId = contract.Name;
            }

            contractIds.TryAdd(contractType, contractId);
            return(contractId);
        }
示例#11
0
        private void InitializeContract(JsonContract contract)
        {
            JsonContainerAttribute containerAttribute = JsonTypeReflector.GetJsonContainerAttribute(contract.UnderlyingType);

            if (containerAttribute != null)
            {
                contract.IsReference = containerAttribute._isReference;
            }
            else
            {
                DataContractAttribute dataContractAttribute = JsonTypeReflector.GetDataContractAttribute(contract.UnderlyingType);
                // doesn't have a null value
                if (dataContractAttribute != null && dataContractAttribute.IsReference)
                {
                    contract.IsReference = true;
                }
            }

            contract.Converter = ResolveContractConverter(contract.UnderlyingType);

            // then see whether object is compadible with any of the built in converters
            contract.InternalConverter = JsonSerializer.GetMatchingConverter(BuiltInConverters, contract.UnderlyingType);

            if (ReflectionUtils.HasDefaultConstructor(contract.CreatedType, true) ||
                contract.CreatedType.IsValueType)
            {
                contract.DefaultCreator = GetDefaultCreator(contract.CreatedType);

                contract.DefaultCreatorNonPublic = (!contract.CreatedType.IsValueType &&
                                                    ReflectionUtils.GetDefaultConstructor(contract.CreatedType) == null);
            }

            ResolveCallbackMethods(contract, contract.UnderlyingType);
        }
        private void GenerateEnumTypeDeclaration(Type enumType)
        {
            DataContractAttribute dataContractAttr = (DataContractAttribute)Attribute.GetCustomAttribute(enumType, typeof(DataContractAttribute));

            if (dataContractAttr != null)
            {
                this.GenerateDataContractAttribute(enumType);
            }

            if (enumType.GetCustomAttributes(typeof(FlagsAttribute), false).Length > 0)
            {
                this.Write("[System.Flags]\r\n");
            }


            this.Write("public enum ");

            this.Write(this.ToStringHelper.ToStringWithCulture(CodeGenUtilities.GetSafeName(enumType.Name)));



            Type underlyingType = enumType.GetEnumUnderlyingType();

            if (underlyingType != typeof(int))
            {
                this.Write(" : ");

                this.Write(this.ToStringHelper.ToStringWithCulture(CodeGenUtilities.GetTypeName(underlyingType)));
            }
        }
        public void TestDataContractAttribute()
        {
            DataContractAttribute x = new DataContractAttribute();

            Assert.AreEqual(null, x.Name, "#01");
            Assert.AreEqual(null, x.Namespace, "#02");
        }
        private void method_7(JsonContract jsonContract_0)
        {
            JsonContainerAttribute attribute = Class139.smethod_0(jsonContract_0.type_0);

            if (attribute != null)
            {
                jsonContract_0.IsReference = attribute.nullable_0;
            }
            else
            {
                DataContractAttribute attribute2 = Class139.smethod_5(jsonContract_0.type_0);
                if ((attribute2 != null) && attribute2.IsReference)
                {
                    jsonContract_0.IsReference = true;
                }
            }
            jsonContract_0.Converter       = this.ResolveContractConverter(jsonContract_0.type_0);
            jsonContract_0.JsonConverter_0 = JsonSerializer.smethod_1(ilist_0, jsonContract_0.type_0);
            if (Class194.smethod_6(jsonContract_0.CreatedType, true) || jsonContract_0.CreatedType.smethod_12())
            {
                jsonContract_0.DefaultCreator          = this.method_6(jsonContract_0.CreatedType);
                jsonContract_0.DefaultCreatorNonPublic = !jsonContract_0.CreatedType.smethod_12() && (Class194.smethod_7(jsonContract_0.CreatedType) == null);
            }
            this.method_8(jsonContract_0, jsonContract_0.type_0);
        }
        public static MemberSerialization GetObjectMemberSerialization(Type objectType, bool ignoreSerializableAttribute)
        {
            JsonObjectAttribute objectAttribute = GetCachedAttribute <JsonObjectAttribute>(objectType);

            if (objectAttribute != null)
            {
                return(objectAttribute.MemberSerialization);
            }

#if !NET20
            DataContractAttribute dataContractAttribute = GetDataContractAttribute(objectType);
            if (dataContractAttribute != null)
            {
                return(MemberSerialization.OptIn);
            }
#endif

#if !(DOTNET || PORTABLE40 || PORTABLE)
            if (!ignoreSerializableAttribute)
            {
                SerializableAttribute serializableAttribute = GetCachedAttribute <SerializableAttribute>(objectType);
                if (serializableAttribute != null)
                {
                    return(MemberSerialization.Fields);
                }
            }
#endif

            // the default
            return(MemberSerialization.OptOut);
        }
        private void InitializeContract(JsonContract contract)
        {
            JsonContainerAttribute jsonContainerAttribute = JsonTypeReflector.GetJsonContainerAttribute(contract.UnderlyingType);

            if (jsonContainerAttribute != null)
            {
                contract.IsReference = jsonContainerAttribute._isReference;
            }
            else
            {
                DataContractAttribute dataContractAttribute = JsonTypeReflector.GetDataContractAttribute(contract.UnderlyingType);
                if (dataContractAttribute != null && dataContractAttribute.IsReference)
                {
                    contract.IsReference = true;
                }
            }
            contract.Converter         = ResolveContractConverter(contract.UnderlyingType);
            contract.InternalConverter = JsonSerializer.GetMatchingConverter(BuiltInConverters, contract.UnderlyingType);
            if (ReflectionUtils.HasDefaultConstructor(contract.CreatedType, nonPublic: true) || contract.CreatedType.IsValueType)
            {
                contract.DefaultCreator          = GetDefaultCreator(contract.CreatedType);
                contract.DefaultCreatorNonPublic = (!contract.CreatedType.IsValueType && ReflectionUtils.GetDefaultConstructor(contract.CreatedType) == null);
            }
            ResolveCallbackMethods(contract, contract.UnderlyingType);
        }
        protected virtual List <MemberInfo> GetSerializableMembers(Type objectType)
        {
            bool ignoreSerializableAttribute  = this.IgnoreSerializableAttribute;
            MemberSerialization serialization = Class139.smethod_7(objectType, ignoreSerializableAttribute);

            if (func_0 == null)
            {
                func_0 = new Func <MemberInfo, bool>(DefaultContractResolver.smethod_5);
            }
            List <MemberInfo> list   = Class194.smethod_27(objectType, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance).Where <MemberInfo>(func_0).ToList <MemberInfo>();
            List <MemberInfo> source = new List <MemberInfo>();

            if (serialization != MemberSerialization.Fields)
            {
                Type type;
                DataContractAttribute attribute = Class139.smethod_5(objectType);
                if (func_1 == null)
                {
                    func_1 = new Func <MemberInfo, bool>(DefaultContractResolver.smethod_6);
                }
                List <MemberInfo> list3 = Class194.smethod_27(objectType, this.DefaultMembersSearchFlags).Where <MemberInfo>(func_1).ToList <MemberInfo>();
                foreach (MemberInfo info in list)
                {
                    if (this.SerializeCompilerGeneratedMembers || !info.IsDefined(typeof(CompilerGeneratedAttribute), true))
                    {
                        if (list3.Contains(info))
                        {
                            source.Add(info);
                        }
                        else if (Class139.smethod_17 <JsonPropertyAttribute>(info) != null)
                        {
                            source.Add(info);
                        }
                        else if ((attribute != null) && (Class139.smethod_17 <DataMemberAttribute>(info) != null))
                        {
                            source.Add(info);
                        }
                        else if ((serialization == MemberSerialization.Fields) && (info.smethod_1() == MemberTypes.Field))
                        {
                            source.Add(info);
                        }
                    }
                }
                if (objectType.smethod_13("System.Data.Objects.DataClasses.EntityObject", out type))
                {
                    source = source.Where <MemberInfo>(new Func <MemberInfo, bool>(this.method_2)).ToList <MemberInfo>();
                }
                return(source);
            }
            foreach (MemberInfo info2 in list)
            {
                FieldInfo info3 = info2 as FieldInfo;
                if ((info3 != null) && !info3.IsStatic)
                {
                    source.Add(info2);
                }
            }
            return(source);
        }
示例#18
0
 /// <summary>
 /// Creates a namespace resolution for a <see cref="DataContractAttribute" />-annotated
 /// type.
 /// </summary>
 protected virtual IdentifierResolution CreateNamespaceResolution(Type type, DataContractAttribute attribute)
 {
     return(string.IsNullOrEmpty(attribute?.Namespace)
         ? string.IsNullOrEmpty(type.Namespace)
             ? null
             : new IdentifierResolution(type.Namespace)
         : new IdentifierResolution(attribute.Namespace, true));
 }
        /// <summary>
        /// Removes properties that do not have the <see cref="DataMemberAttribute"/> attribute from the enum type.
        /// </summary>
        /// <param name="enumTypeConfiguration">The enum type to configure.</param>
        /// <param name="model">The enum model that this type belongs to.</param>
        /// <param name="attribute">The <see cref="Attribute"/> found on this type.</param>
        public override void Apply(EnumTypeConfiguration enumTypeConfiguration, ODataConventionModelBuilder model,
                                   Attribute attribute)
        {
            if (enumTypeConfiguration == null)
            {
                throw Error.ArgumentNull("enumTypeConfiguration");
            }

            if (model == null)
            {
                throw Error.ArgumentNull("model");
            }

            if (!enumTypeConfiguration.AddedExplicitly &&
                model.ModelAliasingEnabled)
            {
                // set the name, and namespace, if not null
                DataContractAttribute dataContractAttribute = attribute as DataContractAttribute;
                if (dataContractAttribute != null)
                {
                    if (dataContractAttribute.Name != null)
                    {
                        enumTypeConfiguration.Name = dataContractAttribute.Name;
                    }

                    if (dataContractAttribute.Namespace != null)
                    {
                        enumTypeConfiguration.Namespace = dataContractAttribute.Namespace;
                    }
                }

                enumTypeConfiguration.AddedExplicitly = false;
            }

            IEnumerable <EnumMemberConfiguration> allMembers = enumTypeConfiguration.Members.ToArray();

            foreach (EnumMemberConfiguration member in allMembers)
            {
                EnumMemberAttribute enumMemberAttribute =
                    enumTypeConfiguration.ClrType.GetField(member.Name)
                    .GetCustomAttributes(typeof(EnumMemberAttribute), inherit: true)
                    .FirstOrDefault() as EnumMemberAttribute;
                if (!member.AddedExplicitly)
                {
                    if (model.ModelAliasingEnabled && enumMemberAttribute != null)
                    {
                        if (!string.IsNullOrWhiteSpace(enumMemberAttribute.Value))
                        {
                            member.Name = enumMemberAttribute.Value;
                        }
                    }
                    else
                    {
                        enumTypeConfiguration.RemoveMember(member.MemberInfo);
                    }
                }
            }
        }
示例#20
0
        private static string BuildTypeIdForDataContract(object appDataObject)
        {
            Type type = appDataObject.GetType();
            DataContractAttribute dataContractAttribute = (DataContractAttribute)type.GetCustomAttributes(typeof(DataContractAttribute), false)[0];
            string arg  = string.IsNullOrEmpty(dataContractAttribute.Name) ? type.Name : dataContractAttribute.Name;
            string arg2 = string.IsNullOrEmpty(dataContractAttribute.Namespace) ? type.Namespace : dataContractAttribute.Namespace;

            return(string.Format("DataContract:{0}, {1}, {2}", arg, arg2, type.Assembly.GetName().Version));
        }
示例#21
0
        protected virtual List <MemberInfo> GetSerializableMembers(Type objectType)
        {
            bool ignoreSerializableAttribute = this.IgnoreSerializableAttribute;
            MemberSerialization objectMemberSerialization = JsonTypeReflector.GetObjectMemberSerialization(objectType, ignoreSerializableAttribute);
            List <MemberInfo>   list = (from m in ReflectionUtils.GetFieldsAndProperties(objectType, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic)
                                        where !ReflectionUtils.IsIndexedProperty(m)
                                        select m).ToList <MemberInfo>();
            List <MemberInfo> list2 = new List <MemberInfo>();

            if (objectMemberSerialization != MemberSerialization.Fields)
            {
                DataContractAttribute dataContractAttribute = JsonTypeReflector.GetDataContractAttribute(objectType);
                List <MemberInfo>     list3 = (from m in ReflectionUtils.GetFieldsAndProperties(objectType, this.DefaultMembersSearchFlags)
                                               where !ReflectionUtils.IsIndexedProperty(m)
                                               select m).ToList <MemberInfo>();
                foreach (MemberInfo current in list)
                {
                    if (this.SerializeCompilerGeneratedMembers || !current.IsDefined(typeof(CompilerGeneratedAttribute), true))
                    {
                        if (list3.Contains(current))
                        {
                            list2.Add(current);
                        }
                        else if (JsonTypeReflector.GetAttribute <JsonPropertyAttribute>(current) != null)
                        {
                            list2.Add(current);
                        }
                        else if (dataContractAttribute != null && JsonTypeReflector.GetAttribute <DataMemberAttribute>(current) != null)
                        {
                            list2.Add(current);
                        }
                        else if (objectMemberSerialization == MemberSerialization.Fields && current.MemberType() == MemberTypes.Field)
                        {
                            list2.Add(current);
                        }
                    }
                }
                Type type;
                if (objectType.AssignableToTypeName("System.Data.Objects.DataClasses.EntityObject", out type))
                {
                    list2 = list2.Where(new Func <MemberInfo, bool>(this.ShouldSerializeEntityMember)).ToList <MemberInfo>();
                }
            }
            else
            {
                foreach (MemberInfo current2 in list)
                {
                    FieldInfo fieldInfo = current2 as FieldInfo;
                    if (fieldInfo != null && !fieldInfo.IsStatic)
                    {
                        list2.Add(current2);
                    }
                }
            }
            return(list2);
        }
        public void Namespace_Set_GetReturnsExpected(string value)
        {
            var attribute = new DataContractAttribute()
            {
                Namespace = value
            };

            Assert.Equal(value, attribute.Namespace);
            Assert.True(attribute.IsNamespaceSetExplicitly);
        }
        public void IsReference_Set_GetReturnsExpected(bool value)
        {
            var attribute = new DataContractAttribute()
            {
                IsReference = value
            };

            Assert.Equal(value, attribute.IsReference);
            Assert.True(attribute.IsReferenceSetExplicitly);
        }
示例#24
0
        public static DataContractAttribute GetDataContractAttribute(Type type)
        {
            DataContractAttribute attribute = null;

            for (Type i = type; attribute == null && i != null; i = i.BaseType)
            {
                attribute = CachedAttributeGetter <DataContractAttribute> .GetAttribute(i);
            }
            return(attribute);
        }
        private void SetPropertySettingsFromAttributes(JsonProperty property, ICustomAttributeProvider attributeProvider, string name, Type declaringType, MemberSerialization memberSerialization, out bool allowNonPublicAccess, out bool hasExplicitAttribute)
        {
            hasExplicitAttribute = false;
            DataContractAttribute dataContractAttribute = JsonTypeReflector.GetDataContractAttribute(declaringType);
            DataMemberAttribute   dataMemberAttribute   = (dataContractAttribute == null || !(attributeProvider is MemberInfo)) ? null : JsonTypeReflector.GetDataMemberAttribute((MemberInfo)attributeProvider);
            JsonPropertyAttribute attribute             = JsonTypeReflector.GetAttribute <JsonPropertyAttribute>(attributeProvider);

            if (attribute != null)
            {
                hasExplicitAttribute = true;
            }
            bool   flag         = JsonTypeReflector.GetAttribute <JsonIgnoreAttribute>(attributeProvider) != null;
            string propertyName = (attribute != null && attribute.PropertyName != null) ? attribute.PropertyName : ((dataMemberAttribute == null || dataMemberAttribute.Name == null) ? name : dataMemberAttribute.Name);

            property.PropertyName   = ResolvePropertyName(propertyName);
            property.UnderlyingName = name;
            if (attribute != null)
            {
                property.Required = attribute.Required;
                property.Order    = attribute._order;
            }
            else if (dataMemberAttribute != null)
            {
                property.Required = (dataMemberAttribute.IsRequired ? Required.AllowNull : Required.Default);
                property.Order    = ((dataMemberAttribute.Order == -1) ? null : new int?(dataMemberAttribute.Order));
            }
            else
            {
                property.Required = Required.Default;
            }
            property.Ignored                = (flag || (memberSerialization == MemberSerialization.OptIn && attribute == null && dataMemberAttribute == null));
            property.Converter              = JsonTypeReflector.GetJsonConverter(attributeProvider, property.PropertyType);
            property.MemberConverter        = JsonTypeReflector.GetJsonConverter(attributeProvider, property.PropertyType);
            property.DefaultValue           = JsonTypeReflector.GetAttribute <DefaultValueAttribute>(attributeProvider)?.Value;
            property.NullValueHandling      = attribute?._nullValueHandling;
            property.DefaultValueHandling   = attribute?._defaultValueHandling;
            property.ReferenceLoopHandling  = attribute?._referenceLoopHandling;
            property.ObjectCreationHandling = attribute?._objectCreationHandling;
            property.TypeNameHandling       = attribute?._typeNameHandling;
            property.IsReference            = attribute?._isReference;
            allowNonPublicAccess            = false;
            if ((DefaultMembersSearchFlags & BindingFlags.NonPublic) == BindingFlags.NonPublic)
            {
                allowNonPublicAccess = true;
            }
            if (attribute != null)
            {
                allowNonPublicAccess = true;
            }
            if (dataMemberAttribute != null)
            {
                allowNonPublicAccess = true;
                hasExplicitAttribute = true;
            }
        }
示例#26
0
        /// <summary>
        /// Returns the xml qualified name for the specified system type id.
        /// </summary>
        /// <remarks>
        /// Returns the xml qualified name for the specified system type id.
        /// </remarks>
        /// <param name="systemType">The underlying type to query and return the Xml qualified name of</param>
        public static XmlQualifiedName GetXmlName(System.Type systemType)
        {
            if (systemType == null)
            {
                return(null);
            }

            object[] attributes = systemType.GetTypeInfo().GetCustomAttributes(typeof(DataContractAttribute), true).ToArray();

            if (attributes != null)
            {
                for (int ii = 0; ii < attributes.Length; ii++)
                {
                    DataContractAttribute contract = attributes[ii] as DataContractAttribute;

                    if (contract != null)
                    {
                        if (String.IsNullOrEmpty(contract.Name))
                        {
                            return(new XmlQualifiedName(systemType.Name, contract.Namespace));
                        }

                        return(new XmlQualifiedName(contract.Name, contract.Namespace));
                    }
                }
            }

            attributes = systemType.GetTypeInfo().GetCustomAttributes(typeof(CollectionDataContractAttribute), true).ToArray();

            if (attributes != null)
            {
                for (int ii = 0; ii < attributes.Length; ii++)
                {
                    CollectionDataContractAttribute contract = attributes[ii] as CollectionDataContractAttribute;

                    if (contract != null)
                    {
                        if (String.IsNullOrEmpty(contract.Name))
                        {
                            return(new XmlQualifiedName(systemType.Name, contract.Namespace));
                        }

                        return(new XmlQualifiedName(contract.Name, contract.Namespace));
                    }
                }
            }

            if (systemType == typeof(System.Byte[]))
            {
                return(new XmlQualifiedName("ByteString"));
            }

            return(new XmlQualifiedName(systemType.FullName));
        }
        private void put_datacontract(Type t, object o, DataContractAttribute dca)
        {
            var fields = t.GetFields();
            var map    = new Dictionary <string, object>();

            foreach (var field in fields)
            {
                DataMemberAttribute dma = (DataMemberAttribute)field.GetCustomAttribute(typeof(DataMemberAttribute));
                if (dma != null)
                {
                    string name = dma.Name;
                    try
                    {
                        map[name] = field.GetValue(o);
                    }
                    catch (Exception x)
                    {
                        throw new PickleException("cannot pickle [DataContract] object:", x);
                    }
                }
            }
            var properties = t.GetProperties();

            foreach (var propinfo in properties)
            {
                if (propinfo.CanRead && propinfo.GetCustomAttribute(typeof(DataMemberAttribute)) != null)
                {
                    string name = propinfo.Name;
                    try
                    {
                        map[name] = propinfo.GetValue(o, null);
                    }
                    catch (Exception x)
                    {
                        throw new PickleException("cannot pickle [DataContract] object:", x);
                    }
                }
            }

            if (string.IsNullOrEmpty(dca.Name))
            {
                // if we're dealing with an anonymous type, don't output the type name.
                if (!o.GetType().Name.StartsWith("<>"))
                {
                    map["__class__"] = o.GetType().FullName;
                }
            }
            else
            {
                map["__class__"] = dca.Name;
            }

            save(map);
        }
        public void Ctor_Default()
        {
            var attribute = new DataContractAttribute();

            Assert.False(attribute.IsReference);
            Assert.False(attribute.IsReferenceSetExplicitly);
            Assert.Null(attribute.Name);
            Assert.False(attribute.IsNameSetExplicitly);
            Assert.Null(attribute.Namespace);
            Assert.False(attribute.IsNamespaceSetExplicitly);
        }
        internal DataContractImplementor(EntityType ospaceEntityType)
        {
            _baseClrType = ospaceEntityType.ClrType;

            var attributes = (DataContractAttribute[])_baseClrType.GetCustomAttributes(typeof(DataContractAttribute), false);

            if (attributes.Length > 0)
            {
                _dataContract = attributes[0];
            }
        }
示例#30
0
 public CustomAttributes(
     JsonIgnoreAttribute jsonIgnoreAttribute,
     JsonPropertyAttribute jsonPropertyAttribute,
     DataContractAttribute dataContractAttribute,
     DataMemberAttribute dataMemberAttribute)
 {
     JsonIgnoreAttribute   = jsonIgnoreAttribute;
     JsonPropertyAttribute = jsonPropertyAttribute;
     DataContractAttribute = dataContractAttribute;
     DataMemberAttribute   = dataMemberAttribute;
 }
示例#31
0
        static TypeMap CreateTypeMap(Type type, DataContractAttribute dca)
        {
            if (dca != null && dca.Name != null && IsInvalidNCName (dca.Name))
                throw new InvalidDataContractException (String.Format ("DataContractAttribute for type '{0}' has an invalid name", type));

            List<TypeMapMember> members = new List<TypeMapMember> ();

            foreach (FieldInfo fi in type.GetFields (BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)) {
                if (dca != null) {
                    object [] atts = fi.GetCustomAttributes (typeof (DataMemberAttribute), true);
                    if (atts.Length == 0)
                        continue;
                    DataMemberAttribute dma = (DataMemberAttribute) atts [0];
                    members.Add (new TypeMapField (fi, dma));
                } else {
                    if (fi.GetCustomAttributes (typeof (NonSerializedAttribute), false).Length > 0)
                        continue;
                    members.Add (new TypeMapField (fi, null));
                }
            }

            if (dca != null) {
                foreach (PropertyInfo pi in type.GetProperties (BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)) {
                    object [] atts = pi.GetCustomAttributes (typeof (DataMemberAttribute), true);
                    if (atts.Length == 0)
                        continue;
                    if (pi.GetIndexParameters ().Length > 0)
                        continue;
                    if (IsCollection (pi.PropertyType)) {
                        if (!pi.CanRead)
                            throw new InvalidDataContractException (String.Format ("Property {0} must have a getter", pi));
                    }
                    else if (!pi.CanRead || !pi.CanWrite)
                        throw new InvalidDataContractException (String.Format ("Non-collection property {0} must have both getter and setter", pi));
                    DataMemberAttribute dma = (DataMemberAttribute) atts [0];
                    members.Add (new TypeMapProperty (pi, dma));
                }
            }

            members.Sort (delegate (TypeMapMember m1, TypeMapMember m2) { return m1.Order - m2.Order; });
            return new TypeMap (type, dca == null ? null : dca.Name, members.ToArray ());
        }