BaseMessagesFormatter.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536
  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. // Copyright 2011 Xamarin Inc (http://www.xamarin.com).
  11. //
  12. // Permission is hereby granted, free of charge, to any person obtaining
  13. // a copy of this software and associated documentation files (the
  14. // "Software"), to deal in the Software without restriction, including
  15. // without limitation the rights to use, copy, modify, merge, publish,
  16. // distribute, sublicense, and/or sell copies of the Software, and to
  17. // permit persons to whom the Software is furnished to do so, subject to
  18. // the following conditions:
  19. //
  20. // The above copyright notice and this permission notice shall be
  21. // included in all copies or substantial portions of the Software.
  22. //
  23. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  24. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  25. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  26. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  27. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  28. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  29. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  30. //
  31. using System;
  32. using System.Collections.Generic;
  33. using System.IO;
  34. using System.Linq;
  35. using System.Reflection;
  36. using System.Runtime.Serialization;
  37. using System.ServiceModel;
  38. using System.ServiceModel.Channels;
  39. using System.ServiceModel.Description;
  40. using System.Text;
  41. using System.Xml;
  42. using System.Xml.Serialization;
  43. namespace System.ServiceModel.Dispatcher
  44. {
  45. // This type is introduced for moonlight compatibility.
  46. internal class OperationFormatter
  47. : IDispatchMessageFormatter, IClientMessageFormatter
  48. {
  49. BaseMessagesFormatter impl;
  50. string operation_name;
  51. public OperationFormatter (OperationDescription od, bool isRpc, bool isEncoded)
  52. {
  53. Validate (od, isRpc, isEncoded);
  54. impl = BaseMessagesFormatter.Create (od);
  55. operation_name = od.Name;
  56. }
  57. public string OperationName {
  58. get { return operation_name; }
  59. }
  60. internal static bool IsValidReturnValue (MessagePartDescription part)
  61. {
  62. return part != null && part.Type != typeof (void);
  63. }
  64. internal static void Validate (OperationDescription od, bool isRpc, bool isEncoded)
  65. {
  66. bool hasParameter = false, hasVoid = false;
  67. foreach (var md in od.Messages) {
  68. if (md.IsTypedMessage || md.IsUntypedMessage) {
  69. if (isRpc && !isEncoded)
  70. throw new InvalidOperationException ("Message with action {0} is either strongly-typed or untyped, but defined as RPC and encoded.");
  71. if (hasParameter && !md.IsVoid)
  72. 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));
  73. if (isRpc && hasVoid)
  74. throw new InvalidOperationException (String.Format ("This operation '{0}' is defined as RPC and contains a message with void, which is not allowed.", od.Name));
  75. } else {
  76. hasParameter |= !md.IsVoid;
  77. hasVoid |= md.IsVoid;
  78. }
  79. }
  80. }
  81. public object DeserializeReply (Message message, object [] parameters)
  82. {
  83. return impl.DeserializeReply (message, parameters);
  84. }
  85. public Message SerializeRequest (MessageVersion messageVersion, object [] parameters)
  86. {
  87. return impl.SerializeRequest (messageVersion, parameters);
  88. }
  89. public void DeserializeRequest (Message message, object [] parameters)
  90. {
  91. impl.DeserializeRequest (message, parameters);
  92. }
  93. public Message SerializeReply (MessageVersion messageVersion, object [] parameters, object result)
  94. {
  95. return impl.SerializeReply (messageVersion, parameters, result);
  96. }
  97. }
  98. internal abstract class BaseMessagesFormatter
  99. : IDispatchMessageFormatter, IClientMessageFormatter
  100. {
  101. MessageDescriptionCollection messages;
  102. bool isAsync;
  103. ParameterInfo [] requestMethodParams;
  104. ParameterInfo [] replyMethodParams;
  105. List<Type> operation_known_types = new List<Type> ();
  106. public BaseMessagesFormatter (MessageDescriptionCollection messages)
  107. {
  108. this.messages = messages;
  109. }
  110. public BaseMessagesFormatter (OperationDescription desc)
  111. : this (desc.Messages)
  112. {
  113. if (desc.SyncMethod != null)
  114. {
  115. isAsync = false;
  116. requestMethodParams = replyMethodParams = desc.SyncMethod.GetParameters ();
  117. return;
  118. }
  119. isAsync = true;
  120. ParameterInfo [] methodParams = desc.BeginMethod.GetParameters ();
  121. requestMethodParams = new ParameterInfo [methodParams.Length - 2];
  122. Array.Copy (methodParams, requestMethodParams, requestMethodParams.Length);
  123. methodParams = desc.EndMethod.GetParameters ();
  124. replyMethodParams = new ParameterInfo [methodParams.Length - 1];
  125. Array.Copy (methodParams, replyMethodParams, replyMethodParams.Length);
  126. operation_known_types.AddRange (desc.KnownTypes);
  127. }
  128. // FIXME: this should be refactored and eliminated.
  129. // XmlSerializerFormatAttribute and DataContractFormatAttribute
  130. // should be handled at ContractDescription.GetContract (to fill
  131. // IOperationBehavior for each).
  132. //
  133. // Fixing the issue above should also fix "Formatter is already filled at initial state" issue described in EndpointDispatcher.cs and ContractDescription.cs.
  134. public static BaseMessagesFormatter Create (OperationDescription desc)
  135. {
  136. MethodInfo attrProvider = desc.SyncMethod ?? desc.BeginMethod;
  137. object [] attrs;
  138. attrs = attrProvider.GetCustomAttributes (typeof (XmlSerializerFormatAttribute), false);
  139. if (attrs != null && attrs.Length > 0)
  140. return new XmlMessagesFormatter (desc, (XmlSerializerFormatAttribute) attrs [0]);
  141. attrs = attrProvider.GetCustomAttributes (typeof (DataContractFormatAttribute), false);
  142. DataContractFormatAttribute dataAttr = null;
  143. if (attrs != null && attrs.Length > 0)
  144. dataAttr = (DataContractFormatAttribute) attrs [0];
  145. return new DataContractMessagesFormatter (desc, dataAttr);
  146. }
  147. public IEnumerable<Type> OperationKnownTypes {
  148. get { return operation_known_types; }
  149. }
  150. protected abstract Message PartsToMessage (
  151. MessageDescription md, MessageVersion version, string action, object [] parts);
  152. protected abstract object [] MessageToParts (MessageDescription md, Message message);
  153. protected abstract Dictionary<MessageHeaderDescription,object> MessageToHeaderObjects (MessageDescription md, Message message);
  154. public Message SerializeRequest (
  155. MessageVersion version, object [] parameters)
  156. {
  157. MessageDescription md = null;
  158. foreach (MessageDescription mdi in messages)
  159. if (mdi.IsRequest)
  160. md = mdi;
  161. object [] parts = CreatePartsArray (md.Body);
  162. var headers = md.Headers.Count > 0 ? new Dictionary<MessageHeaderDescription,object> () : null;
  163. if (md.MessageType != null)
  164. MessageObjectToParts (md, parameters [0], headers, parts);
  165. else {
  166. int index = 0;
  167. foreach (ParameterInfo pi in requestMethodParams)
  168. if (!pi.IsOut)
  169. parts [index++] = parameters [pi.Position];
  170. }
  171. var msg = PartsToMessage (md, version, md.Action, parts);
  172. if (headers != null)
  173. foreach (var pair in headers)
  174. if (pair.Value != null)
  175. msg.Headers.Add (CreateHeader (pair.Key, pair.Value));
  176. return msg;
  177. }
  178. public Message SerializeReply (
  179. MessageVersion version, object [] parameters, object result)
  180. {
  181. // use_response_converter
  182. MessageDescription md = null;
  183. foreach (MessageDescription mdi in messages)
  184. if (!mdi.IsRequest)
  185. md = mdi;
  186. object [] parts = CreatePartsArray (md.Body);
  187. var headers = md.Headers.Count > 0 ? new Dictionary<MessageHeaderDescription,object> () : null;
  188. if (md.MessageType != null)
  189. MessageObjectToParts (md, result, headers, parts);
  190. else {
  191. if (HasReturnValue (md.Body))
  192. parts [0] = result;
  193. int index = ParamsOffset (md.Body);
  194. int paramsIdx = 0;
  195. foreach (ParameterInfo pi in replyMethodParams)
  196. if (pi.IsOut || pi.ParameterType.IsByRef)
  197. parts [index++] = parameters [paramsIdx++];
  198. }
  199. string action = version.Addressing == AddressingVersion.None ? null : md.Action;
  200. var msg = PartsToMessage (md, version, action, parts);
  201. if (headers != null)
  202. foreach (var pair in headers)
  203. if (pair.Value != null)
  204. msg.Headers.Add (CreateHeader (pair.Key, pair.Value));
  205. return msg;
  206. }
  207. MessageHeader CreateHeader (MessageHeaderDescription mh, object value)
  208. {
  209. return MessageHeader.CreateHeader (mh.Name, mh.Namespace, value, mh.MustUnderstand, mh.Actor, mh.Relay);
  210. }
  211. public void DeserializeRequest (Message message, object [] parameters)
  212. {
  213. string action = message.Headers.Action;
  214. MessageDescription md = messages.Find (action);
  215. if (md == null)
  216. throw new ActionNotSupportedException (String.Format ("Action '{0}' is not supported by this operation.", action));
  217. var headers = MessageToHeaderObjects (md, message);
  218. object [] parts = MessageToParts (md, message);
  219. if (md.MessageType != null) {
  220. #if MOBILE
  221. parameters [0] = Activator.CreateInstance (md.MessageType);
  222. #else
  223. parameters [0] = Activator.CreateInstance (md.MessageType, true);
  224. #endif
  225. PartsToMessageObject (md, headers, parts, parameters [0]);
  226. }
  227. else
  228. {
  229. int index = 0;
  230. foreach (ParameterInfo pi in requestMethodParams)
  231. if (!pi.IsOut) {
  232. parameters [index] = parts [index];
  233. index++;
  234. }
  235. }
  236. }
  237. public object DeserializeReply (Message message, object [] parameters)
  238. {
  239. MessageDescription md = null;
  240. foreach (MessageDescription mdi in messages)
  241. if (!mdi.IsRequest)
  242. md = mdi;
  243. var headers = MessageToHeaderObjects (md, message);
  244. object [] parts = MessageToParts (md, message);
  245. if (md.MessageType != null) {
  246. #if MOBILE
  247. object msgObject = Activator.CreateInstance (md.MessageType);
  248. #else
  249. object msgObject = Activator.CreateInstance (md.MessageType, true);
  250. #endif
  251. PartsToMessageObject (md, headers, parts, msgObject);
  252. return msgObject;
  253. }
  254. else {
  255. int index = ParamsOffset (md.Body);
  256. foreach (ParameterInfo pi in replyMethodParams) {
  257. if (pi.IsOut || pi.ParameterType.IsByRef)
  258. parameters [pi.Position] = parts [index++];
  259. }
  260. return HasReturnValue (md.Body) ? parts [0] : null;
  261. }
  262. }
  263. void PartsToMessageObject (MessageDescription md, Dictionary<MessageHeaderDescription,object> headers, object [] parts, object msgObject)
  264. {
  265. if (headers != null)
  266. foreach (var pair in headers) {
  267. var mi = pair.Key.MemberInfo;
  268. if (mi is FieldInfo)
  269. ((FieldInfo) mi).SetValue (msgObject, pair.Value);
  270. else
  271. ((PropertyInfo) mi).SetValue (msgObject, pair.Value, null);
  272. }
  273. var l = new List<MessagePartDescription> (md.Body.Parts);
  274. if (md.Body.ReturnValue != null)
  275. l.Add (md.Body.ReturnValue);
  276. foreach (MessagePartDescription partDesc in l)
  277. if (partDesc.MemberInfo is FieldInfo)
  278. ((FieldInfo) partDesc.MemberInfo).SetValue (msgObject, parts [partDesc.Index]);
  279. else if (partDesc.MemberInfo is PropertyInfo)
  280. ((PropertyInfo) partDesc.MemberInfo).SetValue (msgObject, parts [partDesc.Index], null);
  281. // otherwise, it could be null (in case of undefined return value in MessageContract)
  282. }
  283. void MessageObjectToParts (MessageDescription md, object msgObject, Dictionary<MessageHeaderDescription,object> headers, object [] parts)
  284. {
  285. foreach (var headDesc in md.Headers) {
  286. var mi = headDesc.MemberInfo;
  287. if (mi is FieldInfo)
  288. headers [headDesc] = ((FieldInfo) mi).GetValue (msgObject);
  289. else
  290. headers [headDesc] = ((PropertyInfo) mi).GetValue (msgObject, null);
  291. }
  292. var l = new List<MessagePartDescription> (md.Body.Parts);
  293. if (md.Body.ReturnValue != null)
  294. l.Add (md.Body.ReturnValue);
  295. foreach (MessagePartDescription partDesc in l) {
  296. if (partDesc.MemberInfo == null)
  297. continue;
  298. if (partDesc.MemberInfo is FieldInfo)
  299. parts [partDesc.Index] = ((FieldInfo) partDesc.MemberInfo).GetValue (msgObject);
  300. else
  301. parts [partDesc.Index] = ((PropertyInfo) partDesc.MemberInfo).GetValue (msgObject, null);
  302. }
  303. }
  304. internal static bool HasReturnValue (MessageBodyDescription desc)
  305. {
  306. return desc.ReturnValue != null && desc.ReturnValue.Type != typeof (void);
  307. }
  308. protected static int ParamsOffset (MessageBodyDescription desc)
  309. {
  310. return HasReturnValue (desc) ? 1 : 0;
  311. }
  312. protected static object [] CreatePartsArray (MessageBodyDescription desc)
  313. {
  314. if (HasReturnValue (desc))
  315. return new object [desc.Parts.Count + 1];
  316. return new object [desc.Parts.Count];
  317. }
  318. }
  319. class DataContractMessagesFormatter : BaseMessagesFormatter
  320. {
  321. DataContractFormatAttribute attr;
  322. #if !MOBILE
  323. DataContractSerializerOperationBehavior serializerBehavior;
  324. #endif
  325. public DataContractMessagesFormatter (OperationDescription desc, DataContractFormatAttribute attr)
  326. : base (desc)
  327. {
  328. #if !MOBILE
  329. this.serializerBehavior = desc.Behaviors.Find<DataContractSerializerOperationBehavior>();
  330. #endif
  331. this.attr = attr;
  332. }
  333. public DataContractMessagesFormatter (MessageDescriptionCollection messages, DataContractFormatAttribute attr)
  334. : base (messages)
  335. {
  336. this.attr = attr;
  337. }
  338. Dictionary<MessagePartDescription, XmlObjectSerializer> serializers
  339. = new Dictionary<MessagePartDescription,XmlObjectSerializer> ();
  340. protected override Message PartsToMessage (
  341. MessageDescription md, MessageVersion version, string action, object [] parts)
  342. {
  343. return Message.CreateMessage (version, action, new DataContractBodyWriter (md.Body, this, parts));
  344. }
  345. protected override Dictionary<MessageHeaderDescription,object> MessageToHeaderObjects (MessageDescription md, Message message)
  346. {
  347. if (message.IsEmpty || md.Headers.Count == 0)
  348. return null;
  349. var dic = new Dictionary<MessageHeaderDescription,object> ();
  350. for (int i = 0; i < message.Headers.Count; i++) {
  351. var r = message.Headers.GetReaderAtHeader (i);
  352. var mh = md.Headers.FirstOrDefault (h => h.Name == r.LocalName && h.Namespace == r.NamespaceURI);
  353. if (mh != null)
  354. dic [mh] = ReadHeaderObject (mh.Type, GetSerializer (mh), r);
  355. }
  356. return dic;
  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 && rv.Type != typeof (void))
  372. parts [0] = ReadMessagePart (md.Body.ReturnValue, r);
  373. else if (md.Body.Parts.Contains (key)) {
  374. MessagePartDescription p = md.Body.Parts [key];
  375. parts [p.Index + offset] = ReadMessagePart (p, 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. object ReadMessagePart (MessagePartDescription part, XmlDictionaryReader r)
  385. {
  386. if (part.Type == typeof (Stream))
  387. // FIXME: it seems TransferMode.Streamed* has different serialization than .Buffered. Need to differentiate serialization somewhere (not limited to here).
  388. return new MemoryStream (Convert.FromBase64String (r.ReadElementContentAsString (part.Name, part.Namespace)));
  389. else
  390. return GetSerializer (part).ReadObject (r);
  391. }
  392. XmlObjectSerializer GetSerializer (MessagePartDescription partDesc)
  393. {
  394. if (!serializers.ContainsKey (partDesc))
  395. #if !MOBILE
  396. if (serializerBehavior != null)
  397. serializers [partDesc] = serializerBehavior.CreateSerializer(
  398. partDesc.Type, partDesc.Name, partDesc.Namespace, OperationKnownTypes as IList<Type>);
  399. else
  400. #endif
  401. serializers [partDesc] = new DataContractSerializer (
  402. partDesc.Type, partDesc.Name, partDesc.Namespace, OperationKnownTypes);
  403. return serializers [partDesc];
  404. }
  405. object ReadHeaderObject (Type type, XmlObjectSerializer serializer, XmlDictionaryReader reader)
  406. {
  407. // FIXME: it's a nasty workaround just to avoid UniqueId output as a string.
  408. // Seealso MessageHeader.DefaultMessageHeader.OnWriteHeaderContents().
  409. // Note that msg.Headers.GetHeader<UniqueId> () simply fails (on .NET too) and it is useless. The API is lame by design.
  410. if (type == typeof (UniqueId))
  411. return new UniqueId (reader.ReadElementContentAsString ());
  412. else
  413. return serializer.ReadObject (reader);
  414. }
  415. class DataContractBodyWriter : BodyWriter
  416. {
  417. MessageBodyDescription desc;
  418. object [] parts;
  419. DataContractMessagesFormatter parent;
  420. public DataContractBodyWriter (MessageBodyDescription desc, DataContractMessagesFormatter parent, object [] parts)
  421. : base (false)
  422. {
  423. this.desc = desc;
  424. this.parent = parent;
  425. this.parts = parts;
  426. }
  427. protected override void OnWriteBodyContents (XmlDictionaryWriter writer)
  428. {
  429. int offset = HasReturnValue (desc) ? 1 : 0;
  430. if (desc.WrapperName != null)
  431. writer.WriteStartElement (desc.WrapperName, desc.WrapperNamespace);
  432. if (HasReturnValue (desc))
  433. WriteMessagePart (writer, desc, desc.ReturnValue, parts [0]);
  434. foreach (MessagePartDescription partDesc in desc.Parts)
  435. WriteMessagePart (writer, desc, partDesc, parts [partDesc.Index + offset]);
  436. if (desc.WrapperName != null)
  437. writer.WriteEndElement ();
  438. }
  439. void WriteMessagePart (
  440. XmlDictionaryWriter writer, MessageBodyDescription desc, MessagePartDescription partDesc, object obj)
  441. {
  442. // FIXME: it seems TransferMode.Streamed* has different serialization than .Buffered. Need to differentiate serialization somewhere (not limited to here).
  443. if (partDesc.Type == typeof (Stream)) {
  444. writer.WriteStartElement (partDesc.Name, partDesc.Namespace);
  445. writer.WriteValue (new StreamProvider ((Stream) obj));
  446. writer.WriteEndElement ();
  447. }
  448. else
  449. parent.GetSerializer (partDesc).WriteObject (writer, obj);
  450. }
  451. }
  452. class StreamProvider : IStreamProvider
  453. {
  454. Stream s;
  455. bool busy;
  456. public StreamProvider (Stream s)
  457. {
  458. this.s = s;
  459. }
  460. public Stream GetStream ()
  461. {
  462. if (busy)
  463. throw new InvalidOperationException ("Stream is already in use.");
  464. busy = true;
  465. return s;
  466. }
  467. public void ReleaseStream (Stream stream)
  468. {
  469. if (stream == null)
  470. throw new ArgumentNullException ("stream");
  471. if (this.s != stream)
  472. throw new ArgumentException ("Incorrect parameter stream");
  473. busy = false;
  474. }
  475. }
  476. }
  477. }