BaseMessagesFormatter.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420
  1. //
  2. // DefaultMessageOperationFormatter.cs
  3. //
  4. // Author:
  5. // Atsushi Enomoto <[email protected]>
  6. // Eyal Alaluf <[email protected]>
  7. //
  8. // Copyright (C) 2005-2007 Novell, Inc. http://www.novell.com
  9. // Copyright (C) 2008 Mainsoft Co. http://www.mainsoft.com
  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. using System;
  31. using System.Collections.Generic;
  32. using System.Reflection;
  33. using System.Runtime.Serialization;
  34. using System.ServiceModel;
  35. using System.ServiceModel.Channels;
  36. using System.ServiceModel.Description;
  37. using System.Text;
  38. using System.Xml;
  39. using System.Xml.Serialization;
  40. namespace System.ServiceModel.Dispatcher
  41. {
  42. internal abstract class BaseMessagesFormatter
  43. : IDispatchMessageFormatter, IClientMessageFormatter
  44. {
  45. MessageDescriptionCollection messages;
  46. bool isAsync;
  47. ParameterInfo [] requestMethodParams;
  48. ParameterInfo [] replyMethodParams;
  49. public BaseMessagesFormatter (MessageDescriptionCollection messages)
  50. {
  51. this.messages = messages;
  52. }
  53. public BaseMessagesFormatter (OperationDescription desc)
  54. : this (desc.Messages)
  55. {
  56. if (desc.SyncMethod != null)
  57. {
  58. isAsync = false;
  59. requestMethodParams = replyMethodParams = desc.SyncMethod.GetParameters ();
  60. return;
  61. }
  62. isAsync = true;
  63. ParameterInfo [] methodParams = desc.BeginMethod.GetParameters ();
  64. requestMethodParams = new ParameterInfo [methodParams.Length - 2];
  65. Array.Copy (methodParams, requestMethodParams, requestMethodParams.Length);
  66. methodParams = desc.EndMethod.GetParameters ();
  67. replyMethodParams = new ParameterInfo [methodParams.Length - 1];
  68. Array.Copy (methodParams, replyMethodParams, replyMethodParams.Length);
  69. }
  70. public static BaseMessagesFormatter Create (OperationDescription desc)
  71. {
  72. MethodInfo attrProvider = desc.SyncMethod ?? desc.BeginMethod;
  73. object [] attrs;
  74. #if !NET_2_1
  75. attrs = attrProvider.GetCustomAttributes (typeof (XmlSerializerFormatAttribute), false);
  76. if (attrs != null && attrs.Length > 0)
  77. return new XmlMessagesFormatter (desc, (XmlSerializerFormatAttribute) attrs [0]);
  78. #endif
  79. attrs = attrProvider.GetCustomAttributes (typeof (DataContractFormatAttribute), false);
  80. DataContractFormatAttribute dataAttr = null;
  81. if (attrs != null && attrs.Length > 0)
  82. dataAttr = (DataContractFormatAttribute) attrs [0];
  83. return new DataContractMessagesFormatter (desc, dataAttr);
  84. }
  85. protected abstract Message PartsToMessage (
  86. MessageDescription md, MessageVersion version, string action, object [] parts);
  87. protected abstract object [] MessageToParts (MessageDescription md, Message message);
  88. public Message SerializeRequest (
  89. MessageVersion version, object [] parameters)
  90. {
  91. MessageDescription md = null;
  92. foreach (MessageDescription mdi in messages)
  93. if (mdi.Direction == MessageDirection.Input)
  94. md = mdi;
  95. object [] parts = CreatePartsArray (md.Body);
  96. if (md.MessageType != null)
  97. MessageObjectToParts (md, parameters [0], parts);
  98. else {
  99. int index = 0;
  100. foreach (ParameterInfo pi in requestMethodParams)
  101. if (!pi.IsOut)
  102. parts [index++] = parameters [pi.Position];
  103. }
  104. return PartsToMessage (md, version, md.Action, parts);
  105. }
  106. public Message SerializeReply (
  107. MessageVersion version, object [] parameters, object result)
  108. {
  109. // use_response_converter
  110. MessageDescription md = null;
  111. foreach (MessageDescription mdi in messages)
  112. if (mdi.Direction == MessageDirection.Output)
  113. md = mdi;
  114. object [] parts = CreatePartsArray (md.Body);
  115. if (md.MessageType != null)
  116. MessageObjectToParts (md, result, parts);
  117. else {
  118. if (HasReturnValue (md.Body))
  119. parts [0] = result;
  120. int index = ParamsOffset (md.Body);
  121. foreach (ParameterInfo pi in replyMethodParams)
  122. if (pi.IsOut || pi.ParameterType.IsByRef)
  123. parts [index++] = parameters [pi.Position];
  124. }
  125. string action = version.Addressing == AddressingVersion.None ? null : md.Action;
  126. return PartsToMessage (md, version, action, parts);
  127. }
  128. public void DeserializeRequest (Message message, object [] parameters)
  129. {
  130. string action = message.Headers.Action;
  131. MessageDescription md = messages.Find (action);
  132. if (md == null)
  133. throw new ActionNotSupportedException (String.Format ("Action '{0}' is not supported by this operation.", action));
  134. object [] parts = MessageToParts (md, message);
  135. if (md.MessageType != null) {
  136. #if NET_2_1
  137. parameters [0] = Activator.CreateInstance (md.MessageType);
  138. #else
  139. parameters [0] = Activator.CreateInstance (md.MessageType, true);
  140. #endif
  141. PartsToMessageObject (md, parts, parameters [0]);
  142. }
  143. else
  144. {
  145. int index = 0;
  146. foreach (ParameterInfo pi in requestMethodParams)
  147. if (!pi.IsOut)
  148. parameters [pi.Position] = parts [index++];
  149. }
  150. }
  151. public object DeserializeReply (Message message, object [] parameters)
  152. {
  153. MessageDescription md = null;
  154. foreach (MessageDescription mdi in messages)
  155. if (mdi.Direction == MessageDirection.Output)
  156. md = mdi;
  157. object [] parts = MessageToParts (md, message);
  158. if (md.MessageType != null) {
  159. #if NET_2_1
  160. object msgObject = Activator.CreateInstance (md.MessageType);
  161. #else
  162. object msgObject = Activator.CreateInstance (md.MessageType, true);
  163. #endif
  164. PartsToMessageObject (md, parts, msgObject);
  165. return msgObject;
  166. }
  167. else {
  168. int index = ParamsOffset (md.Body);
  169. foreach (ParameterInfo pi in requestMethodParams)
  170. if (pi.IsOut || pi.ParameterType.IsByRef)
  171. parameters [pi.Position] = parts [index++];
  172. return HasReturnValue (md.Body) ? parts [0] : null;
  173. }
  174. }
  175. void PartsToMessageObject (MessageDescription md, object [] parts, object msgObject)
  176. {
  177. foreach (MessagePartDescription partDesc in md.Body.Parts)
  178. if (partDesc.MemberInfo is FieldInfo)
  179. ((FieldInfo) partDesc.MemberInfo).SetValue (msgObject, parts [partDesc.Index]);
  180. else
  181. ((PropertyInfo) partDesc.MemberInfo).SetValue (msgObject, parts [partDesc.Index], null);
  182. }
  183. void MessageObjectToParts (MessageDescription md, object msgObject, object [] parts)
  184. {
  185. foreach (MessagePartDescription partDesc in md.Body.Parts)
  186. if (partDesc.MemberInfo is FieldInfo)
  187. parts [partDesc.Index] = ((FieldInfo) partDesc.MemberInfo).GetValue (msgObject);
  188. else
  189. parts [partDesc.Index] = ((PropertyInfo) partDesc.MemberInfo).GetValue (msgObject, null);
  190. }
  191. internal static bool HasReturnValue (MessageBodyDescription desc)
  192. {
  193. return desc.ReturnValue != null && desc.ReturnValue.Type != typeof (void);
  194. }
  195. protected static int ParamsOffset (MessageBodyDescription desc)
  196. {
  197. return HasReturnValue (desc) ? 1 : 0;
  198. }
  199. protected static object [] CreatePartsArray (MessageBodyDescription desc)
  200. {
  201. if (HasReturnValue (desc))
  202. return new object [desc.Parts.Count + 1];
  203. return new object [desc.Parts.Count];
  204. }
  205. }
  206. #if !NET_2_1
  207. class XmlMessagesFormatter : BaseMessagesFormatter
  208. {
  209. XmlSerializerFormatAttribute attr;
  210. Dictionary<MessageBodyDescription,XmlSerializer> bodySerializers
  211. = new Dictionary<MessageBodyDescription,XmlSerializer> ();
  212. public XmlMessagesFormatter (OperationDescription desc, XmlSerializerFormatAttribute attr)
  213. : base (desc)
  214. {
  215. this.attr = attr;
  216. }
  217. public XmlMessagesFormatter (MessageDescriptionCollection messages, XmlSerializerFormatAttribute attr)
  218. : base (messages)
  219. {
  220. this.attr = attr;
  221. }
  222. private XmlReflectionMember CreateReflectionMember (MessagePartDescription partDesc, bool isReturnValue)
  223. {
  224. XmlReflectionMember m = new XmlReflectionMember ();
  225. m.IsReturnValue = isReturnValue;
  226. m.MemberName = partDesc.Name;
  227. m.MemberType = partDesc.Type;
  228. return m;
  229. }
  230. protected override Message PartsToMessage (
  231. MessageDescription md, MessageVersion version, string action, object [] parts)
  232. {
  233. return Message.CreateMessage (version, action, new XmlBodyWriter (GetSerializer (md.Body), parts));
  234. }
  235. protected override object [] MessageToParts (MessageDescription md, Message message)
  236. {
  237. if (message.IsEmpty)
  238. return null;
  239. XmlDictionaryReader r = message.GetReaderAtBodyContents ();
  240. return (object []) GetSerializer (md.Body).Deserialize (r);
  241. }
  242. // FIXME: Handle ServiceKnownTypes
  243. XmlSerializer GetSerializer (MessageBodyDescription desc)
  244. {
  245. if (bodySerializers.ContainsKey (desc))
  246. return bodySerializers [desc];
  247. int count = desc.Parts.Count + (HasReturnValue (desc) ? 1 : 0);
  248. XmlReflectionMember [] members = new XmlReflectionMember [count];
  249. int ind = 0;
  250. if (HasReturnValue (desc))
  251. members [ind++] = CreateReflectionMember (desc.ReturnValue, true);
  252. foreach (MessagePartDescription partDesc in desc.Parts)
  253. members [ind++] = CreateReflectionMember (partDesc, false);
  254. // FIXME: Register known types into xmlImporter.
  255. XmlReflectionImporter xmlImporter = new XmlReflectionImporter ();
  256. XmlMembersMapping [] partsMapping = new XmlMembersMapping [1];
  257. partsMapping [0] = xmlImporter.ImportMembersMapping (desc.WrapperName, desc.WrapperNamespace, members, true);
  258. bodySerializers [desc] = XmlSerializer.FromMappings (partsMapping) [0];
  259. return bodySerializers [desc];
  260. }
  261. class XmlBodyWriter : BodyWriter
  262. {
  263. XmlSerializer serializer;
  264. object body;
  265. public XmlBodyWriter (XmlSerializer serializer, object parts)
  266. : base (false)
  267. {
  268. this.serializer = serializer;
  269. this.body = parts;
  270. }
  271. [MonoTODO]
  272. protected override BodyWriter OnCreateBufferedCopy (int maxBufferSize)
  273. {
  274. throw new NotSupportedException ();
  275. }
  276. protected override void OnWriteBodyContents (XmlDictionaryWriter writer)
  277. {
  278. serializer.Serialize (writer, body);
  279. }
  280. }
  281. }
  282. #endif
  283. class DataContractMessagesFormatter : BaseMessagesFormatter
  284. {
  285. DataContractFormatAttribute attr;
  286. public DataContractMessagesFormatter (OperationDescription desc, DataContractFormatAttribute attr)
  287. : base (desc)
  288. {
  289. this.attr = attr;
  290. }
  291. public DataContractMessagesFormatter (MessageDescriptionCollection messages, DataContractFormatAttribute attr)
  292. : base (messages)
  293. {
  294. this.attr = attr;
  295. }
  296. Dictionary<MessagePartDescription, XmlObjectSerializer> serializers
  297. = new Dictionary<MessagePartDescription,XmlObjectSerializer> ();
  298. protected override Message PartsToMessage (
  299. MessageDescription md, MessageVersion version, string action, object [] parts)
  300. {
  301. return Message.CreateMessage (version, action, new DataContractBodyWriter (md.Body, this, parts));
  302. }
  303. protected override object [] MessageToParts (
  304. MessageDescription md, Message message)
  305. {
  306. if (message.IsEmpty)
  307. return null;
  308. int offset = ParamsOffset (md.Body);
  309. object [] parts = CreatePartsArray (md.Body);
  310. XmlDictionaryReader r = message.GetReaderAtBodyContents ();
  311. if (md.Body.WrapperName != null)
  312. r.ReadStartElement (md.Body.WrapperName, md.Body.WrapperNamespace);
  313. for (r.MoveToContent (); r.NodeType == XmlNodeType.Element; r.MoveToContent ()) {
  314. XmlQualifiedName key = new XmlQualifiedName (r.LocalName, r.NamespaceURI);
  315. MessagePartDescription rv = md.Body.ReturnValue;
  316. if (rv != null && rv.Name == key.Name && rv.Namespace == key.Namespace)
  317. parts [0] = GetSerializer (md.Body.ReturnValue).ReadObject (r);
  318. else if (md.Body.Parts.Contains (key)) {
  319. MessagePartDescription p = md.Body.Parts [key];
  320. parts [p.Index + offset] = GetSerializer (p).ReadObject (r);
  321. }
  322. else // Skip unknown elements
  323. r.Skip ();
  324. }
  325. if (md.Body.WrapperName != null && !r.EOF)
  326. r.ReadEndElement ();
  327. return parts;
  328. }
  329. // FIXME: Handle ServiceKnownTypes
  330. XmlObjectSerializer GetSerializer (MessagePartDescription partDesc)
  331. {
  332. if (!serializers.ContainsKey (partDesc))
  333. serializers [partDesc] = new DataContractSerializer (
  334. partDesc.Type, partDesc.Name, partDesc.Namespace);
  335. return serializers [partDesc];
  336. }
  337. class DataContractBodyWriter : BodyWriter
  338. {
  339. MessageBodyDescription desc;
  340. object [] parts;
  341. DataContractMessagesFormatter parent;
  342. public DataContractBodyWriter (MessageBodyDescription desc, DataContractMessagesFormatter parent, object [] parts)
  343. : base (false)
  344. {
  345. this.desc = desc;
  346. this.parent = parent;
  347. this.parts = parts;
  348. }
  349. protected override void OnWriteBodyContents (XmlDictionaryWriter writer)
  350. {
  351. int offset = HasReturnValue (desc) ? 1 : 0;
  352. if (desc.WrapperName != null)
  353. writer.WriteStartElement (desc.WrapperName, desc.WrapperNamespace);
  354. if (HasReturnValue (desc))
  355. WriteMessagePart (writer, desc, desc.ReturnValue, parts [0]);
  356. foreach (MessagePartDescription partDesc in desc.Parts)
  357. WriteMessagePart (writer, desc, partDesc, parts [partDesc.Index + offset]);
  358. if (desc.WrapperName != null)
  359. writer.WriteEndElement ();
  360. }
  361. void WriteMessagePart (
  362. XmlDictionaryWriter writer, MessageBodyDescription desc, MessagePartDescription partDesc, object obj)
  363. {
  364. parent.GetSerializer (partDesc).WriteObject (writer, obj);
  365. }
  366. }
  367. }
  368. }