SoapHttpClientProtocol.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438
  1. //
  2. // System.Web.Services.Protocols.SoapHttpClientProtocol.cs
  3. //
  4. // Author:
  5. // Tim Coleman ([email protected])
  6. // Miguel de Icaza ([email protected])
  7. // Lluis Sanchez Gual ([email protected])
  8. //
  9. // Copyright (C) Tim Coleman, 2002
  10. // Copyright (C) Ximian, Inc, 2003
  11. //
  12. //
  13. // Permission is hereby granted, free of charge, to any person obtaining
  14. // a copy of this software and associated documentation files (the
  15. // "Software"), to deal in the Software without restriction, including
  16. // without limitation the rights to use, copy, modify, merge, publish,
  17. // distribute, sublicense, and/or sell copies of the Software, and to
  18. // permit persons to whom the Software is furnished to do so, subject to
  19. // the following conditions:
  20. //
  21. // The above copyright notice and this permission notice shall be
  22. // included in all copies or substantial portions of the Software.
  23. //
  24. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  25. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  26. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  27. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  28. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  29. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  30. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  31. //
  32. using System.ComponentModel;
  33. using System.IO;
  34. using System.Net;
  35. using System.Web;
  36. using System.Xml;
  37. using System.Text;
  38. using System.Reflection;
  39. using System.Web.Services;
  40. using System.Diagnostics;
  41. using System.Runtime.CompilerServices;
  42. using System.Web.Services.Description;
  43. using System.Web.Services.Discovery;
  44. using System.Xml.Serialization;
  45. using System.Xml.Schema;
  46. using System.Collections;
  47. using System.Threading;
  48. namespace System.Web.Services.Protocols
  49. {
  50. #if NET_2_0
  51. [System.Runtime.InteropServices.ComVisible (true)]
  52. #endif
  53. public class SoapHttpClientProtocol : HttpWebClientProtocol
  54. {
  55. SoapTypeStubInfo type_info;
  56. #if NET_2_0
  57. SoapProtocolVersion soapVersion;
  58. #endif
  59. #region SoapWebClientAsyncResult class
  60. internal class SoapWebClientAsyncResult: WebClientAsyncResult
  61. {
  62. public SoapWebClientAsyncResult (WebRequest request, AsyncCallback callback, object asyncState)
  63. : base (request, callback, asyncState)
  64. {
  65. }
  66. public SoapClientMessage Message;
  67. public SoapExtension[] Extensions;
  68. }
  69. #endregion
  70. #region Constructors
  71. public SoapHttpClientProtocol ()
  72. {
  73. type_info = (SoapTypeStubInfo) TypeStubManager.GetTypeStub (this.GetType (), "Soap");
  74. }
  75. #endregion // Constructors
  76. #region Methods
  77. protected IAsyncResult BeginInvoke (string methodName, object[] parameters, AsyncCallback callback, object asyncState)
  78. {
  79. SoapMethodStubInfo msi = (SoapMethodStubInfo) type_info.GetMethod (methodName);
  80. SoapWebClientAsyncResult ainfo = null;
  81. try
  82. {
  83. SoapClientMessage message = new SoapClientMessage (this, msi, Url, parameters);
  84. message.CollectHeaders (this, message.MethodStubInfo.Headers, SoapHeaderDirection.In);
  85. WebRequest request = GetRequestForMessage (uri, message);
  86. ainfo = new SoapWebClientAsyncResult (request, callback, asyncState);
  87. ainfo.Message = message;
  88. ainfo.Extensions = SoapExtension.CreateExtensionChain (type_info.SoapExtensions[0], msi.SoapExtensions, type_info.SoapExtensions[1]);
  89. ainfo.Request.BeginGetRequestStream (new AsyncCallback (AsyncGetRequestStreamDone), ainfo);
  90. }
  91. catch (Exception ex)
  92. {
  93. if (ainfo != null)
  94. ainfo.SetCompleted (null, ex, false);
  95. }
  96. return ainfo;
  97. }
  98. void AsyncGetRequestStreamDone (IAsyncResult ar)
  99. {
  100. SoapWebClientAsyncResult ainfo = (SoapWebClientAsyncResult) ar.AsyncState;
  101. try
  102. {
  103. SendRequest (ainfo.Request.EndGetRequestStream (ar), ainfo.Message, ainfo.Extensions);
  104. ainfo.Request.BeginGetResponse (new AsyncCallback (AsyncGetResponseDone), ainfo);
  105. }
  106. catch (Exception ex)
  107. {
  108. ainfo.SetCompleted (null, ex, true);
  109. }
  110. }
  111. void AsyncGetResponseDone (IAsyncResult ar)
  112. {
  113. SoapWebClientAsyncResult ainfo = (SoapWebClientAsyncResult) ar.AsyncState;
  114. WebResponse response = null;
  115. try {
  116. response = GetWebResponse (ainfo.Request, ar);
  117. }
  118. catch (WebException ex) {
  119. response = ex.Response;
  120. HttpWebResponse http_response = response as HttpWebResponse;
  121. if (http_response == null || http_response.StatusCode != HttpStatusCode.InternalServerError) {
  122. ainfo.SetCompleted (null, ex, true);
  123. return;
  124. }
  125. }
  126. catch (Exception ex) {
  127. ainfo.SetCompleted (null, ex, true);
  128. return;
  129. }
  130. try {
  131. object[] result = ReceiveResponse (response, ainfo.Message, ainfo.Extensions);
  132. ainfo.SetCompleted (result, null, true);
  133. }
  134. catch (Exception ex) {
  135. ainfo.SetCompleted (null, ex, true);
  136. }
  137. finally {
  138. response.Close();
  139. }
  140. }
  141. protected object[] EndInvoke (IAsyncResult asyncResult)
  142. {
  143. if (!(asyncResult is SoapWebClientAsyncResult)) throw new ArgumentException ("asyncResult is not the return value from BeginInvoke");
  144. SoapWebClientAsyncResult ainfo = (SoapWebClientAsyncResult) asyncResult;
  145. lock (ainfo)
  146. {
  147. if (!ainfo.IsCompleted) ainfo.WaitForComplete ();
  148. if (ainfo.Exception != null) throw ainfo.Exception;
  149. else return (object[]) ainfo.Result;
  150. }
  151. }
  152. public void Discover ()
  153. {
  154. BindingInfo bnd = (BindingInfo) type_info.Bindings [0];
  155. DiscoveryClientProtocol discoverer = new DiscoveryClientProtocol ();
  156. discoverer.Discover (Url);
  157. foreach (object info in discoverer.AdditionalInformation)
  158. {
  159. System.Web.Services.Discovery.SoapBinding sb = info as System.Web.Services.Discovery.SoapBinding;
  160. if (sb != null && sb.Binding.Name == bnd.Name && sb.Binding.Namespace == bnd.Namespace) {
  161. Url = sb.Address;
  162. return;
  163. }
  164. }
  165. string msg = string.Format ("The binding named '{0}' from namespace '{1}' was not found in the discovery document at '{2}'", bnd.Name, bnd.Namespace, Url);
  166. throw new Exception (msg);
  167. }
  168. protected override WebRequest GetWebRequest (Uri uri)
  169. {
  170. return base.GetWebRequest (uri);
  171. }
  172. WebRequest GetRequestForMessage (Uri uri, SoapClientMessage message)
  173. {
  174. WebRequest request = GetWebRequest (uri);
  175. request.Method = "POST";
  176. WebHeaderCollection headers = request.Headers;
  177. headers.Add ("SOAPAction", "\"" + message.Action + "\"");
  178. request.ContentType = message.ContentType + "; charset=utf-8";
  179. return request;
  180. }
  181. #if NET_2_0
  182. [MonoTODO]
  183. protected virtual
  184. #endif
  185. XmlReader GetReaderForMessage (
  186. SoapClientMessage message, int bufferSize)
  187. {
  188. throw new NotImplementedException ();
  189. }
  190. #if NET_2_0
  191. [MonoTODO]
  192. protected virtual
  193. #endif
  194. XmlWriter GetWriterForMessage (
  195. SoapClientMessage message, int bufferSize)
  196. {
  197. throw new NotImplementedException ();
  198. }
  199. void SendRequest (Stream s, SoapClientMessage message, SoapExtension[] extensions)
  200. {
  201. using (s) {
  202. if (extensions != null) {
  203. s = SoapExtension.ExecuteChainStream (extensions, s);
  204. message.SetStage (SoapMessageStage.BeforeSerialize);
  205. SoapExtension.ExecuteProcessMessage (extensions, message, s, true);
  206. }
  207. XmlTextWriter xtw = WebServiceHelper.CreateXmlWriter (s);
  208. #if NET_2_0
  209. bool soap12 = message.SoapVersion == SoapProtocolVersion.Soap12;
  210. #else
  211. bool soap12 = false;
  212. #endif
  213. WebServiceHelper.WriteSoapMessage (xtw, message.MethodStubInfo, SoapHeaderDirection.In, message.Parameters, message.Headers, soap12);
  214. if (extensions != null) {
  215. message.SetStage (SoapMessageStage.AfterSerialize);
  216. SoapExtension.ExecuteProcessMessage (extensions, message, s, true);
  217. }
  218. xtw.Flush ();
  219. xtw.Close ();
  220. }
  221. }
  222. //
  223. // TODO:
  224. // Handle other web responses (multi-output?)
  225. //
  226. object [] ReceiveResponse (WebResponse response, SoapClientMessage message, SoapExtension[] extensions)
  227. {
  228. SoapMethodStubInfo msi = message.MethodStubInfo;
  229. HttpWebResponse http_response = response as HttpWebResponse;
  230. if (http_response != null)
  231. {
  232. HttpStatusCode code = http_response.StatusCode;
  233. if (!(code == HttpStatusCode.Accepted || code == HttpStatusCode.OK || code == HttpStatusCode.InternalServerError)) {
  234. string msg = "The request failed with HTTP status {0}: {1}";
  235. msg = String.Format (msg, (int) code, code);
  236. throw new WebException (msg, null, WebExceptionStatus.ProtocolError, http_response);
  237. }
  238. if (message.OneWay && response.ContentLength <= 0 && (code == HttpStatusCode.Accepted || code == HttpStatusCode.OK)) {
  239. return new object[0];
  240. }
  241. }
  242. //
  243. // Remove optional encoding
  244. //
  245. string ctype;
  246. Encoding encoding = WebServiceHelper.GetContentEncoding (response.ContentType, out ctype);
  247. string expectedCType =
  248. #if NET_2_0
  249. (message.SoapVersion == SoapProtocolVersion.Soap12 ? "application/soap+xml" : "text/xml");
  250. #else
  251. "text/xml";
  252. #endif
  253. if (ctype != expectedCType)
  254. WebServiceHelper.InvalidOperation (
  255. String.Format ("Content is not '{0}' but '{1}'", expectedCType, response.ContentType),
  256. response, encoding);
  257. message.ContentType = ctype;
  258. message.ContentEncoding = encoding.WebName;
  259. Stream stream = response.GetResponseStream ();
  260. if (extensions != null) {
  261. stream = SoapExtension.ExecuteChainStream (extensions, stream);
  262. message.SetStage (SoapMessageStage.BeforeDeserialize);
  263. SoapExtension.ExecuteProcessMessage (extensions, message, stream, false);
  264. }
  265. // Deserialize the response
  266. SoapHeaderCollection headers;
  267. object content;
  268. using (StreamReader reader = new StreamReader (stream, encoding, false)) {
  269. XmlTextReader xml_reader = new XmlTextReader (reader);
  270. WebServiceHelper.ReadSoapMessage (xml_reader, msi, SoapHeaderDirection.Out, out content, out headers);
  271. }
  272. #if NET_2_0
  273. if (content is Soap12Fault)
  274. {
  275. Soap12Fault fault = (Soap12Fault) content;
  276. Soap12FaultReasonText text =
  277. fault.Reason != null &&
  278. fault.Reason.Texts != null &&
  279. fault.Reason.Texts.Length > 0 ?
  280. fault.Reason.Texts [fault.Reason.Texts.Length - 1] : null;
  281. XmlNode detail = (fault.Detail == null) ? null :
  282. (fault.Detail.Children != null &&
  283. fault.Detail.Children.Length > 0) ?
  284. (XmlNode) fault.Detail.Children [0] :
  285. (fault.Detail.Attributes != null &&
  286. fault.Detail.Attributes.Length > 0) ?
  287. fault.Detail.Attributes [0] : null;
  288. SoapFaultSubCode subcode = Soap12Fault.GetSoapFaultSubCode (fault.Code.Subcode);
  289. SoapException ex = new SoapException (
  290. text != null ? text.Value : null,
  291. fault.Code.Value, null, fault.Role,
  292. text != null ? text.XmlLang : null,
  293. detail, subcode, null);
  294. message.SetException (ex);
  295. }
  296. else
  297. #endif
  298. if (content is Fault)
  299. {
  300. Fault fault = (Fault) content;
  301. SoapException ex = new SoapException (fault.faultstring, fault.faultcode, fault.faultactor, fault.detail);
  302. message.SetException (ex);
  303. }
  304. else
  305. message.OutParameters = (object[]) content;
  306. message.SetHeaders (headers);
  307. message.UpdateHeaderValues (this, message.MethodStubInfo.Headers);
  308. if (extensions != null) {
  309. message.SetStage (SoapMessageStage.AfterDeserialize);
  310. SoapExtension.ExecuteProcessMessage (extensions, message, stream, false);
  311. }
  312. if (message.Exception == null)
  313. return message.OutParameters;
  314. else
  315. throw message.Exception;
  316. }
  317. protected object[] Invoke (string method_name, object[] parameters)
  318. {
  319. SoapMethodStubInfo msi = (SoapMethodStubInfo) type_info.GetMethod (method_name);
  320. SoapClientMessage message = new SoapClientMessage (this, msi, Url, parameters);
  321. message.CollectHeaders (this, message.MethodStubInfo.Headers, SoapHeaderDirection.In);
  322. SoapExtension[] extensions = SoapExtension.CreateExtensionChain (type_info.SoapExtensions[0], msi.SoapExtensions, type_info.SoapExtensions[1]);
  323. WebResponse response;
  324. try
  325. {
  326. WebRequest request = GetRequestForMessage (uri, message);
  327. SendRequest (request.GetRequestStream (), message, extensions);
  328. response = GetWebResponse (request);
  329. }
  330. catch (WebException ex)
  331. {
  332. response = ex.Response;
  333. HttpWebResponse http_response = response as HttpWebResponse;
  334. if (http_response == null || http_response.StatusCode != HttpStatusCode.InternalServerError)
  335. throw ex;
  336. }
  337. try {
  338. return ReceiveResponse (response, message, extensions);
  339. }
  340. finally {
  341. response.Close();
  342. }
  343. }
  344. #if NET_2_0
  345. [MonoTODO ("Do something with this")]
  346. [System.Runtime.InteropServices.ComVisible(false)]
  347. [DefaultValue (SoapProtocolVersion.Default)]
  348. public SoapProtocolVersion SoapVersion {
  349. get { return soapVersion; }
  350. set { soapVersion = value; }
  351. }
  352. protected void InvokeAsync (string methodName, object[] parameters, SendOrPostCallback callback)
  353. {
  354. InvokeAsync (methodName, parameters, callback, null);
  355. }
  356. protected void InvokeAsync (string methodName, object[] parameters, SendOrPostCallback callback, object userState)
  357. {
  358. InvokeAsyncInfo info = new InvokeAsyncInfo (callback, userState);
  359. BeginInvoke (methodName, parameters, new AsyncCallback (InvokeAsyncCallback), info);
  360. }
  361. void InvokeAsyncCallback (IAsyncResult ar)
  362. {
  363. InvokeAsyncInfo info = (InvokeAsyncInfo) ar.AsyncState;
  364. SoapWebClientAsyncResult sar = (SoapWebClientAsyncResult) ar;
  365. InvokeCompletedEventArgs args = new InvokeCompletedEventArgs (sar.Exception, false, info.UserState, (object[]) sar.Result);
  366. if (info.Context != null)
  367. info.Context.Send (info.Callback, args);
  368. else
  369. info.Callback (args);
  370. }
  371. #endif
  372. #endregion // Methods
  373. }
  374. }