DiscoveryClientProtocol.cs 10 KB

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