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 if (!message.IsSoap12)
212 headers.Add ("SOAPAction", "\"" + message.Action + "\"");
213 request.ContentType = message.ContentType + "; charset=utf-8";
219 XmlReader GetReaderForMessage (
220 SoapClientMessage message, int bufferSize)
222 throw new NotImplementedException ();
227 XmlWriter GetWriterForMessage (
228 SoapClientMessage message, int bufferSize)
230 throw new NotImplementedException ();
233 void SendRequest (Stream s, SoapClientMessage message, SoapExtension[] extensions)
237 if (extensions != null) {
238 s = SoapExtension.ExecuteChainStream (extensions, s);
239 message.SetStage (SoapMessageStage.BeforeSerialize);
240 SoapExtension.ExecuteProcessMessage (extensions, message, s, true);
243 XmlTextWriter xtw = WebServiceHelper.CreateXmlWriter (s);
244 WebServiceHelper.WriteSoapMessage (xtw, message.MethodStubInfo, SoapHeaderDirection.In, message.Parameters, message.Headers, message.IsSoap12);
246 if (extensions != null) {
247 message.SetStage (SoapMessageStage.AfterSerialize);
248 SoapExtension.ExecuteProcessMessage (extensions, message, s, true);
259 // Handle other web responses (multi-output?)
261 object [] ReceiveResponse (WebResponse response, SoapClientMessage message, SoapExtension[] extensions)
263 SoapMethodStubInfo msi = message.MethodStubInfo;
264 HttpWebResponse http_response = response as HttpWebResponse;
266 if (http_response != null)
268 HttpStatusCode code = http_response.StatusCode;
270 if (!(code == HttpStatusCode.Accepted || code == HttpStatusCode.OK || code == HttpStatusCode.InternalServerError)) {
271 string msg = "The request failed with HTTP status {0}: {1}";
272 msg = String.Format (msg, (int) code, code);
273 throw new WebException (msg, null, WebExceptionStatus.ProtocolError, http_response);
275 if (message.OneWay && response.ContentLength <= 0 && (code == HttpStatusCode.Accepted || code == HttpStatusCode.OK)) {
276 return new object[0];
281 // Remove optional encoding
284 Encoding encoding = WebServiceHelper.GetContentEncoding (response.ContentType, out ctype);
285 ctype = ctype.ToLower (CultureInfo.InvariantCulture);
286 if ((!message.IsSoap12 || ctype != "application/soap+xml") && ctype != "text/xml")
287 WebServiceHelper.InvalidOperation (
288 String.Format ("Not supported Content-Type in the response: '{0}'", response.ContentType),
291 message.ContentType = ctype;
292 message.ContentEncoding = encoding.WebName;
294 Stream stream = response.GetResponseStream ();
296 if (extensions != null) {
297 stream = SoapExtension.ExecuteChainStream (extensions, stream);
298 message.SetStage (SoapMessageStage.BeforeDeserialize);
299 SoapExtension.ExecuteProcessMessage (extensions, message, stream, false);
302 // Deserialize the response
304 SoapHeaderCollection headers;
307 using (StreamReader reader = new StreamReader (stream, encoding, false)) {
308 XmlTextReader xml_reader = new XmlTextReader (reader);
310 WebServiceHelper.ReadSoapMessage (xml_reader, msi, SoapHeaderDirection.Out, message.IsSoap12, out content, out headers);
313 if (content is Soap12Fault) {
314 SoapException ex = WebServiceHelper.Soap12FaultToSoapException ((Soap12Fault) content);
315 message.SetException (ex);
318 if (content is Fault) {
319 Fault fault = (Fault) content;
320 SoapException ex = new SoapException (fault.faultstring, fault.faultcode, fault.faultactor, fault.detail);
321 message.SetException (ex);
324 message.OutParameters = (object[]) content;
326 message.SetHeaders (headers);
327 message.UpdateHeaderValues (this, message.MethodStubInfo.Headers);
329 if (extensions != null) {
330 message.SetStage (SoapMessageStage.AfterDeserialize);
331 SoapExtension.ExecuteProcessMessage (extensions, message, stream, false);
334 if (message.Exception == null)
335 return message.OutParameters;
337 throw message.Exception;
340 protected object[] Invoke (string method_name, object[] parameters)
342 SoapMethodStubInfo msi = (SoapMethodStubInfo) type_info.GetMethod (method_name);
344 SoapClientMessage message = new SoapClientMessage (this, msi, Url, parameters);
345 message.CollectHeaders (this, message.MethodStubInfo.Headers, SoapHeaderDirection.In);
347 SoapExtension[] extensions = SoapExtension.CreateExtensionChain (type_info.SoapExtensions[0], msi.SoapExtensions, type_info.SoapExtensions[1]);
349 WebResponse response;
352 WebRequest request = GetRequestForMessage (uri, message);
353 SendRequest (request.GetRequestStream (), message, extensions);
354 response = GetWebResponse (request);
356 catch (WebException ex)
358 response = ex.Response;
359 HttpWebResponse http_response = response as HttpWebResponse;
360 if (http_response == null || http_response.StatusCode != HttpStatusCode.InternalServerError)
365 return ReceiveResponse (response, message, extensions);
373 [MonoTODO ("Do something with this")]
374 [System.Runtime.InteropServices.ComVisible(false)]
375 [DefaultValue (SoapProtocolVersion.Default)]
376 public SoapProtocolVersion SoapVersion {
377 get { return soapVersion; }
378 set { soapVersion = value; }
381 protected void InvokeAsync (string methodName, object[] parameters, SendOrPostCallback callback)
383 InvokeAsync (methodName, parameters, callback, null);
386 protected void InvokeAsync (string methodName, object[] parameters, SendOrPostCallback callback, object userState)
388 InvokeAsyncInfo info = new InvokeAsyncInfo (callback, userState);
389 BeginInvoke (methodName, parameters, new AsyncCallback (InvokeAsyncCallback), info);
392 void InvokeAsyncCallback (IAsyncResult ar)
394 InvokeAsyncInfo info = (InvokeAsyncInfo) ar.AsyncState;
395 SoapWebClientAsyncResult sar = (SoapWebClientAsyncResult) ar;
396 InvokeCompletedEventArgs args = new InvokeCompletedEventArgs (sar.Exception, false, info.UserState, (object[]) sar.Result);
397 UnregisterMapping (ar.AsyncState);
398 if (info.Context != null)
399 info.Context.Send (info.Callback, args);
401 info.Callback (args);
405 #endregion // Methods