public static ForecastState Reduce(ForecastState state, IAction action) { return(action switch { FetchWeatherForcastDataAction _ => state with { Status = "Loading...", WeatherForecasts = Array.Empty <WeatherForecast>() },
private void loadWeather() { string apiKey = Properties.Settings.Default.ApiKey; if (string.IsNullOrEmpty(apiKey)) { State = ForecastState.ApiKeyError; } else if (State == ForecastState.ApiKeyError) { State = ForecastState.Loading; } Thread weatherThread = new Thread(() => { if (LocationState == LocationApiState.Ok && State != ForecastState.ApiKeyError) { using (WebClient webClient = new WebClient()) { try { // set units string units = "metric"; if (!RegionInfo.CurrentRegion.IsMetric) { units = "imperial"; } // fetch weather string url = string.Format(RequestUrl, latitude, longitude, units, apiKey); parseWeather(webClient.DownloadString(url)); } catch (Exception e) { ShellLogger.Debug("Error fetching weather: " + e.Message); if (State == ForecastState.Loading) { State = ForecastState.FetchError; OnWeatherChanged(); } } } } else { OnWeatherChanged(); } }); weatherThread.Start(); }
private void parseWeather(string payload) { XmlDocument xmlDoc = new XmlDocument(); xmlDoc.LoadXml(payload); // parse xml XmlNode tempNode = xmlDoc.SelectSingleNode("current/temperature"); XmlNode feelsLikeNode = xmlDoc.SelectSingleNode("current/feels_like"); XmlNode humidityNode = xmlDoc.SelectSingleNode("current/humidity"); XmlNode pressureNode = xmlDoc.SelectSingleNode("current/pressure"); XmlNode windSpeedNode = xmlDoc.SelectSingleNode("current/wind/speed"); XmlNode windDirectionNode = xmlDoc.SelectSingleNode("current/wind/direction"); XmlNode weatherNode = xmlDoc.SelectSingleNode("current/weather"); // temperature double.TryParse(tempNode?.Attributes?["value"]?.Value, out Temperature); // feels like double.TryParse(feelsLikeNode?.Attributes?["value"]?.Value, out FeelsLike); // humidity double.TryParse(humidityNode?.Attributes?["value"]?.Value, out Humidity); HumidityUnit = humidityNode?.Attributes?["unit"]?.Value; // pressure double.TryParse(pressureNode?.Attributes?["value"]?.Value, out Pressure); PressureUnit = pressureNode?.Attributes?["unit"]?.Value; // wind speed double.TryParse(windSpeedNode?.Attributes?["value"]?.Value, out WindSpeed); WindSpeedUnit = windSpeedNode?.Attributes?["unit"]?.Value; // wind direction WindDirection = windDirectionNode?.Attributes?["code"]?.Value; // current conditions CurrentConditions = weatherNode?.Attributes?["value"]?.Value; if (!string.IsNullOrEmpty(CurrentConditions)) { CurrentConditions = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(CurrentConditions); } State = ForecastState.Ok; OnWeatherChanged(); }