2010-01-20 Zoltan Varga <vargaz@gmail.com>
[mono.git] / mcs / class / System.Runtime.Serialization / System.Runtime.Serialization / KnownTypeCollection.cs
1 //
2 // KnownTypeCollection.cs
3 //
4 // Author:
5 //      Atsushi Enomoto <atsushi@ximian.com>
6 //
7 // Copyright (C) 2005 Novell, Inc.  http://www.novell.com
8 //
9 // Permission is hereby granted, free of charge, to any person obtaining
10 // a copy of this software and associated documentation files (the
11 // "Software"), to deal in the Software without restriction, including
12 // without limitation the rights to use, copy, modify, merge, publish,
13 // distribute, sublicense, and/or sell copies of the Software, and to
14 // permit persons to whom the Software is furnished to do so, subject to
15 // the following conditions:
16 // 
17 // The above copyright notice and this permission notice shall be
18 // included in all copies or substantial portions of the Software.
19 // 
20 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
21 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
22 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
23 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
24 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
25 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
26 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
27 //
28 #if NET_2_0
29 using System;
30 using System.Collections;
31 using System.Collections.Generic;
32 using System.Collections.ObjectModel;
33 using System.Linq;
34 using System.Reflection;
35 using System.Xml;
36 using System.Xml.Schema;
37
38 using QName = System.Xml.XmlQualifiedName;
39 using System.Xml.Serialization;
40
41 namespace System.Runtime.Serialization
42 {
43 /*
44         XmlFormatter implementation design inference:
45
46         type definitions:
47         - No XML Schema types are directly used. There are some maps from
48           xs:blahType to ms:blahType where the namespaceURI for prefix "ms" is
49           "http://schemas.microsoft.com/2003/10/Serialization/" .
50
51         serializable types:
52         - An object being serialized 1) must be of type System.Object, or
53           2) must be null, or 3) must have either a [DataContract] attribute
54           or a [Serializable] attribute to be serializable.
55         - When the object is either of type System.Object or null, then the
56           XML type is "anyType".
57         - When the object is [Serializable], then the runtime-serialization
58           compatible object graph is written.
59         - Otherwise the serialization is based on contract attributes.
60           ([Serializable] takes precedence).
61
62         type derivation:
63         - For type A to be serializable, the base type B of A must be
64           serializable.
65         - If a type which is [Serializable] and whose base type has a
66           [DataContract], then for base type members [DataContract] is taken.
67         - It is vice versa i.e. if the base type is [Serializable] and the
68           derived type has a [DataContract], then [Serializable] takes place
69           for base members.
70
71         known type collection:
72         - It internally manages mapping store keyed by contract QNames.
73           KnownTypeCollection.Add() checks if the same QName contract already
74           exists (and raises InvalidOperationException if required).
75
76 */
77         internal static class TypeExtensions
78         {
79                 public static T GetCustomAttribute<T> (this Type type, bool inherit)
80                 {
81                         var arr = type.GetCustomAttributes (typeof (T), inherit);
82                         return arr != null && arr.Length == 1 ? (T) arr [0] : default (T);
83                 }
84         }
85
86         internal sealed class KnownTypeCollection : Collection<Type>
87         {
88                 internal const string MSSimpleNamespace =
89                         "http://schemas.microsoft.com/2003/10/Serialization/";
90                 internal const string MSArraysNamespace =
91                         "http://schemas.microsoft.com/2003/10/Serialization/Arrays";
92                 internal const string DefaultClrNamespaceBase =
93                         "http://schemas.datacontract.org/2004/07/";
94
95                 static QName any_type, bool_type,
96                         byte_type, date_type, decimal_type, double_type,
97                         float_type, string_type,
98                         short_type, int_type, long_type,
99                         ubyte_type, ushort_type, uint_type, ulong_type,
100                         // non-TypeCode
101                         any_uri_type, base64_type, duration_type, qname_type,
102                         // custom in ms nsURI schema
103                         char_type, guid_type,
104                         // not in ms nsURI schema
105                         dbnull_type;
106
107                 static KnownTypeCollection ()
108                 {
109                         //any_type, bool_type,  byte_type, date_type, decimal_type, double_type,        float_type, string_type,
110                         // short_type, int_type, long_type,     ubyte_type, ushort_type, uint_type, ulong_type,
111                         //      any_uri_type, base64_type, duration_type, qname_type,
112                         //      char_type, guid_type,   dbnull_type;
113                         string s = MSSimpleNamespace;
114                         any_type = new QName ("anyType", s);
115                         any_uri_type = new QName ("anyURI", s);
116                         bool_type = new QName ("boolean", s);
117                         base64_type = new QName ("base64Binary", s);
118                         date_type = new QName ("dateTime", s);
119                         duration_type = new QName ("duration", s);
120                         qname_type = new QName ("QName", s);
121                         decimal_type = new QName ("decimal", s);
122                         double_type = new QName ("double", s);
123                         float_type = new QName ("float", s);
124                         byte_type = new QName ("byte", s);
125                         short_type = new QName ("short", s);
126                         int_type = new QName ("int", s);
127                         long_type = new QName ("long", s);
128                         ubyte_type = new QName ("unsignedByte", s);
129                         ushort_type = new QName ("unsignedShort", s);
130                         uint_type = new QName ("unsignedInt", s);
131                         ulong_type = new QName ("unsignedLong", s);
132                         string_type = new QName ("string", s);
133                         guid_type = new QName ("guid", s);
134                         char_type = new QName ("char", s);
135
136                         dbnull_type = new QName ("DBNull", MSSimpleNamespace + "System");
137                 }
138
139                 // FIXME: find out how QName and guid are processed
140
141                 internal QName GetXmlName (Type type)
142                 {
143                         SerializationMap map = FindUserMap (type);
144                         if (map != null)
145                                 return map.XmlName;
146                         return GetPredefinedTypeName (type);
147                 }
148
149                 internal static QName GetPredefinedTypeName (Type type)
150                 {
151                         QName name = GetPrimitiveTypeName (type);
152                         if (name != QName.Empty)
153                                 return name;
154                         if (type == typeof (DBNull))
155                                 return dbnull_type;
156                         return QName.Empty;
157                 }
158
159                 internal static QName GetPrimitiveTypeName (Type type)
160                 {
161                         if (type.IsGenericType && type.GetGenericTypeDefinition () == typeof (Nullable<>))
162                                 return GetPrimitiveTypeName (type.GetGenericArguments () [0]);
163
164                         if (type.IsEnum)
165                                 return QName.Empty;
166
167                         switch (Type.GetTypeCode (type)) {
168                         case TypeCode.Object: // other than System.Object
169                         case TypeCode.DBNull: // it is natively mapped, but not in ms serialization namespace.
170                         case TypeCode.Empty:
171                         default:
172                                 if (type == typeof (object))
173                                         return any_type;
174                                 if (type == typeof (Guid))
175                                         return guid_type;
176                                 if (type == typeof (TimeSpan))
177                                         return duration_type;
178                                 if (type == typeof (byte []))
179                                         return base64_type;
180                                 if (type == typeof (Uri))
181                                         return any_uri_type;
182                                 return QName.Empty;
183                         case TypeCode.Boolean:
184                                 return bool_type;
185                         case TypeCode.Byte:
186                                 return ubyte_type;
187                         case TypeCode.Char:
188                                 return char_type;
189                         case TypeCode.DateTime:
190                                 return date_type;
191                         case TypeCode.Decimal:
192                                 return decimal_type;
193                         case TypeCode.Double:
194                                 return double_type;
195                         case TypeCode.Int16:
196                                 return short_type;
197                         case TypeCode.Int32:
198                                 return int_type;
199                         case TypeCode.Int64:
200                                 return long_type;
201                         case TypeCode.SByte:
202                                 return byte_type;
203                         case TypeCode.Single:
204                                 return float_type;
205                         case TypeCode.String:
206                                 return string_type;
207                         case TypeCode.UInt16:
208                                 return ushort_type;
209                         case TypeCode.UInt32:
210                                 return uint_type;
211                         case TypeCode.UInt64:
212                                 return ulong_type;
213                         }
214                 }
215
216                 internal static string PredefinedTypeObjectToString (object obj)
217                 {
218                         Type type = obj.GetType ();
219                         switch (Type.GetTypeCode (type)) {
220                         case TypeCode.Object: // other than System.Object
221                         case TypeCode.Empty:
222                         default:
223                                 if (type == typeof (object))
224                                         return String.Empty;
225                                 if (type == typeof (Guid))
226                                         return XmlConvert.ToString ((Guid) obj);
227                                 if (type == typeof (TimeSpan))
228                                         return XmlConvert.ToString ((TimeSpan) obj);
229                                 if (type == typeof (byte []))
230                                         return Convert.ToBase64String ((byte []) obj);
231                                 if (type == typeof (Uri))
232                                         return ((Uri) obj).ToString ();
233                                 throw new Exception ("Internal error: missing predefined type serialization for type " + type.FullName);
234                         case TypeCode.DBNull: // predefined, but not primitive
235                                 return String.Empty;
236                         case TypeCode.Boolean:
237                                 return XmlConvert.ToString ((bool) obj);
238                         case TypeCode.Byte:
239                                 return XmlConvert.ToString ((int)((byte) obj));
240                         case TypeCode.Char:
241                                 return XmlConvert.ToString ((uint) (char) obj);
242                         case TypeCode.DateTime:
243                                 return XmlConvert.ToString ((DateTime) obj, XmlDateTimeSerializationMode.RoundtripKind);
244                         case TypeCode.Decimal:
245                                 return XmlConvert.ToString ((decimal) obj);
246                         case TypeCode.Double:
247                                 return XmlConvert.ToString ((double) obj);
248                         case TypeCode.Int16:
249                                 return XmlConvert.ToString ((short) obj);
250                         case TypeCode.Int32:
251                                 return XmlConvert.ToString ((int) obj);
252                         case TypeCode.Int64:
253                                 return XmlConvert.ToString ((long) obj);
254                         case TypeCode.SByte:
255                                 return XmlConvert.ToString ((sbyte) obj);
256                         case TypeCode.Single:
257                                 return XmlConvert.ToString ((float) obj);
258                         case TypeCode.String:
259                                 return (string) obj;
260                         case TypeCode.UInt16:
261                                 return XmlConvert.ToString ((int) (ushort) obj);
262                         case TypeCode.UInt32:
263                                 return XmlConvert.ToString ((uint) obj);
264                         case TypeCode.UInt64:
265                                 return XmlConvert.ToString ((ulong) obj);
266                         }
267                 }
268
269                 internal static Type GetPrimitiveTypeFromName (string name)
270                 {
271                         switch (name) {
272                         case "anyURI":
273                                 return typeof (Uri);
274                         case "boolean":
275                                 return typeof (bool);
276                         case "base64Binary":
277                                 return typeof (byte []);
278                         case "dateTime":
279                                 return typeof (DateTime);
280                         case "duration":
281                                 return typeof (TimeSpan);
282                         case "QName":
283                                 return typeof (QName);
284                         case "decimal":
285                                 return typeof (decimal);
286                         case "double":
287                                 return typeof (double);
288                         case "float":
289                                 return typeof (float);
290                         case "byte":
291                                 return typeof (sbyte);
292                         case "short":
293                                 return typeof (short);
294                         case "int":
295                                 return typeof (int);
296                         case "long":
297                                 return typeof (long);
298                         case "unsignedByte":
299                                 return typeof (byte);
300                         case "unsignedShort":
301                                 return typeof (ushort);
302                         case "unsignedInt":
303                                 return typeof (uint);
304                         case "unsignedLong":
305                                 return typeof (ulong);
306                         case "string":
307                                 return typeof (string);
308                         case "anyType":
309                                 return typeof (object);
310                         case "guid":
311                                 return typeof (Guid);
312                         case "char":
313                                 return typeof (char);
314                         default:
315                                 return null;
316                         }
317                 }
318
319
320                 internal static object PredefinedTypeStringToObject (string s,
321                         string name, XmlReader reader)
322                 {
323                         switch (name) {
324                         case "anyURI":
325                                 return new Uri(s,UriKind.RelativeOrAbsolute);
326                         case "boolean":
327                                 return XmlConvert.ToBoolean (s);
328                         case "base64Binary":
329                                 return Convert.FromBase64String (s);
330                         case "dateTime":
331                                 return XmlConvert.ToDateTime (s, XmlDateTimeSerializationMode.RoundtripKind);
332                         case "duration":
333                                 return XmlConvert.ToTimeSpan (s);
334                         case "QName":
335                                 int idx = s.IndexOf (':');
336                                 string l = idx < 0 ? s : s.Substring (idx + 1);
337                                 return idx < 0 ? new QName (l) :
338                                         new QName (l, reader.LookupNamespace (
339                                                 s.Substring (0, idx)));
340                         case "decimal":
341                                 return XmlConvert.ToDecimal (s);
342                         case "double":
343                                 return XmlConvert.ToDouble (s);
344                         case "float":
345                                 return XmlConvert.ToSingle (s);
346                         case "byte":
347                                 return XmlConvert.ToSByte (s);
348                         case "short":
349                                 return XmlConvert.ToInt16 (s);
350                         case "int":
351                                 return XmlConvert.ToInt32 (s);
352                         case "long":
353                                 return XmlConvert.ToInt64 (s);
354                         case "unsignedByte":
355                                 return XmlConvert.ToByte (s);
356                         case "unsignedShort":
357                                 return XmlConvert.ToUInt16 (s);
358                         case "unsignedInt":
359                                 return XmlConvert.ToUInt32 (s);
360                         case "unsignedLong":
361                                 return XmlConvert.ToUInt64 (s);
362                         case "string":
363                                 return s;
364                         case "guid":
365                                 return XmlConvert.ToGuid (s);
366                         case "anyType":
367                                 return s;
368                         case "char":
369                                 return (char) XmlConvert.ToUInt32 (s);
370                         default:
371                                 throw new Exception ("Unanticipated primitive type: " + name);
372                         }
373                 }
374
375                 List<SerializationMap> contracts = new List<SerializationMap> ();
376
377                 public KnownTypeCollection ()
378                 {
379                 }
380
381                 protected override void ClearItems ()
382                 {
383                         base.Clear ();
384                 }
385
386                 protected override void InsertItem (int index, Type type)
387                 {
388                         if (TryRegister (type))
389                                 base.InsertItem (index, type);
390                 }
391
392                 // FIXME: it could remove other types' dependencies.
393                 protected override void RemoveItem (int index)
394                 {
395                         Type t = base [index];
396                         List<SerializationMap> l = new List<SerializationMap> ();
397                         foreach (SerializationMap m in contracts) {
398                                 if (m.RuntimeType == t)
399                                         l.Add (m);
400                         }
401                         foreach (SerializationMap m in l) {
402                                 contracts.Remove (m);
403                                 base.RemoveItem (index);
404                         }
405                 }
406
407                 protected override void SetItem (int index, Type type)
408                 {
409                         if (index == Count)
410                                 InsertItem (index, type);
411                         else {
412                                 RemoveItem (index);
413                                 if (TryRegister (type))
414                                         base.InsertItem (index - 1, type);
415                         }
416                 }
417
418                 internal SerializationMap FindUserMap (QName qname)
419                 {
420                         for (int i = 0; i < contracts.Count; i++)
421                                 if (qname == contracts [i].XmlName)
422                                         return contracts [i];
423                         return null;
424                 }
425
426                 internal Type GetSerializedType (Type type)
427                 {
428                         Type element = GetCollectionElementType (type);
429                         if (element == null)
430                                 return type;
431                         QName name = GetQName (type);
432                         var map = FindUserMap (name);
433                         if (map != null)
434                                 return map.RuntimeType;
435                         return type;
436                 }
437
438                 internal SerializationMap FindUserMap (Type type)
439                 {
440                         for (int i = 0; i < contracts.Count; i++)
441                                 if (type == contracts [i].RuntimeType)
442                                         return contracts [i];
443                         return null;
444                 }
445
446                 internal QName GetQName (Type type)
447                 {
448                         if (IsPrimitiveNotEnum (type))
449                                 return GetPrimitiveTypeName (type);
450
451                         SerializationMap map = FindUserMap (type);
452                         if (map != null)
453                                 // already mapped.
454                                 return map.XmlName; 
455
456                         if (type.IsEnum)
457                                 return GetEnumQName (type);
458
459                         QName qname = GetContractQName (type);
460                         if (qname != null)
461                                 return qname;
462
463                         if (type.GetInterface ("System.Xml.Serialization.IXmlSerializable") != null)
464                                 //FIXME: Reusing GetSerializableQName here, since we just 
465                                 //need name of the type..
466                                 return GetSerializableQName (type);
467
468                         qname = GetCollectionContractQName (type);
469                         if (qname != null)
470                                 return qname;
471
472                         Type element = GetCollectionElementType (type);
473                         if (element != null)
474                                 return GetCollectionQName (element);
475
476                         if (GetAttribute<SerializableAttribute> (type) != null)
477                                 return GetSerializableQName (type);
478
479                         // FIXME: it needs in-depth check.
480                         return QName.Empty;
481                 }
482
483                 QName GetContractQName (Type type)
484                 {
485                         var a = GetAttribute<DataContractAttribute> (type);
486                         return a == null ? null : GetContractQName (type, a.Name, a.Namespace);
487                 }
488
489                 QName GetCollectionContractQName (Type type)
490                 {
491                         var a = GetAttribute<CollectionDataContractAttribute> (type);
492                         return a == null ? null : GetContractQName (type, a.Name, a.Namespace);
493                 }
494
495                 internal static QName GetContractQName (Type type, string name, string ns)
496                 {
497                         if (name == null) {
498                                 // FIXME: there could be decent ways to get 
499                                 // the same result...
500                                 name = type.Namespace == null || type.Namespace.Length == 0 ? type.Name : type.FullName.Substring (type.Namespace.Length + 1).Replace ('+', '.');
501                                 if (type.IsGenericType) {
502                                         name = name.Substring (0, name.IndexOf ('`')) + "Of";
503                                         foreach (var t in type.GetGenericArguments ())
504                                                 name += t.Name; // FIXME: check namespaces too
505                                 }
506                         }
507                         if (ns == null)
508                                 ns = DefaultClrNamespaceBase + type.Namespace;
509                         return new QName (name, ns);
510                 }
511
512                 private QName GetEnumQName (Type type)
513                 {
514                         string name = null, ns = null;
515
516                         if (!type.IsEnum)
517                                 return null;
518
519                         var dca = GetAttribute<DataContractAttribute> (type);
520
521                         if (dca != null) {
522                                 ns = dca.Namespace;
523                                 name = dca.Name;
524                         }
525
526                         if (ns == null)
527                                 ns = DefaultClrNamespaceBase + type.Namespace;
528
529                         if (name == null)
530                                 name = type.Namespace == null ? type.Name : type.FullName.Substring (type.Namespace.Length + 1).Replace ('+', '.');
531
532                         return new QName (name, ns);
533                 }
534
535                 private QName GetCollectionQName (Type element)
536                 {
537                         QName eqname = GetQName (element);
538                         
539                         string ns = eqname.Namespace;
540                         if (eqname.Namespace == MSSimpleNamespace)
541                                 //Arrays of Primitive types
542                                 ns = MSArraysNamespace;
543
544                         return new QName (
545                                 "ArrayOf" + XmlConvert.EncodeLocalName (eqname.Name),
546                                 ns);
547                 }
548
549                 private QName GetSerializableQName (Type type)
550                 {
551                         string xmlName = type.Name;
552                         if (type.IsGenericType) {
553                                 xmlName = xmlName.Substring (0, xmlName.IndexOf ('`')) + "Of";
554                                 foreach (var t in type.GetGenericArguments ())
555                                         xmlName += GetQName (t).Name; // FIXME: check namespaces too
556                         }
557                         string xmlNamespace = DefaultClrNamespaceBase + type.Namespace;
558                         var x = GetAttribute<XmlRootAttribute> (type);
559                         if (x != null) {
560                                 xmlName = x.ElementName;
561                                 xmlNamespace = x.Namespace;
562                         }
563                         return new QName (XmlConvert.EncodeLocalName (xmlName), xmlNamespace);
564                 }
565
566                 internal bool IsPrimitiveNotEnum (Type type)
567                 {
568                         if (type.IsEnum)
569                                 return false;
570                         if (Type.GetTypeCode (type) != TypeCode.Object) // explicitly primitive
571                                 return true;
572                         if (type == typeof (Guid) || type == typeof (object) || type == typeof(TimeSpan) || type == typeof(byte[]) || type==typeof(Uri)) // special primitives
573                                 return true;
574                         // nullable
575                         if (type.IsGenericType && type.GetGenericTypeDefinition () == typeof (Nullable<>))
576                                 return IsPrimitiveNotEnum (type.GetGenericArguments () [0]);
577                         return false;
578                 }
579
580                 internal bool TryRegister (Type type)
581                 {
582                         // exclude predefined maps
583                         if (IsPrimitiveNotEnum (type))
584                                 return false;
585
586                         if (FindUserMap (type) != null)
587                                 return false;
588
589                         if (RegisterEnum (type) != null)
590                                 return true;
591
592                         if (RegisterContract (type) != null)
593                                 return true;
594
595                         if (RegisterIXmlSerializable (type) != null)
596                                 return true;
597
598                         if (RegisterDictionary (type) != null)
599                                 return true;
600
601                         if (RegisterCollectionContract (type) != null)
602                                 return true;
603
604                         if (RegisterCollection (type) != null)
605                                 return true;
606
607                         if (GetAttribute<SerializableAttribute> (type) != null) {
608                                 RegisterSerializable (type);
609                                 return true;
610                         }
611
612                         RegisterDefaultTypeMap (type);
613                         return true;
614                 }
615
616                 internal static Type GetCollectionElementType (Type type)
617                 {
618                         if (type.IsArray)
619                                 return type.GetElementType ();
620
621                         Type [] ifaces = type.GetInterfaces ();
622                         foreach (Type i in ifaces)
623                                 if (i.IsGenericType && i.GetGenericTypeDefinition ().Equals (typeof (ICollection<>)))
624                                         return i.GetGenericArguments () [0];
625                         foreach (Type i in ifaces)
626                                 if (i == typeof (IList))
627                                         return typeof (object);
628                         return null;
629                 }
630
631                 internal T GetAttribute<T> (MemberInfo mi) where T : Attribute
632                 {
633                         object [] atts = mi.GetCustomAttributes (typeof (T), false);
634                         return atts.Length == 0 ? null : (T) atts [0];
635                 }
636
637                 private CollectionContractTypeMap RegisterCollectionContract (Type type)
638                 {
639                         var cdca = GetAttribute<CollectionDataContractAttribute> (type);
640                         if (cdca == null)
641                                 return null;
642
643                         Type element = GetCollectionElementType (type);
644                         if (element == null)
645                                 throw new InvalidOperationException (String.Format ("Type '{0}' is marked as collection contract, but it is not a collection", type));
646
647                         TryRegister (element); // must be registered before the name conflict check.
648
649                         QName qname = GetCollectionContractQName (type);
650                         CheckStandardQName (qname);
651                         if (FindUserMap (qname) != null)
652                                 throw new InvalidOperationException (String.Format ("Failed to add type {0} to known type collection. There already is a registered type for XML name {1}", type, qname));
653
654                         var ret = new CollectionContractTypeMap (type, cdca, element, qname, this);
655                         contracts.Add (ret);
656                         return ret;
657                 }
658
659                 private CollectionTypeMap RegisterCollection (Type type)
660                 {
661                         Type element = GetCollectionElementType (type);
662                         if (element == null)
663                                 return null;
664
665                         TryRegister (element);
666
667                         QName qname = GetCollectionQName (element);
668
669                         var map = FindUserMap (qname);
670                         if (map != null) {
671                                 var cmap = map as CollectionTypeMap;
672                                 if (cmap == null || cmap.RuntimeType != type)
673                                         throw new InvalidOperationException (String.Format ("Failed to add type {0} to known type collection. There already is a registered type for XML name {1}", type, qname));
674                                 return cmap;
675                         }
676
677                         CollectionTypeMap ret =
678                                 new CollectionTypeMap (type, element, qname, this);
679                         contracts.Add (ret);
680                         return ret;
681                 }
682
683                 static bool TypeImplementsIDictionary (Type type)
684                 {
685                         foreach (var iface in type.GetInterfaces ())
686                                 if (iface == typeof (IDictionary) || (iface.IsGenericType && iface.GetGenericTypeDefinition () == typeof (IDictionary<,>)))
687                                         return true;
688
689                         return false;
690                 }
691
692                 // it also supports contract-based dictionary.
693                 private DictionaryTypeMap RegisterDictionary (Type type)
694                 {
695                         if (!TypeImplementsIDictionary (type))
696                                 return null;
697
698                         var cdca = GetAttribute<CollectionDataContractAttribute> (type);
699
700                         DictionaryTypeMap ret =
701                                 new DictionaryTypeMap (type, cdca, this);
702
703                         if (FindUserMap (ret.XmlName) != null)
704                                 throw new InvalidOperationException (String.Format ("Failed to add type {0} to known type collection. There already is a registered type for XML name {1}", type, ret.XmlName));
705                         contracts.Add (ret);
706
707                         TryRegister (ret.KeyType);
708                         TryRegister (ret.ValueType);
709
710                         return ret;
711                 }
712
713                 private SerializationMap RegisterSerializable (Type type)
714                 {
715                         QName qname = GetSerializableQName (type);
716
717                         if (FindUserMap (qname) != null)
718                                 throw new InvalidOperationException (String.Format ("There is already a registered type for XML name {0}", qname));
719
720                         SharedTypeMap ret =
721                                 new SharedTypeMap (type, qname, this);
722                         contracts.Add (ret);
723                         return ret;
724                 }
725
726                 private SerializationMap RegisterIXmlSerializable (Type type)
727                 {
728                         if (type.GetInterface ("System.Xml.Serialization.IXmlSerializable") == null)
729                                 return null;
730
731                         QName qname = GetSerializableQName (type);
732
733                         if (FindUserMap (qname) != null)
734                                 throw new InvalidOperationException (String.Format ("There is already a registered type for XML name {0}", qname));
735
736                         XmlSerializableMap ret = new XmlSerializableMap (type, qname, this);
737                         contracts.Add (ret);
738
739                         return ret;
740                 }
741
742                 void CheckStandardQName (QName qname)
743                 {
744                         switch (qname.Namespace) {
745                         case XmlSchema.Namespace:
746                         case XmlSchema.InstanceNamespace:
747                         case MSSimpleNamespace:
748                         case MSArraysNamespace:
749                                 throw new InvalidOperationException (String.Format ("Namespace {0} is reserved and cannot be used for user serialization", qname.Namespace));
750                         }
751
752                 }
753
754                 private SharedContractMap RegisterContract (Type type)
755                 {
756                         QName qname = GetContractQName (type);
757                         if (qname == null)
758                                 return null;
759                         CheckStandardQName (qname);
760                         if (FindUserMap (qname) != null)
761                                 throw new InvalidOperationException (String.Format ("There is already a registered type for XML name {0}", qname));
762
763                         SharedContractMap ret = new SharedContractMap (type, qname, this);
764                         contracts.Add (ret);
765                         ret.Initialize ();
766
767                         object [] attrs = type.GetCustomAttributes (typeof (KnownTypeAttribute), true);
768                         for (int i = 0; i < attrs.Length; i++) {
769                                 KnownTypeAttribute kt = (KnownTypeAttribute) attrs [i];
770                                 TryRegister (kt.Type);
771                         }
772
773                         return ret;
774                 }
775
776                 DefaultTypeMap RegisterDefaultTypeMap (Type type)
777                 {
778                         DefaultTypeMap ret = new DefaultTypeMap (type, this);
779                         contracts.Add (ret);
780                         return ret;
781                 }
782
783                 private EnumMap RegisterEnum (Type type)
784                 {
785                         QName qname = GetEnumQName (type);
786                         if (qname == null)
787                                 return null;
788
789                         if (FindUserMap (qname) != null)
790                                 throw new InvalidOperationException (String.Format ("There is already a registered type for XML name {0}", qname));
791
792                         EnumMap ret =
793                                 new EnumMap (type, qname, this);
794                         contracts.Add (ret);
795                         return ret;
796                 }
797         }
798 }
799 #endif