DiscoveryClientProtocol.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360
  1. //
  2. // System.Web.Services.Protocols.DiscoveryClientProtocol.cs
  3. //
  4. // Author:
  5. // Dave Bettin ([email protected])
  6. // Lluis Sanchez Gual ([email protected])
  7. //
  8. // Copyright (C) Dave Bettin, 2002
  9. //
  10. //
  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:
  18. //
  19. // The above copyright notice and this permission notice shall be
  20. // included in all copies or substantial portions of the Software.
  21. //
  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.
  29. //
  30. using System.Collections;
  31. using System.IO;
  32. using System.Web.Services.Protocols;
  33. using System.Web.Services.Description;
  34. using System.Xml;
  35. using System.Xml.Schema;
  36. using System.Xml.Serialization;
  37. using System.Net;
  38. using System.Text.RegularExpressions;
  39. namespace System.Web.Services.Discovery {
  40. public class DiscoveryClientProtocol : HttpWebClientProtocol {
  41. #region Fields
  42. private IList additionalInformation = new ArrayList ();
  43. private DiscoveryClientDocumentCollection documents = new DiscoveryClientDocumentCollection();
  44. private DiscoveryExceptionDictionary errors = new DiscoveryExceptionDictionary();
  45. private DiscoveryClientReferenceCollection references = new DiscoveryClientReferenceCollection();
  46. #endregion // Fields
  47. #region Constructors
  48. public DiscoveryClientProtocol ()
  49. {
  50. }
  51. #endregion // Constructors
  52. #region Properties
  53. public IList AdditionalInformation {
  54. get { return additionalInformation; }
  55. }
  56. public DiscoveryClientDocumentCollection Documents {
  57. get { return documents; }
  58. }
  59. public DiscoveryExceptionDictionary Errors {
  60. get { return errors; }
  61. }
  62. public DiscoveryClientReferenceCollection References {
  63. get { return references; }
  64. }
  65. #endregion // Properties
  66. #region Methods
  67. public DiscoveryDocument Discover (string url)
  68. {
  69. Stream stream = Download (ref url);
  70. XmlTextReader reader = new XmlTextReader (stream);
  71. if (!DiscoveryDocument.CanRead (reader))
  72. throw new InvalidOperationException ("The url '" + url + "' does not point to a valid discovery document");
  73. DiscoveryDocument doc = DiscoveryDocument.Read (reader);
  74. reader.Close ();
  75. documents.Add (url, doc);
  76. AddDiscoReferences (doc);
  77. return doc;
  78. }
  79. public DiscoveryDocument DiscoverAny (string url)
  80. {
  81. try
  82. {
  83. string contentType = null;
  84. Stream stream = Download (ref url, ref contentType);
  85. if (contentType.IndexOf ("text/html") != -1)
  86. {
  87. // Look for an alternate url
  88. StreamReader sr = new StreamReader (stream);
  89. string str = sr.ReadToEnd ();
  90. string rex = "link\\s*rel\\s*=\\s*[\"']?alternate[\"']?\\s*";
  91. rex += "type\\s*=\\s*[\"']?text/xml[\"']?\\s*href\\s*=\\s*(?:\"(?<1>[^\"]*)\"|'(?<1>[^']*)'|(?<1>\\S+))";
  92. Regex rob = new Regex (rex, RegexOptions.IgnoreCase);
  93. Match m = rob.Match (str);
  94. if (!m.Success)
  95. throw new InvalidOperationException ("The HTML document does not contain Web service discovery information");
  96. if (url.StartsWith ("/"))
  97. {
  98. Uri uri = new Uri (url);
  99. url = uri.GetLeftPart (UriPartial.Authority) + m.Groups[1];
  100. }
  101. else
  102. {
  103. int i = url.LastIndexOf ('/');
  104. if (i == -1)
  105. throw new InvalidOperationException ("The HTML document does not contain Web service discovery information");
  106. url = url.Substring (0,i+1) + m.Groups[1];
  107. }
  108. stream = Download (ref url);
  109. }
  110. XmlTextReader reader = new XmlTextReader (stream);
  111. reader.MoveToContent ();
  112. DiscoveryDocument doc;
  113. DiscoveryReference refe = null;
  114. if (DiscoveryDocument.CanRead (reader))
  115. {
  116. doc = DiscoveryDocument.Read (reader);
  117. documents.Add (url, doc);
  118. refe = new DiscoveryDocumentReference ();
  119. AddDiscoReferences (doc);
  120. }
  121. else if (ServiceDescription.CanRead (reader))
  122. {
  123. ServiceDescription wsdl = ServiceDescription.Read (reader);
  124. documents.Add (url, wsdl);
  125. doc = new DiscoveryDocument ();
  126. refe = new ContractReference ();
  127. doc.References.Add (refe);
  128. refe.Url = url;
  129. ((ContractReference)refe).ResolveInternal (this, wsdl);
  130. }
  131. else
  132. {
  133. XmlSchema schema = XmlSchema.Read (reader, null);
  134. documents.Add (url, schema);
  135. doc = new DiscoveryDocument ();
  136. refe = new SchemaReference ();
  137. doc.References.Add (refe);
  138. }
  139. refe.ClientProtocol = this;
  140. refe.Url = url;
  141. references.Add (url, refe);
  142. reader.Close ();
  143. return doc;
  144. }
  145. catch (DiscoveryException ex) {
  146. throw ex.Exception;
  147. }
  148. }
  149. void AddDiscoReferences (DiscoveryDocument doc)
  150. {
  151. foreach (DiscoveryReference re in doc.References)
  152. {
  153. re.ClientProtocol = this;
  154. references.Add (re.Url, re);
  155. }
  156. if (doc.AdditionalInfo != null) {
  157. foreach (object info in doc.AdditionalInfo)
  158. additionalInformation.Add (info);
  159. }
  160. }
  161. public Stream Download (ref string url)
  162. {
  163. string contentType = null;
  164. return Download (ref url, ref contentType);
  165. }
  166. public Stream Download (ref string url, ref string contentType)
  167. {
  168. if (url.StartsWith ("http://") || url.StartsWith ("https://"))
  169. {
  170. WebRequest request = GetWebRequest (new Uri(url));
  171. WebResponse resp = request.GetResponse ();
  172. contentType = resp.ContentType;
  173. return resp.GetResponseStream ();
  174. }
  175. else
  176. {
  177. string ext = Path.GetExtension (url).ToLower();
  178. if (ext == ".wsdl" || ext == ".xsd")
  179. {
  180. contentType = "text/xml";
  181. return new FileStream (url, FileMode.Open, FileAccess.Read);
  182. }
  183. else
  184. throw new InvalidOperationException ("Unrecognized file type '" + url + "'. Extension must be one of .wsdl or .xsd");
  185. }
  186. }
  187. public DiscoveryClientResultCollection ReadAll (string topLevelFilename)
  188. {
  189. StreamReader sr = new StreamReader (topLevelFilename);
  190. XmlSerializer ser = new XmlSerializer (typeof (DiscoveryClientResultsFile));
  191. DiscoveryClientResultsFile resfile = (DiscoveryClientResultsFile) ser.Deserialize (sr);
  192. sr.Close ();
  193. foreach (DiscoveryClientResult dcr in resfile.Results)
  194. {
  195. Type type = Type.GetType (dcr.ReferenceTypeName);
  196. DiscoveryReference dr = (DiscoveryReference) Activator.CreateInstance (type);
  197. dr.Url = dcr.Url;
  198. FileStream fs = new FileStream (dcr.Filename, FileMode.Open, FileAccess.Read);
  199. Documents.Add (dr.Url, dr.ReadDocument (fs));
  200. fs.Close ();
  201. References.Add (dr.Url, dr);
  202. }
  203. return resfile.Results;
  204. }
  205. public void ResolveAll ()
  206. {
  207. ArrayList list = new ArrayList (References.Values);
  208. foreach (DiscoveryReference re in list)
  209. {
  210. try
  211. {
  212. if (re is DiscoveryDocumentReference)
  213. ((DiscoveryDocumentReference)re).ResolveAll ();
  214. else
  215. re.Resolve ();
  216. }
  217. catch (DiscoveryException ex)
  218. {
  219. Errors [ex.Url] = ex.Exception;
  220. }
  221. catch (Exception ex)
  222. {
  223. Errors [re.Url] = ex;
  224. }
  225. }
  226. }
  227. public void ResolveOneLevel ()
  228. {
  229. ArrayList list = new ArrayList (References.Values);
  230. foreach (DiscoveryReference re in list)
  231. re.Resolve ();
  232. }
  233. public DiscoveryClientResultCollection WriteAll (string directory, string topLevelFilename)
  234. {
  235. DiscoveryClientResultsFile resfile = new DiscoveryClientResultsFile();
  236. foreach (DiscoveryReference re in References.Values)
  237. {
  238. object doc = Documents [re.Url];
  239. if (doc == null) continue;
  240. string fileName = FindValidName (resfile, re.DefaultFilename);
  241. resfile.Results.Add (new DiscoveryClientResult (re.GetType(), re.Url, fileName));
  242. string filepath = Path.Combine (directory, fileName);
  243. FileStream fs = new FileStream (filepath, FileMode.Create, FileAccess.Write);
  244. re.WriteDocument (doc, fs);
  245. fs.Close ();
  246. }
  247. StreamWriter sw = new StreamWriter (Path.Combine (directory, topLevelFilename));
  248. XmlSerializer ser = new XmlSerializer (typeof (DiscoveryClientResultsFile));
  249. ser.Serialize (sw, resfile);
  250. sw.Close ();
  251. return resfile.Results;
  252. }
  253. string FindValidName (DiscoveryClientResultsFile resfile, string baseName)
  254. {
  255. string name = baseName;
  256. int id = 0;
  257. bool found;
  258. do
  259. {
  260. found = false;
  261. foreach (DiscoveryClientResult res in resfile.Results)
  262. {
  263. if (name == res.Filename) {
  264. found = true; break;
  265. }
  266. }
  267. if (found)
  268. name = Path.GetFileNameWithoutExtension (baseName) + (++id) + Path.GetExtension (baseName);
  269. }
  270. while (found);
  271. return name;
  272. }
  273. #endregion // Methods
  274. #region Classes
  275. public sealed class DiscoveryClientResultsFile {
  276. #region Fields
  277. private DiscoveryClientResultCollection results;
  278. #endregion // Fields
  279. #region Contructors
  280. public DiscoveryClientResultsFile ()
  281. {
  282. results = new DiscoveryClientResultCollection ();
  283. }
  284. #endregion // Constructors
  285. #region Properties
  286. public DiscoveryClientResultCollection Results {
  287. get { return results; }
  288. }
  289. #endregion // Properties
  290. }
  291. #endregion // Classes
  292. }
  293. internal class DiscoveryException : Exception
  294. {
  295. public string Url;
  296. public Exception Exception;
  297. public DiscoveryException (string url, Exception origin)
  298. {
  299. Url = url;
  300. Exception = origin;
  301. }
  302. }
  303. }