SoapHttpClientProtocol.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387
  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. void SendRequest (Stream s, SoapClientMessage message, SoapExtension[] extensions)
  182. {
  183. using (s) {
  184. if (extensions != null) {
  185. s = SoapExtension.ExecuteChainStream (extensions, s);
  186. message.SetStage (SoapMessageStage.BeforeSerialize);
  187. SoapExtension.ExecuteProcessMessage (extensions, message, s, true);
  188. }
  189. XmlTextWriter xtw = WebServiceHelper.CreateXmlWriter (s);
  190. #if NET_2_0
  191. bool soap12 = message.SoapVersion == SoapProtocolVersion.Soap12;
  192. #else
  193. bool soap12 = false;
  194. #endif
  195. WebServiceHelper.WriteSoapMessage (xtw, message.MethodStubInfo, SoapHeaderDirection.In, message.Parameters, message.Headers, soap12);
  196. if (extensions != null) {
  197. message.SetStage (SoapMessageStage.AfterSerialize);
  198. SoapExtension.ExecuteProcessMessage (extensions, message, s, true);
  199. }
  200. xtw.Flush ();
  201. xtw.Close ();
  202. }
  203. }
  204. //
  205. // TODO:
  206. // Handle other web responses (multi-output?)
  207. //
  208. object [] ReceiveResponse (WebResponse response, SoapClientMessage message, SoapExtension[] extensions)
  209. {
  210. SoapMethodStubInfo msi = message.MethodStubInfo;
  211. HttpWebResponse http_response = response as HttpWebResponse;
  212. if (http_response != null)
  213. {
  214. HttpStatusCode code = http_response.StatusCode;
  215. if (!(code == HttpStatusCode.Accepted || code == HttpStatusCode.OK || code == HttpStatusCode.InternalServerError)) {
  216. string msg = "The request failed with HTTP status {0}: {1}";
  217. msg = String.Format (msg, (int) code, code);
  218. throw new WebException (msg, null, WebExceptionStatus.ProtocolError, http_response);
  219. }
  220. if (message.OneWay && response.ContentLength <= 0 && (code == HttpStatusCode.Accepted || code == HttpStatusCode.OK)) {
  221. return new object[0];
  222. }
  223. }
  224. //
  225. // Remove optional encoding
  226. //
  227. string ctype;
  228. Encoding encoding = WebServiceHelper.GetContentEncoding (response.ContentType, out ctype);
  229. if (ctype != "text/xml")
  230. WebServiceHelper.InvalidOperation (
  231. "Content is not 'text/xml' but '" + response.ContentType + "'",
  232. response, encoding);
  233. message.ContentType = ctype;
  234. message.ContentEncoding = encoding.WebName;
  235. Stream stream = response.GetResponseStream ();
  236. if (extensions != null) {
  237. stream = SoapExtension.ExecuteChainStream (extensions, stream);
  238. message.SetStage (SoapMessageStage.BeforeDeserialize);
  239. SoapExtension.ExecuteProcessMessage (extensions, message, stream, false);
  240. }
  241. // Deserialize the response
  242. SoapHeaderCollection headers;
  243. object content;
  244. using (StreamReader reader = new StreamReader (stream, encoding, false)) {
  245. XmlTextReader xml_reader = new XmlTextReader (reader);
  246. WebServiceHelper.ReadSoapMessage (xml_reader, msi, SoapHeaderDirection.Out, out content, out headers);
  247. }
  248. if (content is Fault)
  249. {
  250. Fault fault = (Fault) content;
  251. SoapException ex = new SoapException (fault.faultstring, fault.faultcode, fault.faultactor, fault.detail);
  252. message.SetException (ex);
  253. }
  254. else
  255. message.OutParameters = (object[]) content;
  256. message.SetHeaders (headers);
  257. message.UpdateHeaderValues (this, message.MethodStubInfo.Headers);
  258. if (extensions != null) {
  259. message.SetStage (SoapMessageStage.AfterDeserialize);
  260. SoapExtension.ExecuteProcessMessage (extensions, message, stream, false);
  261. }
  262. if (message.Exception == null)
  263. return message.OutParameters;
  264. else
  265. throw message.Exception;
  266. }
  267. protected object[] Invoke (string method_name, object[] parameters)
  268. {
  269. SoapMethodStubInfo msi = (SoapMethodStubInfo) type_info.GetMethod (method_name);
  270. SoapClientMessage message = new SoapClientMessage (this, msi, Url, parameters);
  271. message.CollectHeaders (this, message.MethodStubInfo.Headers, SoapHeaderDirection.In);
  272. SoapExtension[] extensions = SoapExtension.CreateExtensionChain (type_info.SoapExtensions[0], msi.SoapExtensions, type_info.SoapExtensions[1]);
  273. WebResponse response;
  274. try
  275. {
  276. WebRequest request = GetRequestForMessage (uri, message);
  277. SendRequest (request.GetRequestStream (), message, extensions);
  278. response = GetWebResponse (request);
  279. }
  280. catch (WebException ex)
  281. {
  282. response = ex.Response;
  283. HttpWebResponse http_response = response as HttpWebResponse;
  284. if (http_response == null || http_response.StatusCode != HttpStatusCode.InternalServerError)
  285. throw ex;
  286. }
  287. try {
  288. return ReceiveResponse (response, message, extensions);
  289. }
  290. finally {
  291. response.Close();
  292. }
  293. }
  294. #if NET_2_0
  295. [MonoTODO ("Do something with this")]
  296. [System.Runtime.InteropServices.ComVisible(false)]
  297. [DefaultValue (SoapProtocolVersion.Default)]
  298. public SoapProtocolVersion SoapVersion {
  299. get { return soapVersion; }
  300. set { soapVersion = value; }
  301. }
  302. protected void InvokeAsync (string methodName, object[] parameters, SendOrPostCallback callback)
  303. {
  304. InvokeAsync (methodName, parameters, callback, null);
  305. }
  306. protected void InvokeAsync (string methodName, object[] parameters, SendOrPostCallback callback, object userState)
  307. {
  308. InvokeAsyncInfo info = new InvokeAsyncInfo (callback, userState);
  309. BeginInvoke (methodName, parameters, new AsyncCallback (InvokeAsyncCallback), info);
  310. }
  311. void InvokeAsyncCallback (IAsyncResult ar)
  312. {
  313. InvokeAsyncInfo info = (InvokeAsyncInfo) ar.AsyncState;
  314. SoapWebClientAsyncResult sar = (SoapWebClientAsyncResult) ar;
  315. InvokeCompletedEventArgs args = new InvokeCompletedEventArgs (sar.Exception, false, info.UserState, (object[]) sar.Result);
  316. if (info.Context != null)
  317. info.Context.Send (info.Callback, args);
  318. else
  319. info.Callback (args);
  320. }
  321. #endif
  322. #endregion // Methods
  323. }
  324. }