public XmlObjectSerializerWriteContextComplexJson(DataContractJsonSerializer serializer, DataContract rootTypeDataContract) : base(serializer, serializer.MaxItemsInObjectGraph, new StreamingContext(StreamingContextStates.All), serializer.IgnoreExtensionDataObject)
 {
     this.alwaysEmitXsiType = serializer.AlwaysEmitTypeInformation;
     base.rootTypeDataContract = rootTypeDataContract;
     base.serializerKnownTypeList = serializer.knownTypeList;
     base.dataContractSurrogate = serializer.DataContractSurrogate;
 }
 public void Add(XmlQualifiedName name, DataContract dataContract)
 {
     if (!dataContract.IsBuiltInDataContract)
     {
         this.InternalAdd(name, dataContract);
     }
 }
Пример #3
0
        void ExportDataContract(DataContract dataContract)
        {
            if (dataContract.IsBuiltInDataContract)
                return;
            else if (dataContract is XmlDataContract)
                ExportXmlDataContract((XmlDataContract)dataContract);
            else
            {
                XmlSchema schema = GetSchema(dataContract.StableName.Namespace);

                if (dataContract is ClassDataContract)
                {
                    ClassDataContract classDataContract = (ClassDataContract)dataContract;
                    if (classDataContract.IsISerializable)
                        ExportISerializableDataContract(classDataContract, schema);
                    else
                        ExportClassDataContract(classDataContract, schema);
                }
                else if (dataContract is CollectionDataContract)
                    ExportCollectionDataContract((CollectionDataContract)dataContract, schema);
                else if (dataContract is EnumDataContract)
                    ExportEnumDataContract((EnumDataContract)dataContract, schema);
                ExportTopLevelElement(dataContract, schema);
                Schemas.Reprocess(schema);
            }
        }
 public XmlObjectSerializerReadContextComplexJson(DataContractJsonSerializer serializer, DataContract rootTypeDataContract)
     : base(null, int.MaxValue, new StreamingContext(), true)
 {
     this.rootTypeDataContract = rootTypeDataContract;
     this.serializerKnownTypeList = serializer.KnownTypes;
     _jsonSerializer = serializer;
 }
 internal XmlObjectSerializerReadContextComplex(DataContractSerializer serializer, DataContract rootTypeDataContract, DataContractResolver dataContractResolver)
     : base(serializer, rootTypeDataContract, dataContractResolver)
 {
     _mode = SerializationMode.SharedContract;
     _preserveObjectReferences = serializer.PreserveObjectReferences;
     _serializationSurrogateProvider = serializer.SerializationSurrogateProvider;
 }
 internal XmlObjectSerializerReadContextComplex(DataContractSerializer serializer, DataContract rootTypeDataContract, DataContractResolver dataContractResolver)
     : base(serializer, rootTypeDataContract, dataContractResolver)
 {
     this.mode = SerializationMode.SharedContract;
     this.preserveObjectReferences = serializer.PreserveObjectReferences;
     this.dataContractSurrogate = serializer.DataContractSurrogate;
 }
        internal void CheckIfTypeNeedsVerifcation(DataContract declaredContract, DataContract runtimeContract)
        {
            bool verifyType = true;
            CollectionDataContract collectionContract = declaredContract as CollectionDataContract;
            if (collectionContract != null && collectionContract.UnderlyingType.GetTypeInfo().IsInterface)
            {
                switch (collectionContract.Kind)
                {
                    case CollectionKind.Dictionary:
                    case CollectionKind.GenericDictionary:
                        verifyType = declaredContract.Name == runtimeContract.Name;
                        break;

                    default:
                        Type t = collectionContract.ItemType.MakeArrayType();
                        verifyType = (t != runtimeContract.UnderlyingType);
                        break;
                }
            }

            if (verifyType)
            {
                this.PushKnownTypes(declaredContract);
                VerifyType(runtimeContract);
                this.PopKnownTypes(declaredContract);
            }
        }
 internal static DataContract GetRevisedItemContract(DataContract oldItemContract)
 {
     if (((oldItemContract != null) && oldItemContract.UnderlyingType.IsGenericType) && (oldItemContract.UnderlyingType.GetGenericTypeDefinition() == Globals.TypeOfKeyValue))
     {
         return ClassDataContract.CreateClassDataContractForKeyValue(oldItemContract.UnderlyingType, oldItemContract.Namespace, new string[] { "Key", "Value" });
     }
     return oldItemContract;
 }
 internal XmlObjectSerializerReadContextComplexJson(DataContractJsonSerializerImpl serializer, DataContract rootTypeDataContract)
     : base(serializer, serializer.MaxItemsInObjectGraph, new StreamingContext(), false)
 {
     this.rootTypeDataContract = rootTypeDataContract;
     this.serializerKnownTypeList = serializer.knownTypeList;
     _dateTimeFormat = serializer.DateTimeFormat;
     _useSimpleDictionaryFormat = serializer.UseSimpleDictionaryFormat;
 }
 static DataContract ProcessDataContract(DataContract contract, ExportContext context, MemberInfo memberNode)
 {
     if (contract is ClassDataContract)
     {
         return ProcessClassDataContract((ClassDataContract)contract, context, memberNode);
     }
     throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.GetString(SR.QueryGeneratorPathToMemberNotFound)));
 }
Пример #11
0
 public static JsonReadWriteDelegates GetGeneratedReadWriteDelegates(DataContract c)
 {
     // this method used to be rewritten by an IL transform
     // with the restructuring for multi-file, this is no longer true - instead
     // this has become a normal method
     JsonReadWriteDelegates result;
     return JsonReadWriteDelegates.GetJsonDelegates().TryGetValue(c, out result) ? result : null;
 }
Пример #12
0
 internal XmlObjectSerializerContext(DataContractSerializer serializer, DataContract rootTypeDataContract, DataContractResolver dataContractResolver)
     : this(serializer,
     serializer.MaxItemsInObjectGraph,
     new StreamingContext(StreamingContextStates.All),
     serializer.IgnoreExtensionDataObject,
     dataContractResolver)
 {
     this.rootTypeDataContract = rootTypeDataContract;
     this.serializerKnownTypeList = serializer.knownTypeList;
 }
        internal DataContract ResolveDataContractFromType(string typeName, string typeNs, DataContract memberTypeContract)
        {
            this.PushKnownTypes(this.rootTypeDataContract);
            this.PushKnownTypes(memberTypeContract);
            XmlQualifiedName qname = ParseQualifiedName(typeName);
            DataContract contract = ResolveDataContractFromKnownTypes(qname.Name, TrimNamespace(qname.Namespace), memberTypeContract);

            this.PopKnownTypes(this.rootTypeDataContract);
            this.PopKnownTypes(memberTypeContract);
            return contract;
        }
Пример #14
0
 internal static JsonReadWriteDelegates GetReadWriteDelegatesFromGeneratedAssembly(DataContract c)
 {
     JsonReadWriteDelegates result = GetGeneratedReadWriteDelegates(c);
     if (result == null)
     {
         throw new InvalidDataContractException(string.Format(SR.SerializationCodeIsMissingForType, c.UnderlyingType.ToString()));
     }
     else
     {
         return result;
     }
 }
 internal bool CheckIfNeedsContractNsAtRoot(XmlDictionaryString name, XmlDictionaryString ns, DataContract contract)
 {
     if (name == null)
     {
         return false;
     }
     if ((contract.IsBuiltInDataContract || !contract.CanContainReferences) || contract.IsISerializable)
     {
         return false;
     }
     string str = XmlDictionaryString.GetString(contract.Namespace);
     return (!string.IsNullOrEmpty(str) && !(str == XmlDictionaryString.GetString(ns)));
 }
 internal override object InternalDeserialize(XmlReaderDelegator xmlReader, Type declaredType, DataContract dataContract, string name, string ns)
 {
     if (_mode == SerializationMode.SharedContract)
     {
         //if (dataContractSurrogate == null)
         return base.InternalDeserialize(xmlReader, declaredType, dataContract, name, ns);
         //else
         //    return InternalDeserializeWithSurrogate(xmlReader, declaredType, dataContract, name, ns);
     }
     else
     {
         return InternalDeserializeInSharedTypeMode(xmlReader, -1, declaredType, name, ns);
     }
 }
Пример #17
0
        public static JsonReadWriteDelegates GetGeneratedReadWriteDelegates(DataContract c)
        {
            // this method used to be rewritten by an IL transform
            // with the restructuring for multi-file, this is no longer true - instead
            // this has become a normal method
            JsonReadWriteDelegates result;
#if NET_NATIVE
            // The c passed in could be a clone which is different from the original key,
            // We'll need to get the original key data contract from generated assembly.
            DataContract keyDc = DataContract.GetDataContractFromGeneratedAssembly(c.UnderlyingType);
            return JsonReadWriteDelegates.GetJsonDelegates().TryGetValue(keyDc, out result) ? result : null;
#else
            return JsonReadWriteDelegates.GetJsonDelegates().TryGetValue(c, out result) ? result : null;
#endif
        }
		public void WriteCollectionToXml (XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context, CollectionDataContract collectionContract)
		{
			this.writer = xmlWriter;
			this.obj = obj;
			this.ctx = context;
			this.dataContract = collectionContract;

			InitArgs (collectionContract.UnderlyingType);			

			// DemandMemberAccessPermission(memberAccessFlag);
			if (collectionContract.IsReadOnlyContract)
			{
				DataContract.ThrowInvalidDataContractException (collectionContract.SerializationExceptionMessage, null);
			}

			WriteCollection (collectionContract);
		}
		public void WriteToXml (XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context, ClassDataContract dataContract)
		{
			this.writer = xmlWriter;
			this.obj = obj;
			this.ctx = context;
			this.dataContract = dataContract;

			InitArgs (classContract.UnderlyingType);

			// DemandSerializationFormatterPermission (classContract) - irrelevant
			// DemandMemberAccessPermission (memberAccessFlag) - irrelevant

			if (classContract.IsReadOnlyContract)
			{
				DataContract.ThrowInvalidDataContractException (classContract.SerializationExceptionMessage, null);
			}

			WriteClass (classContract);
		}
 internal DataContract GetDataContract(RuntimeTypeHandle typeHandle, Type type, ref Hashtable surrogateDataContracts)
 {
     DataContract contract = GetDataContractFromSurrogateSelector(this.surrogateSelector, this.Context, typeHandle, type, ref surrogateDataContracts);
     if (contract != null)
     {
         return contract;
     }
     if (this.cachedDataContract == null)
     {
         contract = DataContract.GetDataContract(typeHandle, type, SerializationMode.SharedType);
         this.cachedDataContract = contract;
         return contract;
     }
     DataContract cachedDataContract = this.cachedDataContract;
     if (cachedDataContract.UnderlyingType.TypeHandle.Equals(typeHandle))
     {
         return cachedDataContract;
     }
     return DataContract.GetDataContract(typeHandle, type, SerializationMode.SharedType);
 }
 private void HandleCollectionAssignedToObject(Type declaredType, ref DataContract dataContract, ref object obj, ref bool verifyKnownType)
 {
     if ((declaredType != dataContract.UnderlyingType) && (dataContract is CollectionDataContract))
     {
         if (verifyKnownType)
         {
             this.VerifyType(dataContract, declaredType);
             verifyKnownType = false;
         }
         if (((CollectionDataContract) dataContract).Kind == CollectionKind.Dictionary)
         {
             IDictionary dictionary = obj as IDictionary;
             Dictionary<object, object> dictionary2 = new Dictionary<object, object>();
             foreach (DictionaryEntry entry in dictionary)
             {
                 dictionary2.Add(entry.Key, entry.Value);
             }
             obj = dictionary2;
         }
         dataContract = base.GetDataContract(Globals.TypeOfIEnumerable);
     }
 }
Пример #22
0
        private static bool InvokeSchemaProviderMethod(Type clrType, XmlSchemaSet schemas, out XmlQualifiedName stableName, out XmlSchemaType xsdType, out bool hasRoot)
        {
            xsdType = null;
            hasRoot = true;
            object[] attrs = clrType.GetTypeInfo().GetCustomAttributes(Globals.TypeOfXmlSchemaProviderAttribute, false).ToArray();
            if (attrs == null || attrs.Length == 0)
            {
                stableName = DataContract.GetDefaultStableName(clrType);
                return(false);
            }

            XmlSchemaProviderAttribute provider = (XmlSchemaProviderAttribute)attrs[0];

            if (provider.IsAny)
            {
                xsdType = CreateAnyElementType();
                hasRoot = false;
            }
            string methodName = provider.MethodName;

            if (methodName == null || methodName.Length == 0)
            {
                if (!provider.IsAny)
                {
                    throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.InvalidGetSchemaMethod, DataContract.GetClrTypeFullName(clrType))));
                }
                stableName = DataContract.GetDefaultStableName(clrType);
            }
            else
            {
                MethodInfo getMethod = clrType.GetMethod(methodName, /*BindingFlags.DeclaredOnly |*/ BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public, new Type[] { typeof(XmlSchemaSet) });
                if (getMethod == null)
                {
                    throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.MissingGetSchemaMethod, DataContract.GetClrTypeFullName(clrType), methodName)));
                }

                if (!(Globals.TypeOfXmlQualifiedName.IsAssignableFrom(getMethod.ReturnType)))
                {
                    throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.InvalidReturnTypeOnGetSchemaMethod, DataContract.GetClrTypeFullName(clrType), methodName, DataContract.GetClrTypeFullName(getMethod.ReturnType), DataContract.GetClrTypeFullName(Globals.TypeOfXmlQualifiedName))));
                }

                object typeInfo = getMethod.Invoke(null, new object[] { schemas });

                if (provider.IsAny)
                {
                    if (typeInfo != null)
                    {
                        throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.InvalidNonNullReturnValueByIsAny, DataContract.GetClrTypeFullName(clrType), methodName)));
                    }
                    stableName = DataContract.GetDefaultStableName(clrType);
                }
                else if (typeInfo == null)
                {
                    xsdType    = CreateAnyElementType();
                    hasRoot    = false;
                    stableName = DataContract.GetDefaultStableName(clrType);
                }
                else
                {
                    stableName = (XmlQualifiedName)typeInfo;
                }
            }
            return(true);
        }
Пример #23
0
 public override void WriteFullEndElement()
 {
     if (_depth == 0)
     {
         throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.IXmlSerializableWritePastSubTree, (_obj == null ? string.Empty : DataContract.GetClrTypeFullName(_obj.GetType())))));
     }
     _xmlWriter.WriteFullEndElement();
     _depth--;
 }
        protected void SerializeAndVerifyType(DataContract dataContract, XmlWriterDelegator xmlWriter, object obj, bool verifyKnownType, RuntimeTypeHandle declaredTypeHandle, Type declaredType)
        {
            bool knownTypesAddedInCurrentScope = false;

            if (dataContract.KnownDataContracts != null)
            {
                scopedKnownTypes.Push(dataContract.KnownDataContracts);
                knownTypesAddedInCurrentScope = true;
            }

#if !NET_NATIVE
            if (verifyKnownType)
            {
                if (!IsKnownType(dataContract, declaredType))
                {
                    DataContract knownContract = ResolveDataContractFromKnownTypes(dataContract.StableName.Name, dataContract.StableName.Namespace, null /*memberTypeContract*/);
                    if (knownContract == null || knownContract.UnderlyingType != dataContract.UnderlyingType)
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.DcTypeNotFoundOnSerialize, DataContract.GetClrTypeFullName(dataContract.UnderlyingType), dataContract.StableName.Name, dataContract.StableName.Namespace)));
                    }
                }
            }
#endif
            WriteDataContractValue(dataContract, xmlWriter, obj, declaredTypeHandle);

            if (knownTypesAddedInCurrentScope)
            {
                scopedKnownTypes.Pop();
            }
        }
Пример #25
0
 private object ReflectionInternalDeserialize(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context, CollectionDataContract collectionContract, Type type, string name, string ns)
 {
     return(context.InternalDeserialize(xmlReader, DataContract.GetId(type.TypeHandle), type.TypeHandle, name, ns));
 }
 internal virtual bool WriteClrTypeInfo(XmlWriterDelegator xmlWriter, DataContract dataContract)
 {
     return(false);
 }
Пример #27
0
 private Exception CreateInvalidPrimitiveTypeException(Type type)
 {
     return(new InvalidDataContractException(SR.Format(SR.InvalidPrimitiveType, DataContract.GetClrTypeFullName(type))));
 }
Пример #28
0
        private static bool InvokeSchemaProviderMethod(Type clrType, XmlSchemaSet schemas, out XmlQualifiedName stableName, out XmlSchemaType xsdType, out bool hasRoot)
        {
            xsdType = null;
            hasRoot = true;
            object[] attrs = clrType.GetCustomAttributes(Globals.TypeOfXmlSchemaProviderAttribute, false);
            if (attrs == null || attrs.Length == 0)
            {
                stableName = DataContract.GetDefaultStableName(clrType);
                return(false);
            }

            XmlSchemaProviderAttribute provider = (XmlSchemaProviderAttribute)attrs[0];

            if (provider.IsAny)
            {
                xsdType = CreateAnyElementType();
                hasRoot = false;
            }
            string methodName = provider.MethodName;

            if (methodName == null || methodName.Length == 0)
            {
                if (!provider.IsAny)
                {
                    throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.InvalidGetSchemaMethod, DataContract.GetClrTypeFullName(clrType))));
                }
                stableName = DataContract.GetDefaultStableName(clrType);
            }
            else
            {
                MethodInfo getMethod = clrType.GetMethod(methodName, /*BindingFlags.DeclaredOnly |*/ BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public, null, new Type[] { typeof(XmlSchemaSet) }, null);
                if (getMethod == null)
                {
                    throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.MissingGetSchemaMethod, DataContract.GetClrTypeFullName(clrType), methodName)));
                }

                if (!(Globals.TypeOfXmlQualifiedName.IsAssignableFrom(getMethod.ReturnType)) && !(Globals.TypeOfXmlSchemaType.IsAssignableFrom(getMethod.ReturnType)))
                {
                    throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.InvalidReturnTypeOnGetSchemaMethod, DataContract.GetClrTypeFullName(clrType), methodName, DataContract.GetClrTypeFullName(getMethod.ReturnType), DataContract.GetClrTypeFullName(Globals.TypeOfXmlQualifiedName), typeof(XmlSchemaType))));
                }

                object typeInfo = getMethod.Invoke(null, new object[] { schemas });

                if (provider.IsAny)
                {
                    if (typeInfo != null)
                    {
                        throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.InvalidNonNullReturnValueByIsAny, DataContract.GetClrTypeFullName(clrType), methodName)));
                    }
                    stableName = DataContract.GetDefaultStableName(clrType);
                }
                else if (typeInfo == null)
                {
                    xsdType    = CreateAnyElementType();
                    hasRoot    = false;
                    stableName = DataContract.GetDefaultStableName(clrType);
                }
                else
                {
                    XmlSchemaType providerXsdType = typeInfo as XmlSchemaType;
                    if (providerXsdType != null)
                    {
                        string typeName = providerXsdType.Name;
                        string typeNs   = null;
                        if (typeName == null || typeName.Length == 0)
                        {
                            DataContract.GetDefaultStableName(DataContract.GetClrTypeFullName(clrType), out typeName, out typeNs);
                            stableName = new XmlQualifiedName(typeName, typeNs);
                            providerXsdType.Annotation = GetSchemaAnnotation(ExportActualType(stableName, new XmlDocument()));
                            xsdType = providerXsdType;
                        }
                        else
                        {
                            foreach (XmlSchema schema in schemas.Schemas())
                            {
                                foreach (XmlSchemaObject schemaItem in schema.Items)
                                {
                                    if ((object)schemaItem == (object)providerXsdType)
                                    {
                                        typeNs = schema.TargetNamespace;
                                        if (typeNs == null)
                                        {
                                            typeNs = string.Empty;
                                        }
                                        break;
                                    }
                                }
                                if (typeNs != null)
                                {
                                    break;
                                }
                            }
                            if (typeNs == null)
                            {
                                throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.MissingSchemaType, typeName, DataContract.GetClrTypeFullName(clrType))));
                            }
                            stableName = new XmlQualifiedName(typeName, typeNs);
                        }
                    }
                    else
                    {
                        stableName = (XmlQualifiedName)typeInfo;
                    }
                }
            }
            return(true);
        }
Пример #29
0
        internal static void GetXmlTypeInfo(Type type, out XmlQualifiedName stableName, out XmlSchemaType xsdType, out bool hasRoot)
        {
            if (IsSpecialXmlType(type, out stableName, out xsdType, out hasRoot))
            {
                return;
            }
            XmlSchemaSet schemas = new XmlSchemaSet();

            schemas.XmlResolver = null;
            InvokeSchemaProviderMethod(type, schemas, out stableName, out xsdType, out hasRoot);
            if (stableName.Name == null || stableName.Name.Length == 0)
            {
                throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.InvalidXmlDataContractName, DataContract.GetClrTypeFullName(type))));
            }
        }
Пример #30
0
        private void ExportXmlDataContract(XmlDataContract dataContract)
        {
            XmlQualifiedName typeQName;
            bool             hasRoot;
            XmlSchemaType    xsdType;

            Type clrType = dataContract.UnderlyingType;

            if (!IsSpecialXmlType(clrType, out typeQName, out xsdType, out hasRoot))
            {
                if (!InvokeSchemaProviderMethod(clrType, _schemas, out typeQName, out xsdType, out hasRoot))
                {
                    InvokeGetSchemaMethod(clrType, _schemas, typeQName);
                }
            }

            if (hasRoot)
            {
                if (!(typeQName.Equals(dataContract.StableName)))
                {
                    Fx.Assert("XML data contract type name does not match schema name");
                }

                XmlSchema schema;
                if (SchemaHelper.GetSchemaElement(Schemas,
                                                  new XmlQualifiedName(dataContract.TopLevelElementName.Value, dataContract.TopLevelElementNamespace.Value),
                                                  out schema) == null)
                {
                    XmlSchemaElement topLevelElement = ExportTopLevelElement(dataContract, schema);
                    topLevelElement.IsNillable = dataContract.IsTopLevelElementNullable;
                    ReprocessAll(_schemas);
                }

                XmlSchemaType anonymousType = xsdType;
                xsdType = SchemaHelper.GetSchemaType(_schemas, typeQName, out schema);
                if (anonymousType == null && xsdType == null && typeQName.Namespace != XmlSchema.Namespace)
                {
                    throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.MissingSchemaType, typeQName, DataContract.GetClrTypeFullName(clrType))));
                }
                if (xsdType != null)
                {
                    xsdType.Annotation = GetSchemaAnnotation(
                        ExportSurrogateData(dataContract),
                        dataContract.IsValueType ?
                        GetAnnotationMarkup(IsValueTypeName, XmlConvert.ToString(dataContract.IsValueType), schema) :
                        null
                        );
                }
            }
        }
Пример #31
0
        private void ExportCollectionDataContract(CollectionDataContract collectionDataContract, XmlSchema schema)
        {
            XmlSchemaComplexType type = new XmlSchemaComplexType();

            type.Name = collectionDataContract.StableName.Name;
            schema.Items.Add(type);
            XmlElement genericInfoElement = null, isDictionaryElement = null;

            if (collectionDataContract.UnderlyingType.IsGenericType && CollectionDataContract.IsCollectionDataContract(collectionDataContract.UnderlyingType))
            {
                genericInfoElement = ExportGenericInfo(collectionDataContract.UnderlyingType, Globals.GenericTypeLocalName, Globals.SerializationNamespace);
            }
            if (collectionDataContract.IsDictionary)
            {
                isDictionaryElement = ExportIsDictionary();
            }
            type.Annotation = GetSchemaAnnotation(isDictionaryElement, genericInfoElement, ExportSurrogateData(collectionDataContract));

            XmlSchemaSequence rootSequence = new XmlSchemaSequence();

            XmlSchemaElement element = new XmlSchemaElement();

            element.Name            = collectionDataContract.ItemName;
            element.MinOccurs       = 0;
            element.MaxOccursString = Globals.OccursUnbounded;
            if (collectionDataContract.IsDictionary)
            {
                ClassDataContract    keyValueContract = collectionDataContract.ItemContract as ClassDataContract;
                XmlSchemaComplexType keyValueType     = new XmlSchemaComplexType();
                XmlSchemaSequence    keyValueSequence = new XmlSchemaSequence();
                foreach (DataMember dataMember in keyValueContract.Members)
                {
                    XmlSchemaElement keyValueElement = new XmlSchemaElement();
                    keyValueElement.Name = dataMember.Name;
                    SetElementType(keyValueElement, _dataContractSet.GetMemberTypeDataContract(dataMember), schema);
                    SchemaHelper.AddElementForm(keyValueElement, schema);
                    if (dataMember.IsNullable)
                    {
                        keyValueElement.IsNillable = true;
                    }
                    keyValueElement.Annotation = GetSchemaAnnotation(ExportSurrogateData(dataMember));
                    keyValueSequence.Items.Add(keyValueElement);
                }
                keyValueType.Particle = keyValueSequence;
                element.SchemaType    = keyValueType;
            }
            else
            {
                if (collectionDataContract.IsItemTypeNullable)
                {
                    element.IsNillable = true;
                }
                DataContract itemContract = _dataContractSet.GetItemTypeDataContract(collectionDataContract);
                SetElementType(element, itemContract, schema);
            }
            SchemaHelper.AddElementForm(element, schema);
            rootSequence.Items.Add(element);

            type.Particle = rootSequence;

            if (collectionDataContract.IsReference)
            {
                AddReferenceAttributes(type.Attributes, schema);
            }
        }
Пример #32
0
        private XmlElement ExportGenericInfo(Type clrType, string elementName, string elementNs)
        {
            Type itemType;
            int  nestedCollectionLevel = 0;

            while (CollectionDataContract.IsCollection(clrType, out itemType))
            {
                if (DataContract.GetBuiltInDataContract(clrType) != null ||
                    CollectionDataContract.IsCollectionDataContract(clrType))
                {
                    break;
                }
                clrType = itemType;
                nestedCollectionLevel++;
            }

            Type[]      genericArguments      = null;
            IList <int> genericArgumentCounts = null;

            if (clrType.IsGenericType)
            {
                genericArguments = clrType.GetGenericArguments();
                string typeName;
                if (clrType.DeclaringType == null)
                {
                    typeName = clrType.Name;
                }
                else
                {
                    int nsLen = (clrType.Namespace == null) ? 0 : clrType.Namespace.Length;
                    if (nsLen > 0)
                    {
                        nsLen++; //include the . following namespace
                    }
                    typeName = DataContract.GetClrTypeFullName(clrType).Substring(nsLen).Replace('+', '.');
                }
                int iParam = typeName.IndexOf('[');
                if (iParam >= 0)
                {
                    typeName = typeName.Substring(0, iParam);
                }
                genericArgumentCounts = DataContract.GetDataContractNameForGenericName(typeName, null);
                clrType = clrType.GetGenericTypeDefinition();
            }
            XmlQualifiedName dcqname = DataContract.GetStableName(clrType);

            if (nestedCollectionLevel > 0)
            {
                string collectionName = dcqname.Name;
                for (int n = 0; n < nestedCollectionLevel; n++)
                {
                    collectionName = Globals.ArrayPrefix + collectionName;
                }
                dcqname = new XmlQualifiedName(collectionName, DataContract.GetCollectionNamespace(dcqname.Namespace));
            }
            XmlElement typeElement = XmlDoc.CreateElement(elementName, elementNs);

            XmlAttribute nameAttribute = XmlDoc.CreateAttribute(Globals.GenericNameAttribute);

            nameAttribute.Value = genericArguments != null?XmlConvert.DecodeName(dcqname.Name) : dcqname.Name;

            //nameAttribute.Value = dcqname.Name;
            typeElement.Attributes.Append(nameAttribute);

            XmlAttribute nsAttribute = XmlDoc.CreateAttribute(Globals.GenericNamespaceAttribute);

            nsAttribute.Value = dcqname.Namespace;
            typeElement.Attributes.Append(nsAttribute);

            if (genericArguments != null)
            {
                int argIndex    = 0;
                int nestedLevel = 0;
                foreach (int genericArgumentCount in genericArgumentCounts)
                {
                    for (int i = 0; i < genericArgumentCount; i++, argIndex++)
                    {
                        XmlElement argumentElement = ExportGenericInfo(genericArguments[argIndex], Globals.GenericParameterLocalName, Globals.SerializationNamespace);
                        if (nestedLevel > 0)
                        {
                            XmlAttribute nestedLevelAttribute = XmlDoc.CreateAttribute(Globals.GenericParameterNestedLevelAttribute);
                            nestedLevelAttribute.Value = nestedLevel.ToString(CultureInfo.InvariantCulture);
                            argumentElement.Attributes.Append(nestedLevelAttribute);
                        }
                        typeElement.AppendChild(argumentElement);
                    }
                    nestedLevel++;
                }
                if (genericArgumentCounts[nestedLevel - 1] == 0)
                {
                    XmlAttribute typeNestedLevelsAttribute = XmlDoc.CreateAttribute(Globals.GenericParameterNestedLevelAttribute);
                    typeNestedLevelsAttribute.Value = genericArgumentCounts.Count.ToString(CultureInfo.InvariantCulture);
                    typeElement.Attributes.Append(typeNestedLevelsAttribute);
                }
            }

            return(typeElement);
        }
Пример #33
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);
        }
Пример #34
0
        // Update the overloads whenever you are changing this method
        internal static void WriteClrTypeInfo(XmlWriterDelegator writer, DataContract dataContract, SerializationBinder binder)
        {
            if (!dataContract.IsISerializable && !(dataContract is SurrogateDataContract))
            {
                TypeInformation typeInformation = null;
                Type clrType = dataContract.OriginalUnderlyingType;
                string clrTypeName = null;
                string clrAssemblyName = null;

                if (binder != null)
                {
                    binder.BindToName(clrType, out clrAssemblyName, out clrTypeName);
                }

                if (clrTypeName == null)
                {
                    typeInformation = NetDataContractSerializer.GetTypeInformation(clrType);
                    clrTypeName = typeInformation.FullTypeName;
                }

                if (clrAssemblyName == null)
                {
                    clrAssemblyName = (typeInformation == null) ?
                        NetDataContractSerializer.GetTypeInformation(clrType).AssemblyString :
                        typeInformation.AssemblyString;

                    // Throw in the [TypeForwardedFrom] case to prevent a partially trusted assembly from forwarding itself to an assembly with higher privileges
                    if (!UnsafeTypeForwardingEnabled && !clrType.Assembly.IsFullyTrusted && !IsAssemblyNameForwardingSafe(clrType.Assembly.FullName, clrAssemblyName))
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.GetString(SR.TypeCannotBeForwardedFrom, DataContract.GetClrTypeFullName(clrType), clrType.Assembly.FullName, clrAssemblyName)));
                    }
                }

                WriteClrTypeInfo(writer, clrTypeName, clrAssemblyName);
            }
        }
Пример #35
0
 internal JsonDataContractCriticalHelper(DataContract traditionalDataContract)
 {
     _traditionalDataContract = traditionalDataContract;
     AddCollectionItemContractsToKnownDataContracts();
     _typeName = string.IsNullOrEmpty(traditionalDataContract.Namespace.Value) ? traditionalDataContract.Name.Value : string.Concat(traditionalDataContract.Name.Value, JsonGlobals.NameValueSeparatorString, XmlObjectSerializerWriteContextComplexJson.TruncateDefaultDataContractNamespace(traditionalDataContract.Namespace.Value));
 }
Пример #36
0
        private static void InvokeGetSchemaMethod(Type clrType, XmlSchemaSet schemas, XmlQualifiedName stableName)
        {
            IXmlSerializable ixmlSerializable = (IXmlSerializable)Activator.CreateInstance(clrType);
            XmlSchema        schema           = ixmlSerializable.GetSchema();

            if (schema == null)
            {
                AddDefaultDatasetType(schemas, stableName.Name, stableName.Namespace);
            }
            else
            {
                if (schema.Id == null || schema.Id.Length == 0)
                {
                    throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.InvalidReturnSchemaOnGetSchemaMethod, DataContract.GetClrTypeFullName(clrType))));
                }
                AddDefaultTypedDatasetType(schemas, schema, stableName.Name, stableName.Namespace);
            }
        }
 internal void HandleGraphAtTopLevel(XmlWriterDelegator writer, object obj, DataContract contract)
 {
     writer.WriteXmlnsAttribute(Globals.XsiPrefix, DictionaryGlobals.SchemaInstanceNamespace);
     OnHandleReference(writer, obj, true /*canContainReferences*/);
 }
        internal bool IsKnownType(DataContract dataContract, Type declaredType)
        {
            DataContract knownContract = ResolveDataContractFromKnownTypes(dataContract.StableName.Name, dataContract.StableName.Namespace, null /*memberTypeContract*/, declaredType);

            return(knownContract != null && knownContract.UnderlyingType == dataContract.UnderlyingType);
        }
 internal static XmlObjectSerializerWriteContext CreateContext(DataContractSerializer serializer, DataContract rootTypeDataContract, DataContractResolver dataContractResolver)
 {
     return((serializer.PreserveObjectReferences || serializer.SerializationSurrogateProvider != null)
         ? new XmlObjectSerializerWriteContextComplex(serializer, rootTypeDataContract, dataContractResolver)
         : new XmlObjectSerializerWriteContext(serializer, rootTypeDataContract, dataContractResolver));
 }
Пример #40
0
 public static JsonDataContract GetJsonDataContract(DataContract traditionalDataContract)
 {
     return JsonDataContractCriticalHelper.GetJsonDataContract(traditionalDataContract);
 }
Пример #41
0
        private CollectionSetItemDelegate GetCollectionSetItemDelegate <T>(CollectionDataContract collectionContract, object resultCollectionObject, bool isReadOnlyCollection)
        {
            if (isReadOnlyCollection && collectionContract.Kind == CollectionKind.Array)
            {
                int arraySize = ((Array)resultCollectionObject).Length;
                return((resultCollection, collectionItem, index) =>
                {
                    if (index == arraySize)
                    {
                        XmlObjectSerializerReadContext.ThrowArrayExceededSizeException(arraySize, collectionContract.UnderlyingType);
                    }

                    ((T[])resultCollection)[index] = (T)collectionItem;
                    return resultCollection;
                });
            }
            else if (!isReadOnlyCollection && IsArrayLikeCollection(collectionContract))
            {
                return((resultCollection, collectionItem, index) =>
                {
                    resultCollection = XmlObjectSerializerReadContext.EnsureArraySize((T[])resultCollection, index);
                    ((T[])resultCollection)[index] = (T)collectionItem;
                    return resultCollection;
                });
            }
            else if (collectionContract.Kind == CollectionKind.GenericDictionary || collectionContract.Kind == CollectionKind.Dictionary)
            {
                Type keyType   = collectionContract.ItemType.GenericTypeArguments[0];
                Type valueType = collectionContract.ItemType.GenericTypeArguments[1];
                Func <object, object> objectToKeyValuePairGetKey   = s_objectToKeyValuePairGetKey.MakeGenericMethod(keyType, valueType).CreateDelegate <Func <object, object> >();
                Func <object, object> objectToKeyValuePairGetValue = s_objectToKeyValuePairGetValue.MakeGenericMethod(keyType, valueType).CreateDelegate <Func <object, object> >();

                if (collectionContract.Kind == CollectionKind.GenericDictionary)
                {
                    return((resultCollection, collectionItem, index) =>
                    {
                        object key = objectToKeyValuePairGetKey(collectionItem);
                        object value = objectToKeyValuePairGetValue(collectionItem);

                        collectionContract.AddMethod.Invoke(resultCollection, new object[] { key, value });
                        return resultCollection;
                    });
                }
                else
                {
                    return((resultCollection, collectionItem, index) =>
                    {
                        object key = objectToKeyValuePairGetKey(collectionItem);
                        object value = objectToKeyValuePairGetValue(collectionItem);

                        IDictionary dict = (IDictionary)resultCollection;
                        dict.Add(key, value);
                        return resultCollection;
                    });
                }
            }
            else
            {
                Type collectionType        = resultCollectionObject.GetType();
                Type genericCollectionType = typeof(ICollection <T>);
                Type typeIList             = Globals.TypeOfIList;
                if (genericCollectionType.IsAssignableFrom(collectionType))
                {
                    return((resultCollection, collectionItem, index) =>
                    {
                        ((ICollection <T>)resultCollection).Add((T)collectionItem);
                        return resultCollection;
                    });
                }
                else if (typeIList.IsAssignableFrom(collectionType))
                {
                    return((resultCollection, collectionItem, index) =>
                    {
                        ((IList)resultCollection).Add(collectionItem);
                        return resultCollection;
                    });
                }
                else
                {
                    MethodInfo addMethod = collectionContract.AddMethod;
                    if (addMethod == null)
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.CollectionMustHaveAddMethod, DataContract.GetClrTypeFullName(collectionContract.UnderlyingType))));
                    }

                    return((resultCollection, collectionItem, index) =>
                    {
                        addMethod.Invoke(resultCollection, new object[] { collectionItem });
                        return resultCollection;
                    });
                }
            }
        }
Пример #42
0
 internal static PrimitiveDataContract GetPrimitiveDataContract(Type type)
 {
     return(DataContract.GetBuiltInDataContract(type) as PrimitiveDataContract);
 }
Пример #43
0
        private object ReadItemOfPrimitiveType(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context, Type type, string name, string ns, PrimitiveDataContract primitiveContract, int nullables)
        {
            object value;

            context.ReadAttributes(xmlReader);
            string objectId        = context.ReadIfNullOrRef(xmlReader, type, DataContract.IsTypeSerializable(type));
            bool   typeIsValueType = type.IsValueType;

            if (objectId != null)
            {
                if (objectId.Length == 0)
                {
                    objectId = context.GetObjectId();

                    if (!string.IsNullOrEmpty(objectId) && typeIsValueType)
                    {
                        throw new SerializationException(SR.Format(SR.ValueTypeCannotHaveId, DataContract.GetClrTypeFullName(type)));
                    }

                    if (primitiveContract != null && primitiveContract.UnderlyingType != Globals.TypeOfObject)
                    {
                        value = primitiveContract.ReadXmlValue(xmlReader, context);
                    }
                    else
                    {
                        value = ReflectionInternalDeserialize(xmlReader, context, null /*collectionContract*/, type, name, ns);
                    }
                }
                else
                {
                    if (typeIsValueType)
                    {
                        throw new SerializationException(SR.Format(SR.ValueTypeCannotHaveRef, DataContract.GetClrTypeFullName(type)));
                    }
                    else
                    {
                        value = context.GetExistingObject(objectId, type, name, ns);
                    }
                }
            }
            else
            {
                if (typeIsValueType && nullables == 0)
                {
                    throw new SerializationException(SR.Format(SR.ValueTypeCannotBeNull, DataContract.GetClrTypeFullName(type)));
                }
                else
                {
                    value = null;
                }
            }

            return(value);
        }
 protected virtual void WriteDataContractValue(DataContract dataContract, XmlWriterDelegator xmlWriter, object obj, RuntimeTypeHandle declaredTypeHandle)
 {
     dataContract.WriteXmlValue(xmlWriter, obj, this);
 }
        protected virtual void SerializeWithXsiType(XmlWriterDelegator xmlWriter, object obj, RuntimeTypeHandle objectTypeHandle, Type objectType, int declaredTypeID, RuntimeTypeHandle declaredTypeHandle, Type declaredType)
        {
            bool verifyKnownType = false;

#if !NET_NATIVE
            DataContract dataContract;
            if (declaredType.GetTypeInfo().IsInterface&& CollectionDataContract.IsCollectionInterface(declaredType))
            {
                dataContract = GetDataContractSkipValidation(DataContract.GetId(objectTypeHandle), objectTypeHandle, objectType);
                if (OnHandleIsReference(xmlWriter, dataContract, obj))
                {
                    return;
                }
                dataContract = GetDataContract(declaredTypeHandle, declaredType);
#else
            DataContract dataContract = DataContract.GetDataContractFromGeneratedAssembly(declaredType);
            if (dataContract.TypeIsInterface && dataContract.TypeIsCollectionInterface)
            {
                if (OnHandleIsReference(xmlWriter, dataContract, obj))
                {
                    return;
                }
                if (this.Mode == SerializationMode.SharedType && dataContract.IsValidContract(this.Mode))
                {
                    dataContract = dataContract.GetValidContract(this.Mode);
                }
                else
                {
                    dataContract = GetDataContract(declaredTypeHandle, declaredType);
                }
#endif
                if (!WriteClrTypeInfo(xmlWriter, dataContract) && DataContractResolver != null)
                {
                    if (objectType == null)
                    {
                        objectType = Type.GetTypeFromHandle(objectTypeHandle);
                    }
                    WriteResolvedTypeInfo(xmlWriter, objectType, declaredType);
                }
            }
            else if (declaredType.IsArray)//Array covariance is not supported in XSD. If declared type is array do not write xsi:type. Instead write xsi:type for each item
            {
                // A call to OnHandleIsReference is not necessary here -- arrays cannot be IsReference
                dataContract = GetDataContract(objectTypeHandle, objectType);
                WriteClrTypeInfo(xmlWriter, dataContract);
                dataContract = GetDataContract(declaredTypeHandle, declaredType);
            }
            else
            {
                dataContract = GetDataContract(objectTypeHandle, objectType);
                if (OnHandleIsReference(xmlWriter, dataContract, obj))
                {
                    return;
                }
                if (!WriteClrTypeInfo(xmlWriter, dataContract))
                {
                    DataContract declaredTypeContract = (declaredTypeID >= 0)
                        ? GetDataContract(declaredTypeID, declaredTypeHandle)
                        : GetDataContract(declaredTypeHandle, declaredType);
                    verifyKnownType = WriteTypeInfo(xmlWriter, dataContract, declaredTypeContract);
                }
            }

            SerializeAndVerifyType(dataContract, xmlWriter, obj, verifyKnownType, declaredTypeHandle, declaredType);
        }
        private static void WriteIXmlSerializable(XmlWriterDelegator xmlWriter, object obj, XmlSerializableWriter xmlSerializableWriter)
        {
            xmlSerializableWriter.BeginWrite(xmlWriter.Writer, obj);
            IXmlSerializable xmlSerializable = obj as IXmlSerializable;

            if (xmlSerializable != null)
            {
                xmlSerializable.WriteXml(xmlSerializableWriter);
            }
            else
            {
                XmlElement xmlElement = obj as XmlElement;
                if (xmlElement != null)
                {
                    xmlElement.WriteTo(xmlSerializableWriter);
                }
                else
                {
                    XmlNode[] xmlNodes = obj as XmlNode[];
                    if (xmlNodes != null)
                    {
                        foreach (XmlNode xmlNode in xmlNodes)
                        {
                            xmlNode.WriteTo(xmlSerializableWriter);
                        }
                    }
                    else
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.UnknownXmlType, DataContract.GetClrTypeFullName(obj.GetType()))));
                    }
                }
            }
            xmlSerializableWriter.EndWrite();
        }
Пример #47
0
 internal void EndWrite()
 {
     if (_depth != 0)
     {
         throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.IXmlSerializableMissingEndElements, (_obj == null ? string.Empty : DataContract.GetClrTypeFullName(_obj.GetType())))));
     }
     _obj = null;
 }
Пример #48
0
 protected JsonDataContract(DataContract traditionalDataContract)
 {
     _helper = new JsonDataContractCriticalHelper(traditionalDataContract);
 }
Пример #49
0
        void InternalWriteObjectContent(XmlWriterDelegator writer, object graph, DataContract contract, Hashtable surrogateDataContracts)
        {
            if (MaxItemsInObjectGraph == 0)
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.GetString(SR.ExceededMaxItemsQuota, MaxItemsInObjectGraph)));

            if (IsRootXmlAny(rootName, contract))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.GetString(SR.IsAnyNotSupportedByNetDataContractSerializer, contract.UnderlyingType)));
            }
            else if (graph == null)
            {
                WriteNull(writer);
            }
            else
            {
                Type graphType = graph.GetType();
                if (contract.UnderlyingType != graphType)
                    contract = GetDataContract(graph, ref surrogateDataContracts);

                XmlObjectSerializerWriteContext context = null;
                if (contract.CanContainReferences)
                {
                    context = XmlObjectSerializerWriteContext.CreateContext(this, surrogateDataContracts);
                    context.HandleGraphAtTopLevel(writer, graph, contract);
                }

                WriteClrTypeInfo(writer, contract, binder);
                contract.WriteXmlValue(writer, graph, context);
            }
        }
Пример #50
0
 internal static PrimitiveDataContract GetPrimitiveDataContract(string name, string ns)
 {
     return(DataContract.GetBuiltInDataContract(name, ns) as PrimitiveDataContract);
 }
Пример #51
0
        internal DataContract GetDataContract(RuntimeTypeHandle typeHandle, Type type, ref Hashtable surrogateDataContracts)
        {
            DataContract dataContract = GetDataContractFromSurrogateSelector(surrogateSelector, Context, typeHandle, type, ref surrogateDataContracts);
            if (dataContract != null)
                return dataContract;

            if (cachedDataContract == null)
            {
                dataContract = DataContract.GetDataContract(typeHandle, type, SerializationMode.SharedType);
                cachedDataContract = dataContract;
                return dataContract;
            }

            DataContract currentCachedDataContract = cachedDataContract;
            if (currentCachedDataContract.UnderlyingType.TypeHandle.Equals(typeHandle))
                return currentCachedDataContract;

            return DataContract.GetDataContract(typeHandle, type, SerializationMode.SharedType);
        }
        protected virtual bool WriteTypeInfo(XmlWriterDelegator writer, DataContract contract, DataContract declaredContract)
        {
            if (XmlObjectSerializer.IsContractDeclared(contract, declaredContract))
            {
                return(false);
            }
            bool hasResolver = DataContractResolver != null;

            if (hasResolver)
            {
                WriteResolvedTypeInfo(writer, contract.UnderlyingType, declaredContract.UnderlyingType);
            }
            else
            {
                WriteTypeInfo(writer, contract.Name, contract.Namespace);
            }
            return(hasResolver);
        }
Пример #53
0
 public static JsonDataContract GetJsonDataContract(DataContract traditionalDataContract)
 {
     int id = JsonDataContractCriticalHelper.GetId(traditionalDataContract.UnderlyingType.TypeHandle);
     JsonDataContract dataContract = s_dataContractCache[id];
     if (dataContract == null)
     {
         dataContract = CreateJsonDataContract(id, traditionalDataContract);
         s_dataContractCache[id] = dataContract;
     }
     return dataContract;
 }
Пример #54
0
 internal DataMember(DataContract memberTypeContract, string name, bool isNullable, bool isRequired, bool emitDefaultValue, int order)
 {
     helper = new CriticalHelper(memberTypeContract, name, isNullable, isRequired, emitDefaultValue, order);
 }
Пример #55
0
 private static JsonDataContract CreateJsonDataContract(int id, DataContract traditionalDataContract)
 {
     lock (s_createDataContractLock)
     {
         JsonDataContract dataContract = s_dataContractCache[id];
         if (dataContract == null)
         {
             Type traditionalDataContractType = traditionalDataContract.GetType();
             if (traditionalDataContractType == typeof(ObjectDataContract))
             {
                 dataContract = new JsonObjectDataContract(traditionalDataContract);
             }
             else if (traditionalDataContractType == typeof(StringDataContract))
             {
                 dataContract = new JsonStringDataContract((StringDataContract)traditionalDataContract);
             }
             else if (traditionalDataContractType == typeof(UriDataContract))
             {
                 dataContract = new JsonUriDataContract((UriDataContract)traditionalDataContract);
             }
             else if (traditionalDataContractType == typeof(QNameDataContract))
             {
                 dataContract = new JsonQNameDataContract((QNameDataContract)traditionalDataContract);
             }
             else if (traditionalDataContractType == typeof(ByteArrayDataContract))
             {
                 dataContract = new JsonByteArrayDataContract((ByteArrayDataContract)traditionalDataContract);
             }
             else if (traditionalDataContract.IsPrimitive ||
                 traditionalDataContract.UnderlyingType == Globals.TypeOfXmlQualifiedName)
             {
                 dataContract = new JsonDataContract(traditionalDataContract);
             }
             else if (traditionalDataContractType == typeof(ClassDataContract))
             {
                 dataContract = new JsonClassDataContract((ClassDataContract)traditionalDataContract);
             }
             else if (traditionalDataContractType == typeof(EnumDataContract))
             {
                 dataContract = new JsonEnumDataContract((EnumDataContract)traditionalDataContract);
             }
             else if ((traditionalDataContractType == typeof(GenericParameterDataContract)) ||
                 (traditionalDataContractType == typeof(SpecialTypeDataContract)))
             {
                 dataContract = new JsonDataContract(traditionalDataContract);
             }
             else if (traditionalDataContractType == typeof(CollectionDataContract))
             {
                 dataContract = new JsonCollectionDataContract((CollectionDataContract)traditionalDataContract);
             }
             else if (traditionalDataContractType == typeof(XmlDataContract))
             {
                 dataContract = new JsonXmlDataContract((XmlDataContract)traditionalDataContract);
             }
             else
             {
                 throw new ArgumentException(SR.Format(SR.JsonTypeNotSupportedByDataContractJsonSerializer, traditionalDataContract.UnderlyingType), "traditionalDataContract");
             }
         }
         return dataContract;
     }
 }
 internal virtual bool OnHandleReference(XmlWriterDelegator xmlWriter, object obj, bool canContainCyclicReference)
 {
     if (xmlWriter.depth < depthToCheckCyclicReference)
     {
         return(false);
     }
     if (canContainCyclicReference)
     {
         if (_byValObjectsInScope.Contains(obj))
         {
             throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.CannotSerializeObjectWithCycles, DataContract.GetClrTypeFullName(obj.GetType()))));
         }
         _byValObjectsInScope.Push(obj);
     }
     return(false);
 }
        protected DataContract ResolveDataContractFromKnownTypes(string typeName, string typeNs, DataContract memberTypeContract, Type declaredType)
        {
            XmlQualifiedName qname = new XmlQualifiedName(typeName, typeNs);
            DataContract     dataContract;

            if (DataContractResolver == null)
            {
                dataContract = ResolveDataContractFromKnownTypes(qname);
            }
            else
            {
                dataContract = ResolveDataContractFromDataContractResolver(qname, declaredType);
            }
            if (dataContract == null)
            {
                if (memberTypeContract != null &&
                    !memberTypeContract.UnderlyingType.IsInterface &&
                    memberTypeContract.StableName == qname)
                {
                    dataContract = memberTypeContract;
                }
                if (dataContract == null && rootTypeDataContract != null)
                {
                    dataContract = ResolveDataContractFromRootDataContract(qname);
                }
            }
            return(dataContract);
        }
 private bool ResolveType(Type objectType, Type declaredType, out XmlDictionaryString typeName, out XmlDictionaryString typeNamespace)
 {
     if (!DataContractResolver.TryResolveType(objectType, declaredType, KnownTypeResolver, out typeName, out typeNamespace))
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.ResolveTypeReturnedFalse, DataContract.GetClrTypeFullName(DataContractResolver.GetType()), DataContract.GetClrTypeFullName(objectType))));
     }
     if (typeName == null)
     {
         if (typeNamespace == null)
         {
             return(false);
         }
         else
         {
             throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.ResolveTypeReturnedNull, DataContract.GetClrTypeFullName(DataContractResolver.GetType()), DataContract.GetClrTypeFullName(objectType))));
         }
     }
     if (typeNamespace == null)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.ResolveTypeReturnedNull, DataContract.GetClrTypeFullName(DataContractResolver.GetType()), DataContract.GetClrTypeFullName(objectType))));
     }
     return(true);
 }
Пример #59
0
 internal static DataContract GetDataContract(DataContract declaredTypeContract, Type declaredType, Type objectType)
 {
     if (declaredType.GetTypeInfo().IsInterface && CollectionDataContract.IsCollectionInterface(declaredType))
     {
         return declaredTypeContract;
     }
     else if (declaredType.IsArray)//Array covariance is not supported in XSD
     {
         return declaredTypeContract;
     }
     else
     {
         return DataContract.GetDataContract(objectType.TypeHandle, objectType, SerializationMode.SharedContract);
     }
 }
Пример #60
0
        public DataContractSerializer(Type type, string rootName, string rootNamespace, IEnumerable <Type>?knownTypes)
        {
            XmlDictionary dictionary = new XmlDictionary(2);

            Initialize(type, dictionary.Add(rootName), dictionary.Add(DataContract.GetNamespace(rootNamespace)), knownTypes, int.MaxValue, false, false, null, false);
        }