Do not major_free_swept_blocks on Orbis.
[mono.git] / mcs / class / System.Web.Services / System.Web.Services.Protocols / SoapHttpClientProtocol.cs
1 // 
2 // System.Web.Services.Protocols.SoapHttpClientProtocol.cs
3 //
4 // Author:
5 //   Tim Coleman (tim@timcoleman.com)
6 //   Miguel de Icaza (miguel@ximian.com)
7 //   Lluis Sanchez Gual (lluis@ximian.com)
8 //
9 // Copyright (C) Tim Coleman, 2002
10 // Copyright (C) Ximian, Inc, 2003
11 //
12
13 //
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:
21 // 
22 // The above copyright notice and this permission notice shall be
23 // included in all copies or substantial portions of the Software.
24 // 
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.
32 //
33
34 using System.ComponentModel;
35 using System.Globalization;
36 using System.IO;
37 using System.Net;
38 using System.Web;
39 using System.Xml;
40 using System.Text;
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;
51
52 namespace System.Web.Services.Protocols 
53 {
54         [System.Runtime.InteropServices.ComVisible (true)]
55         public class SoapHttpClientProtocol : HttpWebClientProtocol 
56         {
57                 SoapTypeStubInfo type_info;
58                 SoapProtocolVersion soapVersion;
59
60                 #region SoapWebClientAsyncResult class
61
62                 internal class SoapWebClientAsyncResult: WebClientAsyncResult
63                 {
64                         public SoapWebClientAsyncResult (WebRequest request, AsyncCallback callback, object asyncState)
65                         : base (request, callback, asyncState)
66                         {
67                         }
68                 
69                         public SoapClientMessage Message;
70                         public SoapExtension[] Extensions;
71                 }
72                 #endregion
73
74                 #region Constructors
75
76                 public SoapHttpClientProtocol () 
77                 {
78                         type_info = (SoapTypeStubInfo) TypeStubManager.GetTypeStub (this.GetType (), "Soap");
79                 }
80
81                 #endregion // Constructors
82
83                 #region Methods
84
85                 protected IAsyncResult BeginInvoke (string methodName, object[] parameters, AsyncCallback callback, object asyncState)
86                 {
87                         SoapMethodStubInfo msi = (SoapMethodStubInfo) type_info.GetMethod (methodName);
88
89                         SoapWebClientAsyncResult ainfo = null;
90                         try
91                         {
92                                 SoapClientMessage message = new SoapClientMessage (this, msi, Url, parameters);
93                                 message.CollectHeaders (this, message.MethodStubInfo.Headers, SoapHeaderDirection.In);
94                                 
95                                 WebRequest request = GetRequestForMessage (uri, message);
96                                 
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]);
100
101                                 ainfo.Request.BeginGetRequestStream (new AsyncCallback (AsyncGetRequestStreamDone), ainfo);
102                                 RegisterMapping (asyncState, ainfo);
103                         }
104                         catch (Exception ex)
105                         {
106                                 if (ainfo != null)
107                                         ainfo.SetCompleted (null, ex, false);
108                         }
109
110                         return ainfo;
111                 }
112
113                 void AsyncGetRequestStreamDone (IAsyncResult ar)
114                 {
115                         SoapWebClientAsyncResult ainfo = (SoapWebClientAsyncResult) ar.AsyncState;
116                         try
117                         {
118                                 SendRequest (ainfo.Request.EndGetRequestStream (ar), ainfo.Message, ainfo.Extensions);
119                                 ainfo.Request.BeginGetResponse (new AsyncCallback (AsyncGetResponseDone), ainfo);
120                         }
121                         catch (Exception ex)
122                         {
123                                 ainfo.SetCompleted (null, ex, true);
124                         }
125                 }
126
127                 void AsyncGetResponseDone (IAsyncResult ar)
128                 {
129                         SoapWebClientAsyncResult ainfo = (SoapWebClientAsyncResult) ar.AsyncState;
130                         WebResponse response = null;
131
132                         try {
133                                 response = GetWebResponse (ainfo.Request, ar);
134                         }
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);
140                                         return;
141                                 }
142                         }
143                         catch (Exception ex) {
144                                 ainfo.SetCompleted (null, ex, true);
145                                 return;
146                         }
147
148                         try {
149                                 object[] result = ReceiveResponse (response, ainfo.Message, ainfo.Extensions);
150                                 ainfo.SetCompleted (result, null, true);
151                         }
152                         catch (Exception ex) {
153                                 ainfo.SetCompleted (null, ex, true);
154                         }
155                         finally {
156                                 response.Close();
157                         }
158                 }
159
160                 protected object[] EndInvoke (IAsyncResult asyncResult)
161                 {
162                         if (!(asyncResult is SoapWebClientAsyncResult)) throw new ArgumentException ("asyncResult is not the return value from BeginInvoke");
163
164                         SoapWebClientAsyncResult ainfo = (SoapWebClientAsyncResult) asyncResult;
165                         lock (ainfo)
166                         {
167                                 if (!ainfo.IsCompleted)
168                                         ainfo.WaitForComplete ();
169
170                                 UnregisterMapping (ainfo.AsyncState);
171                                 
172                                 if (ainfo.Exception != null)
173                                         throw ainfo.Exception;
174                                 else
175                                         return (object[]) ainfo.Result;
176                         }
177                 }
178
179                 public void Discover ()
180                 {
181                         BindingInfo bnd = (BindingInfo) type_info.Bindings [0];
182                         
183                         DiscoveryClientProtocol discoverer = new DiscoveryClientProtocol ();
184                         discoverer.Discover (Url);
185                         
186                         foreach (object info in discoverer.AdditionalInformation)
187                         {
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) {
190                                         Url = sb.Address;
191                                         return;
192                                 }
193                         }
194                         
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);
199                 }
200
201                 protected override WebRequest GetWebRequest (Uri uri)
202                 {
203                         return base.GetWebRequest (uri);
204                 }
205
206                 WebRequest GetRequestForMessage (Uri uri, SoapClientMessage message)
207                 {
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";
214                         return request;
215                 }
216
217                 [MonoTODO]
218                 protected virtual
219                 XmlReader GetReaderForMessage (
220                         SoapClientMessage message, int bufferSize)
221                 {
222                         throw new NotImplementedException ();
223                 }
224
225                 [MonoTODO]
226                 protected virtual
227                 XmlWriter GetWriterForMessage (
228                         SoapClientMessage message, int bufferSize)
229                 {
230                         throw new NotImplementedException ();
231                 }
232
233                 void SendRequest (Stream s, SoapClientMessage message, SoapExtension[] extensions)
234                 {
235                         using (s) {
236
237                                 if (extensions != null) {
238                                         s = SoapExtension.ExecuteChainStream (extensions, s);
239                                         message.SetStage (SoapMessageStage.BeforeSerialize);
240                                         SoapExtension.ExecuteProcessMessage (extensions, message, s, true);
241                                 }
242
243                                 XmlTextWriter xtw = WebServiceHelper.CreateXmlWriter (s);
244                                 WebServiceHelper.WriteSoapMessage (xtw, message.MethodStubInfo, SoapHeaderDirection.In, message.Parameters, message.Headers, message.IsSoap12);
245
246                                 if (extensions != null) {
247                                         message.SetStage (SoapMessageStage.AfterSerialize);
248                                         SoapExtension.ExecuteProcessMessage (extensions, message, s, true);
249                                 }
250
251                                 xtw.Flush ();
252                                 xtw.Close ();
253                          }
254                 }
255
256
257                 //
258                 // TODO:
259                 //    Handle other web responses (multi-output?)
260                 //    
261                 object [] ReceiveResponse (WebResponse response, SoapClientMessage message, SoapExtension[] extensions)
262                 {
263                         SoapMethodStubInfo msi = message.MethodStubInfo;
264                         HttpWebResponse http_response = response as HttpWebResponse;
265
266                         if (http_response != null)
267                         {
268                                 HttpStatusCode code = http_response.StatusCode;
269         
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);
274                                 }
275                                 if (message.OneWay && response.ContentLength <= 0 && (code == HttpStatusCode.Accepted || code == HttpStatusCode.OK)) {
276                                         return new object[0];
277                                 }
278                         }
279                         
280                         //
281                         // Remove optional encoding
282                         //
283                         string ctype;
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),
289                                         response, encoding);
290
291                         message.ContentType = ctype;
292                         message.ContentEncoding = encoding.WebName;
293                         
294                         Stream stream = response.GetResponseStream ();
295
296                         if (extensions != null) {
297                                 stream = SoapExtension.ExecuteChainStream (extensions, stream);
298                                 message.SetStage (SoapMessageStage.BeforeDeserialize);
299                                 SoapExtension.ExecuteProcessMessage (extensions, message, stream, false);
300                         }
301                         
302                         // Deserialize the response
303
304                         SoapHeaderCollection headers;
305                         object content;
306
307                         using (StreamReader reader = new StreamReader (stream, encoding, false)) {
308                                 XmlTextReader xml_reader = new XmlTextReader (reader);
309
310                                 WebServiceHelper.ReadSoapMessage (xml_reader, msi, SoapHeaderDirection.Out, message.IsSoap12, out content, out headers);
311                         }
312
313                         if (content is Soap12Fault) {
314                                 SoapException ex = WebServiceHelper.Soap12FaultToSoapException ((Soap12Fault) content);
315                                 message.SetException (ex);
316                         }
317                         else
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);
322                         }
323                         else
324                                 message.OutParameters = (object[]) content;
325                         
326                         message.SetHeaders (headers);
327                         message.UpdateHeaderValues (this, message.MethodStubInfo.Headers);
328
329                         if (extensions != null) {
330                                 message.SetStage (SoapMessageStage.AfterDeserialize);
331                                 SoapExtension.ExecuteProcessMessage (extensions, message, stream, false);
332                         }
333
334                         if (message.Exception == null)
335                                 return message.OutParameters;
336                         else
337                                 throw message.Exception;
338                 }
339
340                 protected object[] Invoke (string method_name, object[] parameters)
341                 {
342                         SoapMethodStubInfo msi = (SoapMethodStubInfo) type_info.GetMethod (method_name);
343                         
344                         SoapClientMessage message = new SoapClientMessage (this, msi, Url, parameters);
345                         message.CollectHeaders (this, message.MethodStubInfo.Headers, SoapHeaderDirection.In);
346
347                         SoapExtension[] extensions = SoapExtension.CreateExtensionChain (type_info.SoapExtensions[0], msi.SoapExtensions, type_info.SoapExtensions[1]);
348
349                         WebResponse response;
350                         try
351                         {
352                                 WebRequest request = GetRequestForMessage (uri, message);
353                                 SendRequest (request.GetRequestStream (), message, extensions);
354                                 response = GetWebResponse (request);
355                         }
356                         catch (WebException ex)
357                         {
358                                 response = ex.Response;
359                                 HttpWebResponse http_response = response as HttpWebResponse;
360                                 if (http_response == null || http_response.StatusCode != HttpStatusCode.InternalServerError)
361                                         throw ex;
362                         }
363
364                         try {
365                                 return ReceiveResponse (response, message, extensions);
366                         }
367                         finally {
368                                 response.Close();
369                         }
370                 }
371                 
372
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; }
379                 }
380                 
381                 protected void InvokeAsync (string methodName, object[] parameters, SendOrPostCallback callback)
382                 {
383                         InvokeAsync (methodName, parameters, callback, null);
384                 }
385
386                 protected void InvokeAsync (string methodName, object[] parameters, SendOrPostCallback callback, object userState)
387                 {
388                         InvokeAsyncInfo info = new InvokeAsyncInfo (callback, userState);
389                         BeginInvoke (methodName, parameters, new AsyncCallback (InvokeAsyncCallback), info);
390                 }
391                 
392                 void InvokeAsyncCallback (IAsyncResult ar)
393                 {
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);
400                         else
401                                 info.Callback (args);
402                 }
403
404
405                 #endregion // Methods
406         }
407 }
408