PageRenderTime 45ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 0ms

/trunk/InfoService/InfoService/Weather/WeatherConnector/Weather.cs

#
C# | 265 lines | 235 code | 27 blank | 3 comment | 16 complexity | dc36a866d8f783090075e79577ca0d74 MD5 | raw file
  1. #region Usings
  2. using System;
  3. using System.Globalization;
  4. using System.IO;
  5. using System.Net;
  6. using System.Xml;
  7. using WeatherConnector.Data;
  8. using WeatherConnector.Expections;
  9. using WeatherConnector.Xml;
  10. #endregion
  11. namespace WeatherConnector
  12. {
  13. public class Weather
  14. {
  15. private const string BaseUrl =
  16. "http://xoap.weather.com/weather/local/{0}?cc=*&dayf=5&link=xoap&prod=xoap&par={1}&key={2}&unit={3}";
  17. private static string _licenseKey;
  18. private static bool _loginSet;
  19. private static string _partnerId;
  20. private string _locationId;
  21. private bool _useFile;
  22. private string _weatherFile;
  23. private readonly XmlDocument _weatherXml = new XmlDocument();
  24. private TemperatureFormat _temperatureFormat = TemperatureFormat.Grad;
  25. private WeatherData _weatherData;
  26. private WeatherEntities _weatherEntities;
  27. public Weather(string locationId, TemperatureFormat temperatureFormat)
  28. {
  29. if (!_loginSet)
  30. {
  31. throw new WeatherNoPartnerIDOrLicenseKeyExpection("No Partner ID and/or License ID is set");
  32. }
  33. if (locationId == String.Empty)
  34. {
  35. throw new WeatherNoLocationIDExpection("No LocationID set");
  36. }
  37. LogEvents.InvokeOnDebug(new WeatherArgs("Creating WeatherConnector with weather location " + locationId + " and temperature format " + _temperatureFormat));
  38. _locationId = locationId;
  39. _temperatureFormat = temperatureFormat;
  40. _useFile = false;
  41. //RefreshWeatherData();
  42. }
  43. public Weather(string pathToWeatherXML)
  44. {
  45. _useFile = true;
  46. _weatherFile = pathToWeatherXML;
  47. }
  48. public Weather()
  49. {
  50. }
  51. public WeatherData WeatherData
  52. {
  53. get { return _weatherData; }
  54. }
  55. public WeatherEntities WeatherEntities
  56. {
  57. get { return _weatherEntities; }
  58. }
  59. public void SetTemperatureFormat(TemperatureFormat temperatureFormat)
  60. {
  61. if (!_useFile)
  62. {
  63. LogEvents.InvokeOnDebug(new WeatherArgs("Setting temperature format to " + temperatureFormat));
  64. _temperatureFormat = temperatureFormat;
  65. }
  66. }
  67. public string Location { get; private set; }
  68. public string LocationId
  69. {
  70. get
  71. {
  72. return _locationId;
  73. }
  74. set
  75. {
  76. LogEvents.InvokeOnDebug(new WeatherArgs("Setting location id to " + value));
  77. _locationId = value;
  78. }
  79. }
  80. public static void SetLoginCreditials(string partnerId, string licenseKey)
  81. {
  82. LogEvents.InvokeOnDebug(new WeatherArgs("Setting login creditials"));
  83. _partnerId = partnerId;
  84. _licenseKey = licenseKey;
  85. _loginSet = true;
  86. }
  87. public bool UpdateWeatherData()
  88. {
  89. if (!_useFile)
  90. {
  91. if (_locationId == String.Empty)
  92. {
  93. LogEvents.InvokeOnError(new WeatherArgs("No location id set"));
  94. return false;
  95. }
  96. string xmlStr = string.Empty;
  97. string tempUnitXML = string.Empty;
  98. switch (_temperatureFormat)
  99. {
  100. case TemperatureFormat.Grad:
  101. tempUnitXML = "m";
  102. break;
  103. case TemperatureFormat.Fahrenheit:
  104. tempUnitXML = "s";
  105. break;
  106. }
  107. LogEvents.InvokeOnInfo(new WeatherArgs("Updating weather data for location id " + _locationId));
  108. string url = String.Format(BaseUrl, _locationId, _partnerId, _licenseKey, tempUnitXML);
  109. using (WebClient client = new WebClient())
  110. {
  111. try
  112. {
  113. LogEvents.InvokeOnDebug(new WeatherArgs("Downloading weather xml for location id " + _locationId));
  114. using (StreamReader reader = new StreamReader(client.OpenRead(url)))
  115. {
  116. xmlStr = reader.ReadToEnd();
  117. LogEvents.InvokeOnDebug(
  118. new WeatherArgs(
  119. "Downloaded weather xml successful. Now checking whether the file has errors..."));
  120. }
  121. }
  122. catch (Exception ex)
  123. {
  124. LogEvents.InvokeOnError(new WeatherArgs("Error downloading weather data", ex.Message,
  125. ex.StackTrace));
  126. return false;
  127. }
  128. }
  129. if (string.IsNullOrEmpty(xmlStr))
  130. {
  131. LogEvents.InvokeOnError(
  132. new WeatherArgs("Error downloading weather data. Downloaded weather xml is empty"));
  133. return false;
  134. }
  135. _weatherXml.LoadXml(xmlStr);
  136. }
  137. else
  138. {
  139. LogEvents.InvokeOnInfo(new WeatherArgs("Updating weather data from file " + _weatherFile));
  140. if(File.Exists(_weatherFile))
  141. {
  142. _weatherXml.Load(_weatherFile);
  143. }
  144. else
  145. {
  146. LogEvents.InvokeOnError(new WeatherArgs("Updating weather data from file " + _weatherFile + " unsuccessful. File doesn't exist"));
  147. return false;
  148. }
  149. }
  150. if (_weatherXml.DocumentElement != null)
  151. {
  152. if (_weatherXml.DocumentElement.SelectSingleNode("//err[@type='0']") != null)
  153. {
  154. LogEvents.InvokeOnError(
  155. new WeatherArgs("Downloading was successful, but weather.com returned an error: " +
  156. _weatherXml.DocumentElement.SelectSingleNode("//err[@type='0']").InnerText));
  157. }
  158. }
  159. else
  160. {
  161. LogEvents.InvokeOnError(new WeatherArgs("Downloading was successful, but the file is not valid"));
  162. return false;
  163. }
  164. WeatherXml.WeatherXmlDocument = _weatherXml;
  165. _locationId = WeatherXml.ParseXmlString("loc/@id");
  166. LogEvents.InvokeOnInfo(new WeatherArgs("Downloaded/Checked successful the weather data for location id " + _locationId));
  167. return ParseWeatherData();
  168. }
  169. public bool ParseWeatherData()
  170. {
  171. LogEvents.InvokeOnDebug(new WeatherArgs("Parsing weather data for location id " + _locationId));
  172. Location = WeatherXml.ParseXmlString("loc/dnam");
  173. LogEvents.InvokeOnDebug(new WeatherArgs("Location id " + _locationId + " seems to be " + Location));
  174. _weatherEntities = new WeatherEntities();
  175. _weatherEntities.TemperatureFormat = WeatherXml.ParseXmlString("head/ut") == "C"
  176. ? TemperatureFormat.Grad
  177. : TemperatureFormat.Fahrenheit;
  178. _weatherEntities.WindSpeed = WeatherXml.ParseXmlString("head/us");
  179. _weatherData = new WeatherData();
  180. _weatherData.TodayImageIcon = WeatherXml.ParseXmlString("cc/icon");
  181. _weatherData.TodayCondition = WeatherXml.ParseXmlString("cc/t");
  182. _weatherData.TodayDate = DateTime.Now;
  183. _weatherData.TodayFeelsLikeTemperature = WeatherXml.ParseXmlString("cc/flik");
  184. _weatherData.TodayHumidity = WeatherXml.ParseXmlString("cc/hmid");
  185. _weatherData.TodaySunrise = WeatherXml.ParseXmlDateTime("loc/sunr", "h:mm tt");
  186. _weatherData.TodaySunset = WeatherXml.ParseXmlDateTime("loc/suns", "h:mm tt");
  187. _weatherData.TodayTemperature = WeatherXml.ParseXmlString("cc/tmp");
  188. //_weatherData.TodayMaxTemperature = WeatherXml.ParseXmlString("dayf/day[@d='0']/hi");
  189. //_weatherData.TodayMinTemperature = WeatherXml.ParseXmlString("dayf/day[@d='0']/low");
  190. _weatherData.TodayUvIndex = string.Format("{0} {1}", WeatherXml.ParseXmlString("cc/uv/i"),
  191. WeatherXml.ParseXmlString("cc/uv/t"));
  192. _weatherData.TodayWindDirection = WeatherXml.ParseXmlString("cc/wind/t");
  193. _weatherData.TodayWindSpeed = WeatherXml.ParseXmlString("cc/wind/s");
  194. bool continueWithParsing = true;
  195. try
  196. {
  197. LogEvents.InvokeOnDebug(new WeatherArgs("Parsing the weather forecast data"));
  198. _weatherXml.DocumentElement.SelectSingleNode("dayf").RemoveChild(_weatherXml.DocumentElement.SelectSingleNode("dayf/lsup"));
  199. }
  200. catch (Exception ex)
  201. {
  202. LogEvents.InvokeOnWarning(new WeatherArgs("Parsing the weather forecast data unsuccesful. It seems that the xml is not valid", ex.Message, ex.StackTrace));
  203. continueWithParsing = false;
  204. }
  205. if (continueWithParsing)
  206. {
  207. WeatherForecast wfc = new WeatherForecast();
  208. int i = 0;
  209. _weatherData.WeatherForecast.Clear();
  210. foreach (XmlNode day in _weatherXml.DocumentElement.SelectSingleNode("dayf"))
  211. {
  212. DateTime dateFXml = WeatherXml.ParseXmlDateTime("dayf/day[@d='" + i + "']/@dt", "MMM d");
  213. dateFXml = new DateTime(DateTime.Now.Year, dateFXml.Month, dateFXml.Day);
  214. wfc = new WeatherForecast();
  215. wfc.Date = new DateTime(DateTime.Now.Year, dateFXml.Month, dateFXml.Day);
  216. wfc.MaxTemperature = WeatherXml.ParseXmlString("dayf/day[@d='" + i + "']/hi");
  217. wfc.MinTemperature = WeatherXml.ParseXmlString("dayf/day[@d='" + i + "']/low");
  218. wfc.Sunrise = WeatherXml.ParseXmlDateTime("dayf/day[@d='" + i + "']/sunr", "h:mm tt");
  219. wfc.Sunset = WeatherXml.ParseXmlDateTime("dayf/day[@d='" + i + "']/suns", "h:mm tt");
  220. wfc.Day = new WeatherDay(WeatherXml.ParseXmlString("dayf/day[@d='" + i + "']/part[@p='d']/t"),
  221. WeatherXml.ParseXmlString("dayf/day[@d='" + i + "']/part[@p='d']/wind/t"),
  222. WeatherXml.ParseXmlString("dayf/day[@d='" + i + "']/part[@p='d']/wind/s"),
  223. WeatherXml.ParseXmlString("dayf/day[@d='" + i + "']/part[@p='d']/hmid"),
  224. WeatherXml.ParseXmlString("dayf/day[@d='" + i + "']/part[@p='d']/icon"));
  225. wfc.Night = new WeatherDay(WeatherXml.ParseXmlString("dayf/day[@d='" + i + "']/part[@p='n']/t"),
  226. WeatherXml.ParseXmlString("dayf/day[@d='" + i + "']/part[@p='n']/wind/t"),
  227. WeatherXml.ParseXmlString("dayf/day[@d='" + i + "']/part[@p='n']/wind/s"),
  228. WeatherXml.ParseXmlString("dayf/day[@d='" + i + "']/part[@p='n']/hmid"),
  229. WeatherXml.ParseXmlString("dayf/day[@d='" + i + "']/part[@p='n']/icon"));
  230. _weatherData.WeatherForecast.Add(wfc);
  231. i++;
  232. }
  233. }
  234. LogEvents.InvokeOnDebug(new WeatherArgs("Parsing of weather data done. See above for possibly errors or warnings"));
  235. return true;
  236. }
  237. }
  238. }