DiscoveryClientProtocol.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  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 (url, 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 (url, 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 if (url.StartsWith ("file://"))
  176. {
  177. WebRequest request = WebRequest.Create (new Uri (url));
  178. WebResponse resp = request.GetResponse ();
  179. contentType = resp.ContentType;
  180. return resp.GetResponseStream ();
  181. }
  182. else
  183. {
  184. string ext = Path.GetExtension (url).ToLower();
  185. if (ext == ".wsdl" || ext == ".xsd")
  186. {
  187. contentType = "text/xml";
  188. return new FileStream (url, FileMode.Open, FileAccess.Read);
  189. }
  190. else
  191. throw new InvalidOperationException ("Unrecognized file type '" + url + "'. Extension must be one of .wsdl or .xsd");
  192. }
  193. }
  194. public DiscoveryClientResultCollection ReadAll (string topLevelFilename)
  195. {
  196. StreamReader sr = new StreamReader (topLevelFilename);
  197. XmlSerializer ser = new XmlSerializer (typeof (DiscoveryClientResultsFile));
  198. DiscoveryClientResultsFile resfile = (DiscoveryClientResultsFile) ser.Deserialize (sr);
  199. sr.Close ();
  200. foreach (DiscoveryClientResult dcr in resfile.Results)
  201. {
  202. Type type = Type.GetType (dcr.ReferenceTypeName);
  203. DiscoveryReference dr = (DiscoveryReference) Activator.CreateInstance (type);
  204. dr.Url = dcr.Url;
  205. FileStream fs = new FileStream (dcr.Filename, FileMode.Open, FileAccess.Read);
  206. Documents.Add (dr.Url, dr.ReadDocument (fs));
  207. fs.Close ();
  208. References.Add (dr.Url, dr);
  209. }
  210. return resfile.Results;
  211. }
  212. public void ResolveAll ()
  213. {
  214. ArrayList list = new ArrayList (References.Values);
  215. foreach (DiscoveryReference re in list)
  216. {
  217. try
  218. {
  219. if (re is DiscoveryDocumentReference)
  220. ((DiscoveryDocumentReference)re).ResolveAll ();
  221. else
  222. re.Resolve ();
  223. }
  224. catch (DiscoveryException ex)
  225. {
  226. Errors [ex.Url] = ex.Exception;
  227. }
  228. catch (Exception ex)
  229. {
  230. Errors [re.Url] = ex;
  231. }
  232. }
  233. }
  234. public void ResolveOneLevel ()
  235. {
  236. ArrayList list = new ArrayList (References.Values);
  237. foreach (DiscoveryReference re in list)
  238. re.Resolve ();
  239. }
  240. public DiscoveryClientResultCollection WriteAll (string directory, string topLevelFilename)
  241. {
  242. DiscoveryClientResultsFile resfile = new DiscoveryClientResultsFile();
  243. foreach (DiscoveryReference re in References.Values)
  244. {
  245. object doc = Documents [re.Url];
  246. if (doc == null) continue;
  247. string fileName = FindValidName (resfile, re.DefaultFilename);
  248. resfile.Results.Add (new DiscoveryClientResult (re.GetType(), re.Url, fileName));
  249. string filepath = Path.Combine (directory, fileName);
  250. FileStream fs = new FileStream (filepath, FileMode.Create, FileAccess.Write);
  251. re.WriteDocument (doc, fs);
  252. fs.Close ();
  253. }
  254. StreamWriter sw = new StreamWriter (Path.Combine (directory, topLevelFilename));
  255. XmlSerializer ser = new XmlSerializer (typeof (DiscoveryClientResultsFile));
  256. ser.Serialize (sw, resfile);
  257. sw.Close ();
  258. return resfile.Results;
  259. }
  260. string FindValidName (DiscoveryClientResultsFile resfile, string baseName)
  261. {
  262. string name = baseName;
  263. int id = 0;
  264. bool found;
  265. do
  266. {
  267. found = false;
  268. foreach (DiscoveryClientResult res in resfile.Results)
  269. {
  270. if (name == res.Filename) {
  271. found = true; break;
  272. }
  273. }
  274. if (found)
  275. name = Path.GetFileNameWithoutExtension (baseName) + (++id) + Path.GetExtension (baseName);
  276. }
  277. while (found);
  278. return name;
  279. }
  280. #endregion // Methods
  281. #region Classes
  282. public sealed class DiscoveryClientResultsFile {
  283. #region Fields
  284. private DiscoveryClientResultCollection results;
  285. #endregion // Fields
  286. #region Contructors
  287. public DiscoveryClientResultsFile ()
  288. {
  289. results = new DiscoveryClientResultCollection ();
  290. }
  291. #endregion // Constructors
  292. #region Properties
  293. public DiscoveryClientResultCollection Results {
  294. get { return results; }
  295. }
  296. #endregion // Properties
  297. }
  298. #endregion // Classes
  299. }
  300. internal class DiscoveryException : Exception
  301. {
  302. public string Url;
  303. public Exception Exception;
  304. public DiscoveryException (string url, Exception origin)
  305. {
  306. Url = url;
  307. Exception = origin;
  308. }
  309. }
  310. }