DiscoveryClientProtocol.cs 9.0 KB

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