BaseMessagesFormatter.cs 13 KB

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