private bool CheckIfConflictingMembersHaveDifferentTypes(DataMember member)
 {
     while (member.ConflictingMember != null)
     {
         if (member.MemberType != member.ConflictingMember.MemberType)
         {
             return true;
         }
         member = member.ConflictingMember;
     }
     return false;
 }
        protected override void ReflectionReadMembers(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context, XmlDictionaryString[] memberNames, XmlDictionaryString[] memberNamespaces, ClassDataContract classContract, ref object obj)
        {
            int memberCount = classContract.MemberNames.Length;
            context.IncrementItemCount(memberCount);
            int memberIndex = -1;
            int firstRequiredMember;
            bool[] requiredMembers = GetRequiredMembers(classContract, out firstRequiredMember);
            bool hasRequiredMembers = (firstRequiredMember < memberCount);
            int requiredIndex = hasRequiredMembers ? firstRequiredMember : -1;
            DataMember[] members = new DataMember[memberCount];
            int reflectedMemberCount = ReflectionGetMembers(classContract, members);
            Debug.Assert(reflectedMemberCount == memberCount, "The value returned by ReflectionGetMembers() should equal to memberCount.");

            while (true)
            {
                if (!XmlObjectSerializerReadContext.MoveToNextElement(xmlReader))
                {
                    return;
                }
                if (hasRequiredMembers)
                {
                    memberIndex = context.GetMemberIndexWithRequiredMembers(xmlReader, memberNames, memberNamespaces, memberIndex, requiredIndex, null);
                }
                else
                {
                    memberIndex = context.GetMemberIndex(xmlReader, memberNames, memberNamespaces, memberIndex, null);
                }

                // GetMemberIndex returns memberNames.Length if member not found
                if (memberIndex < members.Length)
                {
                    ReflectionReadMember(xmlReader, context, classContract, ref obj, memberIndex, members);
                    requiredIndex = memberIndex + 1;
                }
            }
        }
 private bool CheckIfMemberHasConflict(DataMember member, ClassDataContract classContract, ClassDataContract derivedMostClassContract)
 {
     if (this.CheckIfConflictingMembersHaveDifferentTypes(member))
     {
         return true;
     }
     string name = member.Name;
     string str2 = classContract.StableName.Namespace;
     for (ClassDataContract contract = derivedMostClassContract; (contract != null) && (contract != classContract); contract = contract.BaseContract)
     {
         if (str2 == contract.StableName.Namespace)
         {
             List<DataMember> members = contract.Members;
             for (int i = 0; i < members.Count; i++)
             {
                 if (name == members[i].Name)
                 {
                     return this.CheckIfConflictingMembersHaveDifferentTypes(members[i]);
                 }
             }
         }
     }
     return false;
 }
 internal DataContract GetMemberTypeDataContract(DataMember dataMember)
 {
     if (dataMember.MemberInfo != null)
     {
         Type dataMemberType = dataMember.MemberType;
         if (dataMember.IsGetOnlyCollection)
         {
             if (dataContractSurrogate != null)
             {
                 Type dcType = DataContractSurrogateCaller.GetDataContractType(dataContractSurrogate, dataMemberType);
                 if (dcType != dataMemberType)
                 {
                     throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.GetString(SR.SurrogatesWithGetOnlyCollectionsNotSupported,
                         DataContract.GetClrTypeFullName(dataMemberType), DataContract.GetClrTypeFullName(dataMember.MemberInfo.DeclaringType), dataMember.MemberInfo.Name)));
                 }
             }
             return DataContract.GetGetOnlyCollectionDataContract(DataContract.GetId(dataMemberType.TypeHandle), dataMemberType.TypeHandle, dataMemberType, SerializationMode.SharedContract);
         }
         else
         {
             return GetDataContract(dataMemberType);
         }
     }
     return dataMember.MemberTypeContract;
 }
        private XmlElement ExportEmitDefaultValue(DataMember dataMember)
        {
            if (dataMember.EmitDefaultValue)
                return null;
            XmlElement defaultValueElement = XmlDoc.CreateElement(DefaultValueAnnotation.Name, DefaultValueAnnotation.Namespace);
            XmlAttribute emitDefaultValueAttribute = XmlDoc.CreateAttribute(Globals.EmitDefaultValueAttribute);
            emitDefaultValueAttribute.Value = Globals.False;
            defaultValueElement.Attributes.Append(emitDefaultValueAttribute);
            return defaultValueElement;

        }
        void ImportClassMember(XmlSchemaElement element, ClassDataContract dataContract)
        {
            XmlQualifiedName typeName = dataContract.StableName;

            if (element.MinOccurs > 1)
                ThrowTypeCannotBeImportedException(typeName.Name, typeName.Namespace, SR.GetString(SR.ElementMinOccursMustBe, element.Name));
            if (element.MaxOccurs != 1)
                ThrowTypeCannotBeImportedException(typeName.Name, typeName.Namespace, SR.GetString(SR.ElementMaxOccursMustBe, element.Name));

            DataContract memberTypeContract = null;
            string memberName = element.Name;
            bool memberIsRequired = (element.MinOccurs > 0);
            bool memberIsNullable = element.IsNillable;
            bool memberEmitDefaultValue;
            int memberOrder = 0;

            XmlSchemaForm elementForm = (element.Form == XmlSchemaForm.None) ? SchemaHelper.GetSchemaWithType(SchemaObjects, schemaSet, typeName).ElementFormDefault : element.Form;
            if (elementForm != XmlSchemaForm.Qualified)
                ThrowTypeCannotBeImportedException(typeName.Name, typeName.Namespace, SR.GetString(SR.FormMustBeQualified, element.Name));
            CheckIfElementUsesUnsupportedConstructs(typeName, element);

            if (element.SchemaTypeName.IsEmpty)
            {
                if (element.SchemaType != null)
                    memberTypeContract = ImportAnonymousElement(element, new XmlQualifiedName(String.Format(CultureInfo.InvariantCulture, "{0}.{1}Type", typeName.Name, element.Name), typeName.Namespace));
                else if (!element.RefName.IsEmpty)
                    ThrowTypeCannotBeImportedException(typeName.Name, typeName.Namespace, SR.GetString(SR.ElementRefOnLocalElementNotSupported, element.RefName.Name, element.RefName.Namespace));
                else
                    memberTypeContract = ImportType(SchemaExporter.AnytypeQualifiedName);
            }
            else
            {
                XmlQualifiedName memberTypeName = ImportActualType(element.Annotation, element.SchemaTypeName, typeName);
                memberTypeContract = ImportType(memberTypeName);
                if (IsObjectContract(memberTypeContract))
                    needToImportKnownTypesForObject = true;
            }
            bool? emitDefaultValueFromAnnotation = ImportEmitDefaultValue(element.Annotation, typeName);
            if (!memberTypeContract.IsValueType && !memberIsNullable)
            {
                if (emitDefaultValueFromAnnotation != null && emitDefaultValueFromAnnotation.Value)
                    throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.GetString(SR.InvalidEmitDefaultAnnotation, memberName, typeName.Name, typeName.Namespace)));
                memberEmitDefaultValue = false;
            }
            else
                memberEmitDefaultValue = emitDefaultValueFromAnnotation != null ? emitDefaultValueFromAnnotation.Value : Globals.DefaultEmitDefaultValue;

            int prevMemberIndex = dataContract.Members.Count - 1;
            if (prevMemberIndex >= 0)
            {
                DataMember prevMember = dataContract.Members[prevMemberIndex];
                if (prevMember.Order > Globals.DefaultOrder)
                    memberOrder = dataContract.Members.Count;
                DataMember currentMember = new DataMember(memberTypeContract, memberName, memberIsNullable, memberIsRequired, memberEmitDefaultValue, memberOrder);
                int compare = ClassDataContract.DataMemberComparer.Singleton.Compare(prevMember, currentMember);
                if (compare == 0)
                    ThrowTypeCannotBeImportedException(typeName.Name, typeName.Namespace, SR.GetString(SR.CannotHaveDuplicateElementNames, memberName));
                else if (compare > 0)
                    memberOrder = dataContract.Members.Count;
            }
            DataMember dataMember = new DataMember(memberTypeContract, memberName, memberIsNullable, memberIsRequired, memberEmitDefaultValue, memberOrder);

            XmlQualifiedName surrogateDataAnnotationName = SchemaExporter.SurrogateDataAnnotationName;
            dataContractSet.SetSurrogateData(dataMember, ImportSurrogateData(ImportAnnotation(element.Annotation, surrogateDataAnnotationName), surrogateDataAnnotationName.Name, surrogateDataAnnotationName.Namespace));

            dataContract.Members.Add(dataMember);
        }
 private EnumDataContract ImportEnum(XmlQualifiedName typeName, XmlSchemaSimpleTypeRestriction restriction, bool isFlags, XmlSchemaAnnotation annotation)
 {
     EnumDataContract dataContract = new EnumDataContract {
         StableName = typeName,
         BaseContractName = ImportActualType(annotation, SchemaExporter.DefaultEnumBaseTypeName, typeName),
         IsFlags = isFlags
     };
     this.AddDataContract(dataContract);
     dataContract.Values = new List<long>();
     dataContract.Members = new List<DataMember>();
     foreach (XmlSchemaFacet facet in restriction.Facets)
     {
         XmlSchemaEnumerationFacet facet2 = facet as XmlSchemaEnumerationFacet;
         if (facet2 == null)
         {
             ThrowEnumTypeCannotBeImportedException(typeName.Name, typeName.Namespace, System.Runtime.Serialization.SR.GetString("EnumOnlyEnumerationFacetsSupported"));
         }
         if (facet2.Value == null)
         {
             ThrowEnumTypeCannotBeImportedException(typeName.Name, typeName.Namespace, System.Runtime.Serialization.SR.GetString("EnumEnumerationFacetsMustHaveValue"));
         }
         string innerText = this.GetInnerText(typeName, ImportAnnotation(facet2.Annotation, SchemaExporter.EnumerationValueAnnotationName));
         if (innerText == null)
         {
             dataContract.Values.Add(SchemaExporter.GetDefaultEnumValue(isFlags, dataContract.Members.Count));
         }
         else
         {
             dataContract.Values.Add(dataContract.GetEnumValueFromString(innerText));
         }
         DataMember item = new DataMember(facet2.Value);
         dataContract.Members.Add(item);
     }
     return dataContract;
 }
            private void ImportDataMembers()
            {
                /*
                 * DataMembers are used for the deserialization of Exceptions.
                 * DataMembers represent the fields and/or settable properties that the underlying Exception has.
                 * The DataMembers are stored and eventually passed to a ClassDataContract created from the underlying Exception.
                 * The ClassDataContract uses the list of DataMembers to set the fields/properties for the newly created Exception.
                 * If a DataMember is a property it must be settable.
                 */

                Type type = this.UnderlyingType;
                if (type == Globals.TypeOfException)
                {
                    ImportSystemExceptionDataMembers(); //System.Exception must be handled specially because it is the only exception that imports private fields.
                    return;
                }

                List<DataMember> tempMembers;
                if (BaseContract != null)
                {
                    tempMembers = new List<DataMember>(BaseContract.Members);  //Don't set tempMembers = BaseContract.Members and then start adding, because this alters the base's reference.
                }
                else
                {
                    tempMembers = new List<DataMember>();
                }
                Dictionary<string, DataMember> memberNamesTable = new Dictionary<string, DataMember>();

                MemberInfo[] memberInfos;
                memberInfos = type.GetMembers(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public);

                for (int i = 0; i < memberInfos.Length; i++)
                {
                    MemberInfo member = memberInfos[i];

                    //Public properties with set methods can be deserialized with the ClassDataContract
                    PropertyInfo publicProperty = member as PropertyInfo;
                    if (publicProperty != null && publicProperty.SetMethod != null)
                    {
                        DataMember memberContract = new DataMember(member);

                        memberContract.Name = DataContract.EncodeLocalName(member.Name);
                        memberContract.IsRequired = false;
                        memberContract.IsNullable = DataContract.IsTypeNullable(memberContract.MemberType);
                        if (HasNoConflictWithBaseMembers(memberContract))
                        {
                            CheckAndAddMember(tempMembers, memberContract, memberNamesTable);
                        }
                    }
                }

                Interlocked.MemoryBarrier();
                _members = tempMembers;
            }
Example #9
0
 private void ReflectionSetMemberValue(ref object obj, object memberValue, DataMember dataMember)
 {
     dataMember.Setter(ref obj, memberValue);
 }
Example #10
0
 private object ReflectionGetMemberValue(object obj, DataMember dataMember)
 {
     return(dataMember.Getter(obj));
 }
            private int WriteMembers(ClassDataContract classContract, LocalBuilder extensionDataLocal, ClassDataContract derivedMostClassContract)
            {
                int memberCount = (classContract.BaseContract == null) ? 0 :
                                  WriteMembers(classContract.BaseContract, extensionDataLocal, derivedMostClassContract);

                LocalBuilder namespaceLocal = _ilg.DeclareLocal(typeof(XmlDictionaryString), "ns");

                if (_contractNamespacesLocal == null)
                {
                    _ilg.Load(_dataContractArg);
                    _ilg.LoadMember(XmlFormatGeneratorStatics.NamespaceProperty);
                }
                else
                {
                    _ilg.LoadArrayElement(_contractNamespacesLocal, _typeIndex - 1);
                }
                _ilg.Store(namespaceLocal);

                _ilg.Call(_contextArg, XmlFormatGeneratorStatics.IncrementItemCountMethod, classContract.Members.Count);

                for (int i = 0; i < classContract.Members.Count; i++, memberCount++)
                {
                    DataMember   member      = classContract.Members[i];
                    Type         memberType  = member.MemberType;
                    LocalBuilder memberValue = null;
                    if (member.IsGetOnlyCollection)
                    {
                        _ilg.Load(_contextArg);
                        _ilg.Call(XmlFormatGeneratorStatics.StoreIsGetOnlyCollectionMethod);
                    }
                    if (!member.EmitDefaultValue)
                    {
                        memberValue = LoadMemberValue(member);
                        _ilg.IfNotDefaultValue(memberValue);
                    }
                    bool writeXsiType = CheckIfMemberHasConflict(member, classContract, derivedMostClassContract);
                    if (writeXsiType || !TryWritePrimitive(memberType, memberValue, member.MemberInfo, null /*arrayItemIndex*/, namespaceLocal, null /*nameLocal*/, i + _childElementIndex))
                    {
                        WriteStartElement(memberType, classContract.Namespace, namespaceLocal, null /*nameLocal*/, i + _childElementIndex);
                        if (classContract.ChildElementNamespaces[i + _childElementIndex] != null)
                        {
                            _ilg.Load(_xmlWriterArg);
                            _ilg.LoadArrayElement(_childElementNamespacesLocal, i + _childElementIndex);
                            _ilg.Call(XmlFormatGeneratorStatics.WriteNamespaceDeclMethod);
                        }
                        if (memberValue == null)
                        {
                            memberValue = LoadMemberValue(member);
                        }
                        WriteValue(memberValue, writeXsiType);
                        WriteEndElement();
                    }
                    if (!member.EmitDefaultValue)
                    {
                        if (member.IsRequired)
                        {
                            _ilg.Else();
                            _ilg.Call(null, XmlFormatGeneratorStatics.ThrowRequiredMemberMustBeEmittedMethod, member.Name, classContract.UnderlyingType);
                        }
                        _ilg.EndIf();
                    }
                }

                _typeIndex++;
                _childElementIndex += classContract.Members.Count;
                return(memberCount);
            }
Example #12
0
 public void WriteChildToContext(DataMember contextMember, string prefix)
 {
     _xPathBuilder.Append(XPathQueryGenerator.XPathSeparator + prefix + XPathQueryGenerator.NsSeparator + contextMember.Name);
 }
 protected object ReflectionGetMemberValue(object obj, DataMember dataMember)
 {
     return dataMember.Getter(obj);
 }
 protected object?ReflectionGetMemberValue(object obj, DataMember dataMember)
 {
     return(dataMember.Getter(obj));
 }
 private void ImportDataMembers()
 {
     Type underlyingType = base.UnderlyingType;
     FieldInfo[] fields = underlyingType.GetFields(BindingFlags.Public | BindingFlags.Static);
     Dictionary<string, DataMember> memberNamesTable = new Dictionary<string, DataMember>();
     List<DataMember> members = new List<DataMember>(fields.Length);
     List<long> list2 = new List<long>(fields.Length);
     for (int i = 0; i < fields.Length; i++)
     {
         FieldInfo memberInfo = fields[i];
         bool flag = false;
         if (this.hasDataContract)
         {
             object[] customAttributes = memberInfo.GetCustomAttributes(Globals.TypeOfEnumMemberAttribute, false);
             if ((customAttributes != null) && (customAttributes.Length > 0))
             {
                 if (customAttributes.Length > 1)
                 {
                     base.ThrowInvalidDataContractException(System.Runtime.Serialization.SR.GetString("TooManyEnumMembers", new object[] { DataContract.GetClrTypeFullName(memberInfo.DeclaringType), memberInfo.Name }));
                 }
                 EnumMemberAttribute attribute = (EnumMemberAttribute) customAttributes[0];
                 DataMember memberContract = new DataMember(memberInfo);
                 if (attribute.IsValueSetExplicit)
                 {
                     if ((attribute.Value == null) || (attribute.Value.Length == 0))
                     {
                         base.ThrowInvalidDataContractException(System.Runtime.Serialization.SR.GetString("InvalidEnumMemberValue", new object[] { memberInfo.Name, DataContract.GetClrTypeFullName(underlyingType) }));
                     }
                     memberContract.Name = attribute.Value;
                 }
                 else
                 {
                     memberContract.Name = memberInfo.Name;
                 }
                 ClassDataContract.CheckAndAddMember(members, memberContract, memberNamesTable);
                 flag = true;
             }
             object[] objArray2 = memberInfo.GetCustomAttributes(Globals.TypeOfDataMemberAttribute, false);
             if ((objArray2 != null) && (objArray2.Length > 0))
             {
                 base.ThrowInvalidDataContractException(System.Runtime.Serialization.SR.GetString("DataMemberOnEnumField", new object[] { DataContract.GetClrTypeFullName(memberInfo.DeclaringType), memberInfo.Name }));
             }
         }
         else if (!memberInfo.IsNotSerialized)
         {
             DataMember member2 = new DataMember(memberInfo) {
                 Name = memberInfo.Name
             };
             ClassDataContract.CheckAndAddMember(members, member2, memberNamesTable);
             flag = true;
         }
         if (flag)
         {
             object obj2 = memberInfo.GetValue(null);
             if (this.isULong)
             {
                 list2.Add((long) ((IConvertible) obj2).ToUInt64(null));
             }
             else
             {
                 list2.Add(((IConvertible) obj2).ToInt64(null));
             }
         }
     }
     Thread.MemoryBarrier();
     this.members = members;
     this.values = list2;
 }
Example #16
0
            private void ImportDataMembers()
            {
                Type type = this.UnderlyingType;
                FieldInfo[] fields = type.GetFields(BindingFlags.Static | BindingFlags.Public);
                Dictionary<string, DataMember> memberValuesTable = new Dictionary<string, DataMember>();
                List<DataMember> tempMembers = new List<DataMember>(fields.Length);
                List<long> tempValues = new List<long>(fields.Length);

                for (int i = 0; i < fields.Length; i++)
                {
                    FieldInfo field = fields[i];
                    bool enumMemberValid = false;
                    if (_hasDataContract)
                    {
                        object[] memberAttributes = field.GetCustomAttributes(Globals.TypeOfEnumMemberAttribute, false).ToArray();
                        if (memberAttributes != null && memberAttributes.Length > 0)
                        {
                            if (memberAttributes.Length > 1)
                                ThrowInvalidDataContractException(SR.Format(SR.TooManyEnumMembers, DataContract.GetClrTypeFullName(field.DeclaringType), field.Name));
                            EnumMemberAttribute memberAttribute = (EnumMemberAttribute)memberAttributes[0];

                            DataMember memberContract = new DataMember(field);
                            if (memberAttribute.IsValueSetExplicitly)
                            {
                                if (memberAttribute.Value == null || memberAttribute.Value.Length == 0)
                                    ThrowInvalidDataContractException(SR.Format(SR.InvalidEnumMemberValue, field.Name, DataContract.GetClrTypeFullName(type)));
                                memberContract.Name = memberAttribute.Value;
                            }
                            else
                                memberContract.Name = field.Name;
                            ClassDataContract.CheckAndAddMember(tempMembers, memberContract, memberValuesTable);
                            enumMemberValid = true;
                        }

                        object[] dataMemberAttributes = field.GetCustomAttributes(Globals.TypeOfDataMemberAttribute, false).ToArray();
                        if (dataMemberAttributes != null && dataMemberAttributes.Length > 0)
                            ThrowInvalidDataContractException(SR.Format(SR.DataMemberOnEnumField, DataContract.GetClrTypeFullName(field.DeclaringType), field.Name));
                    }
                    else
                    {
                        DataMember memberContract = new DataMember(field);
                        memberContract.Name = field.Name;
                        ClassDataContract.CheckAndAddMember(tempMembers, memberContract, memberValuesTable);
                        enumMemberValid = true;
                    }

                    if (enumMemberValid)
                    {
                        object enumValue = field.GetValue(null);
                        if (_isULong)
                            tempValues.Add((long)Convert.ToUInt64(enumValue, null));
                        else
                            tempValues.Add(Convert.ToInt64(enumValue, null));
                    }
                }

                Interlocked.MemoryBarrier();
                _members = tempMembers;
                _values = tempValues;
            }
 private LocalBuilder LoadMemberValue(DataMember member)
 {
     ilg.LoadAddress(objectLocal);
     ilg.LoadMember(member.MemberInfo);
     LocalBuilder memberValue = ilg.DeclareLocal(member.MemberType, member.Name + "Value");
     ilg.Stloc(memberValue);
     return memberValue;
 }
Example #18
0
        private object ReflectionReadValue(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context, DataMember dataMember, string ns)
        {
            Type   type = dataMember.MemberType;
            string name = dataMember.Name;

            return(ReflectionReadValue(xmlReader, context, type, name, ns, dataMember.MemberPrimitiveContract));
        }
 private bool HasNoConflictWithBaseMembers(DataMember memberContract)
 {
     //Don't add redundant members, this can happen if a property overrides it's base class implementation. Because the overridden property will appear as "declared" in that type.
     foreach (DataMember dm in BaseContract.Members)
     {
         if (dm.Name.Equals(memberContract.Name))
         {
             return false;
         }
     }
     return true;
 }
        int WriteMembers(ClassDataContract classContract, ExtensionDataObject extensionData, ClassDataContract derivedMostClassContract)
        {
            int memberCount = (classContract.BaseContract == null) ? 0 : WriteMembers(classContract.BaseContract, extensionData, derivedMostClassContract);

            XmlDictionaryString ns =
                (contractNamespaces == null) ? dataContract.Namespace :
                contractNamespaces [typeIndex - 1];

            ctx.IncrementItemCount(classContract.Members.Count);

            for (int i = 0; i < classContract.Members.Count; i++, memberCount++)
            {
                DataMember member      = classContract.Members[i];
                Type       memberType  = member.MemberType;
                object     memberValue = null;
                if (member.IsGetOnlyCollection)
                {
                    ctx.StoreIsGetOnlyCollection();
                }
                bool doWrite = true, hasMemberValue = false;
                if (!member.EmitDefaultValue)
                {
                    hasMemberValue = true;
                    memberValue    = LoadMemberValue(member);
                    doWrite        = !IsDefaultValue(memberType, memberValue);
                }

                if (doWrite)
                {
                    bool writeXsiType = CheckIfMemberHasConflict(member, classContract, derivedMostClassContract);
                    if (writeXsiType || !TryWritePrimitive(memberType, hasMemberValue ? () => memberValue : (Func <object>)null, member.MemberInfo, null /*arrayItemIndex*/, ns, null /*nameLocal*/, i + childElementIndex))
                    {
                        WriteStartElement(memberType, classContract.Namespace, ns, null /*nameLocal*/, i + childElementIndex);
                        if (classContract.ChildElementNamespaces [i + childElementIndex] != null)
                        {
                            writer.WriteNamespaceDecl(childElementNamespaces [i + childElementIndex]);
                        }
                        if (memberValue == null)
                        {
                            memberValue = LoadMemberValue(member);
                        }
                        WriteValue(memberType, memberValue, writeXsiType);
                        WriteEndElement();
                    }

                    if (classContract.HasExtensionData)
                    {
                        ctx.WriteExtensionData(writer, extensionData, memberCount);
                    }
                }
                else if (!member.EmitDefaultValue)
                {
                    if (member.IsRequired)
                    {
                        XmlObjectSerializerWriteContext.ThrowRequiredMemberMustBeEmitted(member.Name, classContract.UnderlyingType);
                    }
                }
            }

            typeIndex++;
            childElementIndex += classContract.Members.Count;
            return(memberCount);
        }
        EnumDataContract ImportEnum(XmlQualifiedName typeName, XmlSchemaSimpleTypeRestriction restriction, bool isFlags, XmlSchemaAnnotation annotation)
        {
            EnumDataContract dataContract = new EnumDataContract();
            dataContract.StableName = typeName;
            dataContract.BaseContractName = ImportActualType(annotation, SchemaExporter.DefaultEnumBaseTypeName, typeName);
            dataContract.IsFlags = isFlags;
            AddDataContract(dataContract);

            // CheckIfEnum has already checked if baseType of restriction is string 
            dataContract.Values = new List<long>();
            dataContract.Members = new List<DataMember>();
            foreach (XmlSchemaFacet facet in restriction.Facets)
            {
                XmlSchemaEnumerationFacet enumFacet = facet as XmlSchemaEnumerationFacet;
                if (enumFacet == null)
                    ThrowEnumTypeCannotBeImportedException(typeName.Name, typeName.Namespace, SR.GetString(SR.EnumOnlyEnumerationFacetsSupported));
                if (enumFacet.Value == null)
                    ThrowEnumTypeCannotBeImportedException(typeName.Name, typeName.Namespace, SR.GetString(SR.EnumEnumerationFacetsMustHaveValue));

                string valueInnerText = GetInnerText(typeName, ImportAnnotation(enumFacet.Annotation, SchemaExporter.EnumerationValueAnnotationName));
                if (valueInnerText == null)
                    dataContract.Values.Add(SchemaExporter.GetDefaultEnumValue(isFlags, dataContract.Members.Count));
                else
                    dataContract.Values.Add(dataContract.GetEnumValueFromString(valueInnerText));
                DataMember dataMember = new DataMember(enumFacet.Value);
                dataContract.Members.Add(dataMember);
            }
            return dataContract;
        }
 object LoadMemberValue(DataMember member)
 {
     return(CodeInterpreter.GetMember(member.MemberInfo, objLocal));
 }
        bool CheckIfMemberHasConflict(DataMember dataMember)
        {
            if (dataMember.HasConflictingNameAndType)
                return true;

            DataMember conflictingMember = dataMember.ConflictingMember;
            while (conflictingMember != null)
            {
                if (conflictingMember.HasConflictingNameAndType)
                    return true;
                conflictingMember = conflictingMember.ConflictingMember;
            }

            return false;
        }
Example #24
0
            private int ReadMembers(ClassDataContract classContract, bool[] requiredMembers, Label[] memberLabels, LocalBuilder memberIndexLocal, LocalBuilder requiredIndexLocal)
            {
                int memberCount = (classContract.BaseContract == null) ? 0 : ReadMembers(classContract.BaseContract, requiredMembers,
                                                                                         memberLabels, memberIndexLocal, requiredIndexLocal);

                for (int i = 0; i < classContract.Members.Count; i++, memberCount++)
                {
                    DataMember dataMember = classContract.Members[i];
                    Type       memberType = dataMember.MemberType;
                    _ilg.Case(memberLabels[memberCount], dataMember.Name);
                    if (dataMember.IsRequired)
                    {
                        int nextRequiredIndex = memberCount + 1;
                        for (; nextRequiredIndex < requiredMembers.Length; nextRequiredIndex++)
                        {
                            if (requiredMembers[nextRequiredIndex])
                            {
                                break;
                            }
                        }
                        _ilg.Set(requiredIndexLocal, nextRequiredIndex);
                    }

                    LocalBuilder value = null;

                    if (dataMember.IsGetOnlyCollection)
                    {
                        _ilg.LoadAddress(_objectLocal);
                        _ilg.LoadMember(dataMember.MemberInfo);
                        value = _ilg.DeclareLocal(memberType, dataMember.Name + "Value");
                        _ilg.Stloc(value);
                        _ilg.Call(_contextArg, XmlFormatGeneratorStatics.StoreCollectionMemberInfoMethod, value);
                        ReadValue(memberType, dataMember.Name, classContract.StableName.Namespace);
                    }
                    else
                    {
                        value = ReadValue(memberType, dataMember.Name, classContract.StableName.Namespace);
                        _ilg.LoadAddress(_objectLocal);
                        _ilg.ConvertAddress(_objectLocal.LocalType, _objectType);
                        _ilg.Ldloc(value);
                        _ilg.StoreMember(dataMember.MemberInfo);
                    }

#if FEATURE_LEGACYNETCF
                    // The DataContractSerializer in the full framework doesn't support unordered elements:
                    // deserialization will fail if the data members in the XML are not sorted alphabetically.
                    // But the NetCF DataContractSerializer does support unordered element. To maintain compatibility
                    // with Mango we always search for the member from the beginning of the member list.
                    // We set memberIndexLocal to -1 because GetMemberIndex always starts from memberIndex+1.
                    if (CompatibilitySwitches.IsAppEarlierThanWindowsPhone8)
                    {
                        ilg.Set(memberIndexLocal, (int)-1);
                    }
                    else
#endif // FEATURE_LEGACYNETCF
                    _ilg.Set(memberIndexLocal, memberCount);

                    _ilg.EndCase();
                }
                return(memberCount);
            }
        private static void PopulateReadOnlyCollection(object instance, DataMember member, IEnumerable value)
        {
            Debug.Assert(member.IsGetOnlyCollection);

            CollectionDataContract memberContract = (CollectionDataContract)member.MemberTypeContract;
            var collection = DataContractToObjectConverter.GetMemberValue(instance, member.MemberInfo, instance.GetType());

            // Special case an array
            var array = collection as Array;
            if (array != null)
            {
                Array srcArray = (Array)value;
                Type elementType = srcArray.GetType().GetElementType();

                // Resize
                var resizeMethod = typeof(Array).GetMethod("Resize", BindingFlags.Static | BindingFlags.Public);
                var properResizeMethod = resizeMethod.MakeGenericMethod(elementType);
                properResizeMethod.Invoke(null, new object[] { array, srcArray.Length });

                // Copy
                Array.Copy(srcArray, 0, array, 0, srcArray.Length);
                return;
            }

            // General collection
            IEnumerator enumerator = value.GetEnumerator();
            object currentItem = null;
            object[] currentItemArray = null;

            while (enumerator.MoveNext())
            {
                currentItem = enumerator.Current;
                currentItemArray = new object[] { currentItem };
                // Dictionary
                if (memberContract.IsDictionary)
                {
                    Type currentItemType = currentItem.GetType();
                    MemberInfo keyMember = currentItemType.GetMember("Key")[0];
                    MemberInfo valueMember = currentItemType.GetMember("Value")[0];
                    currentItemArray = new object[] { DataContractToObjectConverter.GetMemberValue(currentItem, keyMember, currentItemType), DataContractToObjectConverter.GetMemberValue(currentItem, valueMember, currentItemType) };
                }

                memberContract.AddMethod.Invoke(collection, currentItemArray);
            }
        }
 private bool CheckIfMemberHasConflict(DataMember dataMember)
 {
     if (dataMember.HasConflictingNameAndType)
     {
         return true;
     }
     for (DataMember member = dataMember.ConflictingMember; member != null; member = member.ConflictingMember)
     {
         if (member.HasConflictingNameAndType)
         {
             return true;
         }
     }
     return false;
 }
 internal DataMember BindGenericParameters(DataContract[] paramContracts, Dictionary<DataContract, DataContract> boundContracts)
 {
     DataContract memberTypeContract = this.MemberTypeContract.BindGenericParameters(paramContracts, boundContracts);
     DataMember boundDataMember = new DataMember(memberTypeContract,
         this.Name,
         !memberTypeContract.IsValueType,
         this.IsRequired,
         this.EmitDefaultValue,
         this.Order);
     return boundDataMember;
 }
 private XmlElement ExportEmitDefaultValue(DataMember dataMember)
 {
     if (dataMember.EmitDefaultValue)
     {
         return null;
     }
     XmlElement element = this.XmlDoc.CreateElement(DefaultValueAnnotation.Name, DefaultValueAnnotation.Namespace);
     System.Xml.XmlAttribute node = this.XmlDoc.CreateAttribute("EmitDefaultValue");
     node.Value = "false";
     element.Attributes.Append(node);
     return element;
 }
 private LocalBuilder LoadMemberValue(DataMember member)
 {
     this.ilg.LoadAddress(this.objectLocal);
     this.ilg.LoadMember(member.MemberInfo);
     LocalBuilder local = this.ilg.DeclareLocal(member.MemberType, member.Name + "Value");
     this.ilg.Stloc(local);
     return local;
 }
Example #30
0
        private void ExportClassDataContract(ClassDataContract classDataContract, XmlSchema schema)
        {
            XmlSchemaComplexType type = new XmlSchemaComplexType();

            type.Name = classDataContract.StableName.Name;
            schema.Items.Add(type);
            XmlElement?genericInfoElement = null;

            if (classDataContract.UnderlyingType.IsGenericType)
            {
                genericInfoElement = ExportGenericInfo(classDataContract.UnderlyingType, Globals.GenericTypeLocalName, Globals.SerializationNamespace);
            }

            XmlSchemaSequence rootSequence = new XmlSchemaSequence();

            for (int i = 0; i < classDataContract.Members !.Count; i++)
            {
                DataMember dataMember = classDataContract.Members[i];

                XmlSchemaElement element = new XmlSchemaElement();
                element.Name = dataMember.Name;
                XmlElement?  actualTypeElement  = null;
                DataContract memberTypeContract = _dataContractSet.GetMemberTypeDataContract(dataMember);
                if (CheckIfMemberHasConflict(dataMember))
                {
                    element.SchemaTypeName = AnytypeQualifiedName;
                    actualTypeElement      = ExportActualType(memberTypeContract.StableName);
                    SchemaHelper.AddSchemaImport(memberTypeContract.StableName.Namespace, schema);
                }
                else
                {
                    SetElementType(element, memberTypeContract, schema);
                }
                SchemaHelper.AddElementForm(element, schema);
                if (dataMember.IsNullable)
                {
                    element.IsNillable = true;
                }
                if (!dataMember.IsRequired)
                {
                    element.MinOccurs = 0;
                }

                element.Annotation = GetSchemaAnnotation(actualTypeElement, ExportSurrogateData(dataMember), ExportEmitDefaultValue(dataMember));
                rootSequence.Items.Add(element);
            }

            XmlElement?isValueTypeElement = null;

            if (classDataContract.BaseContract != null)
            {
                XmlSchemaComplexContentExtension extension = CreateTypeContent(type, classDataContract.BaseContract.StableName, schema);
                extension.Particle = rootSequence;
                if (classDataContract.IsReference && !classDataContract.BaseContract.IsReference)
                {
                    AddReferenceAttributes(extension.Attributes, schema);
                }
            }
            else
            {
                type.Particle = rootSequence;
                if (classDataContract.IsValueType)
                {
                    isValueTypeElement = GetAnnotationMarkup(IsValueTypeName, XmlConvert.ToString(classDataContract.IsValueType), schema);
                }
                if (classDataContract.IsReference)
                {
                    AddReferenceAttributes(type.Attributes, schema);
                }
            }
            type.Annotation = GetSchemaAnnotation(genericInfoElement, ExportSurrogateData(classDataContract), isValueTypeElement);
        }
 internal DataContract GetMemberTypeDataContract(DataMember dataMember)
 {
     if (dataMember.MemberInfo == null)
     {
         return dataMember.MemberTypeContract;
     }
     Type memberType = dataMember.MemberType;
     if (!dataMember.IsGetOnlyCollection)
     {
         return this.GetDataContract(memberType);
     }
     if ((this.dataContractSurrogate != null) && (DataContractSurrogateCaller.GetDataContractType(this.dataContractSurrogate, memberType) != memberType))
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(System.Runtime.Serialization.SR.GetString("SurrogatesWithGetOnlyCollectionsNotSupported", new object[] { DataContract.GetClrTypeFullName(memberType), DataContract.GetClrTypeFullName(dataMember.MemberInfo.DeclaringType), dataMember.MemberInfo.Name })));
     }
     return DataContract.GetGetOnlyCollectionDataContract(DataContract.GetId(memberType.TypeHandle), memberType.TypeHandle, memberType, SerializationMode.SharedContract);
 }
 public void WriteChildToContext(DataMember contextMember, string prefix)
 {
     this.xPathBuilder.Append("/" + prefix + ":" + contextMember.Name);
 }
 public void WriteChildToContext(DataMember contextMember, string prefix)
 {
     this.xPathBuilder.Append(XPathQueryGenerator.XPathSeparator + prefix + XPathQueryGenerator.NsSeparator + contextMember.Name);
 }
Example #34
0
            private void ImportDataMembers()
            {
                Type type = this.UnderlyingType;

                FieldInfo[] fields = type.GetFields(BindingFlags.Static | BindingFlags.Public);
                Dictionary <string, DataMember> memberValuesTable = new Dictionary <string, DataMember>();
                List <DataMember> tempMembers = new List <DataMember>(fields.Length);
                List <long>       tempValues  = new List <long>(fields.Length);

                for (int i = 0; i < fields.Length; i++)
                {
                    FieldInfo field           = fields[i];
                    bool      enumMemberValid = false;
                    if (_hasDataContract)
                    {
                        object[] memberAttributes = field.GetCustomAttributes(Globals.TypeOfEnumMemberAttribute, false).ToArray();
                        if (memberAttributes != null && memberAttributes.Length > 0)
                        {
                            if (memberAttributes.Length > 1)
                            {
                                ThrowInvalidDataContractException(SR.Format(SR.TooManyEnumMembers, DataContract.GetClrTypeFullName(field.DeclaringType), field.Name));
                            }
                            EnumMemberAttribute memberAttribute = (EnumMemberAttribute)memberAttributes[0];

                            DataMember memberContract = new DataMember(field);
                            if (memberAttribute.IsValueSetExplicitly)
                            {
                                if (memberAttribute.Value == null || memberAttribute.Value.Length == 0)
                                {
                                    ThrowInvalidDataContractException(SR.Format(SR.InvalidEnumMemberValue, field.Name, DataContract.GetClrTypeFullName(type)));
                                }
                                memberContract.Name = memberAttribute.Value;
                            }
                            else
                            {
                                memberContract.Name = field.Name;
                            }
                            ClassDataContract.CheckAndAddMember(tempMembers, memberContract, memberValuesTable);
                            enumMemberValid = true;
                        }

                        object[] dataMemberAttributes = field.GetCustomAttributes(Globals.TypeOfDataMemberAttribute, false).ToArray();
                        if (dataMemberAttributes != null && dataMemberAttributes.Length > 0)
                        {
                            ThrowInvalidDataContractException(SR.Format(SR.DataMemberOnEnumField, DataContract.GetClrTypeFullName(field.DeclaringType), field.Name));
                        }
                    }
                    else
                    {
                        if (!field.IsNotSerialized)
                        {
                            DataMember memberContract = new DataMember(field);
                            memberContract.Name = field.Name;
                            ClassDataContract.CheckAndAddMember(tempMembers, memberContract, memberValuesTable);
                            enumMemberValid = true;
                        }
                    }

                    if (enumMemberValid)
                    {
                        object enumValue = field.GetValue(null);
                        if (_isULong)
                        {
                            tempValues.Add((long)Convert.ToUInt64(enumValue, null));
                        }
                        else
                        {
                            tempValues.Add(Convert.ToInt64(enumValue, null));
                        }
                    }
                }

                Interlocked.MemoryBarrier();
                _members = tempMembers;
                _values  = tempValues;
            }
            bool CheckIfMemberHasConflict(DataMember member, ClassDataContract classContract, ClassDataContract derivedMostClassContract)
            {
                // Check for conflict with base type members
                if (CheckIfConflictingMembersHaveDifferentTypes(member))
                    return true;

                // Check for conflict with derived type members
                string name = member.Name;
                string ns = classContract.StableName.Namespace;
                ClassDataContract currentContract = derivedMostClassContract;
                while (currentContract != null && currentContract != classContract)
                {
                    if (ns == currentContract.StableName.Namespace)
                    {
                        List<DataMember> members = currentContract.Members;
                        for (int j = 0; j < members.Count; j++)
                        {
                            if (name == members[j].Name)
                                return CheckIfConflictingMembersHaveDifferentTypes(members[j]);
                        }
                    }
                    currentContract = currentContract.BaseContract;
                }

                return false;
            }
		object LoadMemberValue (DataMember member)
		{
			return CodeInterpreter.GetMember (member.MemberInfo, objLocal);
		}
            private void ImportSystemExceptionDataMembers()
            {
                /*
                 * The data members imported for System.Exception are private fields. They must be treated specially. 
                 * The EssentialExceptionFields Dictionary keeps track of which private fields needs to be imported, and also the name that they should be serialized with.
                 */

                Type type = this.UnderlyingType;
                List<DataMember> tempMembers;
                tempMembers = new List<DataMember>();
                Dictionary<string, DataMember> memberNamesTable = new Dictionary<string, DataMember>();

                foreach (string fieldInfoName in EssentialExceptionFields.Keys)
                {
                    FieldInfo member = type.GetField(fieldInfoName, BindingFlags.NonPublic | BindingFlags.DeclaredOnly | BindingFlags.Instance);

                    if (CanSerializeMember(member))
                    {
                        DataMember memberContract = new DataMember(member);

                        memberContract.Name = DataContract.EncodeLocalName(member.Name);
                        memberContract.IsRequired = false;
                        memberContract.IsNullable = DataContract.IsTypeNullable(memberContract.MemberType);
                        CheckAndAddMember(tempMembers, memberContract, memberNamesTable);
                    }
                }
                Interlocked.MemoryBarrier();
                _members = tempMembers;
            }
        GenericInfo GetGenericInfoForDataMember(DataMember dataMember)
        {
            GenericInfo genericInfo = null;
            if (dataMember.MemberTypeContract.IsValueType && dataMember.IsNullable)
            {
                genericInfo = new GenericInfo(DataContract.GetStableName(Globals.TypeOfNullable), Globals.TypeOfNullable.FullName);
                genericInfo.Add(new GenericInfo(dataMember.MemberTypeContract.StableName, null));
            }
            else
            {
                genericInfo = new GenericInfo(dataMember.MemberTypeContract.StableName, null);
            }

            return genericInfo;
        }
 private static void CheckAndAddMember(List<DataMember> members, DataMember memberContract, Dictionary<string, DataMember> memberNamesTable)
 {
     DataMember existingMemberContract;
     if (memberNamesTable.TryGetValue(memberContract.Name, out existingMemberContract))
     {
         Type declaringType = memberContract.MemberInfo.DeclaringType;
         DataContract.ThrowInvalidDataContractException(
             SR.Format(SR.DupMemberName,
                 existingMemberContract.MemberInfo.Name,
                 memberContract.MemberInfo.Name,
                 DataContract.GetClrTypeFullName(declaringType),
                 memberContract.Name),
             declaringType);
     }
     memberNamesTable.Add(memberContract.Name, memberContract);
     members.Add(memberContract);
 }
 private void ImportClassMember(XmlSchemaElement element, ClassDataContract dataContract)
 {
     bool flag3;
     XmlQualifiedName stableName = dataContract.StableName;
     if (element.MinOccurs > 1M)
     {
         ThrowTypeCannotBeImportedException(stableName.Name, stableName.Namespace, System.Runtime.Serialization.SR.GetString("ElementMinOccursMustBe", new object[] { element.Name }));
     }
     if (element.MaxOccurs != 1M)
     {
         ThrowTypeCannotBeImportedException(stableName.Name, stableName.Namespace, System.Runtime.Serialization.SR.GetString("ElementMaxOccursMustBe", new object[] { element.Name }));
     }
     DataContract contract = null;
     string name = element.Name;
     bool isRequired = element.MinOccurs > 0M;
     bool isNillable = element.IsNillable;
     int order = 0;
     XmlSchemaForm form = (element.Form == XmlSchemaForm.None) ? SchemaHelper.GetSchemaWithType(this.SchemaObjects, this.schemaSet, stableName).ElementFormDefault : element.Form;
     if (form != XmlSchemaForm.Qualified)
     {
         ThrowTypeCannotBeImportedException(stableName.Name, stableName.Namespace, System.Runtime.Serialization.SR.GetString("FormMustBeQualified", new object[] { element.Name }));
     }
     this.CheckIfElementUsesUnsupportedConstructs(stableName, element);
     if (element.SchemaTypeName.IsEmpty)
     {
         if (element.SchemaType != null)
         {
             contract = this.ImportAnonymousElement(element, new XmlQualifiedName(string.Format(CultureInfo.InvariantCulture, "{0}.{1}Type", new object[] { stableName.Name, element.Name }), stableName.Namespace));
         }
         else if (!element.RefName.IsEmpty)
         {
             ThrowTypeCannotBeImportedException(stableName.Name, stableName.Namespace, System.Runtime.Serialization.SR.GetString("ElementRefOnLocalElementNotSupported", new object[] { element.RefName.Name, element.RefName.Namespace }));
         }
         else
         {
             contract = this.ImportType(SchemaExporter.AnytypeQualifiedName);
         }
     }
     else
     {
         XmlQualifiedName typeName = ImportActualType(element.Annotation, element.SchemaTypeName, stableName);
         contract = this.ImportType(typeName);
         if (IsObjectContract(contract))
         {
             this.needToImportKnownTypesForObject = true;
         }
     }
     bool? nullable = this.ImportEmitDefaultValue(element.Annotation, stableName);
     if (!contract.IsValueType && !isNillable)
     {
         if (nullable.HasValue && nullable.Value)
         {
             throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(System.Runtime.Serialization.SR.GetString("InvalidEmitDefaultAnnotation", new object[] { name, stableName.Name, stableName.Namespace })));
         }
         flag3 = false;
     }
     else
     {
         flag3 = nullable.HasValue ? nullable.Value : true;
     }
     int num2 = dataContract.Members.Count - 1;
     if (num2 >= 0)
     {
         DataMember x = dataContract.Members[num2];
         if (x.Order > 0)
         {
             order = dataContract.Members.Count;
         }
         DataMember y = new DataMember(contract, name, isNillable, isRequired, flag3, order);
         int num3 = ClassDataContract.DataMemberComparer.Singleton.Compare(x, y);
         if (num3 == 0)
         {
             ThrowTypeCannotBeImportedException(stableName.Name, stableName.Namespace, System.Runtime.Serialization.SR.GetString("CannotHaveDuplicateElementNames", new object[] { name }));
         }
         else if (num3 > 0)
         {
             order = dataContract.Members.Count;
         }
     }
     DataMember key = new DataMember(contract, name, isNillable, isRequired, flag3, order);
     XmlQualifiedName surrogateDataAnnotationName = SchemaExporter.SurrogateDataAnnotationName;
     this.dataContractSet.SetSurrogateData(key, this.ImportSurrogateData(ImportAnnotation(element.Annotation, surrogateDataAnnotationName), surrogateDataAnnotationName.Name, surrogateDataAnnotationName.Namespace));
     dataContract.Members.Add(key);
 }