· 6 years ago · Nov 27, 2019, 04:50 PM
1public async Task<IEnumerable<WeatherForecast>> GetForecastAsync(string location, int days)
2 {
3 if (location == null) throw new ArgumentNullException("Location can't be null.");
4 if (location == string.Empty) throw new ArgumentException("Location can't be an empty string.");
5 if (days <= 0) throw new ArgumentOutOfRangeException("Days should be greather than zero.");
6 if (days > _MAX_FORECAST_DAYS) throw new ArgumentOutOfRangeException($"Days can't be greater than {_MAX_FORECAST_DAYS}");
7
8 //var query = $"forecast/daily?q={location}&type=accurate&mode=xml&units=metric&cnt={days}&appid={_APP_KEY}";
9 var query = $"forecast?q=London,us&mode=xml&appid=b6907d289e10d714a6e88b30761fae22";
10 var response = await _client.GetAsync(query);
11
12 switch (response.StatusCode)
13 {
14 case HttpStatusCode.Unauthorized:
15 throw new Exception("Invalid API key.");
16 case HttpStatusCode.NotFound:
17 throw new Exception("Location not found.");
18 case HttpStatusCode.OK:
19 var s = await response.Content.ReadAsStringAsync();
20 var x = XElement.Load(new StringReader(s));
21
22 var data = x.Descendants("time").Select(w => new WeatherForecast
23 {
24 Date = DateTime.Now,
25 Description = w.Element("symbol").Attribute("name").Value,
26 WindSpeed = double.Parse(w.Element("windSpeed").Attribute("mps").Value),
27 CurrentTemperature = double.Parse(w.Element("temperature").Attribute("value").Value),
28 MaxTemperature = double.Parse(w.Element("temperature").Attribute("max").Value),
29 MinTemperature = double.Parse(w.Element("temperature").Attribute("min").Value),
30 });
31 return data;
32 default:
33 throw new NotImplementedException(response.StatusCode.ToString());
34 }
35 }
36
37public partial class MainWindow : Window
38 {
39 List<WeatherForecast> forecast;
40 WeatherForecast currentWeather;
41 OpenWeatherMapService service;
42
43 Task API_CALL;
44
45 public MainWindow()
46 {
47 InitializeComponent();
48
49 service = new OpenWeatherMapService();
50 }
51
52 public async Task GetWeather()
53 {
54 try
55 {
56 var weather = await service.GetForecastAsync("London", 3);
57 currentWeather = weather.First();
58 forecast = weather.Skip(1).Take(2).ToList();
59
60 // Update UI element now
61 Date.Text = currentWeather.Date.ToString("MM/dd/yyyy h:mm tt");
62 }
63 catch (Exception ex)
64 {
65 throw new Exception(ex.Message);
66 }
67 }
68
69 private void ButtonGetWeather_Click(object sender, RoutedEventArgs e)
70 {
71 API_CALL = GetWeather();
72 }
73 }