BaseMessagesFormatter.cs 13 KB

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