public async void SearchWeather() { try { HttpClient client = new HttpClient(); client.BaseAddress = new Uri(GetUrl()); var response = await client.GetAsync(client.BaseAddress); response.EnsureSuccessStatusCode(); var jsonResult = response.Content.ReadAsStringAsync().Result; var weather = WeatherModel.FromJson(jsonResult); SetValues(weather); } catch (Exception ex) { throw ex; } }
/// <summary> /// Queries the API for the city set in CityName and CountryTag properties. /// </summary> private void LoadCity() { ErrorText = string.Empty; string apiKey = ConfigurationManager.AppSettings["API key"]; if (apiKey == null) { // Prompt for key APIKeyDialog akd = new APIKeyDialog(string.Empty); akd.ShowDialog(); // Check if set after prompt apiKey = ConfigurationManager.AppSettings["API key"]; if (apiKey == null || apiKey.Length == 0) { ErrorText = "No API key set in App.config!"; } else { LoadCity(); } } else { var client = new RestClient("http://api.openweathermap.org/data/2.5/"); var request = new RestRequest($"weather?q={CityName},{CountryTag}&appid={apiKey}", RestSharp.DataFormat.Json); var response = client.Get(request); // City has been found (HTTP 200) if (response.StatusCode == HttpStatusCode.OK) { JObject responseJson = JObject.Parse(response.Content); //Console.WriteLine(JObject.Parse(response.Content)); // Parsing can throw exception, because not all cities have complete json attribute sets try { Model = WeatherModel.FromJson(JObject.Parse(response.Content)); Model.AdjustUnits(); // Save city into config AddConfigurationEntry("CityName", CityName); AddConfigurationEntry("CountryTag", CountryTag); // Start refresher thread if (!refreshTask.Status.Equals(TaskStatus.Running)) { refreshTask.Start(); } } catch (Exception) { ErrorText = "Incomplete API response for this city!"; MessageBox.Show($"The API response of the city {CityName}, {CountryTag} is incomplete and can't be parsed properly.", "Incomplete city response", MessageBoxButton.OK, MessageBoxImage.Warning); } } // City not found else if (response.StatusCode == HttpStatusCode.NotFound) { ErrorText = "City and/or country could not be found!"; Model = null; } // Invalid API key else if (response.StatusCode == HttpStatusCode.Unauthorized) { ErrorText = "Invalid API key!"; MessageBox.Show("The API key in the App.config is invalid! Please change it in the next prompt.", "Invalid API key", MessageBoxButton.OK, MessageBoxImage.Warning); APIKeyDialog akd = new APIKeyDialog(apiKey); akd.ShowDialog(); } } }