BaseMessagesFormatter.cs 14 KB

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