2 // System.Web.Services.Protocols.SoapHttpClientProtocol.cs
5 // Tim Coleman (tim@timcoleman.com)
6 // Miguel de Icaza (miguel@ximian.com)
7 // Lluis Sanchez Gual (lluis@ximian.com)
9 // Copyright (C) Tim Coleman, 2002
10 // Copyright (C) Ximian, Inc, 2003
14 // Permission is hereby granted, free of charge, to any person obtaining
15 // a copy of this software and associated documentation files (the
16 // "Software"), to deal in the Software without restriction, including
17 // without limitation the rights to use, copy, modify, merge, publish,
18 // distribute, sublicense, and/or sell copies of the Software, and to
19 // permit persons to whom the Software is furnished to do so, subject to
20 // the following conditions:
22 // The above copyright notice and this permission notice shall be
23 // included in all copies or substantial portions of the Software.
25 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
26 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
27 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
28 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
29 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
30 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
31 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
34 using System.ComponentModel;
35 using System.Globalization;
41 using System.Reflection;
42 using System.Web.Services;
43 using System.Diagnostics;
44 using System.Runtime.CompilerServices;
45 using System.Web.Services.Description;
46 using System.Web.Services.Discovery;
47 using System.Xml.Serialization;
48 using System.Xml.Schema;
49 using System.Collections;
50 using System.Threading;
52 namespace System.Web.Services.Protocols
54 [System.Runtime.InteropServices.ComVisible (true)]
55 public class SoapHttpClientProtocol : HttpWebClientProtocol
57 SoapTypeStubInfo type_info;
58 SoapProtocolVersion soapVersion;
60 #region SoapWebClientAsyncResult class
62 internal class SoapWebClientAsyncResult: WebClientAsyncResult
64 public SoapWebClientAsyncResult (WebRequest request, AsyncCallback callback, object asyncState)
65 : base (request, callback, asyncState)
69 public SoapClientMessage Message;
70 public SoapExtension[] Extensions;
76 public SoapHttpClientProtocol ()
78 type_info = (SoapTypeStubInfo) TypeStubManager.GetTypeStub (this.GetType (), "Soap");
81 #endregion // Constructors
85 protected IAsyncResult BeginInvoke (string methodName, object[] parameters, AsyncCallback callback, object asyncState)
87 SoapMethodStubInfo msi = (SoapMethodStubInfo) type_info.GetMethod (methodName);
89 SoapWebClientAsyncResult ainfo = null;
92 SoapClientMessage message = new SoapClientMessage (this, msi, Url, parameters);
93 message.CollectHeaders (this, message.MethodStubInfo.Headers, SoapHeaderDirection.In);
95 WebRequest request = GetRequestForMessage (uri, message);
97 ainfo = new SoapWebClientAsyncResult (request, callback, asyncState);
98 ainfo.Message = message;
99 ainfo.Extensions = SoapExtension.CreateExtensionChain (type_info.SoapExtensions[0], msi.SoapExtensions, type_info.SoapExtensions[1]);
101 ainfo.Request.BeginGetRequestStream (new AsyncCallback (AsyncGetRequestStreamDone), ainfo);
102 RegisterMapping (asyncState, ainfo);
107 ainfo.SetCompleted (null, ex, false);
113 void AsyncGetRequestStreamDone (IAsyncResult ar)
115 SoapWebClientAsyncResult ainfo = (SoapWebClientAsyncResult) ar.AsyncState;
118 SendRequest (ainfo.Request.EndGetRequestStream (ar), ainfo.Message, ainfo.Extensions);
119 ainfo.Request.BeginGetResponse (new AsyncCallback (AsyncGetResponseDone), ainfo);
123 ainfo.SetCompleted (null, ex, true);
127 void AsyncGetResponseDone (IAsyncResult ar)
129 SoapWebClientAsyncResult ainfo = (SoapWebClientAsyncResult) ar.AsyncState;
130 WebResponse response = null;
133 response = GetWebResponse (ainfo.Request, ar);
135 catch (WebException ex) {
136 response = ex.Response;
137 HttpWebResponse http_response = response as HttpWebResponse;
138 if (http_response == null || http_response.StatusCode != HttpStatusCode.InternalServerError) {
139 ainfo.SetCompleted (null, ex, true);
143 catch (Exception ex) {
144 ainfo.SetCompleted (null, ex, true);
149 object[] result = ReceiveResponse (response, ainfo.Message, ainfo.Extensions);
150 ainfo.SetCompleted (result, null, true);
152 catch (Exception ex) {
153 ainfo.SetCompleted (null, ex, true);
160 protected object[] EndInvoke (IAsyncResult asyncResult)
162 if (!(asyncResult is SoapWebClientAsyncResult)) throw new ArgumentException ("asyncResult is not the return value from BeginInvoke");
164 SoapWebClientAsyncResult ainfo = (SoapWebClientAsyncResult) asyncResult;
167 if (!ainfo.IsCompleted)
168 ainfo.WaitForComplete ();
170 UnregisterMapping (ainfo.AsyncState);
172 if (ainfo.Exception != null)
173 throw ainfo.Exception;
175 return (object[]) ainfo.Result;
179 public void Discover ()
181 BindingInfo bnd = (BindingInfo) type_info.Bindings [0];
183 DiscoveryClientProtocol discoverer = new DiscoveryClientProtocol ();
184 discoverer.Discover (Url);
186 foreach (object info in discoverer.AdditionalInformation)
188 System.Web.Services.Discovery.SoapBinding sb = info as System.Web.Services.Discovery.SoapBinding;
189 if (sb != null && sb.Binding.Name == bnd.Name && sb.Binding.Namespace == bnd.Namespace) {
195 string msg = string.Format (
196 "The binding named '{0}' from namespace '{1}' was not found in the discovery document at '{2}'",
197 bnd.Name, bnd.Namespace, Url);
198 throw new Exception (msg);
201 protected override WebRequest GetWebRequest (Uri uri)
203 return base.GetWebRequest (uri);
206 WebRequest GetRequestForMessage (Uri uri, SoapClientMessage message)
208 WebRequest request = GetWebRequest (uri);
209 request.Method = "POST";
210 WebHeaderCollection headers = request.Headers;
211 request.ContentType = message.ContentType + "; charset=utf-8";
212 if (!message.IsSoap12) {
213 headers.Add ("SOAPAction", "\"" + message.Action + "\"");
215 request.ContentType += "; action=\"" + message.Action + "\"";
222 XmlReader GetReaderForMessage (
223 SoapClientMessage message, int bufferSize)
225 throw new NotImplementedException ();
230 XmlWriter GetWriterForMessage (
231 SoapClientMessage message, int bufferSize)
233 throw new NotImplementedException ();
236 void SendRequest (Stream s, SoapClientMessage message, SoapExtension[] extensions)
240 if (extensions != null) {
241 s = SoapExtension.ExecuteChainStream (extensions, s);
242 message.SetStage (SoapMessageStage.BeforeSerialize);
243 SoapExtension.ExecuteProcessMessage (extensions, message, s, true);
246 XmlTextWriter xtw = WebServiceHelper.CreateXmlWriter (s);
247 WebServiceHelper.WriteSoapMessage (xtw, message.MethodStubInfo, SoapHeaderDirection.In, message.Parameters, message.Headers, message.IsSoap12);
249 if (extensions != null) {
250 message.SetStage (SoapMessageStage.AfterSerialize);
251 SoapExtension.ExecuteProcessMessage (extensions, message, s, true);
262 // Handle other web responses (multi-output?)
264 object [] ReceiveResponse (WebResponse response, SoapClientMessage message, SoapExtension[] extensions)
266 SoapMethodStubInfo msi = message.MethodStubInfo;
267 HttpWebResponse http_response = response as HttpWebResponse;
269 if (http_response != null)
271 HttpStatusCode code = http_response.StatusCode;
273 if (!(code == HttpStatusCode.Accepted || code == HttpStatusCode.OK || code == HttpStatusCode.InternalServerError)) {
274 string msg = "The request failed with HTTP status {0}: {1}";
275 msg = String.Format (msg, (int) code, code);
276 throw new WebException (msg, null, WebExceptionStatus.ProtocolError, http_response);
278 if (message.OneWay && response.ContentLength <= 0 && (code == HttpStatusCode.Accepted || code == HttpStatusCode.OK)) {
279 return new object[0];
284 // Remove optional encoding
287 Encoding encoding = WebServiceHelper.GetContentEncoding (response.ContentType, out ctype);
288 ctype = ctype.ToLower (CultureInfo.InvariantCulture);
289 if ((!message.IsSoap12 || ctype != "application/soap+xml") && ctype != "text/xml")
290 WebServiceHelper.InvalidOperation (
291 String.Format ("Not supported Content-Type in the response: '{0}'", response.ContentType),
294 message.ContentType = ctype;
295 message.ContentEncoding = encoding.WebName;
297 Stream stream = response.GetResponseStream ();
299 if (extensions != null) {
300 stream = SoapExtension.ExecuteChainStream (extensions, stream);
301 message.SetStage (SoapMessageStage.BeforeDeserialize);
302 SoapExtension.ExecuteProcessMessage (extensions, message, stream, false);
305 // Deserialize the response
307 SoapHeaderCollection headers;
310 using (StreamReader reader = new StreamReader (stream, encoding, false)) {
311 XmlTextReader xml_reader = new XmlTextReader (reader);
313 WebServiceHelper.ReadSoapMessage (xml_reader, msi, SoapHeaderDirection.Out, message.IsSoap12, out content, out headers);
316 if (content is Soap12Fault) {
317 SoapException ex = WebServiceHelper.Soap12FaultToSoapException ((Soap12Fault) content);
318 message.SetException (ex);
321 if (content is Fault) {
322 Fault fault = (Fault) content;
323 SoapException ex = new SoapException (fault.faultstring, fault.faultcode, fault.faultactor, fault.detail);
324 message.SetException (ex);
327 message.OutParameters = (object[]) content;
329 message.SetHeaders (headers);
330 message.UpdateHeaderValues (this, message.MethodStubInfo.Headers);
332 if (extensions != null) {
333 message.SetStage (SoapMessageStage.AfterDeserialize);
334 SoapExtension.ExecuteProcessMessage (extensions, message, stream, false);
337 if (message.Exception == null)
338 return message.OutParameters;
340 throw message.Exception;
343 protected object[] Invoke (string method_name, object[] parameters)
345 SoapMethodStubInfo msi = (SoapMethodStubInfo) type_info.GetMethod (method_name);
347 SoapClientMessage message = new SoapClientMessage (this, msi, Url, parameters);
348 message.CollectHeaders (this, message.MethodStubInfo.Headers, SoapHeaderDirection.In);
350 SoapExtension[] extensions = SoapExtension.CreateExtensionChain (type_info.SoapExtensions[0], msi.SoapExtensions, type_info.SoapExtensions[1]);
352 WebResponse response;
355 WebRequest request = GetRequestForMessage (uri, message);
356 SendRequest (request.GetRequestStream (), message, extensions);
357 response = GetWebResponse (request);
359 catch (WebException ex)
361 response = ex.Response;
362 HttpWebResponse http_response = response as HttpWebResponse;
363 if (http_response == null || http_response.StatusCode != HttpStatusCode.InternalServerError)
368 return ReceiveResponse (response, message, extensions);
376 [MonoTODO ("Do something with this")]
377 [System.Runtime.InteropServices.ComVisible(false)]
378 [DefaultValue (SoapProtocolVersion.Default)]
379 public SoapProtocolVersion SoapVersion {
380 get { return soapVersion; }
381 set { soapVersion = value; }
384 protected void InvokeAsync (string methodName, object[] parameters, SendOrPostCallback callback)
386 InvokeAsync (methodName, parameters, callback, null);
389 protected void InvokeAsync (string methodName, object[] parameters, SendOrPostCallback callback, object userState)
391 InvokeAsyncInfo info = new InvokeAsyncInfo (callback, userState);
392 BeginInvoke (methodName, parameters, new AsyncCallback (InvokeAsyncCallback), info);
395 void InvokeAsyncCallback (IAsyncResult ar)
397 InvokeAsyncInfo info = (InvokeAsyncInfo) ar.AsyncState;
398 SoapWebClientAsyncResult sar = (SoapWebClientAsyncResult) ar;
399 InvokeCompletedEventArgs args = new InvokeCompletedEventArgs (sar.Exception, false, info.UserState, (object[]) sar.Result);
400 UnregisterMapping (ar.AsyncState);
401 if (info.Context != null)
402 info.Context.Send (info.Callback, args);
404 info.Callback (args);
408 #endregion // Methods