/// <summary> /// Gets the weather data. /// </summary> private static void GetWeatherData() { Debug.Assert(Sources != null && Sources.Any(), "Weather data sources cannot be null or empty."); foreach (WeatherDataSources source in Sources) { try { // Validate the format of the URL Uri sourceUri; if (Uri.TryCreate(source.Url, UriKind.Absolute, out sourceUri) && sourceUri.Scheme == Uri.UriSchemeHttp) { using (System.Net.WebClient client = new System.Net.WebClient()) { string html = client.DownloadString(sourceUri); if (!string.IsNullOrWhiteSpace(html)) { // Get the first line of HTML HtmlDocument = new HtmlAgilityPack.HtmlDocument(); HtmlDocument.LoadHtml(html); DataParser parser = new DataParser(); // TODO: Evaluate whether to use an enumerator here instead of strings switch (source.Airport.ToLowerInvariant()) { case "cynr": parser.SetParseStrategy(new CynrParse()); break; case "cet2": parser.SetParseStrategy(new Cet2Parse()); break; case "cfg6": parser.SetParseStrategy(new Cfg6Parse()); break; case "crl4": parser.SetParseStrategy(new Crl4Parse()); break; default: throw new InvalidOperationException("Invalid airport code specified in the configuration file."); } string data = parser.Parse(); // Parse and store the data if (!string.IsNullOrWhiteSpace(data)) { // Does the string look as we expect? const string pattern = @"^(METAR|SPECI)\s\w{4}\s\d{6}Z(.*)$"; System.Text.RegularExpressions.Regex expression = new System.Text.RegularExpressions.Regex(pattern, System.Text.RegularExpressions.RegexOptions.Compiled); bool isValidData = expression.IsMatch(data); if (!isValidData) { throw new Exception(string.Format("Parsed data returned by {0} is an invalid data format: {1}", sourceUri, data)); } ParseWeatherData(data); } } else { // The HTML was blank, so there's nothing else we can do throw new Exception(string.Format("The HTML document returned by a configured URL ({0}) is empty.", sourceUri)); } } } else { // We had trouble creating the URL using configuration file entries throw new UriFormatException(string.Format("The system was unable to parse a URL ({0}) in the configuration file.", sourceUri)); } } catch (Exception x) { WriteToEventApplicationLog(x); SendMail(x.Message); } } }