public override void WriteFullEndElement() { if (_depth == 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.IXmlSerializableWritePastSubTree, (_obj == null ? string.Empty : DataContract.GetClrTypeFullName(_obj.GetType()))))); } _xmlWriter.WriteFullEndElement(); _depth--; }
internal static void CheckIfTypeIsReference(DataContract dataContract) { if (dataContract.IsReference) { throw XmlObjectSerializer.CreateSerializationException(SR.Format(SR.JsonUnsupportedForIsReference, DataContract.GetClrTypeFullName(dataContract.UnderlyingType), dataContract.IsReference)); } }
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); if (memberAttributes != null && memberAttributes.Length > 0) { if (memberAttributes.Length > 1) { ThrowInvalidDataContractException(SR.TooManyEnumMembers(DataContract.GetClrTypeFullName(field.DeclaringType), field.Name)); } EnumMemberAttribute memberAttribute = (EnumMemberAttribute)memberAttributes[0]; DataMember memberContract = new DataMember(field); // ALTERED_FOR_PORT: Don't have access to .IsSetExplicilty property if (memberAttribute.Value != null && memberAttribute.Value.Length > 0) { memberContract.Name = memberAttribute.Value; } else { memberContract.Name = field.Name; } ClassDataContract.CheckAndAddMember(tempMembers, memberContract, memberValuesTable); enumMemberValid = true; } object[] dataMemberAttributes = field.GetCustomAttributes(Globals.TypeOfDataMemberAttribute, false); if (dataMemberAttributes != null && dataMemberAttributes.Length > 0) { ThrowInvalidDataContractException(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)((IConvertible)enumValue).ToUInt64(null)); } else { tempValues.Add(((IConvertible)enumValue).ToInt64(null)); } } } Thread.MemoryBarrier(); members = tempMembers; values = tempValues; }
internal override DataContract GetDataContract(RuntimeTypeHandle typeHandle, Type type) { DataContract dataContract = null; if (mode == SerializationMode.SharedType && surrogateSelector != null) { dataContract = NetDataContractSerializer.GetDataContractFromSurrogateSelector(surrogateSelector, GetStreamingContext(), typeHandle, type, ref surrogateDataContracts); } if (dataContract != null) { if (IsGetOnlyCollection && dataContract is SurrogateDataContract) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new System.Runtime.Serialization.InvalidDataContractException(SR.Format(SR.SurrogatesWithGetOnlyCollectionsNotSupportedSerDeser, DataContract.GetClrTypeFullName(dataContract.UnderlyingType)))); } return(dataContract); } return(base.GetDataContract(typeHandle, type)); }
void VerifyType(DataContract dataContract, Type declaredType) { bool knownTypesAddedInCurrentScope = false; if (dataContract.KnownDataContracts != null) { scopedKnownTypes.Push(dataContract.KnownDataContracts); knownTypesAddedInCurrentScope = true; } if (!IsKnownType(dataContract, declaredType)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.GetString(SR.DcTypeNotFoundOnSerialize, DataContract.GetClrTypeFullName(dataContract.UnderlyingType), dataContract.StableName.Name, dataContract.StableName.Namespace))); } if (knownTypesAddedInCurrentScope) { scopedKnownTypes.Pop(); } }
public static void ThrowDuplicateMemberException(object obj, XmlDictionaryString[] memberNames, int memberIndex) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SerializationException( SR.GetString(SR.JsonDuplicateMemberInInput, DataContract.GetClrTypeFullName(obj.GetType()), memberNames[memberIndex]))); }
private object InternalDeserializeWithSurrogate(XmlReaderDelegator xmlReader, Type declaredType, DataContract surrogateDataContract, string name, string ns) { DataContract dataContract = surrogateDataContract ?? GetDataContract(DataContractSurrogateCaller.GetDataContractType(dataContractSurrogate, declaredType)); if (IsGetOnlyCollection && dataContract.UnderlyingType != declaredType) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new System.Runtime.Serialization.InvalidDataContractException(SR.Format(SR.SurrogatesWithGetOnlyCollectionsNotSupportedSerDeser, DataContract.GetClrTypeFullName(declaredType)))); } ReadAttributes(xmlReader); string objectId = GetObjectId(); object oldObj = InternalDeserialize(xmlReader, name, ns, declaredType, ref dataContract); object obj = DataContractSurrogateCaller.GetDeserializedObject(dataContractSurrogate, oldObj, dataContract.UnderlyingType, declaredType); ReplaceDeserializedObject(objectId, oldObj, obj); return(obj); }
private XmlElement ExportGenericInfo(Type clrType, string elementName, string elementNs) { int nestedCollectionLevel = 0; while (CollectionDataContract.IsCollection(clrType, out Type 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); }
private void ExportXmlDataContract(XmlDataContract dataContract) { Type clrType = dataContract.UnderlyingType; if (!IsSpecialXmlType(clrType, out XmlQualifiedName typeQName, out XmlSchemaType xsdType, out bool 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"); } if (SchemaHelper.GetSchemaElement(Schemas, new XmlQualifiedName(dataContract.TopLevelElementName.Value, dataContract.TopLevelElementNamespace.Value), out XmlSchema 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 Compat.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 ); } } }
private void VerifyType(DataContract dataContract, Type declaredType) { bool knownTypesAddedInCurrentScope = false; if (dataContract.KnownDataContracts?.Count > 0) { scopedKnownTypes.Push(dataContract.KnownDataContracts); knownTypesAddedInCurrentScope = true; } if (!IsKnownType(dataContract, declaredType)) { throw XmlObjectSerializer.CreateSerializationException(SR.Format(SR.DcTypeNotFoundOnSerialize, DataContract.GetClrTypeFullName(dataContract.UnderlyingType), dataContract.XmlName.Name, dataContract.XmlName.Namespace)); } if (knownTypesAddedInCurrentScope) { scopedKnownTypes.Pop(); } }
internal override bool OnHandleReference(XmlWriterDelegator xmlWriter, object obj, bool canContainCyclicReference) { if (obj.GetType().GetTypeInfo().IsValueType) { return(false); } if (_byValObjectsInScope.Contains(obj)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.CannotSerializeObjectWithCycles, DataContract.GetClrTypeFullName(obj.GetType())))); } _byValObjectsInScope.Push(obj); return(false); }
internal void VerifyType(DataContract dataContract) { DataContract knownContract = ResolveDataContractFromKnownTypes(dataContract.StableName.Name, dataContract.StableName.Namespace, null /*memberTypeContract*/); if (knownContract == null || knownContract.UnderlyingType != dataContract.UnderlyingType) { throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.DcTypeNotFoundOnSerialize, DataContract.GetClrTypeFullName(dataContract.UnderlyingType), dataContract.StableName.Name, dataContract.StableName.Namespace))); } }
private void ReadSimpleDictionary(CollectionDataContract collectionContract, Type keyValueType) { Type[] keyValueTypes = keyValueType.GetGenericArguments(); Type keyType = keyValueTypes[0]; Type valueType = keyValueTypes[1]; int keyTypeNullableDepth = 0; Type keyTypeOriginal = keyType; while (keyType.IsGenericType && keyType.GetGenericTypeDefinition() == Globals.TypeOfNullable) { keyTypeNullableDepth++; keyType = keyType.GetGenericArguments()[0]; } ClassDataContract keyValueDataContract = (ClassDataContract)collectionContract.ItemContract; DataContract keyDataContract = keyValueDataContract.Members[0].MemberTypeContract; KeyParseMode keyParseMode = KeyParseMode.Fail; if (keyType == Globals.TypeOfString || keyType == Globals.TypeOfObject) { keyParseMode = KeyParseMode.AsString; } else if (keyType.IsEnum) { keyParseMode = KeyParseMode.UsingParseEnum; } else if (keyDataContract.ParseMethod != null) { keyParseMode = KeyParseMode.UsingCustomParse; } if (keyParseMode == KeyParseMode.Fail) { ThrowSerializationException( SR.Format( SR.KeyTypeCannotBeParsedInSimpleDictionary, DataContract.GetClrTypeFullName(collectionContract.UnderlyingType), DataContract.GetClrTypeFullName(keyType))); } else { LocalBuilder nodeType = _ilg.DeclareLocal(typeof(XmlNodeType), "nodeType"); _ilg.BeginWhileCondition(); _ilg.Call(_xmlReaderArg, JsonFormatGeneratorStatics.MoveToContentMethod); _ilg.Stloc(nodeType); _ilg.Load(nodeType); _ilg.Load(XmlNodeType.EndElement); _ilg.BeginWhileBody(Cmp.NotEqualTo); _ilg.Load(nodeType); _ilg.Load(XmlNodeType.Element); _ilg.If(Cmp.NotEqualTo); ThrowUnexpectedStateException(XmlNodeType.Element); _ilg.EndIf(); _ilg.Call(_contextArg, XmlFormatGeneratorStatics.IncrementItemCountMethod, 1); if (keyParseMode == KeyParseMode.UsingParseEnum) { _ilg.Load(keyType); } _ilg.Load(_xmlReaderArg); _ilg.Call(JsonFormatGeneratorStatics.GetJsonMemberNameMethod); if (keyParseMode == KeyParseMode.UsingParseEnum) { _ilg.Call(JsonFormatGeneratorStatics.ParseEnumMethod); _ilg.ConvertValue(Globals.TypeOfObject, keyType); } else if (keyParseMode == KeyParseMode.UsingCustomParse) { _ilg.Call(keyDataContract.ParseMethod); } LocalBuilder pairKey = _ilg.DeclareLocal(keyType, "key"); _ilg.Stloc(pairKey); if (keyTypeNullableDepth > 0) { LocalBuilder pairKeyNullable = _ilg.DeclareLocal(keyTypeOriginal, "keyOriginal"); WrapNullableObject(pairKey, pairKeyNullable, keyTypeNullableDepth); pairKey = pairKeyNullable; } LocalBuilder pairValue = ReadValue(valueType, string.Empty); StoreKeyValuePair(_objectLocal, collectionContract, pairKey, pairValue); _ilg.EndWhile(); } }
private void ReadISerializable(ClassDataContract classContract) { ConstructorInfo ctor = classContract.UnderlyingType.GetConstructor(Globals.ScanAllMembers, null, JsonFormatGeneratorStatics.SerInfoCtorArgs, null); if (ctor == null) { throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.SerializationInfo_ConstructorNotFound, DataContract.GetClrTypeFullName(classContract.UnderlyingType)))); } _ilg.LoadAddress(_objectLocal); _ilg.ConvertAddress(_objectLocal.LocalType, _objectType); _ilg.Call(_contextArg, XmlFormatGeneratorStatics.ReadSerializationInfoMethod, _xmlReaderArg, classContract.UnderlyingType); _ilg.Load(_contextArg); _ilg.LoadMember(XmlFormatGeneratorStatics.GetStreamingContextMethod); _ilg.Call(ctor); }
internal void VerifyType(DataContract dataContract) { bool knownTypesAddedInCurrentScope = false; if (dataContract.KnownDataContracts != null) { scopedKnownTypes.Push(dataContract.KnownDataContracts); knownTypesAddedInCurrentScope = true; } DataContract knownContract = ResolveDataContractFromKnownTypes(dataContract.StableName.Name, dataContract.StableName.Namespace, null /*memberTypeContract*/); if (knownContract == null || knownContract.UnderlyingType != dataContract.UnderlyingType) { throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.DcTypeNotFoundOnSerialize, DataContract.GetClrTypeFullName(dataContract.UnderlyingType), dataContract.StableName.Name, dataContract.StableName.Namespace))); } if (knownTypesAddedInCurrentScope) { scopedKnownTypes.Pop(); } }
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 { XmlResolver = null }; InvokeSchemaProviderMethod(type, schemas, out stableName, out xsdType, out hasRoot); if (stableName.Name == null || stableName.Name.Length == 0) { throw Compat.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.InvalidXmlDataContractName, DataContract.GetClrTypeFullName(type)))); } }
public static void ThrowMissingRequiredMembers(object obj, XmlDictionaryString[] memberNames, byte[] expectedElements, byte[] requiredElements) { StringBuilder stringBuilder = new StringBuilder(); int missingMembersCount = 0; for (int i = 0; i < memberNames.Length; i++) { if (IsBitSet(expectedElements, i) && IsBitSet(requiredElements, i)) { if (stringBuilder.Length != 0) { stringBuilder.Append(", "); } stringBuilder.Append(memberNames[i]); missingMembersCount++; } } if (missingMembersCount == 1) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SerializationException(SR.GetString( SR.JsonOneRequiredMemberNotFound, DataContract.GetClrTypeFullName(obj.GetType()), stringBuilder.ToString()))); } else { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SerializationException(SR.GetString( SR.JsonRequiredMembersNotFound, DataContract.GetClrTypeFullName(obj.GetType()), stringBuilder.ToString()))); } }
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 Compat.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 Compat.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 Compat.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 Compat.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 (schemaItem == (object)providerXsdType) { typeNs = schema.TargetNamespace; if (typeNs == null) { typeNs = string.Empty; } break; } } if (typeNs != null) { break; } } if (typeNs == null) { throw Compat.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); }
private void ReadSimpleDictionary(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context, CollectionDataContract collectionContract, Type keyValueType, object dictionary) { Type[] keyValueTypes = keyValueType.GetGenericArguments(); Type keyType = keyValueTypes[0]; Type valueType = keyValueTypes[1]; int keyTypeNullableDepth = 0; Type keyTypeOriginal = keyType; while (keyType.IsGenericType && keyType.GetGenericTypeDefinition() == Globals.TypeOfNullable) { keyTypeNullableDepth++; keyType = keyType.GetGenericArguments()[0]; } ClassDataContract keyValueDataContract = (ClassDataContract)collectionContract.ItemContract; DataContract keyDataContract = keyValueDataContract.Members[0].MemberTypeContract; KeyParseMode keyParseMode = KeyParseMode.Fail; if (keyType == Globals.TypeOfString || keyType == Globals.TypeOfObject) { keyParseMode = KeyParseMode.AsString; } else if (keyType.IsEnum) { keyParseMode = KeyParseMode.UsingParseEnum; } else if (keyDataContract.ParseMethod != null) { keyParseMode = KeyParseMode.UsingCustomParse; } if (keyParseMode == KeyParseMode.Fail) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new InvalidOperationException( SR.Format(SR.KeyTypeCannotBeParsedInSimpleDictionary, DataContract.GetClrTypeFullName(collectionContract.UnderlyingType), DataContract.GetClrTypeFullName(keyType)) )); } while (true) { XmlNodeType nodeType = xmlReader.MoveToContent(); if (nodeType == XmlNodeType.EndElement) { return; } if (nodeType != XmlNodeType.Element) { throw XmlObjectSerializerReadContext.CreateUnexpectedStateException(XmlNodeType.Element, xmlReader); } context.IncrementItemCount(1); string keyString = XmlObjectSerializerReadContextComplexJson.GetJsonMemberName(xmlReader); object pairKey; if (keyParseMode == KeyParseMode.UsingParseEnum) { pairKey = Enum.Parse(keyType, keyString); } else if (keyParseMode == KeyParseMode.UsingCustomParse) { pairKey = keyDataContract.ParseMethod.Invoke(null, new object[] { keyString }); } else { pairKey = keyString; } if (keyTypeNullableDepth > 0) { throw new NotImplementedException("keyTypeNullableDepth > 0"); } object pairValue = ReflectionReadValue(xmlReader, context, valueType, string.Empty, string.Empty); ((IDictionary)dictionary).Add(pairKey, pairValue); } }
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 Compat.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.InvalidReturnSchemaOnGetSchemaMethod, DataContract.GetClrTypeFullName(clrType)))); } AddDefaultTypedDatasetType(schemas, schema, stableName.Name, stableName.Namespace); } }
internal override Type GetSurrogatedType(Type type) { if (dataContractSurrogate == null) { return(base.GetSurrogatedType(type)); } else { type = DataContract.UnwrapNullableType(type); Type surrogateType = DataContractSerializer.GetSurrogatedType(dataContractSurrogate, type); if (IsGetOnlyCollection && surrogateType != type) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new System.Runtime.Serialization.InvalidDataContractException(SR.Format(SR.SurrogatesWithGetOnlyCollectionsNotSupportedSerDeser, DataContract.GetClrTypeFullName(type)))); } else { return(surrogateType); } } }
void CopyMembersAndCheckDuplicateNames() { if (traditionalClassDataContract.MemberNames != null) { int memberCount = traditionalClassDataContract.MemberNames.Length; Dictionary <string, object> memberTable = new Dictionary <string, object>(memberCount); XmlDictionaryString[] decodedMemberNames = new XmlDictionaryString[memberCount]; for (int i = 0; i < memberCount; i++) { if (memberTable.ContainsKey(traditionalClassDataContract.MemberNames[i].Value)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SerializationException(SR.GetString(SR.JsonDuplicateMemberNames, DataContract.GetClrTypeFullName(traditionalClassDataContract.UnderlyingType), traditionalClassDataContract.MemberNames[i].Value))); } else { memberTable.Add(traditionalClassDataContract.MemberNames[i].Value, null); decodedMemberNames[i] = DataContractJsonSerializer.ConvertXmlNameToJsonName(traditionalClassDataContract.MemberNames[i]); } } this.memberNames = decodedMemberNames; } }
internal void WriteJsonISerializable(XmlWriterDelegator xmlWriter, ISerializable obj) #endif { Type objType = obj.GetType(); SerializationInfo serInfo = new SerializationInfo(objType, XmlObjectSerializer.FormatterConverter); GetObjectData(obj, serInfo, GetStreamingContext()); if (DataContract.GetClrTypeFullName(objType) != serInfo.FullTypeName) { throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.GetString(SR.ChangingFullTypeNameNotSupported, serInfo.FullTypeName, DataContract.GetClrTypeFullName(objType)))); } else { base.WriteSerializationInfo(xmlWriter, objType, serInfo); } }
private void VerifyType(DataContract dataContract, Type declaredType) { bool flag = false; if (dataContract.KnownDataContracts != null) { this.scopedKnownTypes.Push(dataContract.KnownDataContracts); flag = true; } if (!base.IsKnownType(dataContract, declaredType)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(System.Runtime.Serialization.SR.GetString("DcTypeNotFoundOnSerialize", new object[] { DataContract.GetClrTypeFullName(dataContract.UnderlyingType), dataContract.StableName.Name, dataContract.StableName.Namespace }))); } if (flag) { this.scopedKnownTypes.Pop(); } }
private void CopyMembersAndCheckDuplicateNames() { if (_traditionalClassDataContract.MemberNames != null) { int memberCount = _traditionalClassDataContract.MemberNames.Length; Dictionary <string, object> memberTable = new Dictionary <string, object>(memberCount); XmlDictionaryString[] decodedMemberNames = new XmlDictionaryString[memberCount]; for (int i = 0; i < memberCount; i++) { if (memberTable.ContainsKey(_traditionalClassDataContract.MemberNames[i].Value)) { throw new SerializationException(SR.Format(SR.JsonDuplicateMemberNames, DataContract.GetClrTypeFullName(_traditionalClassDataContract.UnderlyingType), _traditionalClassDataContract.MemberNames[i].Value)); } else { memberTable.Add(_traditionalClassDataContract.MemberNames[i].Value, null); decodedMemberNames[i] = DataContractJsonSerializerImpl.ConvertXmlNameToJsonName(_traditionalClassDataContract.MemberNames[i]); } } _memberNames = decodedMemberNames; } }
internal void WriteJsonISerializable(XmlWriterDelegator xmlWriter, ISerializable obj) { Type type = obj.GetType(); SerializationInfo info = new SerializationInfo(type, XmlObjectSerializer.FormatterConverter); obj.GetObjectData(info, base.GetStreamingContext()); if (DataContract.GetClrTypeFullName(type) != info.FullTypeName) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(System.Runtime.Serialization.SR.GetString("ChangingFullTypeNameNotSupported", new object[] { info.FullTypeName, DataContract.GetClrTypeFullName(type) }))); } base.WriteSerializationInfo(xmlWriter, type, info); }
private static void WriteClassDataContractMembers(DataContractJsonSerializer serializer, ClassDataContract dataContract, ref Dictionary <string, object> classToDictionary, object value, XmlObjectSerializerWriteContextComplexJson context) { if (dataContract.BaseContract != null) { WriteClassDataContractMembers(serializer, dataContract.BaseContract, ref classToDictionary, value, context); } for (int i = 0; i < dataContract.Members.Count; i++) { DataMember member = dataContract.Members[i]; object memberValue = GetMemberValue(value, dataContract.Members[i].MemberInfo, dataContract.UnderlyingType); string memberName = System.Xml.XmlConvert.DecodeName(member.Name); if (classToDictionary.ContainsKey(memberName)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SerializationException(SR.Format(SR.JsonDuplicateMemberNames, DataContract.GetClrTypeFullName(dataContract.UnderlyingType), memberName))); } if (!member.EmitDefaultValue) { //Dont emit value if its null or default(valuetype) if (memberValue == null || (member.MemberTypeContract.IsValueType && object.Equals(memberValue, Activator.CreateInstance(member.MemberType)))) { continue; } } if (memberValue == null || IsTypePrimitive(member.MemberType)) { classToDictionary[memberName] = memberValue; } else { Type memberValueType = memberValue.GetType(); if (member.MemberType == memberValueType || //Special case Nullable<DateTimeOffset> and Nullable<Struct> (member.IsNullable && !EmitTypeInformation(member.MemberTypeContract, memberValueType))) { classToDictionary[memberName] = serializer.ConvertDataContractToObject(memberValue, member.MemberTypeContract, context, false, member.MemberTypeContract.UnderlyingType.TypeHandle); } else { //Push KnownTypes of this DataContract context.PushKnownTypes(dataContract); DataContract memberValueContract = DataContract.GetDataContract(memberValue.GetType()); if (member.MemberType.GetTypeInfo().IsInterface) { XmlObjectSerializerWriteContextComplexJson.VerifyObjectCompatibilityWithInterface(memberValueContract, memberValue, member.MemberType); } context.CheckIfTypeNeedsVerifcation(member.MemberTypeContract, memberValueContract); classToDictionary[memberName] = serializer.ConvertDataContractToObject(memberValue, memberValueContract, context, true, member.MemberTypeContract.UnderlyingType.TypeHandle); context.PopKnownTypes(dataContract); } } } }
public static void ThrowMissingRequiredMembers(object obj, XmlDictionaryString[] memberNames, byte[] expectedElements, byte[] requiredElements) { StringBuilder builder = new StringBuilder(); int num = 0; for (int i = 0; i < memberNames.Length; i++) { if (IsBitSet(expectedElements, i) && IsBitSet(requiredElements, i)) { if (builder.Length != 0) { builder.Append(", "); } builder.Append(memberNames[i]); num++; } } if (num == 1) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SerializationException(System.Runtime.Serialization.SR.GetString("JsonOneRequiredMemberNotFound", new object[] { DataContract.GetClrTypeFullName(obj.GetType()), builder.ToString() }))); } throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SerializationException(System.Runtime.Serialization.SR.GetString("JsonRequiredMembersNotFound", new object[] { DataContract.GetClrTypeFullName(obj.GetType()), builder.ToString() }))); }
private LocalBuilder ReadValue(Type type, string name, string ns) { LocalBuilder value = ilg.DeclareLocal(type, "valueRead"); LocalBuilder nullableValue = null; int nullables = 0; while (type.IsGenericType && type.GetGenericTypeDefinition() == Globals.TypeOfNullable) { nullables++; type = type.GetGenericArguments()[0]; } PrimitiveDataContract primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(type); if ((primitiveContract != null && primitiveContract.UnderlyingType != Globals.TypeOfObject) || nullables != 0 || type.IsValueType) { LocalBuilder objectId = ilg.DeclareLocal(Globals.TypeOfString, "objectIdRead"); ilg.Call(contextArg, XmlFormatGeneratorStatics.ReadAttributesMethod, xmlReaderArg); ilg.Call(contextArg, XmlFormatGeneratorStatics.ReadIfNullOrRefMethod, xmlReaderArg, type, DataContract.IsTypeSerializable(type)); ilg.Stloc(objectId); // Deserialize null ilg.If(objectId, Cmp.EqualTo, Globals.NullObjectId); if (nullables != 0) { ilg.LoadAddress(value); ilg.InitObj(value.LocalType); } else if (type.IsValueType) { ThrowValidationException(SR.Format(SR.ValueTypeCannotBeNull, DataContract.GetClrTypeFullName(type))); } else { ilg.Load(null); ilg.Stloc(value); } // Deserialize value // Compare against Globals.NewObjectId, which is set to string.Empty ilg.ElseIfIsEmptyString(objectId); ilg.Call(contextArg, XmlFormatGeneratorStatics.GetObjectIdMethod); ilg.Stloc(objectId); if (type.IsValueType) { ilg.IfNotIsEmptyString(objectId); ThrowValidationException(SR.Format(SR.ValueTypeCannotHaveId, DataContract.GetClrTypeFullName(type))); ilg.EndIf(); } if (nullables != 0) { nullableValue = value; value = ilg.DeclareLocal(type, "innerValueRead"); } if (primitiveContract != null && primitiveContract.UnderlyingType != Globals.TypeOfObject) { ilg.Call(xmlReaderArg, primitiveContract.XmlFormatReaderMethod); ilg.Stloc(value); if (!type.IsValueType) { ilg.Call(contextArg, XmlFormatGeneratorStatics.AddNewObjectMethod, value); } } else { InternalDeserialize(value, type, name, ns); } // Deserialize ref ilg.Else(); if (type.IsValueType) { ThrowValidationException(SR.Format(SR.ValueTypeCannotHaveRef, DataContract.GetClrTypeFullName(type))); } else { ilg.Call(contextArg, XmlFormatGeneratorStatics.GetExistingObjectMethod, objectId, type, name, ns); ilg.ConvertValue(Globals.TypeOfObject, type); ilg.Stloc(value); } ilg.EndIf(); if (nullableValue != null) { ilg.If(objectId, Cmp.NotEqualTo, Globals.NullObjectId); WrapNullableObject(value, nullableValue, nullables); ilg.EndIf(); value = nullableValue; } } else { InternalDeserialize(value, type, name, ns); } return(value); }
internal void EndWrite() { if (_depth != 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.IXmlSerializableMissingEndElements, (_obj == null ? string.Empty : DataContract.GetClrTypeFullName(_obj.GetType()))))); } _obj = null; }