private static List <WeatherDetail> GetWeatherInfo(OpenWeatherMap.RootObject root) { var weatherDetails = new List <WeatherDetail>(); foreach (var list in root.list) { var weatherDetail = new WeatherDetail(); var dateTime = DateTimeOffset.FromUnixTimeSeconds(list.dt); weatherDetail.date = dateTime.Date.ToString("dd MMM, yyyy"); weatherDetail.dayOfWeek = dateTime.DayOfWeek.ToString(); weatherDetail.humidity = $"{list.humidity} %"; weatherDetail.windSpeed = $"{list.speed} mps"; if (list.weather != null) { weatherDetail.icon = $"http://openweathermap.org/img/w/{list.weather[0].icon}.png"; weatherDetail.weather = list.weather[0].main; weatherDetail.description = list.weather[0].description; } if (list.temp != null) { weatherDetail.maxTemp = $"{list.temp.max.Floor()} °C"; weatherDetail.minTemp = $"{list.temp.min.Floor()} °C"; weatherDetail.temp = $"{list.temp.day.Floor()} °C"; } weatherDetails.Add(weatherDetail); } return(weatherDetails); }
public async Task <IActionResult> PutWeatherDetail(string id, WeatherDetail weatherDetail) { if (id != weatherDetail.City) { return(BadRequest()); } _context.Entry(weatherDetail).State = EntityState.Modified; try { await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!WeatherDetailExists(id)) { return(NotFound()); } else { throw; } } return(NoContent()); }
public ActionResult CreateWeather(Models.WeatherDetail weatherdetails) { if (ModelState.IsValid) { repo = new WeatherTodayRepo(); WeatherDetail entityWeather = new WeatherDetail(); entityWeather.CityID = weatherdetails.CityID; entityWeather.CityName = weatherdetails.CityName; entityWeather.CountryName = weatherdetails.CountryName; entityWeather.Temperature = weatherdetails.Temperature; entityWeather.Humidity = weatherdetails.Humidity; entityWeather.Visibility = weatherdetails.Visibility; bool status = repo.AddWeatherDetails(entityWeather); if (status) { ViewBag.Msg = "Weather details added successfully"; } else { ViewBag.Msg = "Something went wrong"; } } return(View(weatherdetails)); }
public ActionResult UpdateWeather(Models.WeatherDetail Wd) { if (ModelState.IsValid) { WeatherDetail entityWeather = new WeatherDetail(); entityWeather.CityID = Wd.CityID; entityWeather.CityName = Wd.CityName; entityWeather.CountryName = Wd.CountryName; entityWeather.Temperature = Wd.Temperature; entityWeather.Humidity = Wd.Humidity; entityWeather.Visibility = Wd.Visibility; repo = new WeatherTodayRepo(); bool status = repo.UpdateWeatherDetails(entityWeather); if (status) { Session["CityId"] = null; return(RedirectToAction("ViewAllCityWeatherList", "Weather")); } else { ViewBag.Msg = "Something went wrong"; } } return(View()); }
public JsonResult <WeatherDetail> getWeatherbyCityName(string theCityName) { string[] strarry = webService.getWeatherbyCityName(theCityName); WeatherDetail weatherDetail = new WeatherDetail() { Province = strarry[0].ToString(), City = strarry[1].ToString(), CityCode = Convert.ToInt32(strarry[2].ToString()), PictureName = strarry[3].ToString(), LastUpdateTime = Convert.ToDateTime(strarry[4]), Temperature = strarry[5].ToString(), Survey = strarry[6].ToString(), WindForce = strarry[7].ToString(), BeginPicture = strarry[8].ToString(), EndPicture = strarry[9].ToString(), CurrentWeather = strarry[10].ToString(), WheatherLift = strarry[11].ToString(), NextDayTemperature = strarry[12].ToString(), NextDaySurvey = strarry[13].ToString(), NextDayWindForce = strarry[14].ToString(), NextDayBeginPicture = strarry[15].ToString(), NextDayEndPicture = strarry[16].ToString(), ThirdTemperature = strarry[17].ToString(), ThirdSurvey = strarry[18].ToString(), ThirdWindForce = strarry[19].ToString(), ThirdBeginPicture = strarry[20].ToString(), ThirdDayEndPicture = strarry[21].ToString(), ProvinceAdnCityIntroduce = strarry[22].ToString(), }; return(Json <WeatherDetail>(weatherDetail)); }
//return type WeatherDetail //take a WeatherDetail data as input //save input data to server/database public WeatherDetail CreateWeatherDetail(WeatherDetail weatherDetail) { if (!ModelState.IsValid) { throw new HttpResponseException(HttpStatusCode.BadRequest); } _context.WeatherDetails.Add(weatherDetail); _context.SaveChanges(); return(weatherDetail); }
public void GetCurrentWeatherByCityIdAsync_WhenGivenCityId_ReturnCorrectResult() { Mock <IHttpClient> httpClientMock = TestHelper.GetHttpClientMock(); Mock <IConfig> configMock = TestHelper.GetConfigMock(); var currentWeatherService = new CurrentWeatherService(httpClientMock.Object, configMock.Object, TestHelper.GetMemoryCache()); WeatherDetail weatherDetail = currentWeatherService.GetCurrentWeatherByCityIdAsync(123).Result; Assert.NotNull(weatherDetail); }
public async Task <ActionResult> Delete(WeatherDetail b) { int bid = Convert.ToInt32(TempData["Id"]); using (var httpClient = new HttpClient()) { using (var response = await httpClient.DeleteAsync("http://localhost:17382/api/WeatherDetails/" + bid)) { string apiResponse = await response.Content.ReadAsStringAsync(); } } return(RedirectToAction("Index")); }
public ActionResult UpdateWeather(int CityId) { repo = new WeatherTodayRepo(); WeatherDetail entityWeather = repo.GetWeatherDetailsByCityID(CityId); Models.WeatherDetail modelWeather = new Models.WeatherDetail(); modelWeather.CityID = entityWeather.CityID; modelWeather.CityName = entityWeather.CityName; modelWeather.CountryName = entityWeather.CountryName; modelWeather.Temperature = entityWeather.Temperature; modelWeather.Humidity = entityWeather.Humidity; modelWeather.Visibility = entityWeather.Visibility; return(View(modelWeather)); }
public async Task <ActionResult> Create(WeatherDetail b) { using (var httpClient = new HttpClient()) { StringContent content = new StringContent(JsonConvert.SerializeObject(b), Encoding.UTF8, "application/json"); using (var response = await httpClient.PostAsync("http://localhost:17382/api/WeatherDetails/", content)) { string apiResponse = await response.Content.ReadAsStringAsync(); var obj = JsonConvert.DeserializeObject <WeatherDetail>(apiResponse); } } return(RedirectToAction("Index")); }
public async Task <ActionResult> Edit(WeatherDetail b) { int bid = Convert.ToInt32(TempData["Id"]); using (var httpClient = new HttpClient()) { StringContent content1 = new StringContent(JsonConvert.SerializeObject(b), Encoding.UTF8, "application/json"); using (var response = await httpClient.PutAsync("http://localhost:17382/api/WeatherDetails/" + bid, content1)) { string apiResponse = await response.Content.ReadAsStringAsync(); b = JsonConvert.DeserializeObject <WeatherDetail>(apiResponse); } } return(RedirectToAction("Index")); }
public async Task <ActionResult> Delete(int id) { TempData["Id"] = id; WeatherDetail b = new WeatherDetail(); using (var httpClient = new HttpClient()) { using (var response = await httpClient.GetAsync("http://localhost:17382/api/WeatherDetails/" + id)) { string apiResponse = await response.Content.ReadAsStringAsync(); b = JsonConvert.DeserializeObject <WeatherDetail>(apiResponse); } } return(View(b)); }
public bool AddWeatherDetails(WeatherDetail weatherDetail) { bool status = false; try { weatherDBEntities.WeatherDetails.Add(weatherDetail); weatherDBEntities.SaveChanges(); status = true; } catch (Exception) { status = false; } return(status); }
private Condition fromWeatherDetail(WeatherDetail wd) { DateTime datetime = UnixTimestampToDateTime(wd.dt); return(new Condition() { place = wd.name, weather = wd.weather[0].main, description = wd.weather[0].description, icon = wd.weather[0].icon, temp = wd.main.temp, minTemp = wd.main.temp_min, maxTemp = wd.main.temp_max, windSpeed = wd.wind.speed, clouds = wd.clouds.all, date = datetime }); }
public bool DeleteWeatherDetails(int CityID) { bool status = false; try { WeatherDetail entity = weatherDBEntities.WeatherDetails.Find(CityID); if (entity != null) { weatherDBEntities.WeatherDetails.Remove(entity); weatherDBEntities.SaveChanges(); status = true; } } catch { status = false; } return(status); }
public Condition GetCurrentWeatherDetail() { Condition weatherCondition = null; WeatherDetail wd = new WeatherDetail(); string url = API.API + "/weather?lat=" + API.Latitude + "&lon=" + API.Longitude + "&units=metric&APPID=" + API.Key; // Console.WriteLine(url); using (var client = new WebClient()) { try{ var json = client.DownloadString(url); wd = JsonConvert.DeserializeObject <WeatherDetail>(json); weatherCondition = fromWeatherDetail(wd); }catch { Console.WriteLine("failed to fetch weather data"); return(null); } } return(weatherCondition); }
public async Task <ActionResult <WeatherDetail> > PostWeatherDetail(WeatherDetail weatherDetail) { _context.WeatherDetails.Add(weatherDetail); try { await _context.SaveChangesAsync(); } catch (DbUpdateException) { if (WeatherDetailExists(weatherDetail.City)) { return(Conflict()); } else { throw; } } return(CreatedAtAction("GetWeatherDetail", new { id = weatherDetail.City }, weatherDetail)); }
public bool UpdateWeatherDetails(WeatherDetail weatherDetail) { bool status = false; try { WeatherDetail updatedWeatherDetail = weatherDBEntities.WeatherDetails.Find(weatherDetail.CityID); updatedWeatherDetail.CityID = weatherDetail.CityID; updatedWeatherDetail.CityName = weatherDetail.CityName; updatedWeatherDetail.CountryName = weatherDetail.CountryName; updatedWeatherDetail.Temperature = weatherDetail.Temperature; updatedWeatherDetail.Humidity = weatherDetail.Humidity; updatedWeatherDetail.Visibility = weatherDetail.Visibility; weatherDBEntities.SaveChanges(); status = true; } catch { status = false; } return(status); }
/// <summary> /// 获取城市天气详情信息 /// </summary> /// <param name="cityId">天气城市代号</param> /// <returns>城市天气详情信息</returns> public WeatherDetail GetWeatherDetail(string cityId) { string getUrl = string.Format("http://wthrcdn.etouch.cn/weather_mini?citykey={0}", cityId); JObject weatherResult = SimulateRequest.HttpGet <JObject>(getUrl); string statusStr = weatherResult["status"]?.ToString(); int.TryParse(statusStr, out int status); if (1000 == status) { string weatherStr = weatherResult["data"]?.ToString(); if (!string.IsNullOrWhiteSpace(weatherStr)) { WeatherDetail weatherDetail = JsonConvert.DeserializeObject <WeatherDetail>(weatherStr); if (weatherDetail != null) { if (!string.IsNullOrWhiteSpace(weatherDetail?.yesterday?.fl)) { weatherDetail.yesterday.fl = weatherDetail.yesterday.fl.Replace("<![CDATA[", "").Replace("]]", ""); } if (weatherDetail.forecast != null) { weatherDetail.forecast.ForEach(todaySky => { if (!string.IsNullOrWhiteSpace(todaySky?.fengli)) { todaySky.fengli = todaySky.fengli.Replace("<![CDATA[", "").Replace("]]", ""); } }); } } } } else { throw new WeatherException(status, weatherResult["desc"]?.ToString()); } return(null); }
public WeatherDetail GetWeatherDetailsByCityID(int CityID) { WeatherDetail wd = weatherDBEntities.WeatherDetails.Find(CityID); return(wd); }
public WeatherForecaster CrawlDataFromLink(string link) { link = string.IsNullOrEmpty(link) ? "https://forecast.weather.gov/MapClick.php?lat=37.7772&lon=-105.5168#.XrUr2mgzaHv" : link; //RecurringJob.AddOrUpdate(() => Console.WriteLine("Recurring!"), Cron.Minutely); var urlbase = "https://forecast.weather.gov/"; //Kiêm tra đường dẫn if (!link.Contains(urlbase)) { return(null); } var objReturn = new WeatherForecaster(); var htmlWeb = new HtmlWeb() { AutoDetectEncoding = false, }; try { var document = htmlWeb.Load(link); var weatherDetail = document.DocumentNode.Descendants("div").FirstOrDefault(node => node.Attributes.Contains("id") && node.Attributes["id"].Value == "current_conditions_detail").Descendants("tr").ToList(); //var weatherDetail1 = document.DocumentNode.SelectSingleNode("//div[@id=current_conditions_detail]"); foreach (var item in weatherDetail) { var td = item.ChildNodes.Where(x => x.Name == "td").ToList(); objReturn.WeatherDetail.Add(td[0].InnerText.ToString(), td[1].InnerText.ToString()); } //< !--Graphic and temperatures --> var temperatures = document.DocumentNode.Descendants("div").FirstOrDefault(node => node.Attributes.Contains("id") && node.Attributes["id"].Value == "current_conditions-summary").ChildNodes.ToList(); try { objReturn.Image = urlbase + temperatures.FirstOrDefault(node => node.Attributes.Contains("src")).Attributes["src"].Value; } catch (Exception) { } var current = document.DocumentNode.Descendants("div").FirstOrDefault(node => node.Attributes.Contains("id") && node.Attributes["id"].Value == "current-conditions").ChildNodes.ToList(); var curentpanel_heading = current.FirstOrDefault(node => node.Attributes.Contains("class") && node.Attributes["class"].Value == "panel-heading"); objReturn.Address = curentpanel_heading.Descendants("h2").FirstOrDefault().InnerText; objReturn.TemperatureF = temperatures.FirstOrDefault(node => node.Attributes.Contains("class") && node.Attributes["class"].Value == "myforecast-current-lrg").InnerText; objReturn.TemperatureC = temperatures.FirstOrDefault(node => node.Attributes.Contains("class") && node.Attributes["class"].Value == "myforecast-current-sm").InnerText; objReturn.ForecastCurrent = temperatures.FirstOrDefault(node => node.Attributes.Contains("class") && node.Attributes["class"].Value == "myforecast-current").InnerText; //weather var listForecaseShort = document.DocumentNode.Descendants("ul").FirstOrDefault(node => node.Attributes.Contains("id") && node.Attributes["id"].Value == "seven-day-forecast-list").ChildNodes.ToList(); foreach (var item in listForecaseShort) { var data = item.ChildNodes.FirstOrDefault(node => node.Attributes.Contains("class") && node.Attributes["class"].Value == "tombstone-container"); var obj = new WeatherDetail(); obj.Time = data.ChildNodes.FirstOrDefault(node => node.Attributes.Contains("class") && node.Attributes["class"].Value == "period-name").InnerText; obj.ShortDesc = data.ChildNodes.FirstOrDefault(node => node.Attributes.Contains("class") && node.Attributes["class"].Value == "short-desc").InnerText; obj.Temp = data.ChildNodes.FirstOrDefault(node => node.Attributes.Contains("class") && node.Attributes["class"].Value == "short-desc").NextSibling.InnerText; obj.Image = urlbase + data.ChildNodes.Descendants("img").FirstOrDefault(node => node.Attributes.Contains("src")).Attributes["src"].Value; obj.Description = data.ChildNodes.Descendants("img").FirstOrDefault(node => node.Attributes.Contains("alt")).Attributes["alt"].Value; objReturn.Weathers.Add(obj); } objReturn.Link = link; } catch (Exception) { return(null); } SaveHistoryCrawl(objReturn); return(objReturn); }
public void SetData(WeatherDetail detail) { itemLabel.Text = detail.DetailLabel.AppendColon(); valueLabel.Text = detail.DetailValue; }
private async Task <IResult> SaveData(string strLocationID, DateTime dtTime) { this._IResult.Success = false; var CheckData = await this._IWeatherMainRepository.GetQuery(dtTime, strLocationID); if (CheckData == null) { string strUrl = this._Configuration.GetSection("WeatherAPI").Value; var csCodeArea = this._ICodeAreaRepository.GetAll(); var csCodeLocation = this._ICodeLocationRepository.GetAll(); string strHiours = DateTime.Now.Hour >= 12 ? "12" : "06"; var Result = await this._IApiManagers.Get <Weather>(string.Format(strUrl, strLocationID, dtTime.ToString("yyyy-MM-dd"), strHiours)); if (Result != null) { WeatherMain csWeatherMain = new WeatherMain(); csWeatherMain.ApiId = strLocationID; var Locations = Result.records.locations; #region 資料整理 foreach (var item in Locations) { #region 未建立CODELocation表資料 if (!(await csCodeLocation).Any(x => x.Id == item.dataid)) { CodeLocation CodeLocation = new CodeLocation() { Id = item.dataid, Name = item.locationsName }; var LocationResult = await this._ICodeLocationRepository.Create(CodeLocation); if (!LocationResult.Success) { this._IResult.Success = false; this._IResult.Message = LocationResult.Message + LocationResult.Exception.Message + LocationResult.Exception.StackTrace; break; } } #endregion foreach (var Location in item.location) { #region 未建立CODEArea表資料 if (!(await csCodeArea).Any(x => x.Id == Location.geocode)) { CodeArea CodeArea = new CodeArea() { Id = Location.geocode, CodeLocation = item.dataid, Name = Location.locationName }; var AreaResult = await this._ICodeAreaRepository.Create(CodeArea); if (!AreaResult.Success) { this._IResult.Success = false; this._IResult.Message = AreaResult.Message + AreaResult.Exception.Message + AreaResult.Exception.StackTrace; break; } } #endregion csWeatherMain.LocationId = item.dataid; csWeatherMain.Date = dtTime; csWeatherMain.Ctime = DateTime.Now; WeatherDetail csWeatherDetail = new WeatherDetail(); foreach (var Weather in Location.weatherElement) { csWeatherDetail.AreaId = Location.geocode; var ElementName = (WEATHER)Enum.Parse(typeof(WEATHER), Weather.elementName, true); var ValueModel = Weather.time.FirstOrDefault(); #region 天氣各節點資料 switch (ElementName) { case WEATHER.PoP12h: csWeatherDetail.StartTime = "0600"; csWeatherDetail.EndTime = "1200"; if (ValueModel != null) { DateTime dtStartTime = Convert.ToDateTime(ValueModel.startTime); csWeatherDetail.RainRatio = Convert.ToDecimal(ValueModel.elementValue.FirstOrDefault().value); } else { csWeatherDetail.RainRatio = 0; } break; case WEATHER.Wx: if (ValueModel != null) { csWeatherDetail.States = ValueModel.elementValue.FirstOrDefault().value; } else { csWeatherDetail.States = "N/A"; } break; case WEATHER.AT: if (ValueModel != null) { csWeatherDetail.BodyTemperature = Convert.ToDecimal(ValueModel.elementValue.FirstOrDefault().value); } else { csWeatherDetail.BodyTemperature = 0; } break; case WEATHER.T: if (ValueModel != null) { csWeatherDetail.Temperature = Convert.ToDecimal(ValueModel.elementValue.FirstOrDefault().value); } else { csWeatherDetail.Temperature = 0; } break; case WEATHER.RH: if (ValueModel != null) { csWeatherDetail.Humidity = Convert.ToDecimal(ValueModel.elementValue.FirstOrDefault().value); } else { csWeatherDetail.Humidity = 0; } break; case WEATHER.CI: if (ValueModel != null) { csWeatherDetail.ComfortIndex = Convert.ToDecimal(ValueModel.elementValue[0].value); csWeatherDetail.Comfort = ValueModel.elementValue[1].value; } else { csWeatherDetail.ComfortIndex = 0; csWeatherDetail.Comfort = "N/A"; } break; case WEATHER.WeatherDescription: if (ValueModel != null) { csWeatherDetail.Detail = ValueModel.elementValue.FirstOrDefault().value; } else { csWeatherDetail.Detail = "N/A"; } break; case WEATHER.WS: if (ValueModel != null) { csWeatherDetail.WindSpeed = Convert.ToDecimal(ValueModel.elementValue.FirstOrDefault().value); } else { csWeatherDetail.WindSpeed = 0; } break; case WEATHER.WD: if (ValueModel != null) { csWeatherDetail.WindDirection = ValueModel.elementValue.FirstOrDefault().value; } else { csWeatherDetail.WindDirection = "N/A"; } break; case WEATHER.Td: if (ValueModel != null) { csWeatherDetail.DewPoint = Convert.ToDecimal(ValueModel.elementValue.FirstOrDefault().value); } else { csWeatherDetail.DewPoint = 0; } break; } #endregion } csWeatherMain.WeatherDetails.Add(csWeatherDetail); } } #endregion var DBResult = await this._IWeatherMainRepository.Create(csWeatherMain); this._IResult.Success = DBResult.Success; this._IResult.Exception = DBResult.Exception; this._IResult.Message = DBResult.Message; } } else { this._IResult.Success = false; this._IResult.Message = "已有該天資料"; } return(this._IResult); }
public ActionResult Create(HttpPostedFileBase postedFile) { string filePath = string.Empty; if (postedFile != null) { string path = Server.MapPath("~/Uploads/"); if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } filePath = path + Path.GetFileName(postedFile.FileName); string extension = Path.GetExtension(postedFile.FileName); postedFile.SaveAs(filePath); string[] Lines = { }; Lines = System.IO.File.ReadAllLines(filePath); int count = 0; int NumberOfWords = 0; TimeStamp = null; foreach (string Line in Lines) { count++; if (count > 1 && count < 9) { continue; } string CurrentLine = Line; CurrentLine = Regex.Replace(CurrentLine, " {2,}", " "); ValueOfWeatherData = CurrentLine.Split(' '); NumberOfWords = ValueOfWeatherData.Count() - 1; NumberOfWords--; if (count == 1) { Location = ValueOfWeatherData[NumberOfWords].ToString(); } else if (count >= 9) { WeatherDetail CurrentData = new WeatherDetail(); foreach (string word in ValueOfWeatherData) { if (!string.IsNullOrWhiteSpace(word)) { WeatherData.Add(word); } } for (int i = 0; i < WeatherData.Count(); i++) { CurrentData.LocationId = int.Parse(Location); CurrentData.RealDateTime = (WeatherData[0]); CurrentData.Pressure = float.Parse(WeatherData[1]); CurrentData.Salinity = float.Parse(WeatherData[3]); CurrentData.Turbidity = float.Parse(WeatherData[4]); CurrentData.Oxygen = float.Parse(WeatherData[5]); CurrentData.Fluorescence = float.Parse(WeatherData[6]); CurrentData.Fluorescence = (float)System.Math.Round(CurrentData.Fluorescence, 3); CurrentData.BatteryVoltage = float.Parse(WeatherData[7]); CurrentData.Temperature = float.Parse(WeatherData[2]); CurrentData.LocationName = "Rajshahi"; DateTime now = DateTime.Now; CurrentData.CreateDateTime = now; } // New(CurrentData); db.WeatherDetails.Add(CurrentData); db.SaveChanges(); WeatherData.Clear(); } } } return(View()); }