SoapHttpClientProtocol.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421
  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. RegisterMapping (asyncState, ainfo);
  91. }
  92. catch (Exception ex)
  93. {
  94. if (ainfo != null)
  95. ainfo.SetCompleted (null, ex, false);
  96. }
  97. return ainfo;
  98. }
  99. void AsyncGetRequestStreamDone (IAsyncResult ar)
  100. {
  101. SoapWebClientAsyncResult ainfo = (SoapWebClientAsyncResult) ar.AsyncState;
  102. try
  103. {
  104. SendRequest (ainfo.Request.EndGetRequestStream (ar), ainfo.Message, ainfo.Extensions);
  105. ainfo.Request.BeginGetResponse (new AsyncCallback (AsyncGetResponseDone), ainfo);
  106. }
  107. catch (Exception ex)
  108. {
  109. ainfo.SetCompleted (null, ex, true);
  110. }
  111. }
  112. void AsyncGetResponseDone (IAsyncResult ar)
  113. {
  114. SoapWebClientAsyncResult ainfo = (SoapWebClientAsyncResult) ar.AsyncState;
  115. WebResponse response = null;
  116. try {
  117. response = GetWebResponse (ainfo.Request, ar);
  118. }
  119. catch (WebException ex) {
  120. response = ex.Response;
  121. HttpWebResponse http_response = response as HttpWebResponse;
  122. if (http_response == null || http_response.StatusCode != HttpStatusCode.InternalServerError) {
  123. ainfo.SetCompleted (null, ex, true);
  124. return;
  125. }
  126. }
  127. catch (Exception ex) {
  128. ainfo.SetCompleted (null, ex, true);
  129. return;
  130. }
  131. try {
  132. object[] result = ReceiveResponse (response, ainfo.Message, ainfo.Extensions);
  133. ainfo.SetCompleted (result, null, true);
  134. }
  135. catch (Exception ex) {
  136. ainfo.SetCompleted (null, ex, true);
  137. }
  138. finally {
  139. response.Close();
  140. }
  141. }
  142. protected object[] EndInvoke (IAsyncResult asyncResult)
  143. {
  144. if (!(asyncResult is SoapWebClientAsyncResult)) throw new ArgumentException ("asyncResult is not the return value from BeginInvoke");
  145. SoapWebClientAsyncResult ainfo = (SoapWebClientAsyncResult) asyncResult;
  146. lock (ainfo)
  147. {
  148. if (!ainfo.IsCompleted)
  149. ainfo.WaitForComplete ();
  150. UnregisterMapping (ainfo.AsyncState);
  151. if (ainfo.Exception != null)
  152. throw ainfo.Exception;
  153. else
  154. return (object[]) ainfo.Result;
  155. }
  156. }
  157. public void Discover ()
  158. {
  159. BindingInfo bnd = (BindingInfo) type_info.Bindings [0];
  160. DiscoveryClientProtocol discoverer = new DiscoveryClientProtocol ();
  161. discoverer.Discover (Url);
  162. foreach (object info in discoverer.AdditionalInformation)
  163. {
  164. System.Web.Services.Discovery.SoapBinding sb = info as System.Web.Services.Discovery.SoapBinding;
  165. if (sb != null && sb.Binding.Name == bnd.Name && sb.Binding.Namespace == bnd.Namespace) {
  166. Url = sb.Address;
  167. return;
  168. }
  169. }
  170. string msg = string.Format (
  171. "The binding named '{0}' from namespace '{1}' was not found in the discovery document at '{2}'",
  172. bnd.Name, bnd.Namespace, Url);
  173. throw new Exception (msg);
  174. }
  175. protected override WebRequest GetWebRequest (Uri uri)
  176. {
  177. return base.GetWebRequest (uri);
  178. }
  179. WebRequest GetRequestForMessage (Uri uri, SoapClientMessage message)
  180. {
  181. WebRequest request = GetWebRequest (uri);
  182. request.Method = "POST";
  183. WebHeaderCollection headers = request.Headers;
  184. if (!message.IsSoap12)
  185. headers.Add ("SOAPAction", "\"" + message.Action + "\"");
  186. request.ContentType = message.ContentType + "; charset=utf-8";
  187. return request;
  188. }
  189. #if NET_2_0
  190. [MonoTODO]
  191. protected virtual
  192. #endif
  193. XmlReader GetReaderForMessage (
  194. SoapClientMessage message, int bufferSize)
  195. {
  196. throw new NotImplementedException ();
  197. }
  198. #if NET_2_0
  199. [MonoTODO]
  200. protected virtual
  201. #endif
  202. XmlWriter GetWriterForMessage (
  203. SoapClientMessage message, int bufferSize)
  204. {
  205. throw new NotImplementedException ();
  206. }
  207. void SendRequest (Stream s, SoapClientMessage message, SoapExtension[] extensions)
  208. {
  209. using (s) {
  210. if (extensions != null) {
  211. s = SoapExtension.ExecuteChainStream (extensions, s);
  212. message.SetStage (SoapMessageStage.BeforeSerialize);
  213. SoapExtension.ExecuteProcessMessage (extensions, message, s, true);
  214. }
  215. XmlTextWriter xtw = WebServiceHelper.CreateXmlWriter (s);
  216. WebServiceHelper.WriteSoapMessage (xtw, message.MethodStubInfo, SoapHeaderDirection.In, message.Parameters, message.Headers, message.IsSoap12);
  217. if (extensions != null) {
  218. message.SetStage (SoapMessageStage.AfterSerialize);
  219. SoapExtension.ExecuteProcessMessage (extensions, message, s, true);
  220. }
  221. xtw.Flush ();
  222. xtw.Close ();
  223. }
  224. }
  225. //
  226. // TODO:
  227. // Handle other web responses (multi-output?)
  228. //
  229. object [] ReceiveResponse (WebResponse response, SoapClientMessage message, SoapExtension[] extensions)
  230. {
  231. SoapMethodStubInfo msi = message.MethodStubInfo;
  232. HttpWebResponse http_response = response as HttpWebResponse;
  233. if (http_response != null)
  234. {
  235. HttpStatusCode code = http_response.StatusCode;
  236. if (!(code == HttpStatusCode.Accepted || code == HttpStatusCode.OK || code == HttpStatusCode.InternalServerError)) {
  237. string msg = "The request failed with HTTP status {0}: {1}";
  238. msg = String.Format (msg, (int) code, code);
  239. throw new WebException (msg, null, WebExceptionStatus.ProtocolError, http_response);
  240. }
  241. if (message.OneWay && response.ContentLength <= 0 && (code == HttpStatusCode.Accepted || code == HttpStatusCode.OK)) {
  242. return new object[0];
  243. }
  244. }
  245. //
  246. // Remove optional encoding
  247. //
  248. string ctype;
  249. Encoding encoding = WebServiceHelper.GetContentEncoding (response.ContentType, out ctype);
  250. #if NET_2_0
  251. if ((!message.IsSoap12 || ctype != "application/soap+xml") && ctype != "text/xml")
  252. #else
  253. if (ctype != "text/xml")
  254. #endif
  255. WebServiceHelper.InvalidOperation (
  256. String.Format ("Not supported Content-Type in the response: '{0}'", response.ContentType),
  257. response, encoding);
  258. message.ContentType = ctype;
  259. message.ContentEncoding = encoding.WebName;
  260. Stream stream = response.GetResponseStream ();
  261. if (extensions != null) {
  262. stream = SoapExtension.ExecuteChainStream (extensions, stream);
  263. message.SetStage (SoapMessageStage.BeforeDeserialize);
  264. SoapExtension.ExecuteProcessMessage (extensions, message, stream, false);
  265. }
  266. // Deserialize the response
  267. SoapHeaderCollection headers;
  268. object content;
  269. using (StreamReader reader = new StreamReader (stream, encoding, false)) {
  270. XmlTextReader xml_reader = new XmlTextReader (reader);
  271. WebServiceHelper.ReadSoapMessage (xml_reader, msi, SoapHeaderDirection.Out, message.IsSoap12, out content, out headers);
  272. }
  273. #if NET_2_0
  274. if (content is Soap12Fault) {
  275. SoapException ex = WebServiceHelper.Soap12FaultToSoapException ((Soap12Fault) content);
  276. message.SetException (ex);
  277. }
  278. else
  279. #endif
  280. if (content is Fault) {
  281. Fault fault = (Fault) content;
  282. SoapException ex = new SoapException (fault.faultstring, fault.faultcode, fault.faultactor, fault.detail);
  283. message.SetException (ex);
  284. }
  285. else
  286. message.OutParameters = (object[]) content;
  287. message.SetHeaders (headers);
  288. message.UpdateHeaderValues (this, message.MethodStubInfo.Headers);
  289. if (extensions != null) {
  290. message.SetStage (SoapMessageStage.AfterDeserialize);
  291. SoapExtension.ExecuteProcessMessage (extensions, message, stream, false);
  292. }
  293. if (message.Exception == null)
  294. return message.OutParameters;
  295. else
  296. throw message.Exception;
  297. }
  298. protected object[] Invoke (string method_name, object[] parameters)
  299. {
  300. SoapMethodStubInfo msi = (SoapMethodStubInfo) type_info.GetMethod (method_name);
  301. SoapClientMessage message = new SoapClientMessage (this, msi, Url, parameters);
  302. message.CollectHeaders (this, message.MethodStubInfo.Headers, SoapHeaderDirection.In);
  303. SoapExtension[] extensions = SoapExtension.CreateExtensionChain (type_info.SoapExtensions[0], msi.SoapExtensions, type_info.SoapExtensions[1]);
  304. WebResponse response;
  305. try
  306. {
  307. WebRequest request = GetRequestForMessage (uri, message);
  308. SendRequest (request.GetRequestStream (), message, extensions);
  309. response = GetWebResponse (request);
  310. }
  311. catch (WebException ex)
  312. {
  313. response = ex.Response;
  314. HttpWebResponse http_response = response as HttpWebResponse;
  315. if (http_response == null || http_response.StatusCode != HttpStatusCode.InternalServerError)
  316. throw ex;
  317. }
  318. try {
  319. return ReceiveResponse (response, message, extensions);
  320. }
  321. finally {
  322. response.Close();
  323. }
  324. }
  325. #if NET_2_0
  326. [MonoTODO ("Do something with this")]
  327. [System.Runtime.InteropServices.ComVisible(false)]
  328. [DefaultValue (SoapProtocolVersion.Default)]
  329. public SoapProtocolVersion SoapVersion {
  330. get { return soapVersion; }
  331. set { soapVersion = value; }
  332. }
  333. protected void InvokeAsync (string methodName, object[] parameters, SendOrPostCallback callback)
  334. {
  335. InvokeAsync (methodName, parameters, callback, null);
  336. }
  337. protected void InvokeAsync (string methodName, object[] parameters, SendOrPostCallback callback, object userState)
  338. {
  339. InvokeAsyncInfo info = new InvokeAsyncInfo (callback, userState);
  340. BeginInvoke (methodName, parameters, new AsyncCallback (InvokeAsyncCallback), info);
  341. }
  342. void InvokeAsyncCallback (IAsyncResult ar)
  343. {
  344. InvokeAsyncInfo info = (InvokeAsyncInfo) ar.AsyncState;
  345. SoapWebClientAsyncResult sar = (SoapWebClientAsyncResult) ar;
  346. InvokeCompletedEventArgs args = new InvokeCompletedEventArgs (sar.Exception, false, info.UserState, (object[]) sar.Result);
  347. if (info.Context != null)
  348. info.Context.Send (info.Callback, args);
  349. else
  350. info.Callback (args);
  351. }
  352. #endif
  353. #endregion // Methods
  354. }
  355. }