* ProtocolImporter.cs: Use the binding name as class name for the
[mono.git] / mcs / class / System.XML / System.Xml.Serialization / SoapReflectionImporter.cs
1 // 
2 // System.Xml.Serialization.SoapReflectionImporter 
3 //
4 // Author:
5 //   Tim Coleman (tim@timcoleman.com)
6 //
7 // Copyright (C) Tim Coleman, 2002
8 //
9
10 //
11 // Permission is hereby granted, free of charge, to any person obtaining
12 // a copy of this software and associated documentation files (the
13 // "Software"), to deal in the Software without restriction, including
14 // without limitation the rights to use, copy, modify, merge, publish,
15 // distribute, sublicense, and/or sell copies of the Software, and to
16 // permit persons to whom the Software is furnished to do so, subject to
17 // the following conditions:
18 // 
19 // The above copyright notice and this permission notice shall be
20 // included in all copies or substantial portions of the Software.
21 // 
22 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
23 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
24 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
25 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
26 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
27 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
28 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
29 //
30
31 using System.Collections;
32 using System.Globalization;
33 using System.Reflection;
34 using System.Xml;
35 using System.Xml.Schema;
36
37 namespace System.Xml.Serialization {
38         public class SoapReflectionImporter {
39
40                 SoapAttributeOverrides attributeOverrides;
41                 string initialDefaultNamespace;
42                 ArrayList includedTypes;
43                 ArrayList relatedMaps = new ArrayList ();
44                 ReflectionHelper helper = new ReflectionHelper();
45
46                 #region Constructors
47
48                 public SoapReflectionImporter (): this (null, null)
49                 { 
50                 }
51
52                 public SoapReflectionImporter (SoapAttributeOverrides attributeOverrides): this (attributeOverrides, null)
53                 { 
54                 }
55
56                 public SoapReflectionImporter (string defaultNamespace): this (null, defaultNamespace)
57                 {
58                 }
59
60                 public SoapReflectionImporter (SoapAttributeOverrides attributeOverrides, string defaultNamespace)
61                 { 
62                         if (defaultNamespace == null) initialDefaultNamespace = String.Empty;
63                         else initialDefaultNamespace = defaultNamespace;
64
65                         if (attributeOverrides == null) this.attributeOverrides = new SoapAttributeOverrides();
66                         else this.attributeOverrides = attributeOverrides;
67                 }
68
69                 #endregion // Constructors
70
71                 #region Methods
72
73                 public XmlMembersMapping ImportMembersMapping (string elementName, string ns, XmlReflectionMember[] members)
74                 {
75                         return ImportMembersMapping (elementName, ns, members, true, true, false);
76                 }
77
78                 public XmlMembersMapping ImportMembersMapping (string elementName, string ns, XmlReflectionMember[] members, bool hasWrapperElement, bool writeAccessors)
79                 { 
80                         return ImportMembersMapping (elementName, ns, members, hasWrapperElement, writeAccessors, false);
81                 }
82
83                 public XmlMembersMapping ImportMembersMapping (string elementName, string ns, XmlReflectionMember[] members, bool hasWrapperElement, bool writeAccessors, bool validate)
84                 {
85                         return ImportMembersMapping (elementName, ns, members, hasWrapperElement, writeAccessors, validate, XmlMappingAccess.Read | XmlMappingAccess.Write);
86                 }
87
88 #if NET_2_0
89                 [MonoTODO]
90                 public
91 #endif
92                 XmlMembersMapping ImportMembersMapping (string elementName, string ns, XmlReflectionMember[] members, bool hasWrapperElement, bool writeAccessors, bool validate, XmlMappingAccess access)
93                 {
94                         elementName = XmlConvert.EncodeLocalName (elementName);
95                         XmlMemberMapping[] mapping = new XmlMemberMapping[members.Length];
96                         for (int n=0; n<members.Length; n++)
97                         {
98                                 XmlTypeMapMember mapMem = CreateMapMember (members[n], ns);
99                                 mapping[n] = new XmlMemberMapping (XmlConvert.EncodeLocalName (members[n].MemberName), ns, mapMem, true);
100                         }
101                         XmlMembersMapping mps = new XmlMembersMapping (elementName, ns, hasWrapperElement, writeAccessors, mapping);
102                         mps.RelatedMaps = relatedMaps;
103                         mps.Format = SerializationFormat.Encoded;
104                         Type[] extraTypes = includedTypes != null ? (Type[])includedTypes.ToArray(typeof(Type)) : null;
105                         mps.Source = new MembersSerializationSource (elementName, hasWrapperElement, members, writeAccessors, false, null, extraTypes);
106                         return mps;
107                 }
108
109                 public XmlTypeMapping ImportTypeMapping (Type type)
110                 { 
111                         return ImportTypeMapping (type, null);
112                 }
113
114                 public XmlTypeMapping ImportTypeMapping (Type type, string defaultNamespace)
115                 {
116                         if (type == null)
117                                 throw new ArgumentNullException ("type");
118
119                         if (type == typeof (void))
120                                 throw new InvalidOperationException ("Type " + type.Name + " may not be serialized.");
121
122                         return ImportTypeMapping (TypeTranslator.GetTypeData (type),
123                                 defaultNamespace);
124                 }
125
126                 internal XmlTypeMapping ImportTypeMapping (TypeData typeData, string defaultNamespace)
127                 {
128                         if (typeData == null)
129                                 throw new ArgumentNullException ("typeData");
130
131                         if (typeData.Type == null)
132                                 throw new ArgumentException ("Specified TypeData instance does not have Type set.");
133
134                         string oldNs = initialDefaultNamespace;
135                         if (defaultNamespace == null) defaultNamespace = initialDefaultNamespace;
136                         if (defaultNamespace == null) defaultNamespace = string.Empty;
137                         initialDefaultNamespace = defaultNamespace; 
138
139                         XmlTypeMapping map;
140                         switch (typeData.SchemaType) {
141                                 case SchemaTypes.Class: map = ImportClassMapping (typeData, defaultNamespace); break;
142                                 case SchemaTypes.Array: map = ImportListMapping (typeData, defaultNamespace); break;
143                                 case SchemaTypes.XmlNode: throw CreateTypeException (typeData.Type);
144                                 case SchemaTypes.Primitive: map = ImportPrimitiveMapping (typeData, defaultNamespace); break;
145                                 case SchemaTypes.Enum: map = ImportEnumMapping (typeData, defaultNamespace); break;
146                                 case SchemaTypes.XmlSerializable:
147                                 default: throw new NotSupportedException ("Type " + typeData.Type.FullName + " not supported for XML serialization");
148                         }
149                         map.RelatedMaps = relatedMaps;
150                         map.Format = SerializationFormat.Encoded;
151                         Type[] extraTypes = includedTypes != null ? (Type[])includedTypes.ToArray(typeof(Type)) : null;
152                         map.Source = new SoapTypeSerializationSource (typeData.Type, attributeOverrides, defaultNamespace, extraTypes);
153                         
154                         initialDefaultNamespace = oldNs;
155                         return map;
156                 }
157
158                 XmlTypeMapping CreateTypeMapping (TypeData typeData, string defaultXmlType, string defaultNamespace)
159                 {
160                         string membersNamespace = defaultNamespace;
161                         bool includeInSchema = true;
162
163                         SoapAttributes atts = null;
164                         if (defaultXmlType == null) defaultXmlType = typeData.XmlType;
165
166                         if (!typeData.IsListType)
167                         {
168                                 if (attributeOverrides != null) 
169                                         atts = attributeOverrides[typeData.Type];
170
171                                 if (atts != null && typeData.SchemaType == SchemaTypes.Primitive)
172                                         throw new InvalidOperationException ("SoapType attribute may not be specified for the type " + typeData.FullTypeName);
173                         }
174
175                         if (atts == null) 
176                                 atts = new SoapAttributes (typeData.Type);
177
178                         if (atts.SoapType != null)
179                         {
180                                 if (atts.SoapType.Namespace != null && atts.SoapType.Namespace != string.Empty)
181                                         membersNamespace = atts.SoapType.Namespace;
182
183                                 if (atts.SoapType.TypeName != null && atts.SoapType.TypeName != string.Empty)
184                                         defaultXmlType = XmlConvert.EncodeLocalName (atts.SoapType.TypeName);
185
186                                 includeInSchema = atts.SoapType.IncludeInSchema;
187                         }
188
189                         if (membersNamespace == null) membersNamespace = "";
190                         XmlTypeMapping map = new XmlTypeMapping (defaultXmlType, membersNamespace, typeData, defaultXmlType, membersNamespace);
191                         map.IncludeInSchema = includeInSchema;
192                         relatedMaps.Add (map);
193
194                         return map;
195                 }
196
197                 XmlTypeMapping ImportClassMapping (Type type, string defaultNamespace)
198                 {
199                         TypeData typeData = TypeTranslator.GetTypeData (type);
200                         return ImportClassMapping (typeData, defaultNamespace);
201                 }
202
203                 XmlTypeMapping ImportClassMapping (TypeData typeData, string defaultNamespace)
204                 {
205                         Type type = typeData.Type;
206
207                         if (type.IsValueType) throw CreateStructException (type);
208
209                         if (type == typeof (object)) defaultNamespace = XmlSchema.Namespace;
210
211                         ReflectionHelper.CheckSerializableType (type, false);
212                         XmlTypeMapping map = helper.GetRegisteredClrType (type, GetTypeNamespace (typeData, defaultNamespace));
213                         if (map != null) return map;
214
215                         map = CreateTypeMapping (typeData, null, defaultNamespace);
216                         helper.RegisterClrType (map, type, map.Namespace);
217                         map.MultiReferenceType = true;
218
219                         ClassMap classMap = new ClassMap ();
220                         map.ObjectMap = classMap;
221
222                         // Import members
223
224                         ICollection members = GetReflectionMembers (type);
225                         foreach (XmlReflectionMember rmember in members) {
226                                 if (rmember.SoapAttributes.SoapIgnore) continue;
227                                 classMap.AddMember (CreateMapMember (rmember, defaultNamespace));
228                         }
229
230                         // Import included classes
231
232                         SoapIncludeAttribute[] includes = (SoapIncludeAttribute[])type.GetCustomAttributes (typeof (SoapIncludeAttribute), false);
233                         for (int n=0; n<includes.Length; n++)
234                         {
235                                 Type includedType = includes[n].Type;
236                                 ImportTypeMapping (includedType);
237                         }
238
239                         if (type == typeof (object) && includedTypes != null)
240                         {
241                                 foreach (Type intype in includedTypes)
242                                         map.DerivedTypes.Add (ImportTypeMapping (intype));
243                         }
244
245                         // Register inheritance relations
246
247                         if (type.BaseType != null)
248                         {
249                                 XmlTypeMapping bmap = ImportClassMapping (type.BaseType, defaultNamespace);
250                                 
251                                 if (type.BaseType != typeof (object))
252                                         map.BaseMap = bmap;
253                                         
254                                 // At this point, derived classes of this map must be already registered
255                                 
256                                 RegisterDerivedMap (bmap, map);
257                         }
258                         
259                         return map;
260                 }
261                 
262                 void RegisterDerivedMap (XmlTypeMapping map, XmlTypeMapping derivedMap)
263                 {
264                         map.DerivedTypes.Add (derivedMap);
265                         map.DerivedTypes.AddRange (derivedMap.DerivedTypes);
266                         
267                         if (map.BaseMap != null)
268                                 RegisterDerivedMap (map.BaseMap, derivedMap);
269                         else {
270                                 XmlTypeMapping obmap = ImportTypeMapping (typeof(object));
271                                 if (obmap != map)
272                                         obmap.DerivedTypes.Add (derivedMap);
273                         }
274                 }
275
276                 string GetTypeNamespace (TypeData typeData, string defaultNamespace)
277                 {
278                         string membersNamespace = defaultNamespace;
279
280                         SoapAttributes atts = null;
281
282                         if (!typeData.IsListType)
283                         {
284                                 if (attributeOverrides != null)
285                                         atts = attributeOverrides[typeData.Type];
286                         }
287
288                         if (atts == null)
289                                 atts = new SoapAttributes (typeData.Type);
290
291                         if (atts.SoapType != null)
292                         {
293                                 if (atts.SoapType.Namespace != null && atts.SoapType.Namespace != string.Empty)
294                                         membersNamespace = atts.SoapType.Namespace;
295                         }
296
297                         if (membersNamespace == null) return "";
298                         else return membersNamespace;
299                 }
300                 
301                 XmlTypeMapping ImportListMapping (TypeData typeData, string defaultNamespace)
302                 {
303                         Type type = typeData.Type;
304
305                         XmlTypeMapping map = helper.GetRegisteredClrType (type, XmlSerializer.EncodingNamespace);
306                         if (map != null) return map;
307
308                         ListMap obmap = new ListMap ();
309                         TypeData itemTypeData = typeData.ListItemTypeData;
310
311                         map = CreateTypeMapping (typeData, "Array", XmlSerializer.EncodingNamespace);
312                         helper.RegisterClrType (map, type, XmlSerializer.EncodingNamespace);
313                         map.MultiReferenceType = true;
314                         map.ObjectMap = obmap;
315
316                         XmlTypeMapElementInfo elem = new XmlTypeMapElementInfo (null, itemTypeData);
317                         
318                         if (elem.TypeData.IsComplexType) {
319                                 elem.MappedType = ImportTypeMapping (typeData.ListItemType, defaultNamespace);
320                                 elem.TypeData = elem.MappedType.TypeData;
321                         }
322                                 
323                         elem.ElementName = "Item";
324                         elem.Namespace = string.Empty;
325                         elem.IsNullable = true; // By default, items are nullable
326
327                         XmlTypeMapElementInfoList list = new XmlTypeMapElementInfoList();
328                         list.Add (elem);
329
330                         obmap.ItemInfo = list;
331                         XmlTypeMapping objMap = ImportTypeMapping (typeof(object), defaultNamespace);
332                         objMap.DerivedTypes.Add (map);
333
334                         // Register any of the including types as a derived class of object
335                         SoapIncludeAttribute[] includes = (SoapIncludeAttribute[])type.GetCustomAttributes (typeof (SoapIncludeAttribute), false);
336                         for (int i = 0; i < includes.Length; i++)
337                         {
338                                 Type includedType = includes[i].Type;
339                                 objMap.DerivedTypes.Add(ImportTypeMapping (includedType, defaultNamespace));
340                         }
341                         
342                         return map;
343                 }
344                 
345                 XmlTypeMapping ImportPrimitiveMapping (TypeData typeData, string defaultNamespace)
346                 {
347                         if (typeData.SchemaType == SchemaTypes.Primitive)
348                                 defaultNamespace = typeData.IsXsdType ? XmlSchema.Namespace : XmlSerializer.WsdlTypesNamespace;
349
350                         Type type = typeData.Type;
351                         XmlTypeMapping map = helper.GetRegisteredClrType (type, GetTypeNamespace (typeData, defaultNamespace));
352                         if (map != null) return map;
353                         map = CreateTypeMapping (typeData, null, defaultNamespace);
354                         helper.RegisterClrType (map, type, map.Namespace);
355                         return map;
356                 }
357
358                 XmlTypeMapping ImportEnumMapping (TypeData typeData, string defaultNamespace)
359                 {
360                         Type type = typeData.Type;
361                         XmlTypeMapping map = helper.GetRegisteredClrType (type, GetTypeNamespace (typeData, defaultNamespace));
362                         if (map != null) return map;
363                         
364                         ReflectionHelper.CheckSerializableType (type, false);
365                                 
366                         map = CreateTypeMapping (typeData, null, defaultNamespace);
367                         helper.RegisterClrType (map, type, map.Namespace);
368
369                         map.MultiReferenceType = true;
370                         
371                         string [] names = Enum.GetNames (type);
372                         EnumMap.EnumMapMember[] members = new EnumMap.EnumMapMember[names.Length];
373                         for (int n=0; n<names.Length; n++)
374                         {
375                                 FieldInfo field = type.GetField (names[n]);
376                                 string xmlName = names[n];
377                                 object[] atts = field.GetCustomAttributes (typeof(SoapEnumAttribute), false);
378                                 if (atts.Length > 0) xmlName = ((SoapEnumAttribute)atts[0]).Name;
379                                 long value = ((IConvertible) field.GetValue (null)).ToInt64 (CultureInfo.InvariantCulture);
380                                 members[n] = new EnumMap.EnumMapMember (XmlConvert.EncodeLocalName (xmlName), names[n], value);
381                         }
382
383                         bool isFlags = type.IsDefined (typeof (FlagsAttribute), false);
384                         map.ObjectMap = new EnumMap (members, isFlags);
385                         ImportTypeMapping (typeof(object), defaultNamespace).DerivedTypes.Add (map);
386                         return map;
387                 }
388
389                 ICollection GetReflectionMembers (Type type)
390                 {
391                         ArrayList members = new ArrayList();
392                         PropertyInfo[] properties = type.GetProperties (BindingFlags.Instance | BindingFlags.Public);
393                         foreach (PropertyInfo prop in properties)
394                         {
395                                 if (!prop.CanRead) continue;
396                                 if (!prop.CanWrite && (TypeTranslator.GetTypeData (prop.PropertyType).SchemaType != SchemaTypes.Array || prop.PropertyType.IsArray))
397                                         continue;
398                                         
399                                 SoapAttributes atts = attributeOverrides[type, prop.Name];
400                                 if (atts == null) atts = new SoapAttributes (prop);
401                                 if (atts.SoapIgnore) continue;
402                                 XmlReflectionMember member = new XmlReflectionMember(prop.Name, prop.PropertyType, atts);
403                                 members.Add (member);
404                         }
405
406                         FieldInfo[] fields = type.GetFields (BindingFlags.Instance | BindingFlags.Public);
407                         foreach (FieldInfo field in fields)
408                         {
409                                 SoapAttributes atts = attributeOverrides[type, field.Name];
410                                 if (atts == null) atts = new SoapAttributes (field);
411                                 if (atts.SoapIgnore) continue;
412                                 XmlReflectionMember member = new XmlReflectionMember(field.Name, field.FieldType, atts);
413                                 members.Add (member);
414                         }
415                         return members;
416                 }
417                 
418                 private XmlTypeMapMember CreateMapMember (XmlReflectionMember rmember, string defaultNamespace)
419                 {
420                         XmlTypeMapMember mapMember;
421                         SoapAttributes atts = rmember.SoapAttributes;
422                         TypeData typeData = TypeTranslator.GetTypeData (rmember.MemberType);
423
424                         if (atts.SoapAttribute != null)
425                         {
426                                 // An attribute
427
428                                 if (typeData.SchemaType != SchemaTypes.Enum && typeData.SchemaType != SchemaTypes.Primitive) {
429                                         throw new InvalidOperationException (string.Format (CultureInfo.InvariantCulture,
430                                                 "Cannot serialize member '{0}' of type {1}. " +
431                                                 "SoapAttribute cannot be used to encode complex types.",
432                                                 rmember.MemberName, typeData.FullTypeName));
433                                 }
434
435                                 if (atts.SoapElement != null)
436                                         throw new Exception ("SoapAttributeAttribute and SoapElementAttribute cannot be applied to the same member");
437
438                                 XmlTypeMapMemberAttribute mapAttribute = new XmlTypeMapMemberAttribute ();
439                                 if (atts.SoapAttribute.AttributeName.Length == 0) 
440                                         mapAttribute.AttributeName = XmlConvert.EncodeLocalName (rmember.MemberName);
441                                 else 
442                                         mapAttribute.AttributeName = XmlConvert.EncodeLocalName (atts.SoapAttribute.AttributeName);
443
444                                 mapAttribute.Namespace = (atts.SoapAttribute.Namespace != null) ? atts.SoapAttribute.Namespace : "";
445                                 if (typeData.IsComplexType)
446                                         mapAttribute.MappedType = ImportTypeMapping (typeData.Type, defaultNamespace);
447
448                                 typeData = TypeTranslator.GetTypeData (rmember.MemberType, atts.SoapAttribute.DataType);
449                                 mapMember = mapAttribute;
450                                 mapMember.DefaultValue = GetDefaultValue (typeData, atts.SoapDefaultValue);
451                         }
452                         else
453                         {
454                                 if (typeData.SchemaType == SchemaTypes.Array) mapMember = new XmlTypeMapMemberList ();
455                                 else mapMember = new XmlTypeMapMemberElement ();
456
457                                 if (atts.SoapElement != null && atts.SoapElement.DataType.Length != 0)
458                                         typeData = TypeTranslator.GetTypeData (rmember.MemberType, atts.SoapElement.DataType);
459
460                                 // Creates an ElementInfo that identifies the element
461                                 XmlTypeMapElementInfoList infoList = new XmlTypeMapElementInfoList();
462                                 XmlTypeMapElementInfo elem = new XmlTypeMapElementInfo (mapMember, typeData);
463
464                                 elem.ElementName = XmlConvert.EncodeLocalName ((atts.SoapElement != null && atts.SoapElement.ElementName.Length != 0) ? atts.SoapElement.ElementName : rmember.MemberName);
465                                 elem.Namespace = string.Empty;
466                                 elem.IsNullable = (atts.SoapElement != null) ? atts.SoapElement.IsNullable : false;
467                                 if (typeData.IsComplexType)
468                                         elem.MappedType = ImportTypeMapping (typeData.Type, defaultNamespace);
469                                 
470                                 infoList.Add (elem);
471                                 ((XmlTypeMapMemberElement)mapMember).ElementInfo = infoList;
472                         }
473
474                         mapMember.TypeData = typeData;
475                         mapMember.Name = rmember.MemberName;
476                         mapMember.IsReturnValue = rmember.IsReturnValue;
477                         return mapMember;
478                 }
479                 
480                 public void IncludeType (Type type)
481                 {
482                         if (type == null)
483                                 throw new ArgumentNullException ("type");
484
485                         if (includedTypes == null) includedTypes = new ArrayList ();
486                         if (!includedTypes.Contains (type))
487                                 includedTypes.Add (type);
488                 }
489
490                 public void IncludeTypes (ICustomAttributeProvider provider)
491                 { 
492                         object[] ats = provider.GetCustomAttributes (typeof(SoapIncludeAttribute), true);
493                         foreach (SoapIncludeAttribute at in ats)
494                                 IncludeType (at.Type);
495                 }
496
497                 Exception CreateTypeException (Type type)
498                 {
499                         return new NotSupportedException ("The type " + type.FullName + " may not be serialized with SOAP-encoded messages. Set the Use for your message to Literal");
500                 }
501
502                 Exception CreateStructException (Type type)
503                 {
504                         return new NotSupportedException ("Cannot serialize " + type.FullName + ". Nested structs are not supported with encoded SOAP");
505                 }
506
507                 private object GetDefaultValue (TypeData typeData, object defaultValue)
508                 {
509                         if (defaultValue == DBNull.Value || typeData.SchemaType != SchemaTypes.Enum)
510                                 return defaultValue;
511
512                         if (typeData.Type != defaultValue.GetType ()) {
513                                 string msg = string.Format (CultureInfo.InvariantCulture,
514                                         "Enum {0} cannot be converted to {1}.",
515                                         defaultValue.GetType ().FullName, typeData.FullTypeName);
516                                 throw new InvalidOperationException (msg);
517                         }
518
519                         // get string representation of enum value
520                         string namedValue = Enum.Format (typeData.Type, defaultValue, "g");
521                         // get decimal representation of enum value
522                         string decimalValue = Enum.Format (typeData.Type, defaultValue, "d");
523
524                         // if decimal representation matches string representation, then
525                         // the value is not defined in the enum type (as the "g" format
526                         // will return the decimal equivalent of the value if the value
527                         // is not equal to a combination of named enumerated constants
528                         if (namedValue == decimalValue) {
529                                 string msg = string.Format (CultureInfo.InvariantCulture,
530                                         "Value '{0}' cannot be converted to {1}.", defaultValue,
531                                         defaultValue.GetType ().FullName);
532                                 throw new InvalidOperationException (msg);
533                         }
534
535                         // XmlSerializer expects integral enum value
536                         //return namedValue.Replace (',', ' ');
537                         return defaultValue;
538                 }
539
540                 #endregion // Methods
541         }
542 }