WebServiceHelper.cs 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  1. //
  2. // System.Web.Services.Protocols.WebServiceHelper.cs
  3. //
  4. // Author:
  5. // Lluis Sanchez Gual ([email protected])
  6. //
  7. // Copyright (C) Ximian, Inc. 2003
  8. //
  9. //
  10. // Permission is hereby granted, free of charge, to any person obtaining
  11. // a copy of this software and associated documentation files (the
  12. // "Software"), to deal in the Software without restriction, including
  13. // without limitation the rights to use, copy, modify, merge, publish,
  14. // distribute, sublicense, and/or sell copies of the Software, and to
  15. // permit persons to whom the Software is furnished to do so, subject to
  16. // the following conditions:
  17. //
  18. // The above copyright notice and this permission notice shall be
  19. // included in all copies or substantial portions of the Software.
  20. //
  21. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  22. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  23. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  24. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  25. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  26. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  27. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  28. //
  29. using System;
  30. using System.IO;
  31. using System.Net;
  32. using System.Text;
  33. using System.Xml;
  34. using System.Xml.Schema;
  35. using System.Xml.Serialization;
  36. using System.Web.Services.Description;
  37. namespace System.Web.Services.Protocols
  38. {
  39. internal class WebServiceHelper
  40. {
  41. public const string SoapEnvelopeNamespace = "http://schemas.xmlsoap.org/soap/envelope/";
  42. public const string Soap12EnvelopeNamespace = "http://www.w3.org/2003/05/soap-envelope";
  43. public const string SoapEncodingNamespace = "http://schemas.xmlsoap.org/soap/encoding/";
  44. public const string Soap12EncodingNamespace = "http://www.w3.org/2003/05/soap-encoding";
  45. static readonly char [] trimChars = { '"', '\'' };
  46. static readonly bool prettyXml;
  47. static WebServiceHelper ()
  48. {
  49. string pxml = Environment.GetEnvironmentVariable ("MONO_WEBSERVICES_PRETTYXML");
  50. prettyXml = (pxml != null && pxml != "no");
  51. }
  52. public static XmlTextWriter CreateXmlWriter (Stream s)
  53. {
  54. // What a waste of UTF8encoders, but it has to be thread safe.
  55. XmlTextWriter xtw = new XmlTextWriter (s, new UTF8Encoding (false));
  56. if (prettyXml)
  57. xtw.Formatting = Formatting.Indented;
  58. return xtw;
  59. }
  60. public static Encoding GetContentEncoding (string cts, out string content_type)
  61. {
  62. string encoding;
  63. if (cts == null) cts = "";
  64. encoding = "utf-8";
  65. int start = 0;
  66. int idx = cts.IndexOf (';');
  67. if (idx == -1)
  68. content_type = cts;
  69. else
  70. content_type = cts.Substring (0, idx);
  71. content_type = content_type.Trim ();
  72. for (start = idx + 1; idx != -1;)
  73. {
  74. idx = cts.IndexOf (";", start);
  75. string body;
  76. if (idx == -1)
  77. body = cts.Substring (start);
  78. else
  79. {
  80. body = cts.Substring (start, idx - start);
  81. start = idx + 1;
  82. }
  83. body = body.Trim ();
  84. if (body.StartsWith ("charset="))
  85. {
  86. encoding = body.Substring (8);
  87. encoding = encoding.TrimStart (trimChars).TrimEnd (trimChars);
  88. }
  89. }
  90. return Encoding.GetEncoding (encoding);
  91. }
  92. public static void WriteSoapMessage (XmlTextWriter xtw, SoapMethodStubInfo method, SoapHeaderDirection dir, object bodyContent, SoapHeaderCollection headers, bool soap12)
  93. {
  94. SoapBindingUse methodUse = dir == SoapHeaderDirection.Fault ? SoapBindingUse.Literal : method.Use;
  95. XmlSerializer bodySerializer = method.GetBodySerializer (dir, soap12);
  96. XmlSerializer headerSerializer = method.GetHeaderSerializer (dir);
  97. object[] headerArray = method.GetHeaderValueArray (dir, headers);
  98. WriteSoapMessage (xtw, methodUse, bodySerializer, headerSerializer, bodyContent, headerArray, soap12);
  99. }
  100. public static void WriteSoapMessage (XmlTextWriter xtw, SoapBindingUse methodUse, XmlSerializer bodySerializer, XmlSerializer headerSerializer, object bodyContent, object[] headers, bool soap12)
  101. {
  102. string ns = soap12 ?
  103. WebServiceHelper.Soap12EnvelopeNamespace :
  104. WebServiceHelper.SoapEnvelopeNamespace;
  105. string encNS = soap12 ?
  106. WebServiceHelper.Soap12EncodingNamespace :
  107. WebServiceHelper.SoapEncodingNamespace;
  108. xtw.WriteStartDocument ();
  109. xtw.WriteStartElement ("soap", "Envelope", ns);
  110. xtw.WriteAttributeString ("xmlns", "xsi", null, XmlSchema.InstanceNamespace);
  111. xtw.WriteAttributeString ("xmlns", "xsd", null, XmlSchema.Namespace);
  112. // Serialize headers
  113. if (headers != null)
  114. {
  115. xtw.WriteStartElement ("soap", "Header", ns);
  116. headerSerializer.Serialize (xtw, headers);
  117. xtw.WriteEndElement ();
  118. }
  119. // Serialize body
  120. xtw.WriteStartElement ("soap", "Body", ns);
  121. if (methodUse == SoapBindingUse.Encoded)
  122. xtw.WriteAttributeString ("encodingStyle", ns, encNS);
  123. bodySerializer.Serialize (xtw, bodyContent);
  124. xtw.WriteEndElement ();
  125. xtw.WriteEndElement ();
  126. xtw.Flush ();
  127. }
  128. public static void ReadSoapMessage (XmlTextReader xmlReader, SoapMethodStubInfo method, SoapHeaderDirection dir, out object body, out SoapHeaderCollection headers)
  129. {
  130. XmlSerializer bodySerializer = method.GetBodySerializer (dir, false);// no need to worry about soap12 arg since no call for Fault anyways here.
  131. XmlSerializer headerSerializer = method.GetHeaderSerializer (dir);
  132. ReadSoapMessage (xmlReader, bodySerializer, headerSerializer, out body, out headers);
  133. }
  134. public static void ReadSoapMessage (XmlTextReader xmlReader, XmlSerializer bodySerializer, XmlSerializer headerSerializer, out object body, out SoapHeaderCollection headers)
  135. {
  136. xmlReader.MoveToContent ();
  137. string ns = xmlReader.NamespaceURI;
  138. switch (ns) {
  139. #if NET_2_0
  140. case WebServiceHelper.Soap12EnvelopeNamespace:
  141. #endif
  142. case WebServiceHelper.SoapEnvelopeNamespace:
  143. break;
  144. default:
  145. throw new SoapException (String.Format ("SOAP version mismatch. Namespace '{0}' is not supported in this runtime profile.", ns), SoapException.VersionMismatchFaultCode);
  146. }
  147. xmlReader.ReadStartElement ("Envelope", ns);
  148. headers = ReadHeaders (xmlReader, headerSerializer, ns);
  149. xmlReader.MoveToContent ();
  150. xmlReader.ReadStartElement ("Body", ns);
  151. xmlReader.MoveToContent ();
  152. if (xmlReader.LocalName == "Fault" && xmlReader.NamespaceURI == ns)
  153. bodySerializer = ns == Soap12EnvelopeNamespace ? Soap12Fault.Serializer : Fault.Serializer;
  154. body = bodySerializer.Deserialize (xmlReader);
  155. }
  156. static SoapHeaderCollection ReadHeaders (XmlTextReader xmlReader, XmlSerializer headerSerializer, string ns)
  157. {
  158. SoapHeaderCollection headers = null;
  159. while (! (xmlReader.NodeType == XmlNodeType.Element && xmlReader.LocalName == "Body" && xmlReader.NamespaceURI == ns))
  160. {
  161. if (xmlReader.NodeType == XmlNodeType.Element && xmlReader.LocalName == "Header"
  162. && xmlReader.NamespaceURI == ns && !xmlReader.IsEmptyElement
  163. && headerSerializer != null)
  164. {
  165. xmlReader.ReadStartElement ();
  166. xmlReader.MoveToContent ();
  167. HeaderSerializationHelper uh = new HeaderSerializationHelper (headerSerializer);
  168. headers = uh.Deserialize (xmlReader);
  169. while (xmlReader.NodeType != XmlNodeType.EndElement)
  170. xmlReader.Skip ();
  171. xmlReader.ReadEndElement ();
  172. }
  173. else
  174. xmlReader.Skip ();
  175. }
  176. if (headers != null)
  177. return headers;
  178. else
  179. return new SoapHeaderCollection ();
  180. }
  181. class HeaderSerializationHelper
  182. {
  183. SoapHeaderCollection headers;
  184. XmlSerializer headerSerializer;
  185. public HeaderSerializationHelper (XmlSerializer headerSerializer)
  186. {
  187. this.headers = new SoapHeaderCollection ();
  188. this.headerSerializer = headerSerializer;
  189. }
  190. public SoapHeaderCollection Deserialize (XmlTextReader xmlReader)
  191. {
  192. try {
  193. headerSerializer.UnknownElement += new XmlElementEventHandler (OnAddUnknownHeader);
  194. object[] headerArray = (object[]) headerSerializer.Deserialize (xmlReader);
  195. foreach (SoapHeader h in headerArray)
  196. if (h != null) headers.Add (h);
  197. return headers;
  198. } finally {
  199. headerSerializer.UnknownElement -= new XmlElementEventHandler (OnAddUnknownHeader);
  200. }
  201. }
  202. void OnAddUnknownHeader (object sender, XmlElementEventArgs e)
  203. {
  204. headers.Add (new SoapUnknownHeader (e.Element));
  205. }
  206. }
  207. public static void InvalidOperation (string message, WebResponse response, Encoding enc)
  208. {
  209. if (response == null)
  210. throw new InvalidOperationException (message);
  211. if (enc == null)
  212. enc = Encoding.UTF8;
  213. StringBuilder sb = new StringBuilder ();
  214. sb.Append (message);
  215. if (response.ContentLength > 0) {
  216. sb.Append ("\r\nResponse error message:\r\n--\r\n");
  217. try {
  218. StreamReader resp = new StreamReader (response.GetResponseStream (), enc);
  219. sb.Append (resp.ReadToEnd ());
  220. } catch (Exception) {
  221. }
  222. }
  223. throw new InvalidOperationException (sb.ToString ());
  224. }
  225. }
  226. }