public WeatherForecastModel Post([FromBody] WeatherForecastModel weatherForecast) { var weatherForecastList = _weatherForecastService.GetSummaries(); weatherForecastList.Add(weatherForecast.Summary); return(weatherForecast); }
private async Task <WeatherForecastModel> GetSixDayForecast(string cityId, string zipCode) { string endpoint = GetEndpoint(cityId, zipCode, "forecast"); var response = await _httpClient.GetAsync(endpoint); if (response.IsSuccessStatusCode) { var text = await response.Content.ReadAsStringAsync(); var sixDayForecast = JsonConvert.DeserializeObject <SixDayForecast>(text); var averagedFiveDayForecast = GetAveragedSixDayForecast(sixDayForecast); var weatherForecast = new WeatherForecastModel() { City = sixDayForecast.City, Forecasts = averagedFiveDayForecast }; return(weatherForecast); } else { return(null); } }
public async Task <WeatherForecastModel> GetForecast(string cityId, string zipCode) { _logger.LogDebug($"Getting forecasts for city ID = {cityId} and zipcode = {zipCode}"); //OpenWeatherMap: We recommend making calls to the API no more than one time every 10 minutes for one location //let's cache the response for 10 minutes WeatherForecastModel weatherForecast; if (!_cache.TryGetValue(String.Format(WeatherCache, cityId, zipCode), out weatherForecast)) { _logger.LogDebug($"Missing cache for city ID = {cityId} and zipcode = {zipCode}"); WeatherForecastModel sixDayForecast = await GetSixDayForecast(cityId, zipCode); //sometimes (after 23.00) the openweathermap api returns five next days but not today //in that case we fill the today's value from another endpoint if (sixDayForecast?.Forecasts.Count() < 6) { AveragedDayForecastModel currentForecast = await GetCurrentForecast(cityId, zipCode); sixDayForecast.Forecasts.Insert(0, currentForecast); } weatherForecast = sixDayForecast; _cache.Set(string.Format(WeatherCache, cityId, zipCode), sixDayForecast, TimeSpan.FromMinutes(10)); } return(weatherForecast); }
public async Task <WeatherForecastModel> AddTaskAsync(WeatherForecastModel weatherForecastModel) { var addedmodel = (await _context.WeatherForecasts.AddAsync(weatherForecastModel)).Entity; await _context.SaveChangesAsync(); return(addedmodel); }
public List <WeatherForecastModel> GetWeatherC(string id) { //WeatherForecastModel w = new WeatherForecastModel(); List <WeatherForecastModel> weathers = new List <WeatherForecastModel>(); try { using (SqlConnection conn = new SqlConnection(connectionString)) { conn.Open(); SqlCommand cmd = new SqlCommand(SQL_GetWeather, conn); cmd.Parameters.AddWithValue("@parkCode", id); SqlDataReader reader = cmd.ExecuteReader(); while (reader.Read()) { WeatherForecastModel w = new WeatherForecastModel(); w.ParkCode = Convert.ToString(reader["parkCode"]); w.FiveDayForecastValue = Convert.ToInt32(reader["fiveDayForecastValue"]); w.Low = Convert.ToInt32(reader["low"]); w.High = Convert.ToInt32(reader["high"]); w.Forecast = Convert.ToString(reader["forecast"]); weathers.Add(w); } } } catch (SqlException e) { throw; } return(weathers); }
//public List<WeatherForecastModel> GetForecast(string parkCode) //{ // throw new NotImplementedException(); //} public WeatherForecastModel GetForecast(string parkCode) { WeatherForecastModel output = new WeatherForecastModel(); 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); SqlDataReader reader = cmd.ExecuteReader(); output.ParkCode = parkCode; int i = 0; while (reader.Read()) { i = Convert.ToInt32(reader["fiveDayForecastValue"]); output.High.Add(Convert.ToInt32(reader["high"])); output.Low.Add(Convert.ToInt32(reader["low"])); output.Forecast.Add(Convert.ToString(reader["forecast"])); } } } catch (SqlException) { throw; } return(output); }
public IActionResult Post([FromBody] WeatherForecastModel weatherForecast) { HttpContext.VerifyUserHasAnyAcceptedScope(ScopesRequiredByApiForWriteData); Console.WriteLine("POSTED: " + weatherForecast.Summary); return(Ok()); }
public async Task <ActionResult <WeatherForecastModel> > CreateAsync([FromBody] WeatherForecastModel model) { _logger.LogTrace("Handling CreateAsync"); var weatherForecast = await _mediator.Send(new CreateWeatherForecastCommand { WeatherForecast = _mapper.Map <WeatherForecast>(model) }); return(CreatedAtAction(nameof(GetOneAsync), new{ id = weatherForecast.Id }, weatherForecast)); }
public async Task <WeatherForecastModel> UpdateForecasts(WeatherForecastModel item) { await Clients.All.SendAsync("ReceiveUpdate", item.Date, item.TemperatureC, item.Humidity, item.Pressure, item.Summary); return(item); }
//GET api/<controller>/<action>?city={city}&state={state} public async Task <WeatherForecastModel> GetWeatherByCity(string city, string state) { HttpClient client = new HttpClient(); GeolookupModel geoModel = new GeolookupModel(); ForeCastModel forecastModel = new ForeCastModel(); HttpResponseMessage forecastResponse; weatherAPI = weatherAPI.Replace("{{City}}", city).Replace("{{State}}", state); forecastResponse = client.GetAsync(weatherAPI).Result; if (forecastResponse.IsSuccessStatusCode) { forecastModel = await forecastResponse.Content.ReadAsAsync <ForeCastModel>(); } Forecast forecastWeathermodel = new Forecast(); forecastWeathermodel = forecastModel.forecast; Simpleforecast simpleforecast = forecastWeathermodel.simpleforecast; List <Forecastday> forecastdayList = new List <Forecastday>(); forecastdayList = simpleforecast.forecastday; List <WeatherModel> weatherList = new List <WeatherModel>(); WeatherModel weathermodel = null; foreach (Forecastday forecast in forecastdayList) { weathermodel = new WeatherModel(); weathermodel.weekday = forecast.date.weekday; weathermodel.high = forecast.high.fahrenheit; weathermodel.low = forecast.low.fahrenheit; weathermodel.conditions = forecast.conditions; weathermodel.icon_url = forecast.icon_url; weatherList.Add(weathermodel); } WeatherForecastModel weatherForeCastModel = new WeatherForecastModel(); weatherForeCastModel.weatherModel = weatherList; weatherForeCastModel.city.Name = city; weatherForeCastModel.city.State = state; return(weatherForeCastModel); }
public void Weather_PingReturnsForecastView() { Mock <IWeatherSqlDAL> mockWeather = new Mock <IWeatherSqlDAL>(); Mock <HttpContextBase> mockContext = new Mock <HttpContextBase>(); mockContext.SetupGet(m => m.Session["ParkCode"]).Returns("GND"); mockContext.SetupGet(m => m.Session["ShowFahrenheit"]).Returns(true); var fakePark = new ParkModel() { ParkCode = "GND", ParkName = "GinaNatalieDan" }; var fakeWeather = new WeatherForecastModel(); fakeWeather.Forecast.Add("fakecloudy"); fakeWeather.High.Add(78); fakeWeather.Low.Add(20); fakeWeather.Forecast.Add("fakesnow"); fakeWeather.High.Add(78); fakeWeather.Low.Add(20); fakeWeather.Forecast.Add("fakecloudy"); fakeWeather.High.Add(78); fakeWeather.Low.Add(20); fakeWeather.Forecast.Add("fakesnow"); fakeWeather.High.Add(78); fakeWeather.Low.Add(20); fakeWeather.Forecast.Add("fakesnow"); fakeWeather.High.Add(78); fakeWeather.Low.Add(20); mockWeather.Setup(m => m.GetForecast("GND")).Returns(fakeWeather); WeatherController controller = new WeatherController(mockWeather.Object); controller.ControllerContext = new ControllerContext(mockContext.Object, new System.Web.Routing.RouteData(), controller); var result = controller.Forecast("GND"); Assert.IsTrue(result is ViewResult); var viewResult = result as ViewResult; Assert.AreEqual("Forecast", viewResult.ViewName); }
private async Task <WeatherForecastModel> LoadWeatherForecast() { string url = GetURL(); WeatherForecastModel response = new WeatherForecastModel(); try { response = await APIProcessor <WeatherForecastModel> .APICall(url); } catch (Exception e) { response = await APIProcessor <WeatherForecastModel> .APICall(url); MessageBox.Show("Error while loading weather data. Server response: " + e.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error); } return(response); }
public async Task <WeatherForecastModel> Get() { WeatherForecastModel forecast = null; try { string strUri = _configuration.GetValue <string>("MetaAPI"); WeatherClient client = new WeatherClient(); forecast = await client.GetWeatherData(strUri); } catch (Exception e) { Console.Write("Exception loading Weather Server client", e); } return(forecast); }
private async Task GetData() { _weatherForecastDataList.Clear(); _weatherForecastData = await LoadWeatherForecast(); for (int i = 0; i < _weatherForecastData.list.Count; i++) { WeatherForecastDataModel tmp = new WeatherForecastDataModel(); tmp.Dt = _weatherForecastData.list[i].Dt; tmp.MainTemp = _weatherForecastData.list[i].main.Temp; tmp.MainTempMax = _weatherForecastData.list[i].main.Temp_max; tmp.MainTempMin = _weatherForecastData.list[i].main.Temp_min; tmp.WeatherDescription = _weatherForecastData.list[i].weather[0].Description.ToUpper(); tmp.WeatherIcon = _weatherForecastData.list[i].weather[0].Icon; _weatherForecastDataList.Add(tmp); } WeatherForecastDataReceivedEvent?.Invoke(this, true); }
public async System.Threading.Tasks.Task <IActionResult> IndexAsync([FromBody] WeatherForecastModel model) { if (!ModelState.IsValid) { return(BadRequest(model)); } Debug.WriteLine("Redirecting to success action"); model.Date = DateTime.Now; Db.Add(model); Db.SaveChanges(); await _hubContext.Clients.All.SendAsync("ReceiveUpdate", model.Date, model.TemperatureC, model.Humidity, model.Pressure, model.Summary); return(Ok(model)); }
public async Task <WeatherForecastModel> GetByCityAsync(string cityName) { var weatherForecastModel = new WeatherForecastModel(); using (var client = new HttpClient()) { client.BaseAddress = new Uri(_openWeatherMapConfig.Value.BaseEndpoint); var response = await client.GetAsync($"?q={cityName}&appid={_openWeatherMapConfig.Value.Token}&units={UNIT}"); if (response.IsSuccessStatusCode) { var jsonAsString = await response.Content.ReadAsStringAsync(); var jsonObject = JObject.Parse(jsonAsString)["main"]; weatherForecastModel = jsonObject.ToObject <WeatherForecastModel>(); } } return(weatherForecastModel); }
// GET: Weather public ActionResult Forecast(string parkCode) { WeatherForecastModel model = dal.GetForecast(parkCode); if (Session["ShowFahrenheit"] == null) { Session["ShowFahrenheit"] = true; } model.DisplayFahrenheit = (bool)Session["ShowFahrenheit"]; if ((bool)Session["ShowFahrenheit"] == false) { model.TemperatureConvert(model); } model.PackingList = model.GetPackList(model); return(View("Forecast", model)); }
public WeatherForecastViewModel LoadCurrent() { string jsonString = ""; string url = $"https://api.openweathermap.org/data/2.5/weather?q=budapest&appid={API_KEY}&units=metric"; using (var client = new HttpClient()) { var result = client.GetAsync(url).Result; if (result.IsSuccessStatusCode) { jsonString = result.Content.ReadAsStringAsync().Result; } var json = JObject.Parse(jsonString); CurrentWeather = new WeatherForecastModel( Convert.ToDouble(json.GetValue("main")["temp"]), Convert.ToDateTime(json["dt_txt"]) ); } return(this); }
public IActionResult Reset() { foreach (var forecast in Db.WeatherForecasts) { Db.Remove(forecast); } WeatherForecastModel newForecast1 = new WeatherForecastModel() { Date = DateTime.Now, Name = "Maarslet", Lat = 56.060059, Lon = 10.158049, TemperatureC = 20, Pressure = 20, Humidity = 20, Summary = WeatherForecastModel.SummaryEnum.Warm }; Db.Add(newForecast1); WeatherForecastModel newForecast2 = new WeatherForecastModel() { Date = DateTime.Now, Name = "Katrinebjerg", Lat = 56.172535, Lon = 10.191472, TemperatureC = 21, Pressure = 21, Humidity = 21, Summary = WeatherForecastModel.SummaryEnum.Warm }; Db.Add(newForecast2); Db.SaveChanges(); return(Ok()); }
public async Task <IActionResult> PostAsync( [FromBody] WeatherForecastModel model, CancellationToken cancellationToken) { using (_tracer.StartSpan("save")) { try { //These two lines are for example var traceHeaderHandler = new TraceHeaderPropagatingHandler(() => _tracer); var response = TraceOutgoing(traceHeaderHandler); await _storageLogic.SaveToFileAsync(model, cancellationToken); return(Ok()); } catch (Exception e) { _logger.LogError(e, "Service Error, attention!!!!"); return(StatusCode(StatusCodes.Status500InternalServerError, e.Message)); } } }
public async Task <IActionResult> AddTaskAsync([FromBody] WeatherForecastModel weatherForecastModel) { return(Created("", await _forecastRepository.AddTaskAsync(weatherForecastModel))); }
public void CreateWeatherForecastTo36Hour() { var result = WebRequestHelper.Request(_BaseUrl, "api/v1/rest/datastore/F-C0032-001") .Get(e => e.AddParameter("Authorization", _Authorization)) .Response <CWBResponseJsonModel <WeatherForecastTo36HourJsonModel> >(); //新增地區資料 CreateLocations(result.Records); //從資料庫取得地區資料 Dictionary <string, int> locations = _LocationRepositorie.GetList() .ToDictionary(e => e.Name, e => e.Id); //key = $"{item.LocationName}_{t.StartTime}_{t.EndTime}" var weatherForecasts = new Dictionary <string, WeatherForecastModel>(); //key = $"{key}_{weather.ElementName}" var weatherForecastDetails = new Dictionary <string, WeatherForecastDetailModel>(); foreach (var item in result.Records.Location) { foreach (var weather in item.WeatherElement) { foreach (var t in weather.Time) { //同一個地區 同時間只會有一筆 string key = $"{item.LocationName}_{t.StartTime}_{t.EndTime}"; int weatherId = 0; if (weatherForecasts.ContainsKey(key) == false) { DateTime?startTime = t.StartTime.TryToDateTime(); DateTime?entTime = t.EndTime.TryToDateTime(); if (startTime.HasValue == false || entTime.HasValue == false) { //時間轉型失敗處裡? throw new NotImplementedException(); } var weatherEntity = new WeatherForecastModel { LocationId = locations.GetValueOrDefault(item.LocationName), StartTime = startTime.Value, EndTime = entTime.Value, }; //新增 WeatherForecast 資料 var entity = _WeatherForecastRepository.GetByModel(weatherEntity); //資料不存在則新增 if (entity == null) { weatherForecasts.Add(key, weatherEntity); weatherId = _WeatherForecastRepository.CreateAndResultIdentity <int>(weatherEntity); weatherEntity.Id = weatherId; } else { weatherForecasts.Add(key, entity); weatherId = entity.Id; } } else { weatherId = weatherForecasts[key].Id; } var detailKey = $"{key}_{weather.ElementName}"; if (weatherForecastDetails.ContainsKey(detailKey) == false) { weatherForecastDetails.Add(detailKey, new WeatherForecastDetailModel { ElementType = weather.ElementName.TryToEnum <ElementTypeEnum>().GetValueOrDefault(), ParameterName = t.Parameter.ParameterName, ParameterUnit = t.Parameter.ParameterUnit, ParameterValue = t.Parameter.ParameterValue, WeatherForecastId = weatherId }); } else { //有已經存在的可能性? throw new NotImplementedException(); } } } } //新增 WeatherForecastDetail 資料 var details = weatherForecastDetails.Values.ToList(); _WeatherForecastDetailRepository.MergeInsert(details); }
public WeatherForecastModel Put([FromBody] WeatherForecastModel weatherForecast) { return(weatherForecast); }
/// <summary> /// Fetches forecast info by city name from related remote api /// </summary> /// <param name="cityId">City Id</param> /// <param name="latitude">City coordinates latitude value</param> /// <param name="longitude">City coordinates longitude value</param> /// <returns>ForecastModel</returns> internal static WeatherForecastModel FetchForecastInfo(int cityId, string latitude, string longitude) { WeatherForecastModel weatherForecast = null; var currrentTSHour = Convert.ToInt64((Math.Floor((decimal)(DateTime.Now.ToEpoch()) / 3600) * 3600)); if (!methodRequests.ContainsKey(currrentTSHour)) // eger guncel saat dict icinde yoksa ekleme ve onceki saatle islem yapma bolumu { methodRequests[currrentTSHour] = new ConcurrentDictionary <int, WeatherForecastModel>(); } if (methodRequests[currrentTSHour].ContainsKey(cityId)) { return(methodRequests[currrentTSHour].Where(r => r.Key == cityId).Select(r => r.Value).FirstOrDefault()); } Stopwatch sw = Stopwatch.StartNew(); try { using (var httpClient = new HttpClient()) { using (var response = httpClient.GetAsync(_ForecastWSURL.Replace("[LATITUDE]", latitude ?? "41.0096334").Replace("[LONGITUDE]", longitude ?? "28.9651646")).Result) { using (var content = response.Content) { //get the json result from location api var result = content.ReadAsStringAsync().Result; var forecastModel = Deserialize.FromJson(result); if (forecastModel != null) { var curDayForecast = forecastModel.Daily.Data.OrderBy(r => r.Time).FirstOrDefault(); var ts = curDayForecast.Time; var dailyMinTemperature = (int)Math.Round(curDayForecast.TemperatureMin, 0); var dailyMaxTemperature = (int)Math.Round(curDayForecast.TemperatureMax, 0); var weeklyMinTemperature = (int)Math.Round(forecastModel.Daily.Data.OrderBy(r => r.TemperatureMin).FirstOrDefault().TemperatureMin, 0); var weeklyMaxTemperature = (int)Math.Round(forecastModel.Daily.Data.OrderByDescending(r => r.TemperatureMax).FirstOrDefault().TemperatureMax, 0); sw.Stop(); weatherForecast = new WeatherForecastModel { CityId = cityId, TS = ts, DailyMinTemperature = dailyMinTemperature, DailyMaxTemperature = dailyMaxTemperature, WeeklyMinTemperature = weeklyMinTemperature, WeeklyMaxTemperature = weeklyMaxTemperature, ForecastQueryElapsedMilliseconds = sw.ElapsedMilliseconds, }; //max 50 records if (methodRequests.Count >= 50) { methodRequests[currrentTSHour] = new ConcurrentDictionary <int, WeatherForecastModel>(); } //if cityId does not exist if (!methodRequests[currrentTSHour].ContainsKey(cityId)) { methodRequests[currrentTSHour].TryAdd(cityId, weatherForecast); } //This is more simple to check if the record is available or not then if record not available save etc.. var res = DBlite.ExecuteSQL($"INSERT OR IGNORE INTO Forecast (CityId, DailyMinTemperature, DailyMaxTemperature, WeeklyMinTemperature, WeeklyMaxTemperature, TS, QueryElapsedMilliseconds) VALUES (@CityId, @DailyMinTemperature, @DailyMaxTemperature, @WeeklyMinTemperature, @WeeklyMaxTemperature, @TS, @QueryElapsedMilliseconds);", new ArrayList { new SQLiteParameter("@CityId", cityId), new SQLiteParameter("@DailyMinTemperature", dailyMinTemperature.Obj2String()), new SQLiteParameter("@DailyMaxTemperature", dailyMaxTemperature.Obj2String()), new SQLiteParameter("@WeeklyMinTemperature", weeklyMinTemperature.Obj2String()), new SQLiteParameter("@WeeklyMaxTemperature", weeklyMaxTemperature.Obj2String()), new SQLiteParameter("@TS", ts), new SQLiteParameter("@QueryElapsedMilliseconds", weatherForecast.ForecastQueryElapsedMilliseconds) }); if (res == -1) { Log.Error("Forecast table insert error"); } else { var dt = DBlite.GetData($"SELECT Forecast.Id, Forecast.CityId, Location.CityName, Forecast.DailyMinTemperature, Forecast.DailyMaxTemperature, Forecast.WeeklyMinTemperature, Forecast.WeeklyMaxTemperature, Forecast.TS, Forecast.QueryElapsedMilliseconds AS ForecastQueryElapsedMilliseconds, Location.QueryElapsedMilliseconds AS LocationQueryElapsedMilliseconds FROM Forecast INNER JOIN Location ON Location.Id = Forecast.CityId WHERE Forecast.CityId = @CityId AND Forecast.TS = @TS;", new ArrayList { new SQLiteParameter("@CityId", cityId), new SQLiteParameter("@TS", ts), }); if (dt != null && dt.Rows.Count > 0) { var dr = dt.Rows[0]; weatherForecast = new WeatherForecastModel { CityId = dr["CityId"].Obj2Int32(), TS = dr["TS"].Obj2Int64(), DailyMinTemperature = dr["DailyMinTemperature"].Obj2Int32(), DailyMaxTemperature = dr["DailyMaxTemperature"].Obj2Int32(), WeeklyMinTemperature = dr["WeeklyMinTemperature"].Obj2Int32(), WeeklyMaxTemperature = dr["WeeklyMaxTemperature"].Obj2Int32(), ForecastQueryElapsedMilliseconds = dr["ForecastQueryElapsedMilliseconds"].Obj2Int64(), LocationQueryElapsedMilliseconds = dr["LocationQueryElapsedMilliseconds"].Obj2Int64(), }; } } } } } } } catch (Exception ex) { Log.Error("ForecastService : " + ex.ToString()); } return(weatherForecast); }