private void locationBtn_Click(object sender, EventArgs e) { try { locationName = locationBox.Text.Trim(); locationInfo = gMapsRef.locationReturn(locationName); //Get the city from location information for the weather cityFromGAPI = fc.FindCity(locationInfo.Address); //Get the country from location information for the weather countryFromGAPI = fc.FindCountry(locationInfo.Address); if (cityFromGAPI == "False Entry" || countryFromGAPI == "False Entry") { outputRich.Text = "Try a place, not a city or country!"; } else { weatherReport = oWeatherRef.WeatherReturn(cityFromGAPI, countryFromGAPI); outputRich.Text = "Address: " + locationInfo.Address + "\n" + "Location Name: " + locationInfo.Name + "\n" + "Rating: " + locationInfo.Rating + "\n\n" + "Weather Description: " + weatherReport.Description + "\n" + "High Of: " + weatherReport.TempMax + " degrees\n" + "Low Of: " + weatherReport.TempMin + " degrees\n"; } } catch (Exception ex) { Console.WriteLine(ex.Message); } }
public WeatherReport weatherReport() { var report = new WeatherReport { City = "Vancouver", details = new List <Detail>() { new Detail { Date = DateTime.Parse("2020-04-17"), MeanTemperature = 10 }, new Detail { Date = DateTime.Parse("2020-04-18"), MeanTemperature = 20 }, new Detail { Date = DateTime.Parse("2020-04-19"), MeanTemperature = 17 }, new Detail { Date = DateTime.Parse("2020-04-25"), MeanTemperature = 16 } } }; return(report); }
public async Task <IActionResult> PutWeatherReport(Guid id, WeatherReport weatherReport) { if (id != weatherReport.WeatherReportId) { return(BadRequest()); } _context.Entry(weatherReport).State = EntityState.Modified; try { await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!WeatherReportExists(id)) { return(NotFound()); } else { throw; } } return(NoContent()); }
public async Task <ActionResult <WeatherReport> > PostWeatherReport(WeatherReport weatherReport) { _context.Reports.Add(weatherReport); await _context.SaveChangesAsync(); return(CreatedAtAction("GetWeatherReport", new { id = weatherReport.WeatherReportId }, weatherReport)); }
public async Task <IActionResult> Post([FromBody] Contracts.WeatherReport weatherReport) { var stadium = await context.Stadiums.Where(s => s.Name == weatherReport.Stadium).FirstOrDefaultAsync(); if (stadium == null) { return(BadRequest($"No stadium could be found by name {weatherReport.Stadium}")); } var model = new WeatherReport() { CreatedDate = DateTimeOffset.Now, EmailAddress = weatherReport.EmailAddress, ReportTime = weatherReport.ReportTime.Value, Stadium = stadium, TemperatureDegreesFahrenheit = weatherReport.TemperatureDegreesFahrenheit.Value, WeatherDescription = weatherReport.WeatherDescription }; stadium.CurrentWeather = model; await context.SaveChangesAsync(); return(Ok()); }
public List <WeatherReport> GetWeatherForAllNodes(DateTime?time = null) { List <WeatherReport> reports = new List <WeatherReport>(); foreach (var matchingNode in _config.Nodes) { if (matchingNode == null) { return(null); } var fixedPointLat = matchingNode.Latitude; var fixedPointLon = matchingNode.Longitude; var lat = FixedPointCoordConversion.ToFloat(fixedPointLat); var lon = FixedPointCoordConversion.ToFloat(fixedPointLon); var request = time.HasValue ? new ForecastIORequest(_config.APIKey, lat, lon, time.Value, Unit.us) : new ForecastIORequest(_config.APIKey, lat, lon, Unit.us); var response = request.Get(); var report = new WeatherReport(); report.Hourly = response.hourly?.data?.Select(x => MapWeatherHourly(x, fixedPointLat, fixedPointLon)).ToList(); report.Daily = response.daily?.data?.Select(x => MapWeatherDaily(x, fixedPointLat, fixedPointLon)).ToList(); reports.Add(report); } return(reports); }
public async Task Send(WeatherReport data) { // simulate delay await Task.Delay(100); await Clients.All.SendAsync("Receive", data); }
public WeatherReport GetWeather(string city) { var weatherClient = new OpenWeatherMapClient(); var weatherObject = weatherClient.GetWeather(city); WeatherReport report = new WeatherReport(); Temperature tempatureInfo = new Temperature { Current = weatherObject.Result.main.temp, Low = weatherObject.Result.main.temp_min, High = weatherObject.Result.main.temp_max }; report.Temperatures = tempatureInfo; report.Pressure = weatherObject.Result.main.pressure; report.Humidity = weatherObject.Result.main.humidity; Winds wind = new Winds { Speed = weatherObject.Result.wind.speed, Direction = weatherObject.Result.wind.deg }; report.Winds = wind; report.Description = "Here is today's weather data for " + city + "!"; return(report); }
/// <summary> /// Gets all the data from a sensor type in the blob storage /// according to the date, device and sensor type that are /// entered as the parameters and packs the data in as a weather report. /// </summary> /// <param name="dateText"></param> /// <param name="deviceName"></param> /// <param name="sensorName"></param> /// <returns></returns> public WeatherReport GetWeatherReport(string dateText, string deviceName, string sensorName) { List <SensorType> data = GetDataFromFile(dateText, deviceName, sensorName); if (data == null) { return(null); } DateTime date = DateTime.Parse(dateText); var device = new Device { DeviceName = deviceName, Date = date }; List <SensorList> sensorTypes = new List <SensorList>(); SensorList sensorList = new SensorList(); sensorList.sensorName = sensorName; sensorList.sensorList = data; sensorTypes.Add(sensorList); WeatherReport report = new WeatherReport(); report.Device = device; report.SensorTypes = sensorTypes; return(report); }
//Removing stale data from city report private WeatherReport RemoveStaleWeatherData(WeatherReport existingCityDetails, WeatherReport model) { try { List <Detail> removedDetails = existingCityDetails.details.Where(x => !model.details.Any(y => y.Date == x.Date)).ToList(); for (int i = existingCityDetails.details.Count - 1; i > -1; i--) { Detail detail = existingCityDetails.details[i]; for (int j = 0; j <= removedDetails.Count() - 1; j++) { Detail removedDetail = removedDetails[j]; if (detail.Date == removedDetail.Date) { existingCityDetails.details.RemoveAt(i); } } } _sharedMemory.weatherReports.FirstOrDefault(x => x.City == model.City).details = existingCityDetails.details; return(_sharedMemory.weatherReports.FirstOrDefault(x => x.City == model.City)); } catch (Exception ex) { throw new Exception("Error removing stale data for existing city \n" + ex.Message); } }
//updating existing report for already present days private WeatherReport UpdateTemeperatureForExistingDay(WeatherReport existingCityDetails, WeatherReport model) { List <Detail> updatedTemperatureDetails; try { updatedTemperatureDetails = model.details.Where(x => existingCityDetails.details.Any(y => y.Date == x.Date && y.MeanTemperature != x.MeanTemperature)).ToList(); if (updatedTemperatureDetails != null) { for (int i = 0; i < updatedTemperatureDetails.Count; i++) { for (int j = 0; j < existingCityDetails.details.Count(); j++) { if (existingCityDetails.details[j].Date == updatedTemperatureDetails[i].Date) { existingCityDetails.details[j].MeanTemperature = updatedTemperatureDetails[i].MeanTemperature; } } } } _sharedMemory.weatherReports.FirstOrDefault(x => x.City == model.City).details = existingCityDetails.details; return(_sharedMemory.weatherReports.FirstOrDefault(x => x.City == model.City)); } catch (Exception ex) { throw new Exception("Error updating existing temperature for the day \n" + ex.Message); } }
//Save Weather Report public WeatherReport SaveWeatherReport(WeatherReport model) { if (model == null) { throw new ValidationException("request body can not be empty."); } List <DateTime> duplicateDates = model.details.Select(x => x.Date).Distinct().ToList(); if (duplicateDates.Count < model.details.Count) { throw new DuplicateReportForSameDay("Duplicate weather record for same day is found. Please check"); } try { var isExists = _sharedMemory.weatherReports.Any(x => x.City == model.City); if (!isExists) { AddNewCityReport(model); } else { UpdateExistingCityReport(model); } } catch (Exception ex) { throw new Exception("error updating existing city details \n" + ex.Message); } return(_sharedMemory.weatherReports.FirstOrDefault(x => x.City == model.City)); }
public async Task <List <WeatherReport> > PostAsync([FromBody] CityInput cityInput) { List <WeatherReport> weatherReportList = new List <WeatherReport>(); using (var handler = new HttpClientHandler()) using (var client = new HttpClient(handler)) { client.BaseAddress = new Uri("https://api.openweathermap.org/"); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add( new MediaTypeWithQualityHeaderValue("application/json")); foreach (var city in cityInput.Cities) { var response = await client.GetAsync("/data/2.5/weather?id=" + city.id + "&appid=aa69195559bd4f88d79f9aadeb77a8f6"); if (response.IsSuccessStatusCode) { WeatherReport weatherReport = new WeatherReport(); weatherReport = await response.Content.ReadAsAsync <WeatherReport>(); weatherReportList.Add(weatherReport); } } return(weatherReportList); } }
public WeatherInfo GetWeatherInfo(double lat, double lon) { WeatherReport weatherReport = new WeatherReport(); var client = new RestClient(uriString); var request = new RestRequest("/weather", Method.GET); request.RequestFormat = DataFormat.Json; request.AddParameter("lat", lat); request.AddParameter("lon", lon); IRestResponse <WeatherReport> response = client.Execute <WeatherReport>(request); weatherReport = response.Data; WeatherInfo weatherInfo = new WeatherInfo(); if (weatherReport != null) { weatherInfo.TemperatureDegF = weatherReport.KelvinToDegF(weatherReport.main.temp); weatherInfo.LastUpdate = weatherReport.LongToDateTime(weatherReport.dt); if (weatherReport.weather.Count > 0) { weatherInfo.Conditions = weatherReport.weather[0].description; weatherInfo.IconName = weatherReport.IconToIconName(weatherReport.weather [0].icon); weatherInfo.IconURL = weatherReport.IconToUrl(weatherReport.weather[0].icon); weatherInfo.LocationName = weatherReport.name; } } return(weatherInfo); }
public static WeatherReportDto ToWeatherReportDto(WeatherReport weatherReport) { var forecastConditions = weatherReport.Report.Forecast.Conditions.FirstOrDefault(); return(new WeatherReportDto { DateIssued = weatherReport.Report.Conditions.DateIssued, FlightRules = weatherReport.Report.Conditions.FlightRules, Pressure = weatherReport.Report.Conditions.PressureHg, Temperature = weatherReport.Report.Conditions.TempC, VisibilityDistance = weatherReport.Report.Conditions.Visibility.DistanceSm, WindDirection = weatherReport.Report.Conditions.Wind.Direction.ToString(), WindSpeed = weatherReport.Report.Conditions.Wind.SpeedKts.ToString(), Text = weatherReport.Report.Conditions.Text, TafReport = new WeatherForeCastReport { DateIssued = weatherReport.Report.Forecast.DateIssued, DateStart = weatherReport.Report.Forecast.Period.DateStart, DateEnd = weatherReport.Report.Forecast.Period.DateEnd, FlightRules = forecastConditions.FlightRules, VisibilityDistance = forecastConditions.Visibility.DistanceSm, WindDirection = forecastConditions.Wind.Direction.ToString(), WindSpeed = forecastConditions.Wind.SpeedKts.ToString(), Text = weatherReport.Report.Forecast.Text } }); }
public ActionResult <WeatherReport> SaveWeatherReport(WeatherReport model) { var authorizationHeader = Request.Headers["Authorization"]; var weatherReportService = new WeatherReportService(_sharedMemory, _config); //validating user access bool validUser = weatherReportService.ValidateUserToken(authorizationHeader); if (!validUser) { _logger.LogError("Unauthorized/Invalid user detected while accessing save report API."); return(Forbid()); } //saving weather rport if (model == null) { _logger.LogError("request body can not be empty."); throw new ValidationException("request body can not be empty."); } _logger.LogInformation("Calling weatherReportService to save weather report."); var weatherReport = weatherReportService.SaveWeatherReport(model); return(weatherReport); }
//Updating existing city report private void UpdateExistingCityReport(WeatherReport model) { var existingCityDetails = _sharedMemory.weatherReports.FirstOrDefault(x => x.City == model.City); existingCityDetails = UpdateTemeperatureForExistingDay(existingCityDetails, model); existingCityDetails = UpdateExistingCityReportWithNewDays(existingCityDetails, model); existingCityDetails = RemoveStaleWeatherData(existingCityDetails, model); }
public void TestGlobalWeather() { GlobalWeather gw = new GlobalWeather(); WeatherReport wr = gw.getWeatherReport("LEBL"); Assert.IsNotNull(wr.station); Assert.AreEqual("LEBL", wr.station.icao); Assert.AreEqual("Barcelona / Aeropuerto", wr.station.name); }
static void Main(string[] args) { /* * More info: https://en.wikipedia.org/wiki/Observer_pattern * What problems can the Observer design pattern solve? * * A one-to-many dependency between objects should be defined without making the objects tightly coupled. * It should be ensured that when one object changes state an open-ended number of dependent objects are updated automatically. * It should be possible that one object can notify an open-ended number of other objects. * * Defining a one-to-many dependency between objects by defining one object (subject) * that updates the state of dependent objects directly is inflexible because it commits (tightly couples) the subject to particular dependent objects. * * Tightly coupled objects are hard to implement, change, test, * and reuse because they refer to and know about (how to update) many different objects with different interfaces. */ #region Observer pattern // Configure Observer pattern ConcreteSubject subject = new ConcreteSubject(); subject.Attach(new ConcreteObserver(subject, "X")); subject.Attach(new ConcreteObserver(subject, "Y")); subject.Attach(new ConcreteObserver(subject, "Z")); // Change subject and notify observers subject.SubjectState = "ABC"; subject.Notify(); #endregion #region .Net implementation of observer pattern var publisherWeatherStation = new WeatherReport(); var subscriberGermanyWeatherStation = new GermanyWeatherStation(); var subscriberIranWeatherStation = new IranWeatherStation(); var subscriberUnitedStateWeatherStation = new UnitedStateWeatherStation(); publisherWeatherStation.WeatherChanged += subscriberGermanyWeatherStation.GermanyWeatherChanged; publisherWeatherStation.WeatherChanged += subscriberIranWeatherStation.IranWeatherChanged; publisherWeatherStation.WeatherChanged += subscriberUnitedStateWeatherStation.UnitedStateWeatherChanged; publisherWeatherStation.ReportWeather(new WeatherEventArgs(temperature: 30)); #endregion Console.ReadKey(); }
public void ThenICreateAReportWithMinAndMaxTemperatureFor(string cityName) { var file = new FileHelper(); var htmlPage = new WeatherReport(); string data = htmlPage.ConstructCurrentWeatherReportInHtml(minTemp, maxTemp, cityName); string fileName = file.GetWorkingDirectory() + @"\WeatherReportFiles\CurrentWeatherReport-" + cityName + ".html"; file.CreateAndWriteToFile(fileName, data); }
public void ThenICreateTheWeatherReportFor(string cityName) { var file = new FileHelper(); var htmlPage = new WeatherReport(); string data = htmlPage.ConstructWeatherReportInHtml(weatherObj, hottestDay); string fileName = file.GetWorkingDirectory() + @"\WeatherReportFiles\WeeklyWeatherReport-" + cityName + ".html"; file.CreateAndWriteToFile(fileName, data); }
public void Initalize() { var testHelper = new TestHelper(); _config = testHelper.Configuration; _sharedMemory = new SharedMemory(); _weatherReport = testHelper.weatherReport(); weatherReportService = new WeatherReportService(_sharedMemory, _config); SaveCityReportTest(); }
public IActionResult sortDays(WeatherReport weatherReport) { var listofDays = _context.DailyData .Where(d => d.temperatureMax > 30) .ToList(); ViewData["days"] = listofDays; return(View()); }
public void Should_GetMinTemperatureOf2_When_GetSmallestTemperatureSpreadIsRun() { // Arrange var report = new WeatherReport <IDailyTemperature>(MockedData.GetExpectedTemperatures()); // Act var min = report.GetSmallestTemperatureSpread(); // Assert Assert.AreEqual(2, min); }
public void Should_GetMaxTemperatureOf54_When_GetLargestTemperatureSpreadIsRun() { // Arrange var report = new WeatherReport <IDailyTemperature>(MockedData.GetExpectedTemperatures()); // Act var max = report.GetLargestTemperatureSpread(); // Assert Assert.AreEqual(54, max); // 86 vs. 32 degrees in weather.dat }
public IActionResult GetAllSensorTypesAsync(string date, string deviceName) { WeatherReport report = _weatherRepository.GetWeatherReport(date, deviceName); if (report == null) { return(NotFound("No records found...")); } return(Ok(report)); }
// todo: consider making a generic method that these all call. // given more time perhaps I could make these generic. On the other hand this // can make things a bit unreadable and over optimized. It will do for now. // meeting the requirement is my priority for now. private static List <string> GetWeatherDescriptions(WeatherReport src) { var result = new List <string>(); foreach (var weather in src.weather) { result.Add(weather.description); } return(result); }
/// <summary> /// Constructs a weather report object out of a ipma object /// that comes from IPMA's API, extracting only the relevant information. /// </summary> /// <param name="ipma">IPMA object from JSON deserialization of IPMA's API response</param> /// <param name="date">The weather forecast date of the report</param> /// <param name="locationcode">The location code of the city in the weather report</param> /// <returns>The WeatherReport object constructed from IPMA info</returns> private WeatherReport IPMAToWeatherReport(IPMA ipma, DateTime date, string locationcode) { WeatherReport wr = new WeatherReport(); wr.Location = locationCodes[locationcode]; wr.Date = date; wr.TempMax = ipma.tMax.ToString(); wr.TempMin = ipma.tMin.ToString(); wr.WeatherType = forecastDescPT[int.Parse(ipma.idTipoTempo)]; return(wr); }
/// <summary> /// Creates a map with forecast info and suggests whether to drink beer there or not. /// </summary> /// <param name="location">Location query string.</param> /// <param name="blobName">Blob name on Azure blob storage.</param> /// <returns>ImageFile object with blob name.</returns> private async Task <ImageFile> CreateMap(string location, string blobName) { SearchAddressResult result = _mapServices.SearchAddress(location); ImageFile imageFile = _mapServices.GetMapImage(result.Position.Lon, result.Position.Lat, _mapZoom, blobName); // Add the weather report to the map WeatherReport weatherReport = await _openWeatherService.GetWeatherReport(result.Position.Lat, result.Position.Lon); imageFile.Bytes = AddReportToMap(imageFile.Bytes, weatherReport); return(imageFile); }
public void TestLoadWeatherReport() { string xml = ReadFile(Path.Combine(testFilesLocation, "SampleReport.xml")); WeatherReport report = XmlLoader.ParseWeatherReport(xml, defaultZip); Assert.AreEqual(defaultZip, report.ZipCode); Assert.AreEqual("97.0", report.HighTemp); Assert.AreEqual("78.0", report.LowTemp); Assert.AreEqual("76.0", report.CurrentTemp); Assert.AreEqual("75.0", report.ApparentTemp); Assert.AreEqual("11.0", report.ChanceOfPrecipitation); Assert.AreEqual("Mostly Clear", report.CurrentConditions); }
public void SetWunderground(WundergroundData data) { if (data.forecast.simpleforecast.forecastday[0].high.celsius.IsNullOrWhiteSpace()) { return; } this.wunderground = data; this.weatherReport = new WeatherReport() { Temp = data.current_observation.temp_c, WindDir = data.current_observation.wind_dir, WindSpeed = data.current_observation.wind_kph, Icon = weatherIcons.Where(x=>x.Wunderground.Equals(data.current_observation.icon)).Select(y=>y.Css).FirstOrDefault(), Daily = new List<WeatherDayForecast>(), Hourly = new List<WeatherHourForecast>() }; for(int i = 0 ; i < 3; i++) { weatherReport.Daily.Add(new WeatherDayForecast() { RainChance = data.forecast.simpleforecast.forecastday[i].pop, Date = data.forecast.simpleforecast.forecastday[i].date, TempHigh = data.forecast.simpleforecast.forecastday[i].high.celsius, TempLow = data.forecast.simpleforecast.forecastday[i].low.celsius }); } foreach(HourlyForecast hf in data.hourly_forecast) { weatherReport.Hourly.Add(new WeatherHourForecast() { Hour = int.Parse(hf.FCTTIME.hour), RainFall = double.Parse(hf.qpf.metric), RainChance = int.Parse(hf.pop) }); } }
public UserNewsFeed(string friendsActivities, WeatherReport weatherReport) { this.FriendsActivities = friendsActivities; this.WeatherReport = weatherReport; }
public static WeatherReport WundergroundQuery() { using (var client = new HttpClient(new HttpClientHandler(), true)) { string apikey = "1859ccf0821879ad"; string backupapikey = "5defeac1eb748efd"; string pws = "IZUIDHOL158"; string query = string.Format("http://api.wunderground.com/api/{0}/conditions/forecast/hourly/q/pws:{1}.json", backupapikey, pws); var json = client.GetStringAsync(query).Result; var data = JsonConvert.DeserializeObject<WundergroundData>(json); weatherIcons.Add(new WeatherIcon { Css = "wi-day-sunny", Wunderground = "sunny" }); weatherIcons.Add(new WeatherIcon { Css = "wi-day-sunny", Wunderground = "clear" }); weatherIcons.Add(new WeatherIcon { Css = "wi-day-sunny", Wunderground = "mostlysunny" }); weatherIcons.Add(new WeatherIcon { Css = "wi-day-sunny", Wunderground = "partlysunny" }); weatherIcons.Add(new WeatherIcon { Css = "wi-cloudy", Wunderground = "cloudy" }); weatherIcons.Add(new WeatherIcon { Css = "wi-cloudy", Wunderground = "mostlycloudy" }); weatherIcons.Add(new WeatherIcon { Css = "wi-cloudy", Wunderground = "partlycloudy" }); weatherIcons.Add(new WeatherIcon { Css = "wi-rain", Wunderground = "rain" }); weatherIcons.Add(new WeatherIcon { Css = "wi-rain", Wunderground = "chancerain" }); weatherIcons.Add(new WeatherIcon { Css = "wi-sleet", Wunderground = "chancesleet" }); weatherIcons.Add(new WeatherIcon { Css = "wi-sleet", Wunderground = "sleet" }); weatherIcons.Add(new WeatherIcon { Css = "wi-thunderstorm", Wunderground = "chancetstorms" }); weatherIcons.Add(new WeatherIcon { Css = "wi-thunderstorm", Wunderground = "tstorms" }); weatherIcons.Add(new WeatherIcon { Css = "wi-snow", Wunderground = "chanceflurries" }); weatherIcons.Add(new WeatherIcon { Css = "wi-snow", Wunderground = "chancesnow" }); weatherIcons.Add(new WeatherIcon { Css = "wi-snow", Wunderground = "flurries" }); weatherIcons.Add(new WeatherIcon { Css = "wi-snow", Wunderground = "snow" }); weatherIcons.Add(new WeatherIcon { Css = "wi-fog", Wunderground = "fog" }); weatherIcons.Add(new WeatherIcon { Css = "wi-fog", Wunderground = "hazy" }); var weatherReport = new WeatherReport() { Temp = data.current_observation.temp_c, WindDir = data.current_observation.wind_dir, WindSpeed = data.current_observation.wind_kph, Icon = weatherIcons.Where(x => x.Wunderground.Equals(data.current_observation.icon)).Select(y => y.Css).FirstOrDefault(), Daily = new List<WeatherDayForecast>(), Hourly = new List<WeatherHourForecast>() }; for (int i = 0; i < 3; i++) { weatherReport.Daily.Add(new WeatherDayForecast() { RainChance = data.forecast.simpleforecast.forecastday[i].pop, Date = data.forecast.simpleforecast.forecastday[i].date, TempHigh = data.forecast.simpleforecast.forecastday[i].high.celsius, TempLow = data.forecast.simpleforecast.forecastday[i].low.celsius }); } foreach (HourlyForecast hf in data.hourly_forecast) { weatherReport.Hourly.Add(new WeatherHourForecast() { Hour = int.Parse(hf.FCTTIME.hour), RainFall = double.Parse(hf.qpf.metric), RainChance = int.Parse(hf.pop) }); } return weatherReport; } }