using System; using System.IO; using System.Text; using System.Xml; using HtmlAgilityPack; namespace Endpoint { public class HtmlEndpoint : HttpEndpoint { /// /// Returns the HTML parsed into a standard XmlDocument. /// Uses the HtmlAgilityPack library for "out of the web" (poorly formatted) html file support. /// /// The HTML /// An XmlDocument from the HTML private static XmlDocument GetHtmlXml(string html) { var htmlDocument = new HtmlDocument(); htmlDocument.LoadHtml(html); var xmlDocument = new XmlDocument(); using (Stream stream = new MemoryStream()) { XmlWriter xmlTextWriter = new XmlTextWriter(stream, Encoding.UTF8); htmlDocument.Save(xmlTextWriter); stream.Seek(0, SeekOrigin.Begin); using (var sr = new StreamReader(stream)) xmlDocument.Load(sr); xmlTextWriter.Close(); } return xmlDocument; } /// /// Returns the HTML grabbed from the passed in URL parsed into a standard XmlDocument. /// Uses the HtmlAgilityPack library for "out of the web" html file support. /// /// The URL. /// The post data. /// An XmlDocument from the HTML private static XmlDocument GetHtmlXml(Uri url, string requestContent) { return GetHtmlXml(GetUrlContent(url, "application/x-www-form-urlencoded", requestContent, null)); } /// /// Gets the HTTP endpoint configuration. /// /// The HTTP endpoint configuration. public HtmlEndpointConfiguration HtmlEndpointConfiguration { get { return (HtmlEndpointConfiguration)_httpEndpointConfiguration; } } /// /// Initializes a new instance of the class. /// /// The HttpEndpointConfiguration. public HtmlEndpoint(HtmlEndpointConfiguration config) : base(config) { } /// /// Gets the current status result of the endpoint /// /// Status public override Status GetStatus() { Status baseStatus = base.GetStatus(); if (baseStatus != Status.Up) return baseStatus; try { XmlDocument xml = GetHtmlXml(HttpEndpointConfiguration.Uri, HtmlEndpointConfiguration.RequestContent); // xml.Save(@"c:\test.xml"); XmlNodeList nodes = xml.SelectNodes(HtmlEndpointConfiguration.XpathQuery); // verify html has expected value if (nodes == null || nodes.Count == 0) { StatusDescription = "Couldn't find expected value in html"; return Status.Error; } string value = nodes[0].Value.Trim(); if (value != HtmlEndpointConfiguration.ExpectedXpathResult) { StatusDescription = String.Format("Result was: '{0}', was expecting '{1}'", value, HtmlEndpointConfiguration.ExpectedXpathResult); return Status.Error; } } catch (Exception ex) { StatusDescription = ex.Message; return Status.Error; } return Status.Up; } } }