2
0

MessageHeaders.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439
  1. //
  2. // System.ServiceModel.MessageHeader.cs
  3. //
  4. // Author: Duncan Mak ([email protected])
  5. //
  6. // Copyright (C) 2005 Novell, Inc (http://www.novell.com)
  7. //
  8. // Permission is hereby granted, free of charge, to any person obtaining
  9. // a copy of this software and associated documentation files (the
  10. // "Software"), to deal in the Software without restriction, including
  11. // without limitation the rights to use, copy, modify, merge, publish,
  12. // distribute, sublicense, and/or sell copies of the Software, and to
  13. // permit persons to whom the Software is furnished to do so, subject to
  14. // the following conditions:
  15. //
  16. // The above copyright notice and this permission notice shall be
  17. // included in all copies or substantial portions of the Software.
  18. //
  19. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  20. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  21. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  22. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  23. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  24. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  25. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  26. //
  27. using System;
  28. using System.Collections;
  29. using System.Collections.Generic;
  30. using System.IO;
  31. using System.Runtime.Serialization;
  32. using System.ServiceModel;
  33. using System.Xml;
  34. namespace System.ServiceModel.Channels
  35. {
  36. public sealed class MessageHeaders : IEnumerable<MessageHeaderInfo>, IEnumerable
  37. {
  38. static string [] empty_strings = new string [0];
  39. static readonly XmlReaderSettings reader_settings;
  40. static MessageHeaders ()
  41. {
  42. reader_settings = new XmlReaderSettings ();
  43. reader_settings.ConformanceLevel = ConformanceLevel.Fragment;
  44. }
  45. List<MessageHeaderInfo> l;
  46. Dictionary<Type, XmlObjectSerializer> serializers =
  47. new Dictionary<Type, XmlObjectSerializer> ();
  48. MessageVersion version;
  49. public MessageHeaders (MessageHeaders headers)
  50. : this (headers.MessageVersion)
  51. {
  52. CopyHeadersFrom (headers);
  53. }
  54. public MessageHeaders (MessageVersion version)
  55. : this (version, 10) // let's say 10 is the initial size
  56. {
  57. }
  58. public MessageHeaders (MessageVersion version, int capacity)
  59. {
  60. this.version = version;
  61. l = new List<MessageHeaderInfo> (capacity);
  62. }
  63. public void Add (MessageHeader header)
  64. {
  65. l.Add (header);
  66. }
  67. public void CopyHeaderFrom (Message m, int index)
  68. {
  69. CopyHeaderFrom (m.Headers, index);
  70. }
  71. public void Clear ()
  72. {
  73. l.Clear ();
  74. }
  75. public void CopyHeaderFrom (MessageHeaders headers, int index)
  76. {
  77. l.Add (headers [index]);
  78. }
  79. public void CopyHeadersFrom (Message m)
  80. {
  81. CopyHeadersFrom (m.Headers);
  82. }
  83. public void CopyHeadersFrom (MessageHeaders headers)
  84. {
  85. foreach (MessageHeaderInfo h in headers)
  86. l.Add (h);
  87. }
  88. public void CopyTo (MessageHeaderInfo [] dst, int index)
  89. {
  90. l.CopyTo (dst, index);
  91. }
  92. public int FindHeader (string name, string ns)
  93. {
  94. return FindHeader (name, ns, null);
  95. }
  96. bool HasActor (string actor, string [] candidates)
  97. {
  98. foreach (string c in candidates)
  99. if (c == actor)
  100. return true;
  101. return false;
  102. }
  103. public int FindHeader (string name, string ns, params string [] actors)
  104. {
  105. int found = 0;
  106. int retval = -1;
  107. for (int i = 0; i < l.Count; i++) {
  108. MessageHeaderInfo info = l [i];
  109. if (info.Name == name && info.Namespace == ns) {
  110. if (found > 1)
  111. throw new ArgumentException ("Found multiple matching headers.");
  112. // When no actors are passed, it never
  113. // matches such header that has an
  114. // Actor.
  115. if (actors == null && info.Actor == String.Empty ||
  116. actors != null && HasActor (info.Actor, actors)) {
  117. retval = i;
  118. found++;
  119. }
  120. }
  121. }
  122. return retval;
  123. }
  124. public IEnumerator<MessageHeaderInfo> GetEnumerator ()
  125. {
  126. return l.GetEnumerator ();
  127. }
  128. XmlObjectSerializer GetSerializer<T> (int headerIndex)
  129. {
  130. if (!serializers.ContainsKey (typeof (T)))
  131. serializers [typeof (T)] = new DataContractSerializer (typeof (T), this [headerIndex].Name, this [headerIndex].Namespace);
  132. return serializers [typeof (T)];
  133. }
  134. public T GetHeader<T> (int index)
  135. {
  136. if (l.Count <= index)
  137. throw new ArgumentOutOfRangeException ("index");
  138. var dmh = l [index] as MessageHeader.DefaultMessageHeader;
  139. if (dmh != null && dmh.Value != null && typeof (T).IsAssignableFrom (dmh.Value.GetType ()))
  140. return (T) dmh.Value;
  141. if (typeof (T) == typeof (EndpointAddress)) {
  142. XmlDictionaryReader r = GetReaderAtHeader (index);
  143. return r.NodeType != XmlNodeType.Element ? default (T) : (T) (object) EndpointAddress.ReadFrom (r);
  144. }
  145. else
  146. return GetHeader<T> (index, GetSerializer<T> (index));
  147. }
  148. public T GetHeader<T> (int index, XmlObjectSerializer serializer)
  149. {
  150. if (serializer == null)
  151. throw new ArgumentNullException ("serializer");
  152. XmlDictionaryReader r = GetReaderAtHeader (index);
  153. return (T) serializer.ReadObject (r, false);
  154. }
  155. public T GetHeader<T> (string name, string ns)
  156. {
  157. return GetHeader<T> (name, ns, empty_strings);
  158. }
  159. public T GetHeader<T> (string name, string ns, params string [] actors)
  160. {
  161. int idx = FindHeader (name, ns, actors);
  162. if (idx == -1)
  163. throw new MessageHeaderException (String.Format ("Header '{0}:{1}' was not found for the argument actors: {2}", ns, name, String.Join (",", actors)));
  164. return GetHeader<T> (idx);
  165. }
  166. public T GetHeader<T> (string name, string ns, XmlObjectSerializer serializer)
  167. {
  168. if (serializer == null)
  169. throw new ArgumentNullException ("serializer");
  170. int idx = FindHeader (name, ns);
  171. if (idx < 0)
  172. throw new MessageHeaderException (String.Format ("Header '{0}:{1}' was not found", ns, name));
  173. return GetHeader<T> (idx, serializer);
  174. }
  175. public XmlDictionaryReader GetReaderAtHeader (int index)
  176. {
  177. if (index >= l.Count)
  178. throw new ArgumentOutOfRangeException (String.Format ("Index is out of range. Current header count is {0}", index));
  179. MessageHeader item = (MessageHeader) l [index];
  180. XmlReader reader =
  181. item is MessageHeader.RawMessageHeader ?
  182. ((MessageHeader.RawMessageHeader) item).CreateReader () :
  183. XmlReader.Create (
  184. new StringReader (item.ToString ()),
  185. reader_settings);
  186. reader.MoveToContent ();
  187. XmlDictionaryReader dr = XmlDictionaryReader.CreateDictionaryReader (reader);
  188. dr.MoveToContent ();
  189. return dr;
  190. }
  191. public bool HaveMandatoryHeadersBeenUnderstood ()
  192. {
  193. throw new NotImplementedException ();
  194. }
  195. public bool HaveMandatoryHeadersBeenUnderstood (params string [] actors)
  196. {
  197. throw new NotImplementedException ();
  198. }
  199. public void Insert (int index, MessageHeader header)
  200. {
  201. l.Insert (index, header);
  202. }
  203. public void RemoveAll (string name, string ns)
  204. {
  205. // Shuffle all the ones we want to keep to the start of the list
  206. int j = 0;
  207. for (int i = 0; i < l.Count; i++) {
  208. if (l[i].Name != name || l[i].Namespace != ns) {
  209. l [j++] = l[i];
  210. }
  211. }
  212. // Trim the extra elements off the end of the list.
  213. int count = l.Count - j;
  214. for (int i = 0; i < count; i++)
  215. l.RemoveAt (l.Count - 1);
  216. }
  217. public void RemoveAt (int index)
  218. {
  219. l.RemoveAt (index);
  220. }
  221. IEnumerator IEnumerable.GetEnumerator ()
  222. {
  223. return ((IEnumerable) l).GetEnumerator ();
  224. }
  225. public void WriteHeader (int index, XmlDictionaryWriter writer)
  226. {
  227. if (version.Envelope == EnvelopeVersion.None)
  228. return;
  229. // For AddressingVersion.None, don't output the item.
  230. //
  231. // FIXME: It should even ignore Action, but for now
  232. // service dispatcher won't work without it.
  233. if (version.Addressing == AddressingVersion.None &&
  234. l [index].Name != "Action")
  235. return;
  236. WriteStartHeader (index, writer);
  237. WriteHeaderContents (index, writer);
  238. writer.WriteEndElement ();
  239. }
  240. public void WriteHeader (int index, XmlWriter writer)
  241. {
  242. WriteHeader (index, XmlDictionaryWriter.CreateDictionaryWriter (writer));
  243. }
  244. public void WriteHeaderContents (int index, XmlDictionaryWriter writer)
  245. {
  246. if (index > l.Count)
  247. throw new ArgumentOutOfRangeException ("There is no header at position " + index + ".");
  248. MessageHeader h = l [index] as MessageHeader;
  249. h.WriteHeaderContents (writer, version);
  250. }
  251. public void WriteHeaderContents (int index, XmlWriter writer)
  252. {
  253. WriteHeaderContents (index, XmlDictionaryWriter.CreateDictionaryWriter (writer));
  254. }
  255. public void WriteStartHeader (int index, XmlDictionaryWriter writer)
  256. {
  257. if (index > l.Count)
  258. throw new ArgumentOutOfRangeException ("There is no header at position " + index + ".");
  259. MessageHeader h = l [index] as MessageHeader;
  260. h.WriteStartHeader (writer, version);
  261. }
  262. public void WriteStartHeader (int index, XmlWriter writer)
  263. {
  264. WriteStartHeader (index, XmlDictionaryWriter.CreateDictionaryWriter (writer));
  265. }
  266. public string Action {
  267. get {
  268. int idx = FindHeader ("Action", version.Addressing.Namespace);
  269. return idx < 0 ? null : GetHeader<string> (idx);
  270. }
  271. set {
  272. RemoveAll ("Action", version.Addressing.Namespace);
  273. if (value != null)
  274. Add (MessageHeader.CreateHeader ("Action", version.Addressing.Namespace, value, true));
  275. }
  276. }
  277. public int Count {
  278. get { return l.Count; }
  279. }
  280. #if !NET_2_1
  281. public EndpointAddress FaultTo {
  282. get {
  283. int idx = FindHeader ("FaultTo", Constants.WSA1);
  284. return idx < 0 ? null : GetHeader<EndpointAddress> (idx);
  285. }
  286. set {
  287. if (version.Addressing == AddressingVersion.None)
  288. throw new InvalidOperationException ("WS-Addressing header is not allowed for AddressingVersion.None");
  289. RemoveAll ("FaultTo", Constants.WSA1);
  290. if (value != null)
  291. Add (MessageHeader.CreateHeader ("FaultTo", Constants.WSA1, EndpointAddress10.FromEndpointAddress (value)));
  292. }
  293. }
  294. public EndpointAddress From {
  295. get {
  296. int idx = FindHeader ("From", version.Addressing.Namespace);
  297. return idx < 0 ? null : GetHeader<EndpointAddress> (idx);
  298. }
  299. set {
  300. if (version.Addressing == AddressingVersion.None)
  301. throw new InvalidOperationException ("WS-Addressing header is not allowed for AddressingVersion.None");
  302. RemoveAll ("From", Constants.WSA1);
  303. if (value != null)
  304. Add (MessageHeader.CreateHeader ("From", Constants.WSA1, EndpointAddress10.FromEndpointAddress (value)));
  305. }
  306. }
  307. #endif
  308. public MessageHeaderInfo this [int index] {
  309. get { return l [index]; }
  310. }
  311. public UniqueId MessageId {
  312. get {
  313. int idx = FindHeader ("MessageID", Constants.WSA1);
  314. return idx < 0 ? null : new UniqueId (GetHeader<string> (idx));
  315. }
  316. set {
  317. if (version.Addressing == AddressingVersion.None)
  318. throw new InvalidOperationException ("WS-Addressing header is not allowed for AddressingVersion.None");
  319. RemoveAll ("MessageID", Constants.WSA1);
  320. if (value != null)
  321. Add (MessageHeader.CreateHeader ("MessageID", Constants.WSA1, value.ToString ()));
  322. }
  323. }
  324. public MessageVersion MessageVersion { get { return version; } }
  325. public UniqueId RelatesTo {
  326. get {
  327. int idx = FindHeader ("RelatesTo", Constants.WSA1);
  328. return idx < 0 ? null : new UniqueId (GetHeader<string> (idx));
  329. }
  330. set {
  331. if (version.Addressing == AddressingVersion.None)
  332. throw new InvalidOperationException ("WS-Addressing header is not allowed for AddressingVersion.None");
  333. RemoveAll ("MessageID", Constants.WSA1);
  334. if (value != null)
  335. Add (MessageHeader.CreateHeader ("RelatesTo", Constants.WSA1, value.ToString ()));
  336. }
  337. }
  338. #if !NET_2_1
  339. public EndpointAddress ReplyTo {
  340. get {
  341. int idx = FindHeader ("ReplyTo", Constants.WSA1);
  342. return idx < 0 ? null : GetHeader<EndpointAddress> (idx);
  343. }
  344. set {
  345. if (version.Addressing == AddressingVersion.None)
  346. throw new InvalidOperationException ("WS-Addressing header is not allowed for AddressingVersion.None");
  347. RemoveAll ("ReplyTo", Constants.WSA1);
  348. if (value != null)
  349. Add (MessageHeader.CreateHeader ("ReplyTo", Constants.WSA1, EndpointAddress10.FromEndpointAddress (value)));
  350. }
  351. }
  352. #endif
  353. public Uri To {
  354. get {
  355. int idx = FindHeader ("To", version.Addressing.Namespace);
  356. //FIXME: return idx < 0 ? null : GetHeader<Uri> (idx);
  357. return idx < 0 ? null : new Uri (GetHeader<string> (idx));
  358. }
  359. set {
  360. RemoveAll ("To", version.Addressing.Namespace);
  361. if (value != null)
  362. Add (MessageHeader.CreateHeader ("To", version.Addressing.Namespace, value.AbsoluteUri, true));
  363. }
  364. }
  365. [MonoTODO]
  366. public UnderstoodHeaders UnderstoodHeaders {
  367. get { throw new NotImplementedException (); }
  368. }
  369. }
  370. }