2005-01-31 Zoltan Varga <vargaz@freemail.hu>
[mono.git] / mcs / class / System.Web.Services / System.Web.Services.Protocols / SoapHttpClientProtocol.cs
index 2b17b469e706e8fc32896eb8207d026671909f09..143432a50207121a1ecfd279bc44f86b28837f2a 100644 (file)
 //\r
 // Author:\r
 //   Tim Coleman (tim@timcoleman.com)\r
+//   Miguel de Icaza (miguel@ximian.com)\r
+//   Lluis Sanchez Gual (lluis@ximian.com)\r
 //\r
 // Copyright (C) Tim Coleman, 2002\r
+// Copyright (C) Ximian, Inc, 2003\r
 //\r
+
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
 \r
+using System.IO;\r
 using System.Net;\r
 using System.Web;\r
+using System.Xml;\r
+using System.Text;\r
+using System.Reflection;\r
 using System.Web.Services;\r
+using System.Diagnostics;\r
+using System.Runtime.CompilerServices;\r
+using System.Web.Services.Description;\r
+using System.Web.Services.Discovery;\r
+using System.Xml.Serialization;\r
+using System.Xml.Schema;\r
+using System.Collections;\r
+using System.Threading;\r
 \r
-namespace System.Web.Services.Protocols {\r
-       public class SoapHttpClientProtocol : HttpWebClientProtocol {\r
+namespace System.Web.Services.Protocols \r
+{\r
+       public class SoapHttpClientProtocol : HttpWebClientProtocol \r
+       {\r
+               SoapTypeStubInfo type_info;\r
+#if NET_2_0\r
+               WsiClaims conformanceClaims;\r
+               SoapProtocolVersion soapVersion;\r
+#endif\r
+\r
+               #region SoapWebClientAsyncResult class\r
+\r
+               internal class SoapWebClientAsyncResult: WebClientAsyncResult\r
+               {\r
+                       public SoapWebClientAsyncResult (WebRequest request, AsyncCallback callback, object asyncState)\r
+                       : base (request, callback, asyncState)\r
+                       {\r
+                       }\r
+               \r
+                       public SoapClientMessage Message;\r
+                       public SoapExtension[] Extensions;\r
+               }\r
+               #endregion\r
 \r
                #region Constructors\r
 \r
                public SoapHttpClientProtocol () \r
                {\r
+                       type_info = (SoapTypeStubInfo) TypeStubManager.GetTypeStub (this.GetType (), "Soap");\r
                }\r
-               \r
+\r
                #endregion // Constructors\r
 \r
                #region Methods\r
 \r
-               [MonoTODO]\r
                protected IAsyncResult BeginInvoke (string methodName, object[] parameters, AsyncCallback callback, object asyncState)\r
                {\r
-                       throw new NotImplementedException ();\r
+                       SoapMethodStubInfo msi = (SoapMethodStubInfo) type_info.GetMethod (methodName);\r
+\r
+                       SoapWebClientAsyncResult ainfo = null;\r
+                       try\r
+                       {\r
+                               SoapClientMessage message = new SoapClientMessage (this, msi, Url, parameters);\r
+                               message.CollectHeaders (this, message.MethodStubInfo.Headers, SoapHeaderDirection.In);\r
+                               \r
+                               WebRequest request = GetRequestForMessage (uri, message);\r
+                               \r
+                               ainfo = new SoapWebClientAsyncResult (request, callback, asyncState);\r
+                               ainfo.Message = message;\r
+                               ainfo.Extensions = SoapExtension.CreateExtensionChain (type_info.SoapExtensions[0], msi.SoapExtensions, type_info.SoapExtensions[1]);\r
+\r
+                               ainfo.Request.BeginGetRequestStream (new AsyncCallback (AsyncGetRequestStreamDone), ainfo);\r
+                       }\r
+                       catch (Exception ex)\r
+                       {\r
+                               if (ainfo != null)\r
+                                       ainfo.SetCompleted (null, ex, false);\r
+                       }\r
+\r
+                       return ainfo;\r
                }\r
 \r
-               [MonoTODO]\r
-               public void Discover ()\r
+               void AsyncGetRequestStreamDone (IAsyncResult ar)\r
                {\r
-                       throw new NotImplementedException ();\r
+                       SoapWebClientAsyncResult ainfo = (SoapWebClientAsyncResult) ar.AsyncState;\r
+                       try\r
+                       {\r
+                               SendRequest (ainfo.Request.EndGetRequestStream (ar), ainfo.Message, ainfo.Extensions);\r
+                               ainfo.Request.BeginGetResponse (new AsyncCallback (AsyncGetResponseDone), ainfo);\r
+                       }\r
+                       catch (Exception ex)\r
+                       {\r
+                               ainfo.SetCompleted (null, ex, true);\r
+                       }\r
+               }\r
+\r
+               void AsyncGetResponseDone (IAsyncResult ar)\r
+               {\r
+                       SoapWebClientAsyncResult ainfo = (SoapWebClientAsyncResult) ar.AsyncState;\r
+                       WebResponse response = null;\r
+\r
+                       try {\r
+                               response = GetWebResponse (ainfo.Request, ar);\r
+                       }\r
+                       catch (WebException ex) {\r
+                               response = ex.Response;\r
+                               HttpWebResponse http_response = response as HttpWebResponse;\r
+                               if (http_response == null || http_response.StatusCode != HttpStatusCode.InternalServerError) {\r
+                                       ainfo.SetCompleted (null, ex, true);\r
+                                       return;\r
+                               }\r
+                       }\r
+                       catch (Exception ex) {\r
+                               ainfo.SetCompleted (null, ex, true);\r
+                               return;\r
+                       }\r
+\r
+                       try {\r
+                               object[] result = ReceiveResponse (response, ainfo.Message, ainfo.Extensions);\r
+                               ainfo.SetCompleted (result, null, true);\r
+                       }\r
+                       catch (Exception ex) {\r
+                               ainfo.SetCompleted (null, ex, true);\r
+                       }\r
                }\r
 \r
-               [MonoTODO]\r
                protected object[] EndInvoke (IAsyncResult asyncResult)\r
                {\r
-                       throw new NotImplementedException ();\r
+                       if (!(asyncResult is SoapWebClientAsyncResult)) throw new ArgumentException ("asyncResult is not the return value from BeginInvoke");\r
+\r
+                       SoapWebClientAsyncResult ainfo = (SoapWebClientAsyncResult) asyncResult;\r
+                       lock (ainfo)\r
+                       {\r
+                               if (!ainfo.IsCompleted) ainfo.WaitForComplete ();\r
+                               if (ainfo.Exception != null) throw ainfo.Exception;\r
+                               else return (object[]) ainfo.Result;\r
+                       }\r
+               }\r
+\r
+               public void Discover ()\r
+               {\r
+                       BindingInfo bnd = (BindingInfo) type_info.Bindings [0];\r
+                       \r
+                       DiscoveryClientProtocol discoverer = new DiscoveryClientProtocol ();\r
+                       discoverer.Discover (Url);\r
+                       \r
+                       foreach (object info in discoverer.AdditionalInformation)\r
+                       {\r
+                               System.Web.Services.Discovery.SoapBinding sb = info as System.Web.Services.Discovery.SoapBinding;\r
+                               if (sb != null && sb.Binding.Name == bnd.Name && sb.Binding.Namespace == bnd.Namespace) {\r
+                                       Url = sb.Address;\r
+                                       return;\r
+                               }\r
+                       }\r
+                       \r
+                       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);\r
+                       throw new Exception (msg);\r
                }\r
 \r
                protected override WebRequest GetWebRequest (Uri uri)\r
                {\r
-                       return WebRequest.Create (uri);\r
+                       return base.GetWebRequest (uri);\r
+               }\r
+\r
+               WebRequest GetRequestForMessage (Uri uri, SoapClientMessage message)\r
+               {\r
+                       WebRequest request = GetWebRequest (uri);\r
+                       request.Method = "POST";\r
+                       WebHeaderCollection headers = request.Headers;\r
+                       headers.Add ("SOAPAction", "\"" + message.Action + "\"");\r
+                       request.ContentType = message.ContentType + "; charset=utf-8";\r
+                       return request;\r
+               }\r
+               \r
+               void SendRequest (Stream s, SoapClientMessage message, SoapExtension[] extensions)\r
+               {\r
+                       using (s) {\r
+\r
+                               if (extensions != null) {\r
+                                       s = SoapExtension.ExecuteChainStream (extensions, s);\r
+                                       message.SetStage (SoapMessageStage.BeforeSerialize);\r
+                                       SoapExtension.ExecuteProcessMessage (extensions, message, true);
+                               }
+\r
+                               XmlTextWriter xtw = WebServiceHelper.CreateXmlWriter (s);\r
+                               \r
+                               WebServiceHelper.WriteSoapMessage (xtw, type_info, message.MethodStubInfo.Use, message.MethodStubInfo.RequestSerializer, message.Parameters, message.Headers);\r
+\r
+                               if (extensions != null) {\r
+                                       message.SetStage (SoapMessageStage.AfterSerialize);\r
+                                       SoapExtension.ExecuteProcessMessage (extensions, message, true);
+                               }
+\r
+                               xtw.Flush ();\r
+                               xtw.Close ();\r
+                        }\r
+               }\r
+\r
+\r
+               //\r
+               // TODO:\r
+               //    Handle other web responses (multi-output?)\r
+               //    \r
+               object [] ReceiveResponse (WebResponse response, SoapClientMessage message, SoapExtension[] extensions)\r
+               {\r
+                       SoapMethodStubInfo msi = message.MethodStubInfo;\r
+                       HttpWebResponse http_response = response as HttpWebResponse;\r
+                       \r
+                       if (http_response != null)\r
+                       {\r
+                               HttpStatusCode code = http_response.StatusCode;\r
+       \r
+                               if (!(code == HttpStatusCode.Accepted || code == HttpStatusCode.OK || code == HttpStatusCode.InternalServerError)) {\r
+                                       string msg = "The request failed with HTTP status {0}: {1}";\r
+                                       msg = String.Format (msg, (int) code, code);\r
+                                       throw new WebException (msg, null, WebExceptionStatus.ProtocolError, http_response);\r
+                               }\r
+                               if (response.ContentLength == 0 && (code == HttpStatusCode.Accepted || code == HttpStatusCode.OK)) {\r
+                                       return new object[0];\r
+                               }\r
+                       }\r
+                       \r
+                       //\r
+                       // Remove optional encoding\r
+                       //\r
+                       string ctype;
+                       Encoding encoding = WebServiceHelper.GetContentEncoding (response.ContentType, out ctype);\r
+                       if (ctype != "text/xml")
+                               WebServiceHelper.InvalidOperation (
+                                       "Content is not 'text/xml' but '" + response.ContentType + "'",
+                                       response, encoding);
+\r
+                       message.ContentType = ctype;\r
+                       message.ContentEncoding = encoding.WebName;\r
+                       \r
+                       Stream stream = response.GetResponseStream ();\r
+\r
+                       if (extensions != null) {\r
+                               stream = SoapExtension.ExecuteChainStream (extensions, stream);\r
+                               message.SetStage (SoapMessageStage.BeforeDeserialize);\r
+                               SoapExtension.ExecuteProcessMessage (extensions, message, false);
+                       }
+                       \r
+                       // Deserialize the response\r
+\r
+                       SoapHeaderCollection headers;\r
+                       object content;\r
+\r
+                       using (StreamReader reader = new StreamReader (stream, encoding, false)) {
+                               XmlTextReader xml_reader = new XmlTextReader (reader);
+
+                               WebServiceHelper.ReadSoapMessage (xml_reader, type_info, msi.Use, msi.ResponseSerializer,
+                                                               out content, out headers);
+                       }
+
+                       \r
+                       if (content is Fault)\r
+                       {\r
+                               Fault fault = (Fault) content;\r
+                               SoapException ex = new SoapException (fault.faultstring, fault.faultcode, fault.faultactor, fault.detail);\r
+                               message.SetException (ex);\r
+                       }\r
+                       else\r
+                               message.OutParameters = (object[]) content;\r
+                       \r
+                       message.SetHeaders (headers);\r
+                       message.UpdateHeaderValues (this, message.MethodStubInfo.Headers);\r
+\r
+                       if (extensions != null) {\r
+                               message.SetStage (SoapMessageStage.AfterDeserialize);\r
+                               SoapExtension.ExecuteProcessMessage (extensions, message, false);
+                       }
+\r
+                       if (message.Exception == null)\r
+                               return message.OutParameters;\r
+                       else\r
+                               throw message.Exception;\r
+               }\r
+\r
+               protected object[] Invoke (string method_name, object[] parameters)\r
+               {\r
+                       SoapMethodStubInfo msi = (SoapMethodStubInfo) type_info.GetMethod (method_name);\r
+                       \r
+                       SoapClientMessage message = new SoapClientMessage (this, msi, Url, parameters);\r
+                       message.CollectHeaders (this, message.MethodStubInfo.Headers, SoapHeaderDirection.In);\r
+\r
+                       SoapExtension[] extensions = SoapExtension.CreateExtensionChain (type_info.SoapExtensions[0], msi.SoapExtensions, type_info.SoapExtensions[1]);\r
+\r
+                       WebResponse response;\r
+                       try\r
+                       {\r
+                               WebRequest request = GetRequestForMessage (uri, message);\r
+                               SendRequest (request.GetRequestStream (), message, extensions);\r
+                               response = GetWebResponse (request);\r
+                       }\r
+                       catch (WebException ex)\r
+                       {\r
+                               response = ex.Response;\r
+                               HttpWebResponse http_response = response as HttpWebResponse;\r
+                               if (http_response == null || http_response.StatusCode != HttpStatusCode.InternalServerError)\r
+                                       throw ex;\r
+                       }\r
+\r
+                       return ReceiveResponse (response, message, extensions);\r
+               }\r
+               \r
+#if NET_2_0\r
+\r
+               [MonoTODO ("Do something with this")]\r
+               [System.Runtime.InteropServices.ComVisible(false)]\r
+               [Obsolete]\r
+               public WsiClaims ConformanceClaims {\r
+                       get { return conformanceClaims; }\r
+                       set { conformanceClaims = value; }\r
+               }\r
+               \r
+               [MonoTODO ("Do something with this")]\r
+               [System.Runtime.InteropServices.ComVisible(false)]\r
+               public SoapProtocolVersion SoapVersion {\r
+                       get { return soapVersion; }\r
+                       set { soapVersion = value; }\r
+               }\r
+               \r
+               protected void InvokeAsync (string methodName, object[] parameters, SendOrPostCallback callback)\r
+               {\r
+                       InvokeAsync (methodName, parameters, callback, null);\r
                }\r
 \r
-               [MonoTODO]\r
-               protected object[] Invoke (string methodName, object[] parameters)\r
+               protected void InvokeAsync (string methodName, object[] parameters, SendOrPostCallback callback, object userState)\r
                {\r
-                       throw new NotImplementedException ();\r
+                       InvokeAsyncInfo info = new InvokeAsyncInfo (callback, userState);\r
+                       BeginInvoke (methodName, parameters, new AsyncCallback (InvokeAsyncCallback), info);\r
                }\r
+               \r
+               void InvokeAsyncCallback (IAsyncResult ar)\r
+               {\r
+                       InvokeAsyncInfo info = (InvokeAsyncInfo) ar.AsyncState;\r
+                       SoapWebClientAsyncResult sar = (SoapWebClientAsyncResult) ar;\r
+                       InvokeCompletedEventArgs args = new InvokeCompletedEventArgs (sar.Exception, false, info.UserState, (object[]) sar.Result);\r
+                       if (info.Context != null)\r
+                               info.Context.SendOrPost (info.Callback, args);\r
+                       else\r
+                               info.Callback (args);\r
+               }\r
+\r
+#endif\r
 \r
                #endregion // Methods\r
        }\r
-}\r
+}
+\r