SoapHttpClientProtocol.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378
  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.IO;
  33. using System.Net;
  34. using System.Web;
  35. using System.Xml;
  36. using System.Text;
  37. using System.Reflection;
  38. using System.Web.Services;
  39. using System.Diagnostics;
  40. using System.Runtime.CompilerServices;
  41. using System.Web.Services.Description;
  42. using System.Web.Services.Discovery;
  43. using System.Xml.Serialization;
  44. using System.Xml.Schema;
  45. using System.Collections;
  46. using System.Threading;
  47. namespace System.Web.Services.Protocols
  48. {
  49. public class SoapHttpClientProtocol : HttpWebClientProtocol
  50. {
  51. SoapTypeStubInfo type_info;
  52. #if NET_2_0
  53. SoapProtocolVersion soapVersion;
  54. #endif
  55. #region SoapWebClientAsyncResult class
  56. internal class SoapWebClientAsyncResult: WebClientAsyncResult
  57. {
  58. public SoapWebClientAsyncResult (WebRequest request, AsyncCallback callback, object asyncState)
  59. : base (request, callback, asyncState)
  60. {
  61. }
  62. public SoapClientMessage Message;
  63. public SoapExtension[] Extensions;
  64. }
  65. #endregion
  66. #region Constructors
  67. public SoapHttpClientProtocol ()
  68. {
  69. type_info = (SoapTypeStubInfo) TypeStubManager.GetTypeStub (this.GetType (), "Soap");
  70. }
  71. #endregion // Constructors
  72. #region Methods
  73. protected IAsyncResult BeginInvoke (string methodName, object[] parameters, AsyncCallback callback, object asyncState)
  74. {
  75. SoapMethodStubInfo msi = (SoapMethodStubInfo) type_info.GetMethod (methodName);
  76. SoapWebClientAsyncResult ainfo = null;
  77. try
  78. {
  79. SoapClientMessage message = new SoapClientMessage (this, msi, Url, parameters);
  80. message.CollectHeaders (this, message.MethodStubInfo.Headers, SoapHeaderDirection.In);
  81. WebRequest request = GetRequestForMessage (uri, message);
  82. ainfo = new SoapWebClientAsyncResult (request, callback, asyncState);
  83. ainfo.Message = message;
  84. ainfo.Extensions = SoapExtension.CreateExtensionChain (type_info.SoapExtensions[0], msi.SoapExtensions, type_info.SoapExtensions[1]);
  85. ainfo.Request.BeginGetRequestStream (new AsyncCallback (AsyncGetRequestStreamDone), ainfo);
  86. }
  87. catch (Exception ex)
  88. {
  89. if (ainfo != null)
  90. ainfo.SetCompleted (null, ex, false);
  91. }
  92. return ainfo;
  93. }
  94. void AsyncGetRequestStreamDone (IAsyncResult ar)
  95. {
  96. SoapWebClientAsyncResult ainfo = (SoapWebClientAsyncResult) ar.AsyncState;
  97. try
  98. {
  99. SendRequest (ainfo.Request.EndGetRequestStream (ar), ainfo.Message, ainfo.Extensions);
  100. ainfo.Request.BeginGetResponse (new AsyncCallback (AsyncGetResponseDone), ainfo);
  101. }
  102. catch (Exception ex)
  103. {
  104. ainfo.SetCompleted (null, ex, true);
  105. }
  106. }
  107. void AsyncGetResponseDone (IAsyncResult ar)
  108. {
  109. SoapWebClientAsyncResult ainfo = (SoapWebClientAsyncResult) ar.AsyncState;
  110. WebResponse response = null;
  111. try {
  112. response = GetWebResponse (ainfo.Request, ar);
  113. }
  114. catch (WebException ex) {
  115. response = ex.Response;
  116. HttpWebResponse http_response = response as HttpWebResponse;
  117. if (http_response == null || http_response.StatusCode != HttpStatusCode.InternalServerError) {
  118. ainfo.SetCompleted (null, ex, true);
  119. return;
  120. }
  121. }
  122. catch (Exception ex) {
  123. ainfo.SetCompleted (null, ex, true);
  124. return;
  125. }
  126. try {
  127. object[] result = ReceiveResponse (response, ainfo.Message, ainfo.Extensions);
  128. ainfo.SetCompleted (result, null, true);
  129. }
  130. catch (Exception ex) {
  131. ainfo.SetCompleted (null, ex, true);
  132. }
  133. finally {
  134. response.Close();
  135. }
  136. }
  137. protected object[] EndInvoke (IAsyncResult asyncResult)
  138. {
  139. if (!(asyncResult is SoapWebClientAsyncResult)) throw new ArgumentException ("asyncResult is not the return value from BeginInvoke");
  140. SoapWebClientAsyncResult ainfo = (SoapWebClientAsyncResult) asyncResult;
  141. lock (ainfo)
  142. {
  143. if (!ainfo.IsCompleted) ainfo.WaitForComplete ();
  144. if (ainfo.Exception != null) throw ainfo.Exception;
  145. else return (object[]) ainfo.Result;
  146. }
  147. }
  148. public void Discover ()
  149. {
  150. BindingInfo bnd = (BindingInfo) type_info.Bindings [0];
  151. DiscoveryClientProtocol discoverer = new DiscoveryClientProtocol ();
  152. discoverer.Discover (Url);
  153. foreach (object info in discoverer.AdditionalInformation)
  154. {
  155. System.Web.Services.Discovery.SoapBinding sb = info as System.Web.Services.Discovery.SoapBinding;
  156. if (sb != null && sb.Binding.Name == bnd.Name && sb.Binding.Namespace == bnd.Namespace) {
  157. Url = sb.Address;
  158. return;
  159. }
  160. }
  161. 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);
  162. throw new Exception (msg);
  163. }
  164. protected override WebRequest GetWebRequest (Uri uri)
  165. {
  166. return base.GetWebRequest (uri);
  167. }
  168. WebRequest GetRequestForMessage (Uri uri, SoapClientMessage message)
  169. {
  170. WebRequest request = GetWebRequest (uri);
  171. request.Method = "POST";
  172. WebHeaderCollection headers = request.Headers;
  173. headers.Add ("SOAPAction", "\"" + message.Action + "\"");
  174. request.ContentType = message.ContentType + "; charset=utf-8";
  175. return request;
  176. }
  177. void SendRequest (Stream s, SoapClientMessage message, SoapExtension[] extensions)
  178. {
  179. using (s) {
  180. if (extensions != null) {
  181. s = SoapExtension.ExecuteChainStream (extensions, s);
  182. message.SetStage (SoapMessageStage.BeforeSerialize);
  183. SoapExtension.ExecuteProcessMessage (extensions, message, s, true);
  184. }
  185. XmlTextWriter xtw = WebServiceHelper.CreateXmlWriter (s);
  186. WebServiceHelper.WriteSoapMessage (xtw, message.MethodStubInfo, SoapHeaderDirection.In, message.Parameters, message.Headers);
  187. if (extensions != null) {
  188. message.SetStage (SoapMessageStage.AfterSerialize);
  189. SoapExtension.ExecuteProcessMessage (extensions, message, s, true);
  190. }
  191. xtw.Flush ();
  192. xtw.Close ();
  193. }
  194. }
  195. //
  196. // TODO:
  197. // Handle other web responses (multi-output?)
  198. //
  199. object [] ReceiveResponse (WebResponse response, SoapClientMessage message, SoapExtension[] extensions)
  200. {
  201. SoapMethodStubInfo msi = message.MethodStubInfo;
  202. HttpWebResponse http_response = response as HttpWebResponse;
  203. if (http_response != null)
  204. {
  205. HttpStatusCode code = http_response.StatusCode;
  206. if (!(code == HttpStatusCode.Accepted || code == HttpStatusCode.OK || code == HttpStatusCode.InternalServerError)) {
  207. string msg = "The request failed with HTTP status {0}: {1}";
  208. msg = String.Format (msg, (int) code, code);
  209. throw new WebException (msg, null, WebExceptionStatus.ProtocolError, http_response);
  210. }
  211. if (message.OneWay && response.ContentLength <= 0 && (code == HttpStatusCode.Accepted || code == HttpStatusCode.OK)) {
  212. return new object[0];
  213. }
  214. }
  215. //
  216. // Remove optional encoding
  217. //
  218. string ctype;
  219. Encoding encoding = WebServiceHelper.GetContentEncoding (response.ContentType, out ctype);
  220. if (ctype != "text/xml")
  221. WebServiceHelper.InvalidOperation (
  222. "Content is not 'text/xml' but '" + response.ContentType + "'",
  223. response, encoding);
  224. message.ContentType = ctype;
  225. message.ContentEncoding = encoding.WebName;
  226. Stream stream = response.GetResponseStream ();
  227. if (extensions != null) {
  228. stream = SoapExtension.ExecuteChainStream (extensions, stream);
  229. message.SetStage (SoapMessageStage.BeforeDeserialize);
  230. SoapExtension.ExecuteProcessMessage (extensions, message, stream, false);
  231. }
  232. // Deserialize the response
  233. SoapHeaderCollection headers;
  234. object content;
  235. using (StreamReader reader = new StreamReader (stream, encoding, false)) {
  236. XmlTextReader xml_reader = new XmlTextReader (reader);
  237. WebServiceHelper.ReadSoapMessage (xml_reader, msi, SoapHeaderDirection.Out, out content, out headers);
  238. }
  239. if (content is Fault)
  240. {
  241. Fault fault = (Fault) content;
  242. SoapException ex = new SoapException (fault.faultstring, fault.faultcode, fault.faultactor, fault.detail);
  243. message.SetException (ex);
  244. }
  245. else
  246. message.OutParameters = (object[]) content;
  247. message.SetHeaders (headers);
  248. message.UpdateHeaderValues (this, message.MethodStubInfo.Headers);
  249. if (extensions != null) {
  250. message.SetStage (SoapMessageStage.AfterDeserialize);
  251. SoapExtension.ExecuteProcessMessage (extensions, message, stream, false);
  252. }
  253. if (message.Exception == null)
  254. return message.OutParameters;
  255. else
  256. throw message.Exception;
  257. }
  258. protected object[] Invoke (string method_name, object[] parameters)
  259. {
  260. SoapMethodStubInfo msi = (SoapMethodStubInfo) type_info.GetMethod (method_name);
  261. SoapClientMessage message = new SoapClientMessage (this, msi, Url, parameters);
  262. message.CollectHeaders (this, message.MethodStubInfo.Headers, SoapHeaderDirection.In);
  263. SoapExtension[] extensions = SoapExtension.CreateExtensionChain (type_info.SoapExtensions[0], msi.SoapExtensions, type_info.SoapExtensions[1]);
  264. WebResponse response;
  265. try
  266. {
  267. WebRequest request = GetRequestForMessage (uri, message);
  268. SendRequest (request.GetRequestStream (), message, extensions);
  269. response = GetWebResponse (request);
  270. }
  271. catch (WebException ex)
  272. {
  273. response = ex.Response;
  274. HttpWebResponse http_response = response as HttpWebResponse;
  275. if (http_response == null || http_response.StatusCode != HttpStatusCode.InternalServerError)
  276. throw ex;
  277. }
  278. try {
  279. return ReceiveResponse (response, message, extensions);
  280. }
  281. finally {
  282. response.Close();
  283. }
  284. }
  285. #if NET_2_0
  286. [MonoTODO ("Do something with this")]
  287. [System.Runtime.InteropServices.ComVisible(false)]
  288. public SoapProtocolVersion SoapVersion {
  289. get { return soapVersion; }
  290. set { soapVersion = value; }
  291. }
  292. protected void InvokeAsync (string methodName, object[] parameters, SendOrPostCallback callback)
  293. {
  294. InvokeAsync (methodName, parameters, callback, null);
  295. }
  296. protected void InvokeAsync (string methodName, object[] parameters, SendOrPostCallback callback, object userState)
  297. {
  298. InvokeAsyncInfo info = new InvokeAsyncInfo (callback, userState);
  299. BeginInvoke (methodName, parameters, new AsyncCallback (InvokeAsyncCallback), info);
  300. }
  301. void InvokeAsyncCallback (IAsyncResult ar)
  302. {
  303. InvokeAsyncInfo info = (InvokeAsyncInfo) ar.AsyncState;
  304. SoapWebClientAsyncResult sar = (SoapWebClientAsyncResult) ar;
  305. InvokeCompletedEventArgs args = new InvokeCompletedEventArgs (sar.Exception, false, info.UserState, (object[]) sar.Result);
  306. if (info.Context != null)
  307. info.Context.Send (info.Callback, args);
  308. else
  309. info.Callback (args);
  310. }
  311. #endif
  312. #endregion // Methods
  313. }
  314. }