public async Task<ActionResult> GetWUnderground(WeatherModel weather) { try { string address = weather.Address; string apiKey = "c48aee81124a9dd8"; double lat, lon; string formattedAddress; // Retrieves address info using Google's geocode api FindAddress(address, out lat, out lon, out formattedAddress); WeatherModel forecast = await GetWUnderground(apiKey, formattedAddress); var camelCaseFormatter = new JsonSerializerSettings(); camelCaseFormatter.ContractResolver = new CamelCasePropertyNamesContractResolver(); var jsonResult = new ContentResult { Content = JsonConvert.SerializeObject(forecast, camelCaseFormatter), ContentType = "application/json" }; return jsonResult; } catch (Exception ex) { throw new Exception(ex.Message); } }
public ActionResult GetForecastIO(WeatherModel weather) { try { string address = weather.Address; double lat; double lon; string formattedAddress; // Retrieves address, lat, and lon using Google's Geo Code API FindAddress(address, out lat, out lon, out formattedAddress); // Get weather info from Forecast.io WeatherModel forecast = GetForecastIO((float)lat, (float)lon, formattedAddress); var camelCaseFormatter = new JsonSerializerSettings(); camelCaseFormatter.ContractResolver = new CamelCasePropertyNamesContractResolver(); var jsonResult = new ContentResult { Content = JsonConvert.SerializeObject(forecast, camelCaseFormatter), ContentType = "application/json" }; return jsonResult; } catch (Exception ex) { throw new Exception(ex.Message); } }
public void TestCalculateAverageHumidityNoData() { var model = new WeatherModel(new Weather(), new Weather[] { }); float result = model.CalculateAverageHumidity(); Assert.Equal(0, result); }
public void Get_Given_CountryAndCity_Returns_WeatherModelMappedFromWeather() { //arrange var weatherFromService = new Weather( new Temperature("", 0), 0); var weatherService = Substitute.For <IWeatherService>(); weatherService.GetWeather(Arg.Any <string>(), Arg.Any <string>()) .Returns(weatherFromService); WeatherModel resultFromMapper = new WeatherModel(); var mapper = Substitute.For <ICustomMapper>(); mapper.Map <WeatherModel>(weatherFromService).Returns(resultFromMapper); var sut = new WeatherController(weatherService, mapper) { Request = new HttpRequestMessage(), Configuration = new HttpConfiguration() }; //act var result = sut.Get(Arg.Any <string>(), Arg.Any <string>()); //assert result.ShouldBe(resultFromMapper); }
public static IEnumerable <Record> LoadAll() { using (WeatherModel context = new WeatherModel()) { return(context.Records.OrderByDescending(x => x.Date).ToList()); } }
public ActionResult RefreshWeatherForecast() { var model = new WeatherModel(); string html = RazorExtensionHelpers.RenderViewToString(this.ControllerContext, "~/Views/Parts/Weather.cshtml", model); return(Content(html)); }
private static void AddCurrentWeather(WeatherModel model, AdaptiveCard card, bool isLocation = false) { var current = new ColumnSet(); card.Body.Add(current); var currentColumn = new Column(); current.Columns.Add(currentColumn); currentColumn.Size = "35"; var currentImage = new Image(); currentColumn.Items.Add(currentImage); currentImage.Url = GetIconUrl(model.current.condition.icon); var currentColumn2 = new Column(); current.Columns.Add(currentColumn2); currentColumn2.Size = "65"; string date = DateTime.Parse(model.current.last_updated).DayOfWeek.ToString(); AddTextBlock(currentColumn2, $"{(!isLocation ? model.location.name : model.location.region)} ({date})", TextSize.Large, false); AddTextBlock(currentColumn2, $"{model.current.temp_c.ToString().Split('.')[0]}° C", TextSize.Large); AddTextBlock(currentColumn2, $"{model.current.condition.text}", TextSize.Medium); AddTextBlock(currentColumn2, $"Winds {model.current.wind_mph} mph {model.current.wind_dir}", TextSize.Medium); }
public async Task <IActionResult> Edit(int id, [Bind("Id,Identifier,Timestamp,Date,TemperatureC")] WeatherModel weatherModel) { if (id != weatherModel.Id) { return(NotFound()); } if (ModelState.IsValid) { try { _context.Update(weatherModel); await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!WeatherModelExists(weatherModel.Id)) { return(NotFound()); } else { throw; } } return(RedirectToAction(nameof(Index))); } return(View(weatherModel)); }
/// <summary> /// Getting weather Information /// </summary> /// <param name="city"></param> /// <returns></returns> public ActionResult GetWeather(string city) { WeatherDetails weatherDetails = new WeatherDetails(); WeatherModel weatherModel = weatherDetails.GetWeather(city); return(PartialView("Weather", weatherModel)); }
public async Task <WeatherModel> GetByCity(string country, string city) { var errors = new List <ErrorModel>(); foreach (var provider in _providers) { try { var res = await provider.GetWeather(country, city); if (!res.Errored) { return(res); } errors.Add(res.Error); } catch (Exception ex) { _logger.Warning(ex, "Provider exception. Type: {providerType}, Method: {method}", provider.GetType().Name, nameof(provider.GetWeather)); errors.Add(ErrorModel.FromException(ex, $"Exception from {provider.GetType().Name}")); } } //If we have reached here nothing was returned var errorMessage = $"One or more errors occurred:\n{string.Join("\n", errors.Select(e => e.ErrorMessage))}"; var exceptions = errors.Select(e => e.Exception); return(WeatherModel.FromException(new AggregateException(errorMessage, exceptions))); }
public async Task <WeatherModel> GetWeatherData() { using (var client = new HttpClient()) { client.BaseAddress = new Uri(Weather.URLBASE); var response = await client.GetAsync(Weather.APIKEY + Weather.URLWEATHER); var weatherJson = response.Content.ReadAsStringAsync().Result; System.Diagnostics.Debug.WriteLine("response::- " + weatherJson); WeatherModel weatherModel = new WeatherModel(); if (weatherJson != null) { dynamic jObj = JsonConvert.DeserializeObject(weatherJson); weatherModel.observation_time = (string)jObj["current_observation"]["observation_time"]; weatherModel.temp_c = (string)jObj["current_observation"]["temp_c"]; weatherModel.temp_f = (string)jObj["current_observation"]["temp_f"]; System.Diagnostics.Debug.WriteLine("Fahrenheit:- " + weatherModel.temp_f); System.Diagnostics.Debug.WriteLine("Celsius:- " + weatherModel.temp_c); System.Diagnostics.Debug.WriteLine("Request Time:- " + weatherModel.observation_time); } return(weatherModel); } }
public List <WeatherModel> GetForecasts(string parkCode) { List <WeatherModel> forecastList = new List <WeatherModel>(); try { using (SqlConnection conn = new SqlConnection(connectionString)) { conn.Open(); SqlCommand cmd = new SqlCommand("SELECT * FROM weather WHERE weather.parkcode = @parkCode", conn); cmd.Parameters.AddWithValue("@parkCode", parkCode); SqlDataReader reader = cmd.ExecuteReader(); while (reader.Read()) { WeatherModel forecast = new WeatherModel(); forecast.ParkCode = Convert.ToString(reader["parkCode"]); forecast.FiveDayForecastValue = Convert.ToInt32(reader["fiveDayForecastValue"]); forecast.Forecast = Convert.ToString(reader["forecast"]); forecast.High = Convert.ToInt32(reader["high"]); forecast.Low = Convert.ToInt32(reader["Low"]); forecastList.Add(forecast); } } } catch (SqlException e) { Console.WriteLine(e.Message); throw; } return(forecastList); }
private async Task <WeatherModel> GetWeatherOfflineAsync() { try { var database = new RepositoryDatabase(); var currently = await database.GetAllItems <Currently>(); var weather = new WeatherModel(); weather.Daily = new Daily() { Data = new List <DailyData>(await database.GetAllItems <DailyData>()) }; weather.Hourly = new Hourly() { Data = new List <HourlyData>(await database.GetAllItems <HourlyData>()) }; weather.Currently = currently.FirstOrDefault(); return(weather); } catch (Exception e) { Console.WriteLine(e.Message); return(null); } }
public static Source GetSource(int id) { using (WeatherModel context = new WeatherModel()) { return(context.Sources.FirstOrDefault(s => s.Id == id)); } }
public static IEnumerable <Source> GetSources() { using (WeatherModel context = new WeatherModel()) { return(context.Sources.ToList()); } }
public static IEnumerable <Record> LoadByDateRange(DateTime dateFrom, DateTime dateTo) { using (WeatherModel context = new WeatherModel()) { return(context.Records.Where(r => r.Date >= dateFrom && r.Date <= dateTo).ToList()); } }
public static IEnumerable <Record> LoadByDate(DateTime date, int sourceId) { using (WeatherModel context = new WeatherModel()) { return(context.Records.Where(r => r.SourceId == sourceId).Where(r => r.Date.Day == date.Day && r.Date.Month == date.Month && r.Date.Year == date.Year).ToList()); } }
public static IEnumerable <Record> LoadAll(int id) { using (WeatherModel context = new WeatherModel()) { return(context.Records.Where(s => s.SourceId == id).OrderByDescending(x => x.Date).ToList()); } }
public IActionResult WeatherResult(string City) { WeatherModel weather = new WeatherModel(); weather = weatherDAL.ConvertJsonToWeatherModel(City); return(View(weather)); }
public IList <WeatherModel> GetWeatherAssociatedWithPark(string parkCode) { IList <WeatherModel> weathers = new List <WeatherModel>(); try { using (SqlConnection conn = new SqlConnection(connectionString)) { conn.Open(); SqlCommand cmd = new SqlCommand("Select * from weather where parkCode = @parkCode;", conn); cmd.Parameters.AddWithValue("@parkCode", parkCode); var reader = cmd.ExecuteReader(); while (reader.Read()) { var weather = new WeatherModel() { FiveDayForecastValue = Convert.ToInt32(reader["fiveDayForecastValue"]), LowTemp = Convert.ToInt32(reader["low"]), HighTemp = Convert.ToInt32(reader["high"]), ForeCast = Convert.ToString(reader["forecast"]) }; weathers.Add(weather); } } } catch (Exception) { throw; } return(weathers); }
public static WeatherResponse ToWeatherResponse(WeatherModel model) { if (model == null) { throw new ArgumentNullException(nameof(model)); } if (model.Errored) { throw new InvalidOperationException("An errored model can not be mapped to a response"); } var res = new WeatherResponse(); res.MainDesc = model.Description1.UpperFirst(); res.SecondaryDesc = model.Description2.UpperFirst(); res.CurrentTemp = model.TempCurrent != null? model.TempCurrent.DegreesCelsius.ToTemperatureString('C') : "Unknown"; AddTemperatureModel(res.Props, "Current Temperature", model.TempCurrent); AddTemperatureModel(res.Props, "Min. Temperature", model.TempMin); AddTemperatureModel(res.Props, "Max. Temperature", model.TempMax); res.Props.Add("Humidity", model.Humidity); res.Props.Add("Pressure", model.Pressure); res.Props.Add("Wind Speed", model.WindSpeed); return(res); }
public static async Task SendMessageAsync(DeviceClient deviceClient) { while (true) { _client = new HttpClient(); var response = await _client.GetAsync("http://api.openweathermap.org/data/2.5/weather?q=orebro&appid=62d274c03fa45dffcda1b3b257b696ce"); var data = JsonConvert.DeserializeObject <TemperatureModel>(await response.Content.ReadAsStringAsync()); var weather = new WeatherModel { Temperature = data.main.temp, Humidity = data.main.humidity }; var json = JsonConvert.SerializeObject(weather); var payload = new Microsoft.Azure.Devices.Client.Message(Encoding.UTF8.GetBytes(json)); await deviceClient.SendEventAsync(payload); Console.WriteLine($"Message sent: {json}"); await Task.Delay(60 * 1000); } }
public async Task <ActionResult> CreateWeather(string date, string cityName) { var url = $"http://api.worldweatheronline.com/premium/v1/weather.ashx?key={apiKey}&q={cityName}&format=json&date={date}&lang=tr"; var responseString = await client.GetStringAsync(url); var responseJson = JObject.Parse(responseString); var weather = responseJson.SelectToken("data").SelectToken("weather")[0]; using (var ctx = new IFSAppContext()) { var wm = new WeatherModel() { WeatherDate = DateTime.Parse(weather.SelectToken("date").ToString()), CityName = responseJson.SelectToken("data").SelectToken("request")[0].SelectToken("query").ToString().Split(',')[0], Temperature = (int)weather.SelectToken("avgtempC"), MainStatus = weather.SelectToken("hourly")[4].SelectToken("lang_tr")[0].SelectToken("value").ToString(), IconPath = weather.SelectToken("hourly")[4].SelectToken("weatherIconUrl")[0].SelectToken("value").ToString() }; bool isExists = ctx.WeatherInfos.Where(x => x.WeatherDate == wm.WeatherDate && x.CityName == wm.CityName).FirstOrDefault() != null; if (!isExists) { ctx.WeatherInfos.Add(wm); ctx.SaveChanges(); } return(RedirectToAction("WeatherManagement")); } }
public List <WeatherModel> GetWeather(string parkCode) { try { using (SqlConnection conn = new SqlConnection(connectionString)) { conn.Open(); SqlCommand cmd = new SqlCommand(SQL_GetWeatherFromParkCode, conn); cmd.Parameters.AddWithValue("@parkCode", parkCode); SqlDataReader reader = cmd.ExecuteReader(); while (reader.Read()) { WeatherModel w = new WeatherModel(); w.FiveDayForecastValue = Convert.ToInt32(reader["fiveDayForecastValue"]); w.Low = Convert.ToInt32(reader["low"]); w.High = Convert.ToInt32(reader["high"]); w.Forecast = Convert.ToString(reader["forecast"]); w.ParkCode = Convert.ToString(reader["parkCode"]); weatherList.Add(w); } } } catch (SqlException ex) { throw; } return(weatherList); }
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); }
public static async Task SendMessageAsync(DeviceClient deviceClient) { while (true) { try { var respone = await _client.GetAsync(_connweat); if (respone.IsSuccessStatusCode) { WeatherModel weather = JsonConvert.DeserializeObject <WeatherModel>(await respone.Content.ReadAsStringAsync()); var data = new Current { temperature = weather.current.temperature, humidity = weather.current.humidity }; var json = JsonConvert.SerializeObject(data); var payload = new Message(Encoding.UTF8.GetBytes(json)); await deviceClient.SendEventAsync(payload); Console.WriteLine($"Sent Message: {json}"); await Task.Delay(10 * 1000); } } catch (Exception ex) { Console.WriteLine($"{ex.Message}"); } } }
public CurrentConditions GetCurrentConditions(int id) { // Id is irrelevant here, just used to separate get conditions and get forecast var weather = new WeatherModel(_context); return(weather.GetCurrentConditions()); }
public void OnWeatherLiveSearched(LocalWeatherLiveResult weatherLiveResult, int rCode) { if (rCode == 1000) { if (weatherLiveResult != null && weatherLiveResult.LiveResult != null) { var weatherlive = weatherLiveResult.LiveResult; var model = new WeatherModel { ReportTime = weatherlive.ReportTime, Humidity = weatherlive.Humidity, Temperature = weatherlive.Temperature, Weather = weatherlive.Weather, WindDirection = weatherlive.WindDirection, WindPower = weatherlive.WindPower }; //发回给forms层 MessagingCenter.Send(new object(), SearchPage.QueryWeatherOk, model); } else { //ToastUtil.show(WeatherSearchActivity.this, R.string.no_result); Console.WriteLine("查询天气无数据"); } } else { Console.WriteLine("查询天气错误:" + rCode); } }
void Appstartup(object sender, StartupEventArgs e) { WeatherModel modelInstance = new WeatherModel(); modelInstance.SetCurrentURL("istanbul"); xmlDocument = modelInstance.GetXML(); XmlNode temp_node = xmlDocument.SelectSingleNode("//temperature"); XmlAttribute temp_value = temp_node.Attributes["value"]; string temp_string = temp_value.Value; temperature = temp_string; temp_node = xmlDocument.SelectSingleNode("//humidity"); temp_value = temp_node.Attributes["value"]; temp_string = temp_value.Value; humidity = temp_string; temp_node = xmlDocument.SelectSingleNode("//clouds"); temp_value = temp_node.Attributes["name"]; temp_string = temp_value.Value; clouds = temp_string; temp_node = xmlDocument.SelectSingleNode("//speed"); temp_value = temp_node.Attributes["name"]; temp_string = temp_value.Value; wind = temp_string; Instance = this; }
protected override WeatherModel MapResponse(string responseBody) { var jObj = JsonConvert.DeserializeObject <dynamic>(responseBody); var weather = jObj.weather[0]; var main = jObj.main; var wind = jObj.wind; var desc1 = (string)weather.main; var desc2 = (string)weather.description; var tempMin = _temperatureModelFactory.FromKelvin((decimal)main.temp_min); var tempMax = _temperatureModelFactory.FromKelvin((decimal)main.temp_max); var tempCurrent = _temperatureModelFactory.FromKelvin((decimal)main.temp); var humidity = (decimal?)main.humidity; var pressure = (decimal?)main.pressure; var windSpeed = (decimal?)wind.speed; var windDeg = (decimal?)wind.deg; var model = new WeatherModel( desc1, desc2, tempMin, tempMax, tempCurrent, pressure, humidity, windDeg, windSpeed); return(model); }
public static AdaptiveCard GetCard(string place, string lat = null, string lon = null) { bool isLocation = false; WeatherModel model = null; if (!string.IsNullOrWhiteSpace(place) && lat == null && lon == null) { model = new Repository().GetWeatherData(ConfigurationManager.AppSettings["APIXUKey"], GetBy.CityName, place, Days.Five); } else if (string.IsNullOrEmpty(place) && lat != null && lon != null) { isLocation = true; model = new Repository().GetWeatherDataByLatLong(ConfigurationManager.AppSettings["APIXUKey"], lat, lon, Days.Five); _latitude = null; _longitude = null; } var card = new AdaptiveCard(); if (model != null) { if (model.current != null) { card.Speak = $"<s>Today the temperature is {model.current.temp_c} in {(!isLocation ? model.location.name : model.location.region)}</s><s>Winds are {model.current.wind_mph} miles per hour from the {model.current.wind_dir}</s>"; } if (model.forecast != null && model.forecast.forecastday != null) { AddCurrentWeather(model, card, isLocation); AddForecast(!isLocation ? model.location.name : model.location.region, model, card); return(card); } } return(null); }
public static async Task DisplayWeather(WeatherModel wm, SocketCommandContext context) { EmbedBuilder eb = new EmbedBuilder { Color = Color.Teal }; eb.WithTitle($"Weather for {wm.Name},{wm.Sys.Country}"); eb.WithDescription($"{wm.WeatherDescriptionModel.Description}"); eb.AddField("Temperature", $"{ToFarenheit(wm.Main.Temp)}°F ({ToCelcius(wm.Main.Temp)}°C)", true); eb.AddField("Humidity", $"{wm.Main.Humidity}%", true); eb.AddField("Wind speed", $"{ToKmPerHour(wm.Wind.Speed)}km/h ({ToMilesPerHour(wm.Wind.Speed)}miles/h)", true); eb.AddField("Max Temperature", $"{ToFarenheit(wm.Main.Temp_max)}°F ({ToCelcius(wm.Main.Temp_max)}°C)", true); eb.AddField("Min Temperature", $"{ToFarenheit(wm.Main.Temp_min)}°F ({ToCelcius(wm.Main.Temp_min)}°C)", true); eb.WithThumbnailUrl($"http://openweathermap.org/img/w/{wm.WeatherDescriptionModel.Icon}.png"); EmbedFooterBuilder efb = EmbedBuilderFunctions.AddFooter(context).Result; efb.Text += " - Powered by the API OpenWeatherMap"; eb.WithFooter(efb); await context.Channel.SendMessageAsync(embed : eb.Build()); }
public ApixuWeatherData(WeatherModel data) { Temperature = data.current.temp_c; WindDirection = data.current.wind_degree; WindSpeed = (int)data.current.wind_kph; Condition = data.current.condition.text; Humidity = data.current.humidity; Pressure = data.current.pressure_mb / 1.3332239; }
// Retrieves weather from forecast.io and populates the model private WeatherModel GetForecastIO(float lat, float lon, string formattedAddress) { var request = new ForecastIORequest("d1d02d9b39d4125af3216ea665368a5c", lat, lon, Unit.us); var response = request.Get(); WeatherModel weather = new WeatherModel(response, formattedAddress); return weather; }
/* * In order to get all our weather needs we need to query 4 different request for Weather Underground. * This takes a performance hit. Hence, we are using asynchronous call to minimize the performance hit */ private async Task<WeatherModel> GetWUnderground(string apiKey, string addr) { var ctsDaily = new CancellationTokenSource(); var ctsCC = new CancellationTokenSource(); var ctsPlanner = new CancellationTokenSource(); var ctsAstronomy = new CancellationTokenSource(); // 7 Day weather var dailyResults = WUndergroundDaily(apiKey, ctsDaily); // Current conditions var currentConditionResults = WUndergroundCurrCondition(apiKey, ctsCC); // Planner (chance of precipitation) var plannerResults = WUndergroundPlanner(apiKey, ctsPlanner); // Astronomy var astronomyResults = WUndergroundAstronomy(apiKey, ctsAstronomy); await Task.WhenAll(dailyResults, currentConditionResults, plannerResults, astronomyResults); WeatherModel weather = new WeatherModel(currentConditionResults.Result, dailyResults.Result, plannerResults.Result, astronomyResults.Result, addr); return weather; }