2 using System.Collections;
3 using System.Collections.Generic;
5 using System.Reflection;
8 namespace System.Runtime.Serialization
10 internal partial class XmlFormatWriterGenerator
12 partial class CriticalHelper
14 internal XmlFormatClassWriterDelegate GenerateClassWriter(ClassDataContract classContract)
16 return (XmlWriterDelegator xw, object obj, XmlObjectSerializerWriteContext ctx, ClassDataContract ctr) => new XmlFormatWriterInterpreter (classContract).WriteToXml (xw, obj, ctx, ctr);
19 internal XmlFormatCollectionWriterDelegate GenerateCollectionWriter(CollectionDataContract collectionContract)
21 return (XmlWriterDelegator xw, object obj, XmlObjectSerializerWriteContext ctx, CollectionDataContract ctr) => new XmlFormatWriterInterpreter (collectionContract).WriteCollectionToXml (xw, obj, ctx, ctr);
26 class XmlFormatWriterInterpreter
28 public XmlFormatWriterInterpreter (ClassDataContract classContract)
30 this.classContract = classContract;
33 public XmlFormatWriterInterpreter (CollectionDataContract collectionContract)
35 this.collectionContract = collectionContract;
38 ClassDataContract classContract;
40 CollectionDataContract collectionContract;
42 XmlWriterDelegator writer = null;
44 XmlObjectSerializerWriteContext ctx = null;
45 DataContract dataContract = null;
46 object objLocal = null;
48 ClassDataContract classDataContract {
49 get { return (ClassDataContract) dataContract; }
51 CollectionDataContract collectionDataContract {
52 get {return (CollectionDataContract) dataContract; }
55 XmlDictionaryString [] contractNamespaces = null;
56 XmlDictionaryString [] memberNames = null;
57 XmlDictionaryString [] childElementNamespaces = null;
59 int childElementIndex = 0;
61 public void WriteToXml (XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context, ClassDataContract dataContract)
63 this.writer = xmlWriter;
66 this.dataContract = dataContract;
68 InitArgs (classContract.UnderlyingType);
70 // DemandSerializationFormatterPermission (classContract) - irrelevant
71 // DemandMemberAccessPermission (memberAccessFlag) - irrelevant
73 if (classContract.IsReadOnlyContract)
75 DataContract.ThrowInvalidDataContractException (classContract.SerializationExceptionMessage, null);
78 WriteClass (classContract);
81 public void WriteCollectionToXml (XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context, CollectionDataContract collectionContract)
83 this.writer = xmlWriter;
86 this.dataContract = collectionContract;
88 InitArgs (collectionContract.UnderlyingType);
90 // DemandMemberAccessPermission(memberAccessFlag);
91 if (collectionContract.IsReadOnlyContract)
93 DataContract.ThrowInvalidDataContractException (collectionContract.SerializationExceptionMessage, null);
96 WriteCollection (collectionContract);
99 void InitArgs (Type objType)
101 if (objType == Globals.TypeOfDateTimeOffsetAdapter) {
102 objLocal = DateTimeOffsetAdapter.GetDateTimeOffsetAdapter ((DateTimeOffset) obj);
105 objLocal = CodeInterpreter.ConvertValue (obj, typeof (object), objType);
108 void InvokeOnSerializing (ClassDataContract classContract, object objSerialized, XmlObjectSerializerWriteContext ctx)
110 if (classContract.BaseContract != null)
111 InvokeOnSerializing (classContract.BaseContract, objSerialized, ctx);
112 if (classContract.OnSerializing != null) {
113 classContract.OnSerializing.Invoke (objSerialized, new object [] {ctx.GetStreamingContext ()});
117 void InvokeOnSerialized (ClassDataContract classContract, object objSerialized, XmlObjectSerializerWriteContext ctx)
119 if (classContract.BaseContract != null)
120 InvokeOnSerialized (classContract.BaseContract, objSerialized, ctx);
121 if (classContract.OnSerialized != null) {
122 classContract.OnSerialized.Invoke (objSerialized, new object [] {ctx.GetStreamingContext ()});
126 void WriteClass (ClassDataContract classContract)
128 InvokeOnSerializing (classContract, objLocal, ctx);
130 if (classContract.IsISerializable)
131 ctx.WriteISerializable (writer, (ISerializable) objLocal);
134 if (classContract.ContractNamespaces.Length > 1)
135 contractNamespaces = classDataContract.ContractNamespaces;
136 memberNames = classDataContract.MemberNames;
138 for (int i = 0; i < classContract.ChildElementNamespaces.Length; i++)
140 if (classContract.ChildElementNamespaces[i] != null)
142 childElementNamespaces = classDataContract.ChildElementNamespaces;
146 if (classContract.HasExtensionData)
148 ExtensionDataObject extensionData = ((IExtensibleDataObject) objLocal).ExtensionData;
149 ctx.WriteExtensionData (writer, extensionData, -1);
151 WriteMembers (classContract, extensionData, classContract);
154 WriteMembers (classContract, null, classContract);
156 InvokeOnSerialized (classContract, objLocal, ctx);
159 void WriteCollection(CollectionDataContract collectionContract)
161 XmlDictionaryString itemNamespace = dataContract.Namespace;
163 XmlDictionaryString itemName = collectionDataContract.CollectionItemName;
165 if (collectionContract.ChildElementNamespace != null)
166 writer.WriteNamespaceDecl (collectionDataContract.ChildElementNamespace);
168 if (collectionContract.Kind == CollectionKind.Array)
170 Type itemType = collectionContract.ItemType;
172 ctx.IncrementArrayCount (writer, (Array) objLocal);
174 if (!TryWritePrimitiveArray(collectionContract.UnderlyingType, itemType, () => objLocal, itemName, itemNamespace))
176 var arr = (Array) objLocal;
177 var idx = new int [1];
178 for (i = 0; i < arr.Length; i++) {
179 if (!TryWritePrimitive(itemType, null, null, i, itemNamespace, itemName, 0)) {
180 WriteStartElement (itemType, collectionContract.Namespace, itemNamespace, itemName, 0);
182 var mbrVal = arr.GetValue (idx);
183 WriteValue (itemType, mbrVal, false);
191 MethodInfo incrementCollectionCountMethod = null;
192 switch (collectionContract.Kind)
194 case CollectionKind.Collection:
195 case CollectionKind.List:
196 case CollectionKind.Dictionary:
197 incrementCollectionCountMethod = XmlFormatGeneratorStatics.IncrementCollectionCountMethod;
199 case CollectionKind.GenericCollection:
200 case CollectionKind.GenericList:
201 incrementCollectionCountMethod = XmlFormatGeneratorStatics.IncrementCollectionCountGenericMethod.MakeGenericMethod(collectionContract.ItemType);
203 case CollectionKind.GenericDictionary:
204 incrementCollectionCountMethod = XmlFormatGeneratorStatics.IncrementCollectionCountGenericMethod.MakeGenericMethod(Globals.TypeOfKeyValuePair.MakeGenericType(collectionContract.ItemType.GetGenericArguments()));
207 if (incrementCollectionCountMethod != null)
208 incrementCollectionCountMethod.Invoke (ctx, new object [] {writer, objLocal});
210 bool isDictionary = false, isGenericDictionary = false;
211 Type enumeratorType = null;
212 Type [] keyValueTypes = null;
213 if (collectionContract.Kind == CollectionKind.GenericDictionary)
215 isGenericDictionary = true;
216 keyValueTypes = collectionContract.ItemType.GetGenericArguments ();
217 enumeratorType = Globals.TypeOfGenericDictionaryEnumerator.MakeGenericType (keyValueTypes);
219 else if (collectionContract.Kind == CollectionKind.Dictionary)
222 keyValueTypes = new Type[] { Globals.TypeOfObject, Globals.TypeOfObject };
223 enumeratorType = Globals.TypeOfDictionaryEnumerator;
227 enumeratorType = collectionContract.GetEnumeratorMethod.ReturnType;
229 MethodInfo moveNextMethod = enumeratorType.GetMethod (Globals.MoveNextMethodName, BindingFlags.Instance | BindingFlags.Public, null, Globals.EmptyTypeArray, null);
230 MethodInfo getCurrentMethod = enumeratorType.GetMethod (Globals.GetCurrentMethodName, BindingFlags.Instance | BindingFlags.Public, null, Globals.EmptyTypeArray, null);
231 if (moveNextMethod == null || getCurrentMethod == null)
233 if (enumeratorType.IsInterface)
235 if (moveNextMethod == null)
236 moveNextMethod = XmlFormatGeneratorStatics.MoveNextMethod;
237 if (getCurrentMethod == null)
238 getCurrentMethod = XmlFormatGeneratorStatics.GetCurrentMethod;
242 Type ienumeratorInterface = Globals.TypeOfIEnumerator;
243 CollectionKind kind = collectionContract.Kind;
244 if (kind == CollectionKind.GenericDictionary || kind == CollectionKind.GenericCollection || kind == CollectionKind.GenericEnumerable)
246 Type[] interfaceTypes = enumeratorType.GetInterfaces();
247 foreach (Type interfaceType in interfaceTypes)
249 if (interfaceType.IsGenericType
250 && interfaceType.GetGenericTypeDefinition() == Globals.TypeOfIEnumeratorGeneric
251 && interfaceType.GetGenericArguments()[0] == collectionContract.ItemType)
253 ienumeratorInterface = interfaceType;
258 if (moveNextMethod == null)
259 moveNextMethod = CollectionDataContract.GetTargetMethodWithName(Globals.MoveNextMethodName, enumeratorType, ienumeratorInterface);
260 if (getCurrentMethod == null)
261 getCurrentMethod = CollectionDataContract.GetTargetMethodWithName(Globals.GetCurrentMethodName, enumeratorType, ienumeratorInterface);
264 Type elementType = getCurrentMethod.ReturnType;
265 object currentValue = null; // of elementType
267 var enumerator = (IEnumerator) collectionContract.GetEnumeratorMethod.Invoke (objLocal, new object [0]);
270 enumerator = new CollectionDataContract.DictionaryEnumerator ((IDictionaryEnumerator) enumerator);
272 else if (isGenericDictionary)
274 Type ctorParam = Globals.TypeOfIEnumeratorGeneric.MakeGenericType(Globals.TypeOfKeyValuePair.MakeGenericType(keyValueTypes));
275 ConstructorInfo dictEnumCtor = enumeratorType.GetConstructor(Globals.ScanAllMembers, null, new Type[] { ctorParam }, null);
276 enumerator = (IEnumerator) Activator.CreateInstance (enumeratorType, new object [] {enumerator});
279 var emptyArray = new object [0];
280 while (enumerator != null && enumerator.MoveNext ()) {
281 currentValue = getCurrentMethod.Invoke (enumerator, emptyArray);
283 if (incrementCollectionCountMethod == null)
284 XmlFormatGeneratorStatics.IncrementItemCountMethod.Invoke (ctx, new object [] {1});
286 if (!TryWritePrimitive (elementType, () => currentValue, null, null, itemNamespace, itemName, 0))
288 WriteStartElement (elementType, collectionContract.Namespace, itemNamespace, itemName, 0);
289 if (isGenericDictionary || isDictionary)
290 collectionDataContract.ItemContract.WriteXmlValue (writer, currentValue, ctx);
292 WriteValue (elementType, currentValue, false);
299 int WriteMembers (ClassDataContract classContract, ExtensionDataObject extensionData, ClassDataContract derivedMostClassContract)
301 int memberCount = (classContract.BaseContract == null) ? 0 : WriteMembers (classContract.BaseContract, extensionData, derivedMostClassContract);
303 XmlDictionaryString ns =
304 (contractNamespaces == null) ? dataContract.Namespace :
305 contractNamespaces [typeIndex - 1];
307 ctx.IncrementItemCount (classContract.Members.Count);
309 for (int i = 0; i < classContract.Members.Count; i++, memberCount++) {
311 DataMember member = classContract.Members[i];
312 Type memberType = member.MemberType;
313 object memberValue = null;
314 if (member.IsGetOnlyCollection)
315 ctx.StoreIsGetOnlyCollection ();
316 bool doWrite = true, hasMemberValue = false;
317 if (!member.EmitDefaultValue)
319 hasMemberValue = true;
320 memberValue = LoadMemberValue (member);
321 doWrite = !IsDefaultValue (memberType, memberValue);
326 bool writeXsiType = CheckIfMemberHasConflict (member, classContract, derivedMostClassContract);
327 if (writeXsiType || !TryWritePrimitive (memberType, hasMemberValue ? () => memberValue : (Func<object>) null, member.MemberInfo, null /*arrayItemIndex*/, ns, null /*nameLocal*/, i + childElementIndex)) {
328 WriteStartElement (memberType, classContract.Namespace, ns, null /*nameLocal*/, i + childElementIndex);
329 if (classContract.ChildElementNamespaces [i + childElementIndex] != null)
330 writer.WriteNamespaceDecl (childElementNamespaces [i + childElementIndex]);
331 if (memberValue == null)
332 memberValue = LoadMemberValue (member);
333 WriteValue (memberType, memberValue, writeXsiType);
337 if (classContract.HasExtensionData)
338 ctx.WriteExtensionData (writer, extensionData, memberCount);
339 } else if (!member.EmitDefaultValue) {
340 if (member.IsRequired)
341 XmlObjectSerializerWriteContext.ThrowRequiredMemberMustBeEmitted (member.Name, classContract.UnderlyingType);
346 childElementIndex += classContract.Members.Count;
351 internal bool IsDefaultValue (Type type, object value)
353 return GetDefaultValue (type).Equals (value);
356 internal object GetDefaultValue(Type type)
358 if (type.IsValueType)
360 switch (Type.GetTypeCode(type))
362 case TypeCode.Boolean:
368 case TypeCode.UInt16:
370 case TypeCode.UInt32:
373 case TypeCode.UInt64:
375 case TypeCode.Single:
377 case TypeCode.Double:
379 case TypeCode.Decimal:
380 return default (decimal);
381 case TypeCode.DateTime:
382 return default (DateTime);
388 bool CheckIfMemberHasConflict(DataMember member, ClassDataContract classContract, ClassDataContract derivedMostClassContract)
390 // Check for conflict with base type members
391 if (CheckIfConflictingMembersHaveDifferentTypes(member))
394 // Check for conflict with derived type members
395 string name = member.Name;
396 string ns = classContract.StableName.Namespace;
397 ClassDataContract currentContract = derivedMostClassContract;
398 while (currentContract != null && currentContract != classContract)
400 if (ns == currentContract.StableName.Namespace)
402 List<DataMember> members = currentContract.Members;
403 for (int j = 0; j < members.Count; j++)
405 if (name == members[j].Name)
406 return CheckIfConflictingMembersHaveDifferentTypes(members[j]);
409 currentContract = currentContract.BaseContract;
415 bool CheckIfConflictingMembersHaveDifferentTypes(DataMember member)
417 while (member.ConflictingMember != null)
419 if (member.MemberType != member.ConflictingMember.MemberType)
421 member = member.ConflictingMember;
426 bool NeedsPrefix(Type type, XmlDictionaryString ns)
428 return type == Globals.TypeOfXmlQualifiedName && (ns != null && ns.Value != null && ns.Value.Length > 0);
431 void WriteStartElement (Type type, XmlDictionaryString ns, XmlDictionaryString namespaceLocal, XmlDictionaryString nameLocal, int nameIndex)
433 bool needsPrefix = NeedsPrefix(type, ns);
434 nameLocal = nameLocal ?? memberNames [nameIndex];
436 writer.WriteStartElement (Globals.ElementPrefix, nameLocal, namespaceLocal);
438 writer.WriteStartElement (nameLocal, namespaceLocal);
441 void WriteEndElement ()
443 writer.WriteEndElement ();
446 void WriteValue (Type memberType, object memberValue, bool writeXsiType)
448 Pointer memberValueRefPointer = null;
449 if (memberType.IsPointer)
450 memberValueRefPointer = (Pointer) XmlFormatGeneratorStatics.BoxPointer.Invoke (null, new object [] {memberValue, memberType});
451 bool isNullableOfT = (memberType.IsGenericType &&
452 memberType.GetGenericTypeDefinition() == Globals.TypeOfNullable);
453 if (memberType.IsValueType && !isNullableOfT)
455 PrimitiveDataContract primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(memberType);
456 if (primitiveContract != null && !writeXsiType)
457 primitiveContract.XmlFormatContentWriterMethod.Invoke (writer, new object [] {memberValue});
459 InternalSerialize(XmlFormatGeneratorStatics.InternalSerializeMethod, () => memberValue, memberType, writeXsiType);
465 memberValue = UnwrapNullableObject(() => memberValue, ref memberType, out isNull); //Leaves !HasValue on stack
467 isNull = memberValue == null;
469 XmlFormatGeneratorStatics.WriteNullMethod.Invoke (ctx, new object [] {writer, memberType, DataContract.IsTypeSerializable(memberType)});
471 PrimitiveDataContract primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(memberType);
472 if (primitiveContract != null && primitiveContract.UnderlyingType != Globals.TypeOfObject && !writeXsiType) {
474 primitiveContract.XmlFormatContentWriterMethod.Invoke (writer, new object [] {memberValue});
476 primitiveContract.XmlFormatContentWriterMethod.Invoke (ctx, new object [] {writer, memberValue});
478 bool isNull2 = false;
479 if (memberType == Globals.TypeOfObject || //boxed Nullable<T>
480 memberType == Globals.TypeOfValueType ||
481 ((IList)Globals.TypeOfNullable.GetInterfaces()).Contains(memberType)) {
482 var unwrappedMemberValue = CodeInterpreter.ConvertValue (memberValue, memberType.GetType (), Globals.TypeOfObject);
483 memberValue = unwrappedMemberValue;
484 isNull2 = memberValue == null;
487 XmlFormatGeneratorStatics.WriteNullMethod.Invoke (ctx, new object [] {writer, memberType, DataContract.IsTypeSerializable(memberType)});
489 InternalSerialize((isNullableOfT ? XmlFormatGeneratorStatics.InternalSerializeMethod : XmlFormatGeneratorStatics.InternalSerializeReferenceMethod),
490 () => memberValue, memberType, writeXsiType);
497 void InternalSerialize (MethodInfo methodInfo, Func<object> memberValue, Type memberType, bool writeXsiType)
499 var v = memberValue ();
500 var typeHandleValue = Type.GetTypeHandle (v);
501 var isDeclaredType = typeHandleValue.Equals (CodeInterpreter.ConvertValue (v, memberType, Globals.TypeOfObject));
502 methodInfo.Invoke (ctx, new object [] {writer, memberValue != null ? v : null, isDeclaredType, writeXsiType, DataContract.GetId (memberType.TypeHandle), memberType.TypeHandle});
505 object UnwrapNullableObject(Func<object> memberValue, ref Type memberType, out bool isNull)// Leaves !HasValue on stack
507 object v = memberValue ();
509 while (memberType.IsGenericType && memberType.GetGenericTypeDefinition () == Globals.TypeOfNullable) {
510 Type innerType = memberType.GetGenericArguments () [0];
511 if ((bool) XmlFormatGeneratorStatics.GetHasValueMethod.MakeGenericMethod (innerType).Invoke (null, new object [] {v}))
512 v = XmlFormatGeneratorStatics.GetNullableValueMethod.MakeGenericMethod (innerType).Invoke (null, new object [] {v});
515 v = XmlFormatGeneratorStatics.GetDefaultValueMethod.MakeGenericMethod (memberType).Invoke (null, new object [0]);
517 memberType = innerType;
523 bool TryWritePrimitive(Type type, Func<object> value, MemberInfo memberInfo, int? arrayItemIndex, XmlDictionaryString ns, XmlDictionaryString name, int nameIndex)
525 PrimitiveDataContract primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(type);
526 if (primitiveContract == null || primitiveContract.UnderlyingType == Globals.TypeOfObject)
529 object callee = null;
530 var args = new List<object> ();
533 if (type.IsValueType)
539 // load primitive value
542 else if (memberInfo != null)
543 args.Add (CodeInterpreter.GetMember (memberInfo, objLocal));
545 args.Add (((Array) objLocal).GetValue (new int [] {(int) arrayItemIndex}));
550 if (memberNames.Length <= nameIndex) throw new Exception (string.Format ("@@@@@@@@@@@@@@@@@@@ {0} {1} ({2}/{3})", type, memberInfo, nameIndex, memberNames.Length));
551 args.Add (memberNames [nameIndex]);
555 // call method to write primitive
556 primitiveContract.XmlFormatWriterMethod.Invoke (callee, args.ToArray ());
560 bool TryWritePrimitiveArray (Type type, Type itemType, Func<object> value, XmlDictionaryString itemName, XmlDictionaryString itemNamespace)
562 PrimitiveDataContract primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(itemType);
563 if (primitiveContract == null)
566 string writeArrayMethod = null;
567 switch (Type.GetTypeCode(itemType))
569 case TypeCode.Boolean:
570 writeArrayMethod = "WriteBooleanArray";
572 case TypeCode.DateTime:
573 writeArrayMethod = "WriteDateTimeArray";
575 case TypeCode.Decimal:
576 writeArrayMethod = "WriteDecimalArray";
579 writeArrayMethod = "WriteInt32Array";
582 writeArrayMethod = "WriteInt64Array";
584 case TypeCode.Single:
585 writeArrayMethod = "WriteSingleArray";
587 case TypeCode.Double:
588 writeArrayMethod = "WriteDoubleArray";
593 if (writeArrayMethod != null)
595 typeof (XmlWriterDelegator).GetMethod (writeArrayMethod, Globals.ScanAllMembers, null, new Type[] { type, typeof (XmlDictionaryString), typeof (XmlDictionaryString) }, null).Invoke (writer, new object [] {value (), itemName, itemNamespace});
601 object LoadMemberValue (DataMember member)
603 return CodeInterpreter.GetMember (member.MemberInfo, objLocal);