2 // System.Xml.Serialization.SoapReflectionImporter
5 // Tim Coleman (tim@timcoleman.com)
7 // Copyright (C) Tim Coleman, 2002
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:
19 // The above copyright notice and this permission notice shall be
20 // included in all copies or substantial portions of the Software.
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.
31 using System.Collections;
32 using System.Globalization;
33 using System.Reflection;
35 using System.Xml.Schema;
37 namespace System.Xml.Serialization {
38 public class SoapReflectionImporter {
40 SoapAttributeOverrides attributeOverrides;
41 string initialDefaultNamespace;
42 ArrayList includedTypes;
43 ArrayList relatedMaps = new ArrayList ();
44 ReflectionHelper helper = new ReflectionHelper();
48 public SoapReflectionImporter (): this (null, null)
52 public SoapReflectionImporter (SoapAttributeOverrides attributeOverrides): this (attributeOverrides, null)
56 public SoapReflectionImporter (string defaultNamespace): this (null, defaultNamespace)
60 public SoapReflectionImporter (SoapAttributeOverrides attributeOverrides, string defaultNamespace)
62 if (defaultNamespace == null) initialDefaultNamespace = String.Empty;
63 else initialDefaultNamespace = defaultNamespace;
65 if (attributeOverrides == null) this.attributeOverrides = new SoapAttributeOverrides();
66 else this.attributeOverrides = attributeOverrides;
69 #endregion // Constructors
73 public XmlMembersMapping ImportMembersMapping (string elementName, string ns, XmlReflectionMember[] members)
75 return ImportMembersMapping (elementName, ns, members, true, true, false);
78 public XmlMembersMapping ImportMembersMapping (string elementName, string ns, XmlReflectionMember[] members, bool hasWrapperElement, bool writeAccessors)
80 return ImportMembersMapping (elementName, ns, members, hasWrapperElement, writeAccessors, false);
83 public XmlMembersMapping ImportMembersMapping (string elementName, string ns, XmlReflectionMember[] members, bool hasWrapperElement, bool writeAccessors, bool validate)
85 return ImportMembersMapping (elementName, ns, members, hasWrapperElement, writeAccessors, validate, XmlMappingAccess.Read | XmlMappingAccess.Write);
92 XmlMembersMapping ImportMembersMapping (string elementName, string ns, XmlReflectionMember[] members, bool hasWrapperElement, bool writeAccessors, bool validate, XmlMappingAccess access)
94 elementName = XmlConvert.EncodeLocalName (elementName);
95 XmlMemberMapping[] mapping = new XmlMemberMapping[members.Length];
96 for (int n=0; n<members.Length; n++)
98 XmlTypeMapMember mapMem = CreateMapMember (members[n], ns);
99 mapping[n] = new XmlMemberMapping (XmlConvert.EncodeLocalName (members[n].MemberName), ns, mapMem, true);
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);
109 public XmlTypeMapping ImportTypeMapping (Type type)
111 return ImportTypeMapping (type, null);
114 public XmlTypeMapping ImportTypeMapping (Type type, string defaultNamespace)
117 throw new ArgumentNullException ("type");
119 if (type == typeof (void))
120 throw new InvalidOperationException ("Type " + type.Name + " may not be serialized.");
122 return ImportTypeMapping (TypeTranslator.GetTypeData (type),
126 internal XmlTypeMapping ImportTypeMapping (TypeData typeData, string defaultNamespace)
128 if (typeData == null)
129 throw new ArgumentNullException ("typeData");
131 if (typeData.Type == null)
132 throw new ArgumentException ("Specified TypeData instance does not have Type set.");
134 string oldNs = initialDefaultNamespace;
135 if (defaultNamespace == null) defaultNamespace = initialDefaultNamespace;
136 if (defaultNamespace == null) defaultNamespace = string.Empty;
137 initialDefaultNamespace = defaultNamespace;
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");
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);
154 initialDefaultNamespace = oldNs;
158 XmlTypeMapping CreateTypeMapping (TypeData typeData, string defaultXmlType, string defaultNamespace)
160 string membersNamespace = defaultNamespace;
161 bool includeInSchema = true;
163 SoapAttributes atts = null;
164 if (defaultXmlType == null) defaultXmlType = typeData.XmlType;
166 if (!typeData.IsListType)
168 if (attributeOverrides != null)
169 atts = attributeOverrides[typeData.Type];
171 if (atts != null && typeData.SchemaType == SchemaTypes.Primitive)
172 throw new InvalidOperationException ("SoapType attribute may not be specified for the type " + typeData.FullTypeName);
176 atts = new SoapAttributes (typeData.Type);
178 if (atts.SoapType != null)
180 if (atts.SoapType.Namespace != null && atts.SoapType.Namespace != string.Empty)
181 membersNamespace = atts.SoapType.Namespace;
183 if (atts.SoapType.TypeName != null && atts.SoapType.TypeName != string.Empty)
184 defaultXmlType = XmlConvert.EncodeLocalName (atts.SoapType.TypeName);
186 includeInSchema = atts.SoapType.IncludeInSchema;
189 if (membersNamespace == null) membersNamespace = "";
190 XmlTypeMapping map = new XmlTypeMapping (defaultXmlType, membersNamespace, typeData, defaultXmlType, membersNamespace);
191 map.IncludeInSchema = includeInSchema;
192 relatedMaps.Add (map);
197 XmlTypeMapping ImportClassMapping (Type type, string defaultNamespace)
199 TypeData typeData = TypeTranslator.GetTypeData (type);
200 return ImportClassMapping (typeData, defaultNamespace);
203 XmlTypeMapping ImportClassMapping (TypeData typeData, string defaultNamespace)
205 Type type = typeData.Type;
207 if (type.IsValueType) throw CreateStructException (type);
209 if (type == typeof (object)) defaultNamespace = XmlSchema.Namespace;
211 ReflectionHelper.CheckSerializableType (type, false);
212 XmlTypeMapping map = helper.GetRegisteredClrType (type, GetTypeNamespace (typeData, defaultNamespace));
213 if (map != null) return map;
215 map = CreateTypeMapping (typeData, null, defaultNamespace);
216 helper.RegisterClrType (map, type, map.Namespace);
217 map.MultiReferenceType = true;
219 ClassMap classMap = new ClassMap ();
220 map.ObjectMap = classMap;
224 ICollection members = GetReflectionMembers (type);
225 foreach (XmlReflectionMember rmember in members) {
226 if (rmember.SoapAttributes.SoapIgnore) continue;
227 classMap.AddMember (CreateMapMember (rmember, defaultNamespace));
230 // Import included classes
232 SoapIncludeAttribute[] includes = (SoapIncludeAttribute[])type.GetCustomAttributes (typeof (SoapIncludeAttribute), false);
233 for (int n=0; n<includes.Length; n++)
235 Type includedType = includes[n].Type;
236 ImportTypeMapping (includedType);
239 if (type == typeof (object) && includedTypes != null)
241 foreach (Type intype in includedTypes)
242 map.DerivedTypes.Add (ImportTypeMapping (intype));
245 // Register inheritance relations
247 if (type.BaseType != null)
249 XmlTypeMapping bmap = ImportClassMapping (type.BaseType, defaultNamespace);
251 if (type.BaseType != typeof (object))
254 // At this point, derived classes of this map must be already registered
256 RegisterDerivedMap (bmap, map);
262 void RegisterDerivedMap (XmlTypeMapping map, XmlTypeMapping derivedMap)
264 map.DerivedTypes.Add (derivedMap);
265 map.DerivedTypes.AddRange (derivedMap.DerivedTypes);
267 if (map.BaseMap != null)
268 RegisterDerivedMap (map.BaseMap, derivedMap);
270 XmlTypeMapping obmap = ImportTypeMapping (typeof(object));
272 obmap.DerivedTypes.Add (derivedMap);
276 string GetTypeNamespace (TypeData typeData, string defaultNamespace)
278 string membersNamespace = defaultNamespace;
280 SoapAttributes atts = null;
282 if (!typeData.IsListType)
284 if (attributeOverrides != null)
285 atts = attributeOverrides[typeData.Type];
289 atts = new SoapAttributes (typeData.Type);
291 if (atts.SoapType != null)
293 if (atts.SoapType.Namespace != null && atts.SoapType.Namespace != string.Empty)
294 membersNamespace = atts.SoapType.Namespace;
297 if (membersNamespace == null) return "";
298 else return membersNamespace;
301 XmlTypeMapping ImportListMapping (TypeData typeData, string defaultNamespace)
303 Type type = typeData.Type;
305 XmlTypeMapping map = helper.GetRegisteredClrType (type, XmlSerializer.EncodingNamespace);
306 if (map != null) return map;
308 ListMap obmap = new ListMap ();
309 TypeData itemTypeData = typeData.ListItemTypeData;
311 map = CreateTypeMapping (typeData, "Array", XmlSerializer.EncodingNamespace);
312 helper.RegisterClrType (map, type, XmlSerializer.EncodingNamespace);
313 map.MultiReferenceType = true;
314 map.ObjectMap = obmap;
316 XmlTypeMapElementInfo elem = new XmlTypeMapElementInfo (null, itemTypeData);
318 if (elem.TypeData.IsComplexType) {
319 elem.MappedType = ImportTypeMapping (typeData.ListItemType, defaultNamespace);
320 elem.TypeData = elem.MappedType.TypeData;
323 elem.ElementName = "Item";
324 elem.Namespace = string.Empty;
325 elem.IsNullable = true; // By default, items are nullable
327 XmlTypeMapElementInfoList list = new XmlTypeMapElementInfoList();
330 obmap.ItemInfo = list;
331 XmlTypeMapping objMap = ImportTypeMapping (typeof(object), defaultNamespace);
332 objMap.DerivedTypes.Add (map);
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++)
338 Type includedType = includes[i].Type;
339 objMap.DerivedTypes.Add(ImportTypeMapping (includedType, defaultNamespace));
345 XmlTypeMapping ImportPrimitiveMapping (TypeData typeData, string defaultNamespace)
347 if (typeData.SchemaType == SchemaTypes.Primitive)
348 defaultNamespace = typeData.IsXsdType ? XmlSchema.Namespace : XmlSerializer.WsdlTypesNamespace;
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);
358 XmlTypeMapping ImportEnumMapping (TypeData typeData, string defaultNamespace)
360 Type type = typeData.Type;
361 XmlTypeMapping map = helper.GetRegisteredClrType (type, GetTypeNamespace (typeData, defaultNamespace));
362 if (map != null) return map;
364 ReflectionHelper.CheckSerializableType (type, false);
366 map = CreateTypeMapping (typeData, null, defaultNamespace);
367 helper.RegisterClrType (map, type, map.Namespace);
369 map.MultiReferenceType = true;
371 string [] names = Enum.GetNames (type);
372 EnumMap.EnumMapMember[] members = new EnumMap.EnumMapMember[names.Length];
373 for (int n=0; n<names.Length; n++)
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);
383 bool isFlags = type.IsDefined (typeof (FlagsAttribute), false);
384 map.ObjectMap = new EnumMap (members, isFlags);
385 ImportTypeMapping (typeof(object), defaultNamespace).DerivedTypes.Add (map);
389 ICollection GetReflectionMembers (Type type)
391 ArrayList members = new ArrayList();
392 PropertyInfo[] properties = type.GetProperties (BindingFlags.Instance | BindingFlags.Public);
393 foreach (PropertyInfo prop in properties)
395 if (!prop.CanRead) continue;
396 if (!prop.CanWrite && (TypeTranslator.GetTypeData (prop.PropertyType).SchemaType != SchemaTypes.Array || prop.PropertyType.IsArray))
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);
406 FieldInfo[] fields = type.GetFields (BindingFlags.Instance | BindingFlags.Public);
407 foreach (FieldInfo field in fields)
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);
418 private XmlTypeMapMember CreateMapMember (XmlReflectionMember rmember, string defaultNamespace)
420 XmlTypeMapMember mapMember;
421 SoapAttributes atts = rmember.SoapAttributes;
422 TypeData typeData = TypeTranslator.GetTypeData (rmember.MemberType);
424 if (atts.SoapAttribute != null)
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));
435 if (atts.SoapElement != null)
436 throw new Exception ("SoapAttributeAttribute and SoapElementAttribute cannot be applied to the same member");
438 XmlTypeMapMemberAttribute mapAttribute = new XmlTypeMapMemberAttribute ();
439 if (atts.SoapAttribute.AttributeName.Length == 0)
440 mapAttribute.AttributeName = XmlConvert.EncodeLocalName (rmember.MemberName);
442 mapAttribute.AttributeName = XmlConvert.EncodeLocalName (atts.SoapAttribute.AttributeName);
444 mapAttribute.Namespace = (atts.SoapAttribute.Namespace != null) ? atts.SoapAttribute.Namespace : "";
445 if (typeData.IsComplexType)
446 mapAttribute.MappedType = ImportTypeMapping (typeData.Type, defaultNamespace);
448 typeData = TypeTranslator.GetTypeData (rmember.MemberType, atts.SoapAttribute.DataType);
449 mapMember = mapAttribute;
450 mapMember.DefaultValue = GetDefaultValue (typeData, atts.SoapDefaultValue);
454 if (typeData.SchemaType == SchemaTypes.Array) mapMember = new XmlTypeMapMemberList ();
455 else mapMember = new XmlTypeMapMemberElement ();
457 if (atts.SoapElement != null && atts.SoapElement.DataType.Length != 0)
458 typeData = TypeTranslator.GetTypeData (rmember.MemberType, atts.SoapElement.DataType);
460 // Creates an ElementInfo that identifies the element
461 XmlTypeMapElementInfoList infoList = new XmlTypeMapElementInfoList();
462 XmlTypeMapElementInfo elem = new XmlTypeMapElementInfo (mapMember, typeData);
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);
471 ((XmlTypeMapMemberElement)mapMember).ElementInfo = infoList;
474 mapMember.TypeData = typeData;
475 mapMember.Name = rmember.MemberName;
476 mapMember.IsReturnValue = rmember.IsReturnValue;
480 public void IncludeType (Type type)
483 throw new ArgumentNullException ("type");
485 if (includedTypes == null) includedTypes = new ArrayList ();
486 if (!includedTypes.Contains (type))
487 includedTypes.Add (type);
490 public void IncludeTypes (ICustomAttributeProvider provider)
492 object[] ats = provider.GetCustomAttributes (typeof(SoapIncludeAttribute), true);
493 foreach (SoapIncludeAttribute at in ats)
494 IncludeType (at.Type);
497 Exception CreateTypeException (Type type)
499 return new NotSupportedException ("The type " + type.FullName + " may not be serialized with SOAP-encoded messages. Set the Use for your message to Literal");
502 Exception CreateStructException (Type type)
504 return new NotSupportedException ("Cannot serialize " + type.FullName + ". Nested structs are not supported with encoded SOAP");
507 private object GetDefaultValue (TypeData typeData, object defaultValue)
509 if (defaultValue == DBNull.Value || typeData.SchemaType != SchemaTypes.Enum)
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);
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");
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);
535 // XmlSerializer expects integral enum value
536 //return namedValue.Replace (',', ' ');
540 #endregion // Methods