DiscoveryClientProtocol.cs 11 KB

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