void weatherClient_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e) { if (e.Error == null) { Task.Factory.StartNew(() => { DataContractJsonSerializer dc = new DataContractJsonSerializer(typeof(WorldWeatherInfo)); WorldWeatherInfo worldWeatherInfo = (WorldWeatherInfo)dc.ReadObject(e.Result); ObservableCollection <CityWeather> tempWeatherInCities = new ObservableCollection <CityWeather>(); foreach (CityWeatherInfo weatherInfo in worldWeatherInfo.list) { CityWeather cityWeather = ViewModelSource.Create(() => new CityWeather(weatherInfo)); string cityWithId = string.Format("{0};{1}", cityWeather.City, cityWeather.CityID); if (capitals.Contains(cityWeather.City) || capitals.Contains(cityWithId)) { if (cityWeather.WeatherDescriptions != null && cityWeather.WeatherDescriptions.Count > 0) { cityWeather.WeatherIconPath = "http://openweathermap.org/img/w/" + cityWeather.WeatherDescriptions[0].IconName + ".png"; } tempWeatherInCities.Add(cityWeather); } } lock (weatherLocker) { WeatherInCities = tempWeatherInCities; } this.uiDispatcher.Invoke(new Action(() => UpdateCurrentTemperatureType())); }); } }
public void GetForecastForCityAsync(CityWeather cityWeather) { string link = string.Format("http://api.openweathermap.org/data/2.5/forecast?units=metric&id={0}&APPID={1}", cityWeather.CityID.ToString(), OpenWeatherKey); WebClient forecastClient = new WebClient(); forecastClient.OpenReadCompleted += forecastClient_OpenReadCompleted; forecastClient.OpenReadAsync(new Uri(link), cityWeather); }
void forecastClient_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e) { if (e.Error == null) { ((WebClient)sender).OpenReadCompleted -= forecastClient_OpenReadCompleted; Stream stream = e.Result; CityWeather cityWeatherInfo = (CityWeather)e.UserState; Task.Factory.StartNew(() => { DataContractJsonSerializer dc = new DataContractJsonSerializer(typeof(ForecastInfo)); ForecastInfo forecast = (ForecastInfo)dc.ReadObject(stream); this.uiDispatcher.Invoke(new Action(() => { cityWeatherInfo.SetForecast(forecast.list); })); }); } }