DiscoveryClientProtocol.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  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. Uri tmp = new Uri (url);
  107. tmp = new Uri (tmp, m.Groups [1].ToString ());
  108. url = tmp.ToString ();
  109. }
  110. stream = Download (ref url);
  111. }
  112. XmlTextReader reader = new XmlTextReader (url, stream);
  113. reader.MoveToContent ();
  114. DiscoveryDocument doc;
  115. DiscoveryReference refe = null;
  116. if (DiscoveryDocument.CanRead (reader))
  117. {
  118. doc = DiscoveryDocument.Read (reader);
  119. documents.Add (url, doc);
  120. refe = new DiscoveryDocumentReference ();
  121. AddDiscoReferences (doc);
  122. }
  123. else if (ServiceDescription.CanRead (reader))
  124. {
  125. ServiceDescription wsdl = ServiceDescription.Read (reader);
  126. documents.Add (url, wsdl);
  127. doc = new DiscoveryDocument ();
  128. refe = new ContractReference ();
  129. doc.References.Add (refe);
  130. refe.Url = url;
  131. ((ContractReference)refe).ResolveInternal (this, wsdl);
  132. }
  133. else
  134. {
  135. XmlSchema schema = XmlSchema.Read (reader, null);
  136. documents.Add (url, schema);
  137. doc = new DiscoveryDocument ();
  138. refe = new SchemaReference ();
  139. doc.References.Add (refe);
  140. }
  141. refe.ClientProtocol = this;
  142. refe.Url = url;
  143. references.Add (url, refe);
  144. reader.Close ();
  145. return doc;
  146. }
  147. catch (DiscoveryException ex) {
  148. throw ex.Exception;
  149. }
  150. }
  151. void AddDiscoReferences (DiscoveryDocument doc)
  152. {
  153. foreach (DiscoveryReference re in doc.References)
  154. {
  155. re.ClientProtocol = this;
  156. references.Add (re.Url, re);
  157. }
  158. if (doc.AdditionalInfo != null) {
  159. foreach (object info in doc.AdditionalInfo)
  160. additionalInformation.Add (info);
  161. }
  162. }
  163. public Stream Download (ref string url)
  164. {
  165. string contentType = null;
  166. return Download (ref url, ref contentType);
  167. }
  168. public Stream Download (ref string url, ref string contentType)
  169. {
  170. if (url.StartsWith ("http://") || url.StartsWith ("https://"))
  171. {
  172. WebRequest request = GetWebRequest (new Uri(url));
  173. WebResponse resp = request.GetResponse ();
  174. contentType = resp.ContentType;
  175. return resp.GetResponseStream ();
  176. }
  177. else if (url.StartsWith ("file://"))
  178. {
  179. WebRequest request = WebRequest.Create (new Uri (url));
  180. WebResponse resp = request.GetResponse ();
  181. contentType = resp.ContentType;
  182. return resp.GetResponseStream ();
  183. }
  184. else
  185. {
  186. string ext = Path.GetExtension (url).ToLower();
  187. if (ext == ".wsdl" || ext == ".xsd")
  188. {
  189. contentType = "text/xml";
  190. return new FileStream (url, FileMode.Open, FileAccess.Read);
  191. }
  192. else
  193. throw new InvalidOperationException ("Unrecognized file type '" + url + "'. Extension must be one of .wsdl or .xsd");
  194. }
  195. }
  196. [Obsolete ("This method will be removed from a future version. The method call is no longer required for resource discovery", false)]
  197. public void LoadExternals ()
  198. {
  199. }
  200. public DiscoveryClientResultCollection ReadAll (string topLevelFilename)
  201. {
  202. StreamReader sr = new StreamReader (topLevelFilename);
  203. XmlSerializer ser = new XmlSerializer (typeof (DiscoveryClientResultsFile));
  204. DiscoveryClientResultsFile resfile = (DiscoveryClientResultsFile) ser.Deserialize (sr);
  205. sr.Close ();
  206. foreach (DiscoveryClientResult dcr in resfile.Results)
  207. {
  208. Type type = Type.GetType (dcr.ReferenceTypeName);
  209. DiscoveryReference dr = (DiscoveryReference) Activator.CreateInstance (type);
  210. dr.Url = dcr.Url;
  211. FileStream fs = new FileStream (dcr.Filename, FileMode.Open, FileAccess.Read);
  212. Documents.Add (dr.Url, dr.ReadDocument (fs));
  213. fs.Close ();
  214. References.Add (dr.Url, dr);
  215. }
  216. return resfile.Results;
  217. }
  218. public void ResolveAll ()
  219. {
  220. ArrayList list = new ArrayList (References.Values);
  221. foreach (DiscoveryReference re in list)
  222. {
  223. try
  224. {
  225. if (re is DiscoveryDocumentReference)
  226. ((DiscoveryDocumentReference)re).ResolveAll ();
  227. else
  228. re.Resolve ();
  229. }
  230. catch (DiscoveryException ex)
  231. {
  232. Errors [ex.Url] = ex.Exception;
  233. }
  234. catch (Exception ex)
  235. {
  236. Errors [re.Url] = ex;
  237. }
  238. }
  239. }
  240. public void ResolveOneLevel ()
  241. {
  242. ArrayList list = new ArrayList (References.Values);
  243. foreach (DiscoveryReference re in list)
  244. re.Resolve ();
  245. }
  246. public DiscoveryClientResultCollection WriteAll (string directory, string topLevelFilename)
  247. {
  248. DiscoveryClientResultsFile resfile = new DiscoveryClientResultsFile();
  249. foreach (DiscoveryReference re in References.Values)
  250. {
  251. object doc = Documents [re.Url];
  252. if (doc == null) continue;
  253. string fileName = FindValidName (resfile, re.DefaultFilename);
  254. resfile.Results.Add (new DiscoveryClientResult (re.GetType(), re.Url, fileName));
  255. string filepath = Path.Combine (directory, fileName);
  256. FileStream fs = new FileStream (filepath, FileMode.Create, FileAccess.Write);
  257. re.WriteDocument (doc, fs);
  258. fs.Close ();
  259. }
  260. StreamWriter sw = new StreamWriter (Path.Combine (directory, topLevelFilename));
  261. XmlSerializer ser = new XmlSerializer (typeof (DiscoveryClientResultsFile));
  262. ser.Serialize (sw, resfile);
  263. sw.Close ();
  264. return resfile.Results;
  265. }
  266. string FindValidName (DiscoveryClientResultsFile resfile, string baseName)
  267. {
  268. string name = baseName;
  269. int id = 0;
  270. bool found;
  271. do
  272. {
  273. found = false;
  274. foreach (DiscoveryClientResult res in resfile.Results)
  275. {
  276. if (name == res.Filename) {
  277. found = true; break;
  278. }
  279. }
  280. if (found)
  281. name = Path.GetFileNameWithoutExtension (baseName) + (++id) + Path.GetExtension (baseName);
  282. }
  283. while (found);
  284. return name;
  285. }
  286. #endregion // Methods
  287. #region Classes
  288. public sealed class DiscoveryClientResultsFile {
  289. #region Fields
  290. private DiscoveryClientResultCollection results;
  291. #endregion // Fields
  292. #region Contructors
  293. public DiscoveryClientResultsFile ()
  294. {
  295. results = new DiscoveryClientResultCollection ();
  296. }
  297. #endregion // Constructors
  298. #region Properties
  299. public DiscoveryClientResultCollection Results {
  300. get { return results; }
  301. }
  302. #endregion // Properties
  303. }
  304. #endregion // Classes
  305. }
  306. internal class DiscoveryException : Exception
  307. {
  308. public string Url;
  309. public Exception Exception;
  310. public DiscoveryException (string url, Exception origin)
  311. {
  312. Url = url;
  313. Exception = origin;
  314. }
  315. }
  316. }