SoapReflectionImporter.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500
  1. //
  2. // System.Xml.Serialization.SoapReflectionImporter
  3. //
  4. // Author:
  5. // Tim Coleman ([email protected])
  6. //
  7. // Copyright (C) Tim Coleman, 2002
  8. //
  9. //
  10. // Permission is hereby granted, free of charge, to any person obtaining
  11. // a copy of this software and associated documentation files (the
  12. // "Software"), to deal in the Software without restriction, including
  13. // without limitation the rights to use, copy, modify, merge, publish,
  14. // distribute, sublicense, and/or sell copies of the Software, and to
  15. // permit persons to whom the Software is furnished to do so, subject to
  16. // the following conditions:
  17. //
  18. // The above copyright notice and this permission notice shall be
  19. // included in all copies or substantial portions of the Software.
  20. //
  21. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  22. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  23. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  24. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  25. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  26. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  27. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  28. //
  29. using System.Collections;
  30. using System.Globalization;
  31. using System.Reflection;
  32. using System.Xml;
  33. using System.Xml.Schema;
  34. namespace System.Xml.Serialization {
  35. public class SoapReflectionImporter {
  36. SoapAttributeOverrides attributeOverrides;
  37. string initialDefaultNamespace;
  38. ArrayList includedTypes;
  39. ArrayList relatedMaps = new ArrayList ();
  40. ReflectionHelper helper = new ReflectionHelper();
  41. #region Constructors
  42. public SoapReflectionImporter (): this (null, null)
  43. {
  44. }
  45. public SoapReflectionImporter (SoapAttributeOverrides attributeOverrides): this (attributeOverrides, null)
  46. {
  47. }
  48. public SoapReflectionImporter (string defaultNamespace): this (null, defaultNamespace)
  49. {
  50. }
  51. public SoapReflectionImporter (SoapAttributeOverrides attributeOverrides, string defaultNamespace)
  52. {
  53. if (defaultNamespace == null) initialDefaultNamespace = String.Empty;
  54. else initialDefaultNamespace = defaultNamespace;
  55. if (attributeOverrides == null) this.attributeOverrides = new SoapAttributeOverrides();
  56. else this.attributeOverrides = attributeOverrides;
  57. }
  58. #endregion // Constructors
  59. #region Methods
  60. public XmlMembersMapping ImportMembersMapping (string elementName, string ns, XmlReflectionMember[] members)
  61. {
  62. return ImportMembersMapping (elementName, ns, members, true, true, false);
  63. }
  64. public XmlMembersMapping ImportMembersMapping (string elementName, string ns, XmlReflectionMember[] members, bool hasWrapperElement, bool writeAccessors)
  65. {
  66. return ImportMembersMapping (elementName, ns, members, hasWrapperElement, writeAccessors, false);
  67. }
  68. public XmlMembersMapping ImportMembersMapping (string elementName, string ns, XmlReflectionMember[] members, bool hasWrapperElement, bool writeAccessors, bool validate)
  69. {
  70. elementName = XmlConvert.EncodeLocalName (elementName);
  71. XmlMemberMapping[] mapping = new XmlMemberMapping[members.Length];
  72. for (int n=0; n<members.Length; n++)
  73. {
  74. XmlTypeMapMember mapMem = CreateMapMember (members[n], ns);
  75. mapping[n] = new XmlMemberMapping (XmlConvert.EncodeLocalName (members[n].MemberName), ns, mapMem, true);
  76. }
  77. XmlMembersMapping mps = new XmlMembersMapping (elementName, ns, hasWrapperElement, writeAccessors, mapping);
  78. mps.RelatedMaps = relatedMaps;
  79. mps.Format = SerializationFormat.Encoded;
  80. Type[] extraTypes = includedTypes != null ? (Type[])includedTypes.ToArray(typeof(Type)) : null;
  81. mps.Source = new MembersSerializationSource (elementName, hasWrapperElement, members, writeAccessors, false, null, extraTypes);
  82. return mps;
  83. }
  84. public XmlTypeMapping ImportTypeMapping (Type type)
  85. {
  86. return ImportTypeMapping (type, null);
  87. }
  88. public XmlTypeMapping ImportTypeMapping (Type type, string defaultNamespace)
  89. {
  90. if (type == null)
  91. throw new ArgumentNullException ("type");
  92. if (type == typeof (void))
  93. throw new InvalidOperationException ("Type " + type.Name + " may not be serialized.");
  94. return ImportTypeMapping (TypeTranslator.GetTypeData (type),
  95. defaultNamespace);
  96. }
  97. internal XmlTypeMapping ImportTypeMapping (TypeData typeData, string defaultNamespace)
  98. {
  99. if (typeData == null)
  100. throw new ArgumentNullException ("typeData");
  101. if (typeData.Type == null)
  102. throw new ArgumentException ("Specified TypeData instance does not have Type set.");
  103. string oldNs = initialDefaultNamespace;
  104. if (defaultNamespace == null) defaultNamespace = initialDefaultNamespace;
  105. if (defaultNamespace == null) defaultNamespace = string.Empty;
  106. initialDefaultNamespace = defaultNamespace;
  107. XmlTypeMapping map;
  108. switch (typeData.SchemaType) {
  109. case SchemaTypes.Class: map = ImportClassMapping (typeData, defaultNamespace); break;
  110. case SchemaTypes.Array: map = ImportListMapping (typeData, defaultNamespace); break;
  111. case SchemaTypes.XmlNode: throw CreateTypeException (typeData.Type);
  112. case SchemaTypes.Primitive: map = ImportPrimitiveMapping (typeData, defaultNamespace); break;
  113. case SchemaTypes.Enum: map = ImportEnumMapping (typeData, defaultNamespace); break;
  114. case SchemaTypes.XmlSerializable:
  115. default: throw new NotSupportedException ("Type " + typeData.Type.FullName + " not supported for XML serialization");
  116. }
  117. map.RelatedMaps = relatedMaps;
  118. map.Format = SerializationFormat.Encoded;
  119. Type[] extraTypes = includedTypes != null ? (Type[])includedTypes.ToArray(typeof(Type)) : null;
  120. map.Source = new SoapTypeSerializationSource (typeData.Type, attributeOverrides, defaultNamespace, extraTypes);
  121. initialDefaultNamespace = oldNs;
  122. return map;
  123. }
  124. XmlTypeMapping CreateTypeMapping (TypeData typeData, string defaultXmlType, string defaultNamespace)
  125. {
  126. string membersNamespace = defaultNamespace;
  127. bool includeInSchema = true;
  128. SoapAttributes atts = null;
  129. if (defaultXmlType == null) defaultXmlType = typeData.XmlType;
  130. if (!typeData.IsListType)
  131. {
  132. if (attributeOverrides != null)
  133. atts = attributeOverrides[typeData.Type];
  134. if (atts != null && typeData.SchemaType == SchemaTypes.Primitive)
  135. throw new InvalidOperationException ("SoapType attribute may not be specified for the type " + typeData.FullTypeName);
  136. }
  137. if (atts == null)
  138. atts = new SoapAttributes (typeData.Type);
  139. if (atts.SoapType != null)
  140. {
  141. if (atts.SoapType.Namespace != null && atts.SoapType.Namespace != string.Empty)
  142. membersNamespace = atts.SoapType.Namespace;
  143. if (atts.SoapType.TypeName != null && atts.SoapType.TypeName != string.Empty)
  144. defaultXmlType = XmlConvert.EncodeLocalName (atts.SoapType.TypeName);
  145. includeInSchema = atts.SoapType.IncludeInSchema;
  146. }
  147. if (membersNamespace == null) membersNamespace = "";
  148. XmlTypeMapping map = new XmlTypeMapping (defaultXmlType, membersNamespace, typeData, defaultXmlType, membersNamespace);
  149. map.IncludeInSchema = includeInSchema;
  150. relatedMaps.Add (map);
  151. return map;
  152. }
  153. XmlTypeMapping ImportClassMapping (Type type, string defaultNamespace)
  154. {
  155. TypeData typeData = TypeTranslator.GetTypeData (type);
  156. return ImportClassMapping (typeData, defaultNamespace);
  157. }
  158. XmlTypeMapping ImportClassMapping (TypeData typeData, string defaultNamespace)
  159. {
  160. Type type = typeData.Type;
  161. if (type.IsValueType) throw CreateStructException (type);
  162. if (type == typeof (object)) defaultNamespace = XmlSchema.Namespace;
  163. ReflectionHelper.CheckSerializableType (type, false);
  164. XmlTypeMapping map = helper.GetRegisteredClrType (type, GetTypeNamespace (typeData, defaultNamespace));
  165. if (map != null) return map;
  166. map = CreateTypeMapping (typeData, null, defaultNamespace);
  167. helper.RegisterClrType (map, type, map.Namespace);
  168. map.MultiReferenceType = true;
  169. ClassMap classMap = new ClassMap ();
  170. map.ObjectMap = classMap;
  171. // Import members
  172. try
  173. {
  174. ICollection members = GetReflectionMembers (type);
  175. foreach (XmlReflectionMember rmember in members)
  176. {
  177. if (rmember.SoapAttributes.SoapIgnore) continue;
  178. classMap.AddMember (CreateMapMember (rmember, map.Namespace));
  179. }
  180. }
  181. catch (Exception ex)
  182. {
  183. throw helper.CreateError (map, ex.Message);
  184. }
  185. // Import included classes
  186. SoapIncludeAttribute[] includes = (SoapIncludeAttribute[])type.GetCustomAttributes (typeof (SoapIncludeAttribute), false);
  187. for (int n=0; n<includes.Length; n++)
  188. {
  189. Type includedType = includes[n].Type;
  190. ImportTypeMapping (includedType);
  191. }
  192. if (type == typeof (object) && includedTypes != null)
  193. {
  194. foreach (Type intype in includedTypes)
  195. map.DerivedTypes.Add (ImportTypeMapping (intype));
  196. }
  197. // Register inheritance relations
  198. if (type.BaseType != null)
  199. {
  200. XmlTypeMapping bmap = ImportClassMapping (type.BaseType, defaultNamespace);
  201. if (type.BaseType != typeof (object))
  202. map.BaseMap = bmap;
  203. // At this point, derived classes of this map must be already registered
  204. RegisterDerivedMap (bmap, map);
  205. }
  206. return map;
  207. }
  208. void RegisterDerivedMap (XmlTypeMapping map, XmlTypeMapping derivedMap)
  209. {
  210. map.DerivedTypes.Add (derivedMap);
  211. map.DerivedTypes.AddRange (derivedMap.DerivedTypes);
  212. if (map.BaseMap != null)
  213. RegisterDerivedMap (map.BaseMap, derivedMap);
  214. else {
  215. XmlTypeMapping obmap = ImportTypeMapping (typeof(object));
  216. if (obmap != map)
  217. obmap.DerivedTypes.Add (derivedMap);
  218. }
  219. }
  220. string GetTypeNamespace (TypeData typeData, string defaultNamespace)
  221. {
  222. string membersNamespace = defaultNamespace;
  223. SoapAttributes atts = null;
  224. if (!typeData.IsListType)
  225. {
  226. if (attributeOverrides != null)
  227. atts = attributeOverrides[typeData.Type];
  228. }
  229. if (atts == null)
  230. atts = new SoapAttributes (typeData.Type);
  231. if (atts.SoapType != null)
  232. {
  233. if (atts.SoapType.Namespace != null && atts.SoapType.Namespace != string.Empty)
  234. membersNamespace = atts.SoapType.Namespace;
  235. }
  236. if (membersNamespace == null) return "";
  237. else return membersNamespace;
  238. }
  239. XmlTypeMapping ImportListMapping (TypeData typeData, string defaultNamespace)
  240. {
  241. Type type = typeData.Type;
  242. XmlTypeMapping map = helper.GetRegisteredClrType (type, XmlSerializer.EncodingNamespace);
  243. if (map != null) return map;
  244. ListMap obmap = new ListMap ();
  245. TypeData itemTypeData = typeData.ListItemTypeData;
  246. map = CreateTypeMapping (typeData, "Array", XmlSerializer.EncodingNamespace);
  247. helper.RegisterClrType (map, type, XmlSerializer.EncodingNamespace);
  248. map.MultiReferenceType = true;
  249. map.ObjectMap = obmap;
  250. XmlTypeMapElementInfo elem = new XmlTypeMapElementInfo (null, itemTypeData);
  251. if (elem.TypeData.IsComplexType) {
  252. elem.MappedType = ImportTypeMapping (typeData.ListItemType, defaultNamespace);
  253. elem.TypeData = elem.MappedType.TypeData;
  254. }
  255. elem.ElementName = "Item";
  256. elem.Namespace = string.Empty;
  257. elem.IsNullable = true; // By default, items are nullable
  258. XmlTypeMapElementInfoList list = new XmlTypeMapElementInfoList();
  259. list.Add (elem);
  260. obmap.ItemInfo = list;
  261. XmlTypeMapping objMap = ImportTypeMapping (typeof(object), defaultNamespace);
  262. objMap.DerivedTypes.Add (map);
  263. // Register any of the including types as a derived class of object
  264. SoapIncludeAttribute[] includes = (SoapIncludeAttribute[])type.GetCustomAttributes (typeof (SoapIncludeAttribute), false);
  265. for (int i = 0; i < includes.Length; i++)
  266. {
  267. Type includedType = includes[i].Type;
  268. objMap.DerivedTypes.Add(ImportTypeMapping (includedType, defaultNamespace));
  269. }
  270. return map;
  271. }
  272. XmlTypeMapping ImportPrimitiveMapping (TypeData typeData, string defaultNamespace)
  273. {
  274. Type type = typeData.Type;
  275. XmlTypeMapping map = helper.GetRegisteredClrType (type, GetTypeNamespace (typeData, defaultNamespace));
  276. if (map != null) return map;
  277. map = CreateTypeMapping (typeData, null, defaultNamespace);
  278. helper.RegisterClrType (map, type, map.Namespace);
  279. return map;
  280. }
  281. XmlTypeMapping ImportEnumMapping (TypeData typeData, string defaultNamespace)
  282. {
  283. Type type = typeData.Type;
  284. XmlTypeMapping map = helper.GetRegisteredClrType (type, GetTypeNamespace (typeData, defaultNamespace));
  285. if (map != null) return map;
  286. ReflectionHelper.CheckSerializableType (type, false);
  287. map = CreateTypeMapping (typeData, null, defaultNamespace);
  288. helper.RegisterClrType (map, type, map.Namespace);
  289. map.MultiReferenceType = true;
  290. string [] names = Enum.GetNames (type);
  291. EnumMap.EnumMapMember[] members = new EnumMap.EnumMapMember[names.Length];
  292. for (int n=0; n<names.Length; n++)
  293. {
  294. FieldInfo field = type.GetField (names[n]);
  295. string xmlName = names[n];
  296. object[] atts = field.GetCustomAttributes (typeof(SoapEnumAttribute), false);
  297. if (atts.Length > 0) xmlName = ((SoapEnumAttribute)atts[0]).Name;
  298. long value = ((IConvertible) field.GetValue (null)).ToInt64 (CultureInfo.InvariantCulture);
  299. members[n] = new EnumMap.EnumMapMember (XmlConvert.EncodeLocalName (xmlName), names[n], value);
  300. }
  301. bool isFlags = type.IsDefined (typeof (FlagsAttribute), false);
  302. map.ObjectMap = new EnumMap (members, isFlags);
  303. ImportTypeMapping (typeof(object), defaultNamespace).DerivedTypes.Add (map);
  304. return map;
  305. }
  306. ICollection GetReflectionMembers (Type type)
  307. {
  308. ArrayList members = new ArrayList();
  309. PropertyInfo[] properties = type.GetProperties (BindingFlags.Instance | BindingFlags.Public);
  310. foreach (PropertyInfo prop in properties)
  311. {
  312. if (!prop.CanRead) continue;
  313. if (!prop.CanWrite && (TypeTranslator.GetTypeData (prop.PropertyType).SchemaType != SchemaTypes.Array || prop.PropertyType.IsArray))
  314. continue;
  315. SoapAttributes atts = attributeOverrides[type, prop.Name];
  316. if (atts == null) atts = new SoapAttributes (prop);
  317. if (atts.SoapIgnore) continue;
  318. XmlReflectionMember member = new XmlReflectionMember(prop.Name, prop.PropertyType, atts);
  319. members.Add (member);
  320. }
  321. FieldInfo[] fields = type.GetFields (BindingFlags.Instance | BindingFlags.Public);
  322. foreach (FieldInfo field in fields)
  323. {
  324. SoapAttributes atts = attributeOverrides[type, field.Name];
  325. if (atts == null) atts = new SoapAttributes (field);
  326. if (atts.SoapIgnore) continue;
  327. XmlReflectionMember member = new XmlReflectionMember(field.Name, field.FieldType, atts);
  328. members.Add (member);
  329. }
  330. return members;
  331. }
  332. private XmlTypeMapMember CreateMapMember (XmlReflectionMember rmember, string defaultNamespace)
  333. {
  334. XmlTypeMapMember mapMember;
  335. SoapAttributes atts = rmember.SoapAttributes;
  336. TypeData typeData = TypeTranslator.GetTypeData (rmember.MemberType);
  337. if (atts.SoapAttribute != null)
  338. {
  339. // An attribute
  340. if (atts.SoapElement != null)
  341. throw new Exception ("SoapAttributeAttribute and SoapElementAttribute cannot be applied to the same member");
  342. XmlTypeMapMemberAttribute mapAttribute = new XmlTypeMapMemberAttribute ();
  343. if (atts.SoapAttribute.AttributeName.Length == 0)
  344. mapAttribute.AttributeName = XmlConvert.EncodeLocalName (rmember.MemberName);
  345. else
  346. mapAttribute.AttributeName = XmlConvert.EncodeLocalName (atts.SoapAttribute.AttributeName);
  347. mapAttribute.Namespace = (atts.SoapAttribute.Namespace != null) ? atts.SoapAttribute.Namespace : "";
  348. if (typeData.IsComplexType)
  349. mapAttribute.MappedType = ImportTypeMapping (typeData.Type, defaultNamespace);
  350. typeData = TypeTranslator.GetTypeData (rmember.MemberType, atts.SoapAttribute.DataType);
  351. mapMember = mapAttribute;
  352. }
  353. else
  354. {
  355. if (typeData.SchemaType == SchemaTypes.Array) mapMember = new XmlTypeMapMemberList ();
  356. else mapMember = new XmlTypeMapMemberElement ();
  357. if (atts.SoapElement != null && atts.SoapElement.DataType.Length != 0)
  358. typeData = TypeTranslator.GetTypeData (rmember.MemberType, atts.SoapElement.DataType);
  359. // Creates an ElementInfo that identifies the element
  360. XmlTypeMapElementInfoList infoList = new XmlTypeMapElementInfoList();
  361. XmlTypeMapElementInfo elem = new XmlTypeMapElementInfo (mapMember, typeData);
  362. elem.ElementName = XmlConvert.EncodeLocalName ((atts.SoapElement != null && atts.SoapElement.ElementName.Length != 0) ? atts.SoapElement.ElementName : rmember.MemberName);
  363. elem.Namespace = string.Empty;
  364. elem.IsNullable = (atts.SoapElement != null) ? atts.SoapElement.IsNullable : false;
  365. if (typeData.IsComplexType)
  366. elem.MappedType = ImportTypeMapping (typeData.Type, defaultNamespace);
  367. infoList.Add (elem);
  368. ((XmlTypeMapMemberElement)mapMember).ElementInfo = infoList;
  369. }
  370. mapMember.TypeData = typeData;
  371. mapMember.Name = rmember.MemberName;
  372. mapMember.IsReturnValue = rmember.IsReturnValue;
  373. return mapMember;
  374. }
  375. public void IncludeType (Type type)
  376. {
  377. if (type == null)
  378. throw new ArgumentNullException ("type");
  379. if (includedTypes == null) includedTypes = new ArrayList ();
  380. if (!includedTypes.Contains (type))
  381. includedTypes.Add (type);
  382. }
  383. public void IncludeTypes (ICustomAttributeProvider provider)
  384. {
  385. object[] ats = provider.GetCustomAttributes (typeof(SoapIncludeAttribute), true);
  386. foreach (SoapIncludeAttribute at in ats)
  387. IncludeType (at.Type);
  388. }
  389. Exception CreateTypeException (Type type)
  390. {
  391. return new NotSupportedException ("The type " + type.FullName + " may not be serialized with SOAP-encoded messages. Set the Use for your message to Literal");
  392. }
  393. Exception CreateStructException (Type type)
  394. {
  395. return new NotSupportedException ("Cannot serialize " + type.FullName + ". Nested structs are not supported with encoded SOAP");
  396. }
  397. #endregion // Methods
  398. }
  399. }