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;
173 // This check does not exist in the original dynamic code,
174 // but there is no other way to check type mismatch.
175 // CollectionSerialization.ArrayContract() shows that it is required.
176 if (objLocal.GetType ().GetElementType () != itemType)
177 throw new InvalidCastException (string.Format ("Cannot cast array of {0} to array of {1}", objLocal.GetType ().GetElementType (), itemType));
179 ctx.IncrementArrayCount (writer, (Array) objLocal);
181 if (!TryWritePrimitiveArray(collectionContract.UnderlyingType, itemType, () => objLocal, itemName, itemNamespace))
183 var arr = (Array) objLocal;
184 var idx = new int [1];
185 for (i = 0; i < arr.Length; i++) {
186 if (!TryWritePrimitive(itemType, null, null, i, itemNamespace, itemName, 0)) {
187 WriteStartElement (itemType, collectionContract.Namespace, itemNamespace, itemName, 0);
189 var mbrVal = arr.GetValue (idx);
190 WriteValue (itemType, mbrVal, false);
198 MethodInfo incrementCollectionCountMethod = null;
199 switch (collectionContract.Kind)
201 case CollectionKind.Collection:
202 case CollectionKind.List:
203 case CollectionKind.Dictionary:
204 incrementCollectionCountMethod = XmlFormatGeneratorStatics.IncrementCollectionCountMethod;
206 case CollectionKind.GenericCollection:
207 case CollectionKind.GenericList:
208 incrementCollectionCountMethod = XmlFormatGeneratorStatics.IncrementCollectionCountGenericMethod.MakeGenericMethod(collectionContract.ItemType);
210 case CollectionKind.GenericDictionary:
211 incrementCollectionCountMethod = XmlFormatGeneratorStatics.IncrementCollectionCountGenericMethod.MakeGenericMethod(Globals.TypeOfKeyValuePair.MakeGenericType(collectionContract.ItemType.GetGenericArguments()));
214 if (incrementCollectionCountMethod != null)
215 incrementCollectionCountMethod.Invoke (ctx, new object [] {writer, objLocal});
217 bool isDictionary = false, isGenericDictionary = false;
218 Type enumeratorType = null;
219 Type [] keyValueTypes = null;
220 if (collectionContract.Kind == CollectionKind.GenericDictionary)
222 isGenericDictionary = true;
223 keyValueTypes = collectionContract.ItemType.GetGenericArguments ();
224 enumeratorType = Globals.TypeOfGenericDictionaryEnumerator.MakeGenericType (keyValueTypes);
226 else if (collectionContract.Kind == CollectionKind.Dictionary)
229 keyValueTypes = new Type[] { Globals.TypeOfObject, Globals.TypeOfObject };
230 enumeratorType = Globals.TypeOfDictionaryEnumerator;
234 enumeratorType = collectionContract.GetEnumeratorMethod.ReturnType;
236 MethodInfo moveNextMethod = enumeratorType.GetMethod (Globals.MoveNextMethodName, BindingFlags.Instance | BindingFlags.Public, null, Globals.EmptyTypeArray, null);
237 MethodInfo getCurrentMethod = enumeratorType.GetMethod (Globals.GetCurrentMethodName, BindingFlags.Instance | BindingFlags.Public, null, Globals.EmptyTypeArray, null);
238 if (moveNextMethod == null || getCurrentMethod == null)
240 if (enumeratorType.IsInterface)
242 if (moveNextMethod == null)
243 moveNextMethod = XmlFormatGeneratorStatics.MoveNextMethod;
244 if (getCurrentMethod == null)
245 getCurrentMethod = XmlFormatGeneratorStatics.GetCurrentMethod;
249 Type ienumeratorInterface = Globals.TypeOfIEnumerator;
250 CollectionKind kind = collectionContract.Kind;
251 if (kind == CollectionKind.GenericDictionary || kind == CollectionKind.GenericCollection || kind == CollectionKind.GenericEnumerable)
253 Type[] interfaceTypes = enumeratorType.GetInterfaces();
254 foreach (Type interfaceType in interfaceTypes)
256 if (interfaceType.IsGenericType
257 && interfaceType.GetGenericTypeDefinition() == Globals.TypeOfIEnumeratorGeneric
258 && interfaceType.GetGenericArguments()[0] == collectionContract.ItemType)
260 ienumeratorInterface = interfaceType;
265 if (moveNextMethod == null)
266 moveNextMethod = CollectionDataContract.GetTargetMethodWithName(Globals.MoveNextMethodName, enumeratorType, ienumeratorInterface);
267 if (getCurrentMethod == null)
268 getCurrentMethod = CollectionDataContract.GetTargetMethodWithName(Globals.GetCurrentMethodName, enumeratorType, ienumeratorInterface);
271 Type elementType = getCurrentMethod.ReturnType;
272 object currentValue = null; // of elementType
274 var enumerator = (IEnumerator) collectionContract.GetEnumeratorMethod.Invoke (objLocal, new object [0]);
277 enumerator = new CollectionDataContract.DictionaryEnumerator ((IDictionaryEnumerator) enumerator);
279 else if (isGenericDictionary)
281 Type ctorParam = Globals.TypeOfIEnumeratorGeneric.MakeGenericType(Globals.TypeOfKeyValuePair.MakeGenericType(keyValueTypes));
282 ConstructorInfo dictEnumCtor = enumeratorType.GetConstructor(Globals.ScanAllMembers, null, new Type[] { ctorParam }, null);
283 enumerator = (IEnumerator) Activator.CreateInstance (enumeratorType, new object [] {enumerator});
286 var emptyArray = new object [0];
287 while (enumerator != null && enumerator.MoveNext ()) {
288 currentValue = getCurrentMethod.Invoke (enumerator, emptyArray);
290 if (incrementCollectionCountMethod == null)
291 XmlFormatGeneratorStatics.IncrementItemCountMethod.Invoke (ctx, new object [] {1});
293 if (!TryWritePrimitive (elementType, () => currentValue, null, null, itemNamespace, itemName, 0))
295 WriteStartElement (elementType, collectionContract.Namespace, itemNamespace, itemName, 0);
296 if (isGenericDictionary || isDictionary)
297 collectionDataContract.ItemContract.WriteXmlValue (writer, currentValue, ctx);
299 WriteValue (elementType, currentValue, false);
306 int WriteMembers (ClassDataContract classContract, ExtensionDataObject extensionData, ClassDataContract derivedMostClassContract)
308 int memberCount = (classContract.BaseContract == null) ? 0 : WriteMembers (classContract.BaseContract, extensionData, derivedMostClassContract);
310 XmlDictionaryString ns =
311 (contractNamespaces == null) ? dataContract.Namespace :
312 contractNamespaces [typeIndex - 1];
314 ctx.IncrementItemCount (classContract.Members.Count);
316 for (int i = 0; i < classContract.Members.Count; i++, memberCount++) {
318 DataMember member = classContract.Members[i];
319 Type memberType = member.MemberType;
320 object memberValue = null;
321 if (member.IsGetOnlyCollection)
322 ctx.StoreIsGetOnlyCollection ();
323 bool doWrite = true, hasMemberValue = false;
324 if (!member.EmitDefaultValue)
326 hasMemberValue = true;
327 memberValue = LoadMemberValue (member);
328 doWrite = !IsDefaultValue (memberType, memberValue);
333 bool writeXsiType = CheckIfMemberHasConflict (member, classContract, derivedMostClassContract);
334 if (writeXsiType || !TryWritePrimitive (memberType, hasMemberValue ? () => memberValue : (Func<object>) null, member.MemberInfo, null /*arrayItemIndex*/, ns, null /*nameLocal*/, i + childElementIndex)) {
335 WriteStartElement (memberType, classContract.Namespace, ns, null /*nameLocal*/, i + childElementIndex);
336 if (classContract.ChildElementNamespaces [i + childElementIndex] != null)
337 writer.WriteNamespaceDecl (childElementNamespaces [i + childElementIndex]);
338 if (memberValue == null)
339 memberValue = LoadMemberValue (member);
340 WriteValue (memberType, memberValue, writeXsiType);
344 if (classContract.HasExtensionData)
345 ctx.WriteExtensionData (writer, extensionData, memberCount);
346 } else if (!member.EmitDefaultValue) {
347 if (member.IsRequired)
348 XmlObjectSerializerWriteContext.ThrowRequiredMemberMustBeEmitted (member.Name, classContract.UnderlyingType);
353 childElementIndex += classContract.Members.Count;
358 internal bool IsDefaultValue (Type type, object value)
360 return GetDefaultValue (type).Equals (value);
363 internal object GetDefaultValue(Type type)
365 if (type.IsValueType)
367 switch (Type.GetTypeCode(type))
369 case TypeCode.Boolean:
375 case TypeCode.UInt16:
377 case TypeCode.UInt32:
380 case TypeCode.UInt64:
382 case TypeCode.Single:
384 case TypeCode.Double:
386 case TypeCode.Decimal:
387 return default (decimal);
388 case TypeCode.DateTime:
389 return default (DateTime);
395 bool CheckIfMemberHasConflict(DataMember member, ClassDataContract classContract, ClassDataContract derivedMostClassContract)
397 // Check for conflict with base type members
398 if (CheckIfConflictingMembersHaveDifferentTypes(member))
401 // Check for conflict with derived type members
402 string name = member.Name;
403 string ns = classContract.StableName.Namespace;
404 ClassDataContract currentContract = derivedMostClassContract;
405 while (currentContract != null && currentContract != classContract)
407 if (ns == currentContract.StableName.Namespace)
409 List<DataMember> members = currentContract.Members;
410 for (int j = 0; j < members.Count; j++)
412 if (name == members[j].Name)
413 return CheckIfConflictingMembersHaveDifferentTypes(members[j]);
416 currentContract = currentContract.BaseContract;
422 bool CheckIfConflictingMembersHaveDifferentTypes(DataMember member)
424 while (member.ConflictingMember != null)
426 if (member.MemberType != member.ConflictingMember.MemberType)
428 member = member.ConflictingMember;
433 bool NeedsPrefix(Type type, XmlDictionaryString ns)
435 return type == Globals.TypeOfXmlQualifiedName && (ns != null && ns.Value != null && ns.Value.Length > 0);
438 void WriteStartElement (Type type, XmlDictionaryString ns, XmlDictionaryString namespaceLocal, XmlDictionaryString nameLocal, int nameIndex)
440 bool needsPrefix = NeedsPrefix(type, ns);
441 nameLocal = nameLocal ?? memberNames [nameIndex];
443 writer.WriteStartElement (Globals.ElementPrefix, nameLocal, namespaceLocal);
445 writer.WriteStartElement (nameLocal, namespaceLocal);
448 void WriteEndElement ()
450 writer.WriteEndElement ();
453 void WriteValue (Type memberType, object memberValue, bool writeXsiType)
455 Pointer memberValueRefPointer = null;
456 if (memberType.IsPointer)
457 memberValueRefPointer = (Pointer) XmlFormatGeneratorStatics.BoxPointer.Invoke (null, new object [] {memberValue, memberType});
458 bool isNullableOfT = (memberType.IsGenericType &&
459 memberType.GetGenericTypeDefinition() == Globals.TypeOfNullable);
460 if (memberType.IsValueType && !isNullableOfT)
462 PrimitiveDataContract primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(memberType);
463 if (primitiveContract != null && !writeXsiType)
464 primitiveContract.XmlFormatContentWriterMethod.Invoke (writer, new object [] {memberValue});
466 InternalSerialize(XmlFormatGeneratorStatics.InternalSerializeMethod, () => memberValue, memberType, writeXsiType);
472 memberValue = UnwrapNullableObject(() => memberValue, ref memberType, out isNull); //Leaves !HasValue on stack
474 isNull = memberValue == null;
476 XmlFormatGeneratorStatics.WriteNullMethod.Invoke (ctx, new object [] {writer, memberType, DataContract.IsTypeSerializable(memberType)});
478 PrimitiveDataContract primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(memberType);
479 if (primitiveContract != null && primitiveContract.UnderlyingType != Globals.TypeOfObject && !writeXsiType) {
481 primitiveContract.XmlFormatContentWriterMethod.Invoke (writer, new object [] {memberValue});
483 primitiveContract.XmlFormatContentWriterMethod.Invoke (ctx, new object [] {writer, memberValue});
485 bool isNull2 = false;
486 if (memberType == Globals.TypeOfObject || //boxed Nullable<T>
487 memberType == Globals.TypeOfValueType ||
488 ((IList)Globals.TypeOfNullable.GetInterfaces()).Contains(memberType)) {
489 var unwrappedMemberValue = CodeInterpreter.ConvertValue (memberValue, memberType.GetType (), Globals.TypeOfObject);
490 memberValue = unwrappedMemberValue;
491 isNull2 = memberValue == null;
494 XmlFormatGeneratorStatics.WriteNullMethod.Invoke (ctx, new object [] {writer, memberType, DataContract.IsTypeSerializable(memberType)});
496 InternalSerialize((isNullableOfT ? XmlFormatGeneratorStatics.InternalSerializeMethod : XmlFormatGeneratorStatics.InternalSerializeReferenceMethod),
497 () => memberValue, memberType, writeXsiType);
504 void InternalSerialize (MethodInfo methodInfo, Func<object> memberValue, Type memberType, bool writeXsiType)
506 var v = memberValue ();
507 var typeHandleValue = Type.GetTypeHandle (v);
508 var isDeclaredType = typeHandleValue.Equals (CodeInterpreter.ConvertValue (v, memberType, Globals.TypeOfObject));
509 methodInfo.Invoke (ctx, new object [] {writer, memberValue != null ? v : null, isDeclaredType, writeXsiType, DataContract.GetId (memberType.TypeHandle), memberType.TypeHandle});
512 object UnwrapNullableObject(Func<object> memberValue, ref Type memberType, out bool isNull)// Leaves !HasValue on stack
514 object v = memberValue ();
516 while (memberType.IsGenericType && memberType.GetGenericTypeDefinition () == Globals.TypeOfNullable) {
517 Type innerType = memberType.GetGenericArguments () [0];
518 if ((bool) XmlFormatGeneratorStatics.GetHasValueMethod.MakeGenericMethod (innerType).Invoke (null, new object [] {v}))
519 v = XmlFormatGeneratorStatics.GetNullableValueMethod.MakeGenericMethod (innerType).Invoke (null, new object [] {v});
522 v = XmlFormatGeneratorStatics.GetDefaultValueMethod.MakeGenericMethod (memberType).Invoke (null, new object [0]);
524 memberType = innerType;
530 bool TryWritePrimitive(Type type, Func<object> value, MemberInfo memberInfo, int? arrayItemIndex, XmlDictionaryString ns, XmlDictionaryString name, int nameIndex)
532 PrimitiveDataContract primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(type);
533 if (primitiveContract == null || primitiveContract.UnderlyingType == Globals.TypeOfObject)
536 object callee = null;
537 var args = new List<object> ();
540 if (type.IsValueType)
546 // load primitive value
549 else if (memberInfo != null)
550 args.Add (CodeInterpreter.GetMember (memberInfo, objLocal));
552 args.Add (((Array) objLocal).GetValue (new int [] {(int) arrayItemIndex}));
557 if (memberNames.Length <= nameIndex) throw new Exception (string.Format ("@@@@@@@@@@@@@@@@@@@ {0} {1} ({2}/{3})", type, memberInfo, nameIndex, memberNames.Length));
558 args.Add (memberNames [nameIndex]);
562 // call method to write primitive
563 primitiveContract.XmlFormatWriterMethod.Invoke (callee, args.ToArray ());
567 bool TryWritePrimitiveArray (Type type, Type itemType, Func<object> value, XmlDictionaryString itemName, XmlDictionaryString itemNamespace)
569 PrimitiveDataContract primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(itemType);
570 if (primitiveContract == null)
573 string writeArrayMethod = null;
574 switch (Type.GetTypeCode(itemType))
576 case TypeCode.Boolean:
577 writeArrayMethod = "WriteBooleanArray";
579 case TypeCode.DateTime:
580 writeArrayMethod = "WriteDateTimeArray";
582 case TypeCode.Decimal:
583 writeArrayMethod = "WriteDecimalArray";
586 writeArrayMethod = "WriteInt32Array";
589 writeArrayMethod = "WriteInt64Array";
591 case TypeCode.Single:
592 writeArrayMethod = "WriteSingleArray";
594 case TypeCode.Double:
595 writeArrayMethod = "WriteDoubleArray";
600 if (writeArrayMethod != null)
602 typeof (XmlWriterDelegator).GetMethod (writeArrayMethod, Globals.ScanAllMembers, null, new Type[] { type, typeof (XmlDictionaryString), typeof (XmlDictionaryString) }, null).Invoke (writer, new object [] {value (), itemName, itemNamespace});
608 object LoadMemberValue (DataMember member)
610 return CodeInterpreter.GetMember (member.MemberInfo, objLocal);