public async Task <WeatherResult> GetWeather(string country, string city) { if (string.IsNullOrEmpty(country) || string.IsNullOrEmpty(city)) { throw new OneOfParametersIsEmptyException(); } string apiWeatherUri = String.Format("/api/Weather/{0}/{1}", country, city); HttpResponseMessage response = await _httpClient.GetAsync( new Uri(System.Configuration.ConfigurationManager.AppSettings["WeatherWebApiAddress"]), apiWeatherUri); if (response.IsSuccessStatusCode) { WeatherResult weatherResult = await _responseToWeatherResultMapper.Map(response); if (weatherResult?.location == null) { throw new InvalidParameters(); } return(weatherResult); } else { throw new WebApiInternalErrorException(); } }
public void SendMessageToUser(WeatherResult weather) { using (var mailClient = new SmtpClient(MailServer)) { var basicCredentials = new NetworkCredential(MailFrom, MailPass); using (var message = new MailMessage()) { MailAddress from = new MailAddress(MailFrom, "Carlos Encine"); MailAddress to = new MailAddress(MailTo, "destination"); mailClient.Host = MailServer; mailClient.UseDefaultCredentials = false; mailClient.Credentials = basicCredentials; var weatherDate = Convert.ToDateTime(weather.Data.Date); message.From = from; message.To.Add(to); message.Subject = $"Clima agora: {weatherDate:dd/MM/yyyy hh:mm}"; string clima = $"Tempo na cidade de {weather.Name} - {weather.State}\n" + $"----------------------------------------------------------------------\n" + $"Temperatura: {weather.Data.Temperature}°C\n" + $"Humidade: {weather.Data.Humidity}%\n" + $"Condição: {weather.Data.Condition}\n" + $"Sensação Termica: {weather.Data.Sensation}°C"; message.Body = clima; mailClient.Send(message); } } }
private void setValues(WeatherResult response) { if (response.weatherObservation != null) { observation = response.weatherObservation; } else { observation = new WeatherObservation { stationName = "NotFound", }; } //if (response != null) //{ // this.Elevation = response.weatherObservation.elevation; // this.Humidity = response.weatherObservation.humidity; // this.Temperature = response.weatherObservation.temperature; // this.StationName = response.weatherObservation.stationName; //} //else //{ // Elevation = default(long); // Humidity = default(long); // Temperature = default(long); // StationName = default(string); //} }
public static WeatherViewModel Map(WeatherResult weatherResult) { if (weatherResult?.location == null) { return(new WeatherViewModel() { IsSucceeded = false, City = "", Country = "", Temperature = "0.0 C", Humidity = "0.0" }); } else { return(new WeatherViewModel() { IsSucceeded = true, City = weatherResult.location.city, Country = weatherResult.location.country, Temperature = weatherResult.temperature.value.ToString("0.##") + " C", Humidity = weatherResult.humidity.ToString("0.##") }); } }
public static void getWeather(double Latitude, double Longitude, Action <WeatherResult> callback) { var parameters = new HttpParameters(); parameters.Add("APPID", APIKEY); parameters.Add("lat", Latitude); parameters.Add("lon", Longitude); HttpCommunicator.Get(HOST, null, parameters, (response) => { JObject js = JObject.Parse(response); var temp = js["main"]["temp"].ToString(); var weat = js["weather"][0]["main"].ToString(); var obj = new WeatherResult(); obj.tempreture = K2C(float.Parse(temp)).ToString("0.##"); obj.weather = weat; if (callback != null) { callback.Invoke(obj); } }, (e, retry) => { Log.Error("Weather", "ERROR {0} : retry after 3sec", e); Thread.Sleep(3000); if (retry != null) { retry.Invoke(); } }); }
/// <summary> /// Call the url to get the weather asynchronously, once has read the json result, convert to a weather result /// </summary> /// <param name="location"></param> /// <returns></returns> public async Task <WeatherResult> GetWeather(string location) { WeatherResult weatherResult = null; try { var uri = new Uri(_baseUri, location); var response = await _httpClient.GetStringAsync(uri.ToString()); if (response.StatusCode != System.Net.HttpStatusCode.OK) { _log.WarnFormat("{0} {1}", this._name, response.StatusCode.ToString()); return(null); } var jsonObj = JObject.Parse(response.Content); weatherResult = this.GetFromJson(jsonObj); } catch (Exception ex) { _log.ErrorFormat("{0} {1}", this._name, ex.Message); } return(weatherResult); }
public async Task <IActionResult> Zip(string zip) { using (var client = new HttpClient()) { try { client.BaseAddress = new Uri(_appSettings.WeatherDataUrl); var response = await client.GetAsync($"/by-zip/{zip}"); response.EnsureSuccessStatusCode(); var stringResult = await response.Content.ReadAsStringAsync(); var weather = JsonConvert.DeserializeObject <OpenWeatherResponse>(stringResult); if (weather.Weather == null || weather.Main == null) { return(NotFound(new { Error = weather.Message })); } var result = new WeatherResult(weather); result.Zip = zip; return(Ok(result)); } catch (HttpRequestException httpRequestException) { return(BadRequest($"Error getting weather from OpenWeather: {httpRequestException.Message}")); } } }
public async Task <WeatherResult> GetWeatherForDateByLocation(DateTime date, string woeId) { var response = await this .Client .GetAsync($"{woeId}/{date.ToString("yyyy/MM/dd")}"); if (!response.IsSuccessStatusCode) { throw new WeatherByLocationAndDateError( "Failed to get weather by location and date", woeId, date); } var result = new WeatherResult { ConsolidatedWeather = JsonConvert .DeserializeObject <ConsolidatedWeather[]> (await response .Content .ReadAsStringAsync()), WoeId = long.Parse(woeId) }; return(result); }
public Page1(LCD l) { lcd = l; InitializeComponent(); update_timer = new DispatcherTimer(); update_timer.Interval = new TimeSpan(0, 0, 0, 0, 200); update_timer.Tick += new EventHandler(updateTimer_Tick); weatherTimer = new DispatcherTimer(); weatherTimer.Interval = new TimeSpan(0, 10, 0); weatherTimer.Tick += new EventHandler(weatherTimer_Tick); update_timer.Start(); weatherTimer.Start(); yw = new YahooWeather(); wr = yw.getWeather("Trelleborg", "SE", false); if (wr != null) { imgWeather.Source = setWeatherImage(wr.Condition.Code); updateLables(); setForecast(); } }
private WeatherResult getFreshCache(string zip, DateTime now) { DateTime windowStart = now.Add(new TimeSpan(0, -30, 0)); WeatherResult res = db.WeatherResult.Where(m => m.Zipcode == zip && m.Time >= windowStart && m.Time <= now).FirstOrDefault(); return(res); }
public async Task <WeatherResult> Get(string id) { var result = await GetWeatherByZip(id); var weather = new WeatherResult(); weather.Location.Name = (string)result["location"]["name"]; weather.Location.Lat = (double)result["location"]["lat"]; weather.Location.Long = (double)result["location"]["lon"]; foreach (var forecastday in result["forecast"]["forecastday"]) { var day = forecastday["day"]; var forecast = new Forecast(); forecast.Date = (DateTime)forecastday["date"]; forecast.MaxTemp = (double)day["maxtemp_f"]; forecast.MinTemp = (double)day["mintemp_f"]; forecast.Condition = (string)day["condition"]["text"]; forecast.IconUrl = (string)day["condition"]["icon"]; weather.Forecasts.Add(forecast); } return(weather); }
/// <summary> /// Get weather by country name and city name /// </summary> public Weather GetWeather(string countryName, string cityName) { // Get from service //IassetBackend.Data.GlobalWeatherService.GlobalWeather WeatherService = new IassetBackend.Data.GlobalWeatherService.GlobalWeather(); //string response = WeatherService.GetWeather(cityName,countryName); // Get mocked data ***Service doesn't return any data*** string response = GetWeatherMockedData(); //Deseriallize XmlSerializer xmlSerializer = new XmlSerializer(typeof(WeatherResult)); WeatherResult weatherResult = xmlSerializer.Deserialize(new MemoryStream(Encoding.UTF8.GetBytes(response))) as WeatherResult; var weather = new Weather(); //Mapping weather.Country = new Country { Name = countryName }; weather.City = new City { Name = cityName }; var config = new MapperConfiguration(cfg => cfg.CreateMap <WeatherResult, Weather>()); IMapper mapper = config.CreateMapper(); var dest = mapper.Map <WeatherResult, Weather>(weatherResult, weather); return(weather); }
public WeatherModel Get(string zip) { WeatherModel model = new WeatherModel(); string url = string.Format("http://api.openweathermap.org/data/2.5/weather?zip={0},us&appid={1}&units=imperial", zip, APIKey); try { WebRequest request = WebRequest.Create(url); WebResponse response = request.GetResponse(); Stream responseStream = response.GetResponseStream(); StreamReader reader = new StreamReader(responseStream); WeatherResult weatherResult = JsonConvert.DeserializeObject(reader.ReadToEnd(), typeof(WeatherResult)) as WeatherResult; model.CurrentTemperature = weatherResult.main.temp.ToString(); model.LowTemperature = weatherResult.main.temp_min.ToString(); model.HighTemperature = weatherResult.main.temp_max.ToString(); model.Weather = weatherResult.weather[0].description; model.WindSpeed = weatherResult.wind.speed.ToString(); model.Station = weatherResult.name; } catch { //log actual error internally throw new Exception("Unable to retrieve weather data"); } return(model); }
private bool IsDangerDanger(WeatherResult weather) { int weatherCode; try { weatherCode = int.Parse(weather.WeatherCode.ToString("N")); } catch (Exception) { return(true); } if (weatherCode >= 232 && weatherCode <= 501) { return(true); } if (weatherCode <= 500 && weatherCode <= 781) { return(true); } if (weatherCode <= 900 && weatherCode <= 902) { return(true); } if (weatherCode <= 957) { return(true); } if (weather.Wind.Speed > DroningConstants.MaxWindSpeed) { return(true); } return(false); }
// Ustabil, danske bogstaver som ÆØÅ virker på nogens requests public async Task <IActionResult> GetWeather(string name) { City city = _db.Cities.Include(x => x.coordinates).FirstOrDefault(x => x.name.ToUpper().Contains(name.ToUpper())); if (city != null) { string jsonres = await _factory.CreateClient().GetStringAsync($"https://api.openweathermap.org/data/2.5/onecall?lat={city.coordinates.lat}&lon={city.coordinates.lon}&appid={apiKey}"); WeatherData weather = JsonConvert.DeserializeObject <WeatherData>(jsonres); DateTimeOffset dt = DateTimeOffset.UnixEpoch.AddSeconds(weather.current.dt); DateTime current = dt.DateTime; WeatherResult weatherResult = new WeatherResult() { AirTempC = weather.current.temp, WindSpeed = weather.current.wind_speed, Time = current //Add multiple parameters }; return(Ok(weatherResult)); } return(NotFound()); }
// POST api/transfernumberapi public string Post([FromBody] string requestStr) { try { WeatherRequest requests = JsonConvert.DeserializeObject <WeatherRequest>(requestStr); string output = ""; WeatherRepository repository = new WeatherRepository(); WeatherResult results = repository.Check(requests); output = JsonConvert.SerializeObject(results); return(output); } catch (Exception ex) { //發生錯誤時,傳回HTTP 500及錯誤訊息 var resp = new HttpResponseMessage() { StatusCode = HttpStatusCode.InternalServerError, Content = new StringContent(ex.Message), ReasonPhrase = "Web API Error" }; throw new HttpResponseException(resp); } }
public void SetWeather() { mainWeather = weathers[Random.Range(0, weathers.Count)]; secondaryWeather = weathers[Random.Range(0, weathers.Count)]; result = weatherData.GetResult(mainWeather.weatherName, secondaryWeather.weatherName); }
public async Task <ActionResult> Forecast(ForecastViewModel vm) { if (ModelState.IsValid) { //try to parse vm address as an integer for zip code, or text for city and state bool isZip = isZipCode(vm.Address) ? true : false; //post to openweather for temperature, min/max string queryString = ""; if (isZip) { //check to see if there exists a record with same zip code captured in last 30 minutes WeatherResult cacheRes = getFreshCache(vm.Address, DateTime.Now); if (cacheRes != null) { vm.temp = cacheRes.Temp; vm.temp_max = cacheRes.Max_temp; vm.temp_min = cacheRes.Min_temp; vm.cacheHit = true; return(View("ForecastDetails", vm)); } queryString = "?zip=" + vm.Address + ",us&units=imperial&" + appKeyQueryString; } else { queryString = "?q=" + vm.Address + ",us&units=imperial&" + appKeyQueryString; } HttpClient client = new HttpClient(); client.BaseAddress = new Uri(weatherURL); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); HttpResponseMessage response = client.GetAsync(queryString).Result; if (response.IsSuccessStatusCode) { //parse results and set to view model details string jsonRes = await response.Content.ReadAsStringAsync(); Forecast forecast = JsonConvert.DeserializeObject <Forecast>(jsonRes); vm.temp = forecast.main.temp; vm.temp_max = forecast.main.temp_max; vm.temp_min = forecast.main.temp_min; //if request was by zip, cache results for later storage if (isZip) { storeWeatherResults(vm.Address, DateTime.Now, vm.temp, vm.temp_max, vm.temp_min); } return(View("ForecastDetails", vm)); } client.Dispose(); } return(View(vm)); }
private void weatherTimer_Tick(object sender, EventArgs e) { wr = yw.getWeather("Trelleborg", "SE", false); if (wr != null) { imgWeather.Source = setWeatherImage(wr.Condition.Code); updateLables(); setForecast(); } }
public WeatherData(WeatherResult currentWeatherResult, TemperatureUnit tempUnit) { City = currentWeatherResult.City; Country = currentWeatherResult.Country; Temp = currentWeatherResult.Temp; TempMax = currentWeatherResult.TempMax; TempMin = currentWeatherResult.TempMin; Humidity = currentWeatherResult.Humidity; TempUnit = tempUnit; }
public async Task <WeatherResult> GetWeatherAsync(string city, string stateCode, string countryCode) { var forecast = new Forecast(); city = $"{city}, {stateCode}"; var weather = await forecast.GetWeatherDataByCityNameAsync(ApiKey, city, countryCode); WeatherResult result = weather?.ToResult(); return(result); }
private void SetValues(WeatherResult weather) { var stationName = weather.weatherObservation.stationName; var elevation = weather.weatherObservation.elevation; var temperature = weather.weatherObservation.temperature; var humidity = weather.weatherObservation.humidity; StationName = stationName; Elevation = elevation; Temperature = temperature; Humidity = humidity; }
public static WeatherResult ToResult(this WeatherData weatherData) { Kelvin kelvin = new Kelvin(weatherData.main.temp); LatitudeLongitude location = new LatitudeLongitude(weatherData.coord.lat, weatherData.coord.lon); WindSpeed windSpeed = new WindSpeed(new KilometersPerHour(weatherData.wind.speed), weatherData.wind.deg); WeatherResult result = new WeatherResult(kelvin, location, windSpeed); return(result); }
/// <summary> /// 查询天气信息 /// </summary> /// <param name="queryParam">查询参数</param> /// <returns>城市的天气结果</returns> public WeatherResult SearchWeather(SkyCityParam queryParam) { queryParam.output = "JSON"; string jsonResult = SearchOriginalWeather(queryParam); if (!string.IsNullOrWhiteSpace(jsonResult)) { jsonResult = jsonResult.Replace("[]", "\"\""); } WeatherResult queryResult = JsonConvert.DeserializeObject <WeatherResult>(jsonResult); return(queryResult); }
/// <summary> /// 获取心知天气 /// </summary> /// <param name="city">城市</param> /// <returns></returns> private WeatherInfo GetSeniverseWeather(string city) { if (string.IsNullOrEmpty(city)) { return(null); } WeatherInfo weatherInfo = new WeatherInfo() { results = new List <WeatherResult>() }; try { string requestUrl = "https://api.seniverse.com/v3/weather/now.json?"; string param = $"key={apikey}&location={city}&language={language}&unit=c"; requestUrl += param; string response = HttpClientHelper.Get(requestUrl); var seniverseWeather = SerializeHelper.SerializeJsonToObject <SeniverseWeather>(response); if (seniverseWeather == null) { return(null); } if (seniverseWeather.results == null || seniverseWeather.results.Length <= 0) { return(null); } foreach (var item in seniverseWeather.results) { WeatherResult weatherResult = new WeatherResult(); weatherResult.country = item.location.country; weatherResult.id = item.location.id; weatherResult.name = item.location.name; weatherResult.path = item.location.path; weatherResult.timezone = item.location.timezone; weatherResult.timezone_offset = item.location.timezone_offset; weatherResult.last_update = item.last_update; weatherResult.text = item.now.text; weatherResult.temperature = item.now.temperature + "℃"; string code = item.now.code; byte[] bytes = FileReadWriteHelper.ReadBytesFromBitmap(GetBitmap(code)); weatherResult.icon = Base64Helper.Encoding(bytes); weatherInfo.results.Add(weatherResult); } } catch (System.Exception ex) { LogHelper.WriteError(ex); } return(weatherInfo); }
private void storeWeatherResults(string address, DateTime now, decimal temp, decimal max_temp, decimal min_temp) { WeatherResult weather_res = new WeatherResult { Zipcode = address, Time = now, Temp = temp, Max_temp = max_temp, Min_temp = min_temp }; db.WeatherResult.Add(weather_res); db.SaveChanges(); }
/// <summary> /// 获取Jirengu天气(备用查询天气方案(地级市也可查询)) /// </summary> /// <param name="city">城市</param> /// <returns></returns> private WeatherInfo GetJirenguWeather(string city) { if (string.IsNullOrEmpty(city)) { return(null); } WeatherInfo weatherInfo = new WeatherInfo() { results = new List <WeatherResult>() }; try { string requestUrl = $"http://api.jirengu.com/getWeather.php?city={city}"; string response = HttpClientHelper.Get(requestUrl); var jirenguWeather = SerializeHelper.SerializeJsonToObject <JirenguWeather>(response); if (jirenguWeather == null) { return(null); } if (jirenguWeather.results == null || jirenguWeather.results.Length <= 0) { return(null); } foreach (var item in jirenguWeather.results) { int i = 0; WeatherResult weatherResult = new WeatherResult(); weatherResult.path = item.currentCity; weatherResult.text = item.weather_data[i].weather; string tempStr = item.weather_data[i].date; Regex reg = new Regex(@"实时:(.+)℃\)"); Match match = reg.Match(tempStr); string temperature = match.Groups[1].Value; weatherResult.temperature = temperature + "℃"; string code = GetWeatherCode(item.weather_data[i].weather); byte[] bytes = FileReadWriteHelper.ReadBytesFromBitmap(GetBitmap(code)); weatherResult.icon = Base64Helper.Encoding(bytes); weatherInfo.results.Add(weatherResult); i++; } } catch (Exception ex) { LogHelper.WriteError(ex); } return(weatherInfo); }
public async Task WebApiGetWeather_InvalidParameters_EmptyResponse(string country, string city) { var WebApiUri = new Uri(System.Configuration.ConfigurationManager.AppSettings["WeatherWebApiAddress"]); string apiWeatherUri = String.Format("/api/Weather/{0}/{1}", country, city); HttpClient httpClient = new HttpClient(); httpClient.BaseAddress = WebApiUri; var result = await httpClient.GetAsync(apiWeatherUri); WeatherResult weatherResult = await result.Content.ReadAsAsync <WeatherResult>(); Assert.True(weatherResult.location == null); }
/// <summary> /// Create a weather result from a json object passed as a parameter /// </summary> /// <param name="jsonObj"></param> /// <returns></returns> private WeatherResult GetFromJson(JObject jsonObj) { WeatherResult obj = new WeatherResult(); if (jsonObj.Count==0) return null; obj.Temperature = (float)jsonObj[this._temperatureKey]; obj.Wind = (float)jsonObj[this._windKey]; obj.Location = (string)jsonObj["Location"]; obj.TemperatureUnit = this._temperatureUnit; obj.WindUnit = this._windUnit; return obj; }
public async Task <WeatherResult> GetWeathers() { var res = new WeatherResult() { Observations = new List <WeatherItem>() }; foreach (var item in stations) { var wh = await GetWeather(item.Key); res.Observations.Add(wh); } return(res); }
public static async Task <WeatherResult> GetWeatherInformationAsync(string city) { var result = new WeatherResult(); using (HttpClient client = new HttpClient()) { var query = string.Format(BASE_URL, city, API_KEY); var response = await client.GetAsync(query); var json = await response.Content.ReadAsStringAsync(); result = JsonConvert.DeserializeObject <WeatherResult>(json); } return(result); }
/// <summary> /// Gets the result. /// </summary> /// <param name="Html">The HTML.</param> /// <returns></returns> private List<WeatherResult> getResult(string Html) { List<WeatherResult> result = new List<WeatherResult>(); int indexOf = 0; MatchCollection temMatchs = Regex.Matches(Html, @"(高温|低温)\s*<strong>(\d+)<strong>", RegexOptions.Multiline | RegexOptions.IgnoreCase); foreach (Match dayMatch in Regex.Matches(Html, @"(\d+)日(星期[\u4E00-\u9FA5])", RegexOptions.IgnoreCase | RegexOptions.Multiline)) { WeatherResult singleResult = new WeatherResult() { Day=string.Format(@"{0}日",dayMatch.Groups[1].Value), WeekDay=dayMatch.Groups[2].Value }; singleResult.MinTemperature = temMatchs[indexOf].Groups[2].Value; if (temMatchs.Count % 2 == 0 && indexOf == 0) { } else { singleResult.MaxTemperature = temMatchs[indexOf+1].Groups[2].Value; } result.Add(singleResult); indexOf++; } return result; }