2 // System.Web.Services.Protocols.WebServiceHelper.cs
5 // Lluis Sanchez Gual (lluis@ximian.com)
7 // Copyright (C) Ximian, Inc. 2003
11 // Permission is hereby granted, free of charge, to any person obtaining
12 // a copy of this software and associated documentation files (the
13 // "Software"), to deal in the Software without restriction, including
14 // without limitation the rights to use, copy, modify, merge, publish,
15 // distribute, sublicense, and/or sell copies of the Software, and to
16 // permit persons to whom the Software is furnished to do so, subject to
17 // the following conditions:
19 // The above copyright notice and this permission notice shall be
20 // included in all copies or substantial portions of the Software.
22 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
23 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
24 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
25 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
26 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
27 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
28 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
36 using System.Xml.Schema;
37 using System.Xml.Serialization;
38 using System.Web.Services.Description;
40 namespace System.Web.Services.Protocols
42 internal class WebServiceHelper
44 public const string SoapEnvelopeNamespace = "http://schemas.xmlsoap.org/soap/envelope/";
45 public const string Soap12EnvelopeNamespace = "http://www.w3.org/2003/05/soap-envelope";
46 public const string SoapEncodingNamespace = "http://schemas.xmlsoap.org/soap/encoding/";
47 public const string Soap12EncodingNamespace = "http://www.w3.org/2003/05/soap-encoding";
48 static readonly char [] trimChars = { '"', '\'' };
49 static readonly bool prettyXml;
51 static WebServiceHelper ()
53 string pxml = Environment.GetEnvironmentVariable ("MONO_WEBSERVICES_PRETTYXML");
54 prettyXml = (pxml != null && pxml != "no");
57 public static XmlTextWriter CreateXmlWriter (Stream s)
59 // What a waste of UTF8encoders, but it has to be thread safe.
60 XmlTextWriter xtw = new XmlTextWriter (s, new UTF8Encoding (false));
63 xtw.Formatting = Formatting.Indented;
68 public static Encoding GetContentEncoding (string cts, out string content_type)
72 if (cts == null) cts = "";
76 int idx = cts.IndexOf (';');
80 content_type = cts.Substring (0, idx);
82 content_type = content_type.Trim ();
83 for (start = idx + 1; idx != -1;)
85 idx = cts.IndexOf (";", start);
88 body = cts.Substring (start);
91 body = cts.Substring (start, idx - start);
95 if (body.StartsWith ("charset="))
97 encoding = body.Substring (8);
98 encoding = encoding.TrimStart (trimChars).TrimEnd (trimChars);
102 return Encoding.GetEncoding (encoding);
105 public static void WriteSoapMessage (XmlTextWriter xtw, SoapMethodStubInfo method, SoapHeaderDirection dir, object bodyContent, SoapHeaderCollection headers, bool soap12)
107 SoapBindingUse methodUse = dir == SoapHeaderDirection.Fault ? SoapBindingUse.Literal : method.Use;
108 XmlSerializer bodySerializer = method.GetBodySerializer (dir, soap12);
109 XmlSerializer headerSerializer = method.GetHeaderSerializer (dir);
110 object[] headerArray = method.GetHeaderValueArray (dir, headers);
111 WriteSoapMessage (xtw, methodUse, bodySerializer, headerSerializer, bodyContent, headerArray, soap12);
114 public static void WriteSoapMessage (XmlTextWriter xtw, SoapBindingUse methodUse, XmlSerializer bodySerializer, XmlSerializer headerSerializer, object bodyContent, object[] headers, bool soap12)
117 WebServiceHelper.Soap12EnvelopeNamespace :
118 WebServiceHelper.SoapEnvelopeNamespace;
119 string encNS = soap12 ?
120 WebServiceHelper.Soap12EncodingNamespace :
121 WebServiceHelper.SoapEncodingNamespace;
122 xtw.WriteStartDocument ();
123 xtw.WriteStartElement ("soap", "Envelope", ns);
124 xtw.WriteAttributeString ("xmlns", "xsi", null, XmlSchema.InstanceNamespace);
125 xtw.WriteAttributeString ("xmlns", "xsd", null, XmlSchema.Namespace);
130 xtw.WriteStartElement ("soap", "Header", ns);
131 headerSerializer.Serialize (xtw, headers);
132 xtw.WriteEndElement ();
136 xtw.WriteStartElement ("soap", "Body", ns);
138 if (methodUse == SoapBindingUse.Encoded)
139 xtw.WriteAttributeString ("encodingStyle", ns, encNS);
141 bodySerializer.Serialize (xtw, bodyContent);
143 xtw.WriteEndElement ();
144 xtw.WriteEndElement ();
148 public static void ReadSoapMessage (XmlTextReader xmlReader, SoapMethodStubInfo method, SoapHeaderDirection dir, bool soap12, out object body, out SoapHeaderCollection headers)
150 XmlSerializer bodySerializer = method.GetBodySerializer (dir, false);// no need to worry about soap12 arg since no call for Fault anyways here.
151 XmlSerializer headerSerializer = method.GetHeaderSerializer (dir);
152 ReadSoapMessage (xmlReader, bodySerializer, headerSerializer, soap12, out body, out headers);
155 public static void ReadSoapMessage (XmlTextReader xmlReader, XmlSerializer bodySerializer, XmlSerializer headerSerializer, bool soap12, out object body, out SoapHeaderCollection headers)
157 xmlReader.MoveToContent ();
158 string ns = xmlReader.NamespaceURI;
161 case WebServiceHelper.Soap12EnvelopeNamespace:
163 case WebServiceHelper.SoapEnvelopeNamespace:
166 throw new SoapException (String.Format ("SOAP version mismatch. Namespace '{0}' is not supported in this runtime profile.", ns), VersionMismatchFaultCode (soap12));
168 xmlReader.ReadStartElement ("Envelope", ns);
170 headers = ReadHeaders (xmlReader, headerSerializer, ns);
172 xmlReader.MoveToContent ();
173 xmlReader.ReadStartElement ("Body", ns);
174 xmlReader.MoveToContent ();
176 if (xmlReader.LocalName == "Fault" && xmlReader.NamespaceURI == ns)
177 bodySerializer = ns == Soap12EnvelopeNamespace ? Soap12Fault.Serializer : Fault.Serializer;
179 body = bodySerializer.Deserialize (xmlReader);
182 static SoapHeaderCollection ReadHeaders (XmlTextReader xmlReader, XmlSerializer headerSerializer, string ns)
184 SoapHeaderCollection headers = null;
185 while (! (xmlReader.NodeType == XmlNodeType.Element && xmlReader.LocalName == "Body" && xmlReader.NamespaceURI == ns))
187 if (xmlReader.NodeType == XmlNodeType.Element && xmlReader.LocalName == "Header"
188 && xmlReader.NamespaceURI == ns && !xmlReader.IsEmptyElement
189 && headerSerializer != null)
191 xmlReader.ReadStartElement ();
192 xmlReader.MoveToContent ();
194 HeaderSerializationHelper uh = new HeaderSerializationHelper (headerSerializer);
195 headers = uh.Deserialize (xmlReader);
197 while (xmlReader.NodeType != XmlNodeType.EndElement)
200 xmlReader.ReadEndElement ();
208 return new SoapHeaderCollection ();
211 class HeaderSerializationHelper
213 SoapHeaderCollection headers;
214 XmlSerializer headerSerializer;
216 public HeaderSerializationHelper (XmlSerializer headerSerializer)
218 this.headers = new SoapHeaderCollection ();
219 this.headerSerializer = headerSerializer;
222 public SoapHeaderCollection Deserialize (XmlTextReader xmlReader)
225 headerSerializer.UnknownElement += new XmlElementEventHandler (OnAddUnknownHeader);
226 object[] headerArray = (object[]) headerSerializer.Deserialize (xmlReader);
227 foreach (SoapHeader h in headerArray)
228 if (h != null) headers.Add (h);
231 headerSerializer.UnknownElement -= new XmlElementEventHandler (OnAddUnknownHeader);
235 void OnAddUnknownHeader (object sender, XmlElementEventArgs e)
237 headers.Add (new SoapUnknownHeader (e.Element));
242 public static SoapException Soap12FaultToSoapException (Soap12Fault fault)
244 Soap12FaultReasonText text =
245 fault.Reason != null &&
246 fault.Reason.Texts != null &&
247 fault.Reason.Texts.Length > 0 ?
248 fault.Reason.Texts [fault.Reason.Texts.Length - 1] : null;
249 XmlNode detail = (fault.Detail == null) ? null :
250 (fault.Detail.Children != null &&
251 fault.Detail.Children.Length > 0) ?
252 (XmlNode) fault.Detail.Children [0] :
253 (fault.Detail.Attributes != null &&
254 fault.Detail.Attributes.Length > 0) ?
255 fault.Detail.Attributes [0] : null;
256 SoapFaultSubCode subcode = Soap12Fault.GetSoapFaultSubCode (fault.Code.Subcode);
257 return new SoapException (
258 text != null ? text.Value : null,
259 fault.Code.Value, null, fault.Role,
260 text != null ? text.XmlLang : null,
261 detail, subcode, null);
265 public static XmlQualifiedName ClientFaultCode (bool soap12)
268 return soap12 ? Soap12FaultCodes.SenderFaultCode : SoapException.ClientFaultCode;
270 return SoapException.ClientFaultCode;
274 public static XmlQualifiedName ServerFaultCode (bool soap12)
277 return soap12 ? Soap12FaultCodes.ReceiverFaultCode : SoapException.ServerFaultCode;
279 return SoapException.ServerFaultCode;
283 public static XmlQualifiedName MustUnderstandFaultCode (bool soap12)
286 return soap12 ? Soap12FaultCodes.ReceiverFaultCode : SoapException.MustUnderstandFaultCode;
288 return SoapException.MustUnderstandFaultCode;
292 public static XmlQualifiedName VersionMismatchFaultCode (bool soap12)
295 return soap12 ? Soap12FaultCodes.VersionMismatchFaultCode : SoapException.VersionMismatchFaultCode;
297 return SoapException.VersionMismatchFaultCode;
301 public static void InvalidOperation (string message, WebResponse response, Encoding enc)
303 if (response == null)
304 throw new InvalidOperationException (message);
309 StringBuilder sb = new StringBuilder ();
311 if (response.ContentLength > 0) {
312 sb.Append ("\r\nResponse error message:\r\n--\r\n");
315 StreamReader resp = new StreamReader (response.GetResponseStream (), enc);
316 sb.Append (resp.ReadToEnd ());
317 } catch (Exception) {
321 throw new InvalidOperationException (sb.ToString ());