BaseMessagesFormatter.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486
  1. //
  2. // DefaultMessageOperationFormatter.cs
  3. //
  4. // Author:
  5. // Atsushi Enomoto <[email protected]>
  6. // Eyal Alaluf <[email protected]>
  7. //
  8. // Copyright (C) 2005-2010 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. // This type is introduced for moonlight compatibility.
  43. internal class OperationFormatter
  44. : IDispatchMessageFormatter, IClientMessageFormatter
  45. {
  46. BaseMessagesFormatter impl;
  47. string operation_name;
  48. public OperationFormatter (OperationDescription od, bool isRpc, bool isEncoded)
  49. {
  50. Validate (od, isRpc, isEncoded);
  51. impl = BaseMessagesFormatter.Create (od);
  52. operation_name = od.Name;
  53. }
  54. public string OperationName {
  55. get { return operation_name; }
  56. }
  57. public bool IsValidReturnValue (MessagePartDescription part)
  58. {
  59. return part != null && part.Type != typeof (void);
  60. }
  61. void Validate (OperationDescription od, bool isRpc, bool isEncoded)
  62. {
  63. bool hasParameter = false, hasVoid = false;
  64. foreach (var md in od.Messages) {
  65. if (md.IsTypedMessage || md.IsUntypedMessage) {
  66. if (isRpc && !isEncoded)
  67. throw new InvalidOperationException ("Message with action {0} is either strongly-typed or untyped, but defined as RPC and encoded.");
  68. if (hasParameter && !md.IsVoid)
  69. throw new InvalidOperationException (String.Format ("Operation '{0}' contains a message with parameters. Strongly-typed or untyped message can be paired only with strongly-typed, untyped or void message.", od.Name));
  70. if (isRpc && hasVoid)
  71. throw new InvalidOperationException (String.Format ("This operation '{0}' is defined as RPC and contains a message with void, which is not allowed.", od.Name));
  72. } else {
  73. hasParameter |= !md.IsVoid;
  74. hasVoid |= md.IsVoid;
  75. }
  76. }
  77. }
  78. public object DeserializeReply (Message message, object [] parameters)
  79. {
  80. return impl.DeserializeReply (message, parameters);
  81. }
  82. public Message SerializeRequest (MessageVersion messageVersion, object [] parameters)
  83. {
  84. return impl.SerializeRequest (messageVersion, parameters);
  85. }
  86. public void DeserializeRequest (Message message, object [] parameters)
  87. {
  88. impl.DeserializeRequest (message, parameters);
  89. }
  90. public Message SerializeReply (MessageVersion messageVersion, object [] parameters, object result)
  91. {
  92. return impl.SerializeReply (messageVersion, parameters, result);
  93. }
  94. }
  95. internal abstract class BaseMessagesFormatter
  96. : IDispatchMessageFormatter, IClientMessageFormatter
  97. {
  98. MessageDescriptionCollection messages;
  99. bool isAsync;
  100. ParameterInfo [] requestMethodParams;
  101. ParameterInfo [] replyMethodParams;
  102. public BaseMessagesFormatter (MessageDescriptionCollection messages)
  103. {
  104. this.messages = messages;
  105. }
  106. public BaseMessagesFormatter (OperationDescription desc)
  107. : this (desc.Messages)
  108. {
  109. if (desc.SyncMethod != null)
  110. {
  111. isAsync = false;
  112. requestMethodParams = replyMethodParams = desc.SyncMethod.GetParameters ();
  113. return;
  114. }
  115. isAsync = true;
  116. ParameterInfo [] methodParams = desc.BeginMethod.GetParameters ();
  117. requestMethodParams = new ParameterInfo [methodParams.Length - 2];
  118. Array.Copy (methodParams, requestMethodParams, requestMethodParams.Length);
  119. methodParams = desc.EndMethod.GetParameters ();
  120. replyMethodParams = new ParameterInfo [methodParams.Length - 1];
  121. Array.Copy (methodParams, replyMethodParams, replyMethodParams.Length);
  122. }
  123. public static BaseMessagesFormatter Create (OperationDescription desc)
  124. {
  125. MethodInfo attrProvider = desc.SyncMethod ?? desc.BeginMethod;
  126. object [] attrs;
  127. #if !NET_2_1
  128. attrs = attrProvider.GetCustomAttributes (typeof (XmlSerializerFormatAttribute), false);
  129. if (attrs != null && attrs.Length > 0)
  130. return new XmlMessagesFormatter (desc, (XmlSerializerFormatAttribute) attrs [0]);
  131. #endif
  132. attrs = attrProvider.GetCustomAttributes (typeof (DataContractFormatAttribute), false);
  133. DataContractFormatAttribute dataAttr = null;
  134. if (attrs != null && attrs.Length > 0)
  135. dataAttr = (DataContractFormatAttribute) attrs [0];
  136. return new DataContractMessagesFormatter (desc, dataAttr);
  137. }
  138. protected abstract Message PartsToMessage (
  139. MessageDescription md, MessageVersion version, string action, object [] parts);
  140. protected abstract object [] MessageToParts (MessageDescription md, Message message);
  141. public Message SerializeRequest (
  142. MessageVersion version, object [] parameters)
  143. {
  144. MessageDescription md = null;
  145. foreach (MessageDescription mdi in messages)
  146. if (mdi.IsRequest)
  147. md = mdi;
  148. object [] parts = CreatePartsArray (md.Body);
  149. if (md.MessageType != null)
  150. MessageObjectToParts (md, parameters [0], parts);
  151. else {
  152. int index = 0;
  153. foreach (ParameterInfo pi in requestMethodParams)
  154. if (!pi.IsOut)
  155. parts [index++] = parameters [pi.Position];
  156. }
  157. return PartsToMessage (md, version, md.Action, parts);
  158. }
  159. public Message SerializeReply (
  160. MessageVersion version, object [] parameters, object result)
  161. {
  162. // use_response_converter
  163. MessageDescription md = null;
  164. foreach (MessageDescription mdi in messages)
  165. if (!mdi.IsRequest)
  166. md = mdi;
  167. object [] parts = CreatePartsArray (md.Body);
  168. if (md.MessageType != null)
  169. MessageObjectToParts (md, result, parts);
  170. else {
  171. if (HasReturnValue (md.Body))
  172. parts [0] = result;
  173. int index = ParamsOffset (md.Body);
  174. int paramsIdx = 0;
  175. foreach (ParameterInfo pi in replyMethodParams)
  176. if (pi.IsOut || pi.ParameterType.IsByRef)
  177. parts [index++] = parameters [paramsIdx++];
  178. }
  179. string action = version.Addressing == AddressingVersion.None ? null : md.Action;
  180. return PartsToMessage (md, version, action, parts);
  181. }
  182. public void DeserializeRequest (Message message, object [] parameters)
  183. {
  184. string action = message.Headers.Action;
  185. MessageDescription md = messages.Find (action);
  186. if (md == null)
  187. throw new ActionNotSupportedException (String.Format ("Action '{0}' is not supported by this operation.", action));
  188. object [] parts = MessageToParts (md, message);
  189. if (md.MessageType != null) {
  190. #if NET_2_1
  191. parameters [0] = Activator.CreateInstance (md.MessageType);
  192. #else
  193. parameters [0] = Activator.CreateInstance (md.MessageType, true);
  194. #endif
  195. PartsToMessageObject (md, parts, parameters [0]);
  196. }
  197. else
  198. {
  199. int index = 0;
  200. foreach (ParameterInfo pi in requestMethodParams)
  201. if (!pi.IsOut) {
  202. parameters [index] = parts [index];
  203. index++;
  204. }
  205. }
  206. }
  207. public object DeserializeReply (Message message, object [] parameters)
  208. {
  209. MessageDescription md = null;
  210. foreach (MessageDescription mdi in messages)
  211. if (!mdi.IsRequest)
  212. md = mdi;
  213. object [] parts = MessageToParts (md, message);
  214. if (md.MessageType != null) {
  215. #if NET_2_1
  216. object msgObject = Activator.CreateInstance (md.MessageType);
  217. #else
  218. object msgObject = Activator.CreateInstance (md.MessageType, true);
  219. #endif
  220. PartsToMessageObject (md, parts, msgObject);
  221. return msgObject;
  222. }
  223. else {
  224. int index = ParamsOffset (md.Body);
  225. foreach (ParameterInfo pi in requestMethodParams)
  226. if (pi.IsOut || pi.ParameterType.IsByRef)
  227. parameters [pi.Position] = parts [index++];
  228. return HasReturnValue (md.Body) ? parts [0] : null;
  229. }
  230. }
  231. void PartsToMessageObject (MessageDescription md, object [] parts, object msgObject)
  232. {
  233. foreach (MessagePartDescription partDesc in md.Body.Parts)
  234. if (partDesc.MemberInfo is FieldInfo)
  235. ((FieldInfo) partDesc.MemberInfo).SetValue (msgObject, parts [partDesc.Index]);
  236. else
  237. ((PropertyInfo) partDesc.MemberInfo).SetValue (msgObject, parts [partDesc.Index], null);
  238. }
  239. void MessageObjectToParts (MessageDescription md, object msgObject, object [] parts)
  240. {
  241. foreach (MessagePartDescription partDesc in md.Body.Parts)
  242. if (partDesc.MemberInfo is FieldInfo)
  243. parts [partDesc.Index] = ((FieldInfo) partDesc.MemberInfo).GetValue (msgObject);
  244. else
  245. parts [partDesc.Index] = ((PropertyInfo) partDesc.MemberInfo).GetValue (msgObject, null);
  246. }
  247. internal static bool HasReturnValue (MessageBodyDescription desc)
  248. {
  249. return desc.ReturnValue != null && desc.ReturnValue.Type != typeof (void);
  250. }
  251. protected static int ParamsOffset (MessageBodyDescription desc)
  252. {
  253. return HasReturnValue (desc) ? 1 : 0;
  254. }
  255. protected static object [] CreatePartsArray (MessageBodyDescription desc)
  256. {
  257. if (HasReturnValue (desc))
  258. return new object [desc.Parts.Count + 1];
  259. return new object [desc.Parts.Count];
  260. }
  261. }
  262. #if !NET_2_1
  263. class XmlMessagesFormatter : BaseMessagesFormatter
  264. {
  265. XmlSerializerFormatAttribute attr;
  266. Dictionary<MessageBodyDescription,XmlSerializer> bodySerializers
  267. = new Dictionary<MessageBodyDescription,XmlSerializer> ();
  268. public XmlMessagesFormatter (OperationDescription desc, XmlSerializerFormatAttribute attr)
  269. : base (desc)
  270. {
  271. this.attr = attr;
  272. }
  273. public XmlMessagesFormatter (MessageDescriptionCollection messages, XmlSerializerFormatAttribute attr)
  274. : base (messages)
  275. {
  276. this.attr = attr;
  277. }
  278. private XmlReflectionMember CreateReflectionMember (MessagePartDescription partDesc, bool isReturnValue)
  279. {
  280. XmlReflectionMember m = new XmlReflectionMember ();
  281. m.IsReturnValue = isReturnValue;
  282. m.MemberName = partDesc.Name;
  283. m.MemberType = partDesc.Type;
  284. return m;
  285. }
  286. protected override Message PartsToMessage (
  287. MessageDescription md, MessageVersion version, string action, object [] parts)
  288. {
  289. return Message.CreateMessage (version, action, new XmlBodyWriter (GetSerializer (md.Body), parts));
  290. }
  291. protected override object [] MessageToParts (MessageDescription md, Message message)
  292. {
  293. if (message.IsEmpty)
  294. return null;
  295. XmlDictionaryReader r = message.GetReaderAtBodyContents ();
  296. return (object []) GetSerializer (md.Body).Deserialize (r);
  297. }
  298. // FIXME: Handle ServiceKnownTypes
  299. XmlSerializer GetSerializer (MessageBodyDescription desc)
  300. {
  301. if (bodySerializers.ContainsKey (desc))
  302. return bodySerializers [desc];
  303. int count = desc.Parts.Count + (HasReturnValue (desc) ? 1 : 0);
  304. XmlReflectionMember [] members = new XmlReflectionMember [count];
  305. int ind = 0;
  306. if (HasReturnValue (desc))
  307. members [ind++] = CreateReflectionMember (desc.ReturnValue, true);
  308. foreach (MessagePartDescription partDesc in desc.Parts)
  309. members [ind++] = CreateReflectionMember (partDesc, false);
  310. // FIXME: Register known types into xmlImporter.
  311. XmlReflectionImporter xmlImporter = new XmlReflectionImporter ();
  312. XmlMembersMapping [] partsMapping = new XmlMembersMapping [1];
  313. partsMapping [0] = xmlImporter.ImportMembersMapping (desc.WrapperName, desc.WrapperNamespace, members, true);
  314. bodySerializers [desc] = XmlSerializer.FromMappings (partsMapping) [0];
  315. return bodySerializers [desc];
  316. }
  317. class XmlBodyWriter : BodyWriter
  318. {
  319. XmlSerializer serializer;
  320. object body;
  321. public XmlBodyWriter (XmlSerializer serializer, object parts)
  322. : base (false)
  323. {
  324. this.serializer = serializer;
  325. this.body = parts;
  326. }
  327. protected override BodyWriter OnCreateBufferedCopy (int maxBufferSize)
  328. {
  329. return new XmlBodyWriter (serializer, body);
  330. }
  331. protected override void OnWriteBodyContents (XmlDictionaryWriter writer)
  332. {
  333. serializer.Serialize (writer, body);
  334. }
  335. }
  336. }
  337. #endif
  338. class DataContractMessagesFormatter : BaseMessagesFormatter
  339. {
  340. DataContractFormatAttribute attr;
  341. public DataContractMessagesFormatter (OperationDescription desc, DataContractFormatAttribute attr)
  342. : base (desc)
  343. {
  344. this.attr = attr;
  345. }
  346. public DataContractMessagesFormatter (MessageDescriptionCollection messages, DataContractFormatAttribute attr)
  347. : base (messages)
  348. {
  349. this.attr = attr;
  350. }
  351. Dictionary<MessagePartDescription, XmlObjectSerializer> serializers
  352. = new Dictionary<MessagePartDescription,XmlObjectSerializer> ();
  353. protected override Message PartsToMessage (
  354. MessageDescription md, MessageVersion version, string action, object [] parts)
  355. {
  356. return Message.CreateMessage (version, action, new DataContractBodyWriter (md.Body, this, parts));
  357. }
  358. protected override object [] MessageToParts (
  359. MessageDescription md, Message message)
  360. {
  361. if (message.IsEmpty)
  362. return null;
  363. int offset = ParamsOffset (md.Body);
  364. object [] parts = CreatePartsArray (md.Body);
  365. XmlDictionaryReader r = message.GetReaderAtBodyContents ();
  366. if (md.Body.WrapperName != null)
  367. r.ReadStartElement (md.Body.WrapperName, md.Body.WrapperNamespace);
  368. for (r.MoveToContent (); r.NodeType == XmlNodeType.Element; r.MoveToContent ()) {
  369. XmlQualifiedName key = new XmlQualifiedName (r.LocalName, r.NamespaceURI);
  370. MessagePartDescription rv = md.Body.ReturnValue;
  371. if (rv != null && rv.Name == key.Name && rv.Namespace == key.Namespace)
  372. parts [0] = GetSerializer (md.Body.ReturnValue).ReadObject (r);
  373. else if (md.Body.Parts.Contains (key)) {
  374. MessagePartDescription p = md.Body.Parts [key];
  375. parts [p.Index + offset] = GetSerializer (p).ReadObject (r);
  376. }
  377. else // Skip unknown elements
  378. r.Skip ();
  379. }
  380. if (md.Body.WrapperName != null && !r.EOF)
  381. r.ReadEndElement ();
  382. return parts;
  383. }
  384. // FIXME: Handle ServiceKnownTypes
  385. XmlObjectSerializer GetSerializer (MessagePartDescription partDesc)
  386. {
  387. if (!serializers.ContainsKey (partDesc))
  388. serializers [partDesc] = new DataContractSerializer (
  389. partDesc.Type, partDesc.Name, partDesc.Namespace);
  390. return serializers [partDesc];
  391. }
  392. class DataContractBodyWriter : BodyWriter
  393. {
  394. MessageBodyDescription desc;
  395. object [] parts;
  396. DataContractMessagesFormatter parent;
  397. public DataContractBodyWriter (MessageBodyDescription desc, DataContractMessagesFormatter parent, object [] parts)
  398. : base (false)
  399. {
  400. this.desc = desc;
  401. this.parent = parent;
  402. this.parts = parts;
  403. }
  404. protected override void OnWriteBodyContents (XmlDictionaryWriter writer)
  405. {
  406. int offset = HasReturnValue (desc) ? 1 : 0;
  407. if (desc.WrapperName != null)
  408. writer.WriteStartElement (desc.WrapperName, desc.WrapperNamespace);
  409. if (HasReturnValue (desc))
  410. WriteMessagePart (writer, desc, desc.ReturnValue, parts [0]);
  411. foreach (MessagePartDescription partDesc in desc.Parts)
  412. WriteMessagePart (writer, desc, partDesc, parts [partDesc.Index + offset]);
  413. if (desc.WrapperName != null)
  414. writer.WriteEndElement ();
  415. }
  416. void WriteMessagePart (
  417. XmlDictionaryWriter writer, MessageBodyDescription desc, MessagePartDescription partDesc, object obj)
  418. {
  419. parent.GetSerializer (partDesc).WriteObject (writer, obj);
  420. }
  421. }
  422. }
  423. }