public static string WriteFileInfo(string File, WeatherReading reading) { //Write Weather Values back to file string output = ""; // Start the child process. Process p = new Process(); string Arguments = ""; if (reading.AmbientTemperature != 99999) { Arguments = Arguments + " -\"AmbientTemperature=" + reading.AmbientTemperature + "\""; } if (reading.Humidity != 99999) { Arguments = Arguments + " -\"Humidity=" + reading.Humidity + "\""; } if (reading.Pressure != 99999) { Arguments = Arguments + " -\"Pressure=" + reading.Pressure + "\""; } // Redirect the output stream of the child process. p.StartInfo.UseShellExecute = false; p.StartInfo.RedirectStandardOutput = true; p.StartInfo.CreateNoWindow = true; p.StartInfo.Arguments = "\"" + File + "\"" + Arguments; p.StartInfo.FileName = "exiftool.exe"; p.Start(); output = File + Arguments + " --- " + p.StandardOutput.ReadToEnd(); p.WaitForExit(10000); return(output); }
public async Task <IActionResult> Put([FromODataUri] Guid key, WeatherReading update) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } if (key != update.Id) { return(BadRequest()); } _dbContext.Entry(update).State = EntityState.Modified; try { await _dbContext.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!WeatherReadingExists(key)) { return(NotFound()); } else { throw; } } return(Updated(update)); }
public async Task <HttpStatusCode> WeatherReading([FromBody] WeatherReading reading) { try { var dbPlace = _context.Place.Where(p => p.Name == reading.Place.Name).FirstOrDefault(); if (dbPlace == null) { await _context.Place.AddAsync(reading.Place); await _context.SaveChangesAsync(); dbPlace = await _context.Place.FirstOrDefaultAsync(w => w.Lat == reading.Place.Lat && w.Long == reading.Place.Long); } reading.Place = dbPlace; await _context.WeatherReading.AddAsync(reading); await _context.SaveChangesAsync(); await SendMessage(reading); return(HttpStatusCode.Accepted); } catch (Exception e) { return(HttpStatusCode.InternalServerError); } }
public async Task GetAllWeatherReadingsOnDateReturnsOnlyOne() { var reading = new WeatherReading { Date = DateTime.Now, TemperatureC = 10, Humidity = 100, AirPressure = 1000, Place = new Place { Lat = 58, Long = 10, Name = "Aarhus" } }; var reading2 = new WeatherReading { Date = DateTime.Now.AddDays(-2), TemperatureC = 10, Humidity = 100, AirPressure = 1000, Place = new Place { Lat = 58, Long = 10, Name = "Aarhus V" } }; DbContext.WeatherReading.Add(reading); DbContext.WeatherReading.Add(reading2); DbContext.SaveChanges(); var result = await uut.WeatherReadingByDate(DateTime.Now.Date); Assert.True(result.Count() == 1); }
public async Task <IActionResult> PostAsync([FromBody] WeatherReading reading) { _logger.LogDebug(reading.ToString()); await _service.SaveAsync(reading); return(Ok()); }
public ViewResult Index() { if (!IsWeatherActual) { UpdateWeather(); IsWeatherActual = true; } User user = (User)Session["User"]; IEnumerable <WeatherReading> WeatherReadings = weatherRepository.WeatherReadings.OrderByDescending(x => x.Date); List <WeatherViewModel> model = new List <WeatherViewModel>(); foreach (var city in user.Cities) { WeatherReading weather = WeatherReadings.FirstOrDefault(x => x.CityID == city.CityID); if (weather != null) { WeatherViewModel singleModel = new WeatherViewModel() { CityID = city.CityID, CityName = city.Name, Country = city.Country, Temperature = weather.Temperature, Humidity = weather.Humidity }; model.Add(singleModel); } } return(View(model)); }
public static void Initialize(IServiceProvider serviceProvider) { var randomTime = new Random(); var randomTemp = new Random(); using (var context = new ApiContext(serviceProvider.GetRequiredService <DbContextOptions <ApiContext> >())) { for (int i = 1; i < 6; i++) { var forecast = new WeatherForecast() { Id = Guid.NewGuid(), Date = DateTime.Now.AddSeconds(randomTime.Next(1, 5) * -1), Summary = "Record " + i.ToString() }; var reading = new WeatherReading() { Id = Guid.NewGuid(), Temperature = randomTemp.Next(-20, 55), TemperatureSystem = "C" }; forecast.Readings.Add(reading); context.WeatherForecasts.Add(forecast); context.WeatherReadings.Add(reading); } context.SaveChanges(); } }
} //Measures power of light and heat from sun public SVMWeather(WeatherReading wr) { PlantNumber = wr.PlantNumber; DateAndTime = wr.DateAndTime; AmbientTemp = wr.AmbientTemp; ModuleTemp = wr.ModuleTemp; Irradiation = wr.Irradiation; }
public static WeatherReading CreateWeatherReading(global::System.Guid ID, global::System.Guid forecastId, int temperature) { WeatherReading weatherReading = new WeatherReading(); weatherReading.Id = ID; weatherReading.ForecastId = forecastId; weatherReading.Temperature = temperature; return(weatherReading); }
static void CreateRecordWithRelatedEntities() { try { var random = new Random(); var weatherForecast = new WeatherForecast() { Id = Guid.NewGuid(), Date = DateTimeOffset.Now, Summary = "Human entered" }; var reading1 = new WeatherReading() { Id = Guid.NewGuid(), ForecastId = weatherForecast.Id, Temperature = random.Next(-20, 55), TemperatureSystem = "C" }; weatherForecast.Readings.Add(reading1); _odataContext.AddToWeatherForecasts(weatherForecast); _odataContext.AddRelatedObject(weatherForecast, nameof(WeatherForecast.Readings), reading1); _odataContext.SaveChanges(SaveChangesOptions.BatchWithSingleChangeset); WeatherForecast data = _odataContext.WeatherForecasts.Where(w => w.Id == weatherForecast.Id).FirstOrDefault(); if (data != null) { Console.WriteLine("Added 1 record."); Console.WriteLine($"ID = {data.Id}"); Console.WriteLine($"Date = {data.Date}"); Console.WriteLine($"Summary = {data.Summary}"); Console.WriteLine($"Readings Count = {data.Readings.Count}"); for (var i = 0; i < data.Readings.Count; i++) { var reading = data.Readings[i]; Console.WriteLine($"Reading #{i + 1} = {reading.Temperature} {reading.TemperatureSystem}"); } Console.WriteLine(""); } else { Console.WriteLine("No record was added."); } } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.ToString()); Console.WriteLine(ex.ToString()); } }
public WeatherViewModel(WeatherReading outdoorConditions, Temperature indoorTemperature) { int TIME_ZONE = -8; // Note: Adjust time zone value here DateTime = DateTimeOffset.FromUnixTimeSeconds(outdoorConditions.dt).LocalDateTime.AddHours(TIME_ZONE); WeatherCode = outdoorConditions.weather[0].id; OutdoorTemperature = (int)(outdoorConditions.main.temp - 273); IndoorTemperature = (int)indoorTemperature.Celsius; }
public WeatherViewModel(WeatherReading outdoorConditions, AtmosphericConditions indoorConditions) { int TIME_ZONE = -8; // Note: Adjust time zone value here DateTime = DateTimeOffset.FromUnixTimeSeconds(outdoorConditions.DateTime).LocalDateTime.AddHours(TIME_ZONE); WeatherCode = outdoorConditions.Weather[0].Id; OutdoorTemperature = (int)(outdoorConditions.WeatherValues.Temperature - 273); IndoorTemperature = (int)indoorConditions.Temperature; }
public async Task <IActionResult> PostFromRelatedEntity(WeatherReading WeatherReading) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } _dbContext.WeatherReadings.Add(WeatherReading); await _dbContext.SaveChangesAsync(); return(Created(WeatherReading)); }
public void DownloadCityWeather(City city) { DateTime start = DateTime.Now; string url = string.Format("http://api.openweathermap.org/data/2.5/weather?APPID=75a3e7d73376fa1ae08a542ca103899a&id={0}", city._Id); WebClient client = new WebClient(); string json = client.DownloadString(url); JsonViewModel jsonModel = new JavaScriptSerializer().Deserialize <JsonViewModel>(json); WeatherReading weather = new WeatherReading() { CityID = city.CityID, Temperature = jsonModel.Main.Temp, Humidity = jsonModel.Main.Humidity, Date = DateTime.Now }; weatherRepository.AddWeatherReading(weather); DateTime stop = DateTime.Now; TimeSpan timeSpan = start - stop; double seconds = timeSpan.TotalSeconds; }
public async Task GetAllWeatherReadingsOnDate() { var reading = new WeatherReading { Date = DateTime.Now, TemperatureC = 10, Humidity = 100, AirPressure = 1000, Place = new Place { Lat = 58, Long = 10, Name = "Aarhus" } }; DbContext.WeatherReading.Add(reading); DbContext.SaveChanges(); var result = await uut.WeatherReadingByDate(DateTime.Now.Date); Assert.IsInstanceOf <IEnumerable <WeatherReadingDto> >(result); }
private WeatherReading ProcessWeatherLine(string line) { WeatherReading weatherReading = default(WeatherReading); DateTime date = new DateTime(int.Parse(line.Substring(0, 4)), int.Parse(line.Substring(5, 2)), int.Parse(line.Substring(8, 2)), int.Parse(line.Substring(11, 2)), 0, 0); //Parsed Values float tempFloat; float?cTenthsTemp = Single.TryParse(line.Substring(13, 6), out tempFloat) && tempFloat > -9000 ? tempFloat : (float?)null; if (cTenthsTemp.HasValue) { weatherReading = new WeatherReading { ReadingTime = date, Temp = ((cTenthsTemp.Value / 10.0f) * 1.8f) + 32 }; } return(weatherReading); }
public void AddToWeatherReadings(WeatherReading weatherReading) { base.AddObject("WeatherReadings", weatherReading); }
public Task SaveAsync(WeatherReading reading) => _readings.InsertOneAsync(reading);
public async Task SendMessage(WeatherReading reading) { var dtoReading = new WeatherReadingDto(reading); var jcontent = Newtonsoft.Json.JsonConvert.SerializeObject(dtoReading); await _hub.Clients.All.SendAsync("newForecast", jcontent); }
static void Main(string[] args) { bool WriteToFile = false; string ActiveFilePath = Directory.GetCurrentDirectory(); List <WeatherReading> reading = new List <WeatherReading>(); //Check for Exiftool - if not found display error message. double ExiftoolVersion = CheckExiftool(); if (ExiftoolVersion != 0) { Console.WriteLine("Exiftool version " + ExiftoolVersion); } else { Console.WriteLine("Exiftool not found! WeatherTag needs exiftool in order to work properly."); Environment.Exit(0); } //Fetch jpg files in directory, if none found display error string[] ImageFiles = Directory.GetFiles(ActiveFilePath, "*.jpg"); if (ImageFiles.Count() == 0) { Console.WriteLine("No .jpg files found."); Environment.Exit(0); } string WeatherHistoryFile = Directory.GetCurrentDirectory() + "\\weatherhistory.csv"; //Check for -write flag, if found then matched weather values will be writen back to the jpg file EXIF metadata. for (int i = 0; i < args.Count(); i++) { if (args[i].ToString().ToLower().Trim() == "-write") { WriteToFile = true; } } if (WriteToFile == false) { Console.WriteLine("No changes to file(s) will be performed - To write weather tags use -write flag"); } //Console.WriteLine("Weather file: " + WeatherHistoryFile); //Load weather history file into stream try { using (var reader = new StreamReader(WeatherHistoryFile)) { while (!reader.EndOfStream) { var line = reader.ReadLine(); //Remove any measurement symbols line = line.Replace("°", ""); line = line.Replace("C", ""); line = line.Replace("hPa", ""); line = line.Replace("%", ""); var values = line.Split(','); Double ambientTemperature = 99999; Double humidity = 99999; Double pressure = 99999; DateTime Date1 = DateTime.Parse(values[0].ToString().Trim() + " " + values[1].ToString().Trim()); //Load Ambient Temperature value, if invalid mark as invalid = 99999 try { ambientTemperature = Double.Parse(values[2].ToString().Trim()); //Check for valid Ambient Temperature Range in Celsius if ((ambientTemperature < -100) || (ambientTemperature > 150)) { ambientTemperature = 99999; } } catch { ambientTemperature = 99999; } //Load Humidity value, if invalid mark as invalid = 99999 try { humidity = Double.Parse(values[3].ToString().Trim()); //Check for valid Humidity Range if ((humidity < 0) || (humidity > 100)) { humidity = 99999; } } catch { humidity = 99999; } try { pressure = Double.Parse(values[4].ToString().Trim()); //Check for valid Pressure Range if ((pressure < 800) || (pressure > 1100)) { pressure = 99999; } } catch { pressure = 99999; } reading.Add(new WeatherReading(Date1, ambientTemperature, humidity, pressure)); } } } catch { Console.WriteLine(WeatherHistoryFile + " not found or unable to open."); Environment.Exit(0); } //For each image file in the folder, add the closest reading from the weather history file. for (int q = 0; q < ImageFiles.Count(); q++) { DateTime PhotoDate; bool NoPhotoDate = false; //Get the image's Created Time, if not found or an error occurs set to error value of 1/1/2050 12:00 AM try { PhotoDate = GetFileDate(ImageFiles[q]); } catch { PhotoDate = DateTime.Parse("1/1/2050 12:00 AM"); NoPhotoDate = true; } Double MinDiffTime = 30; WeatherReading closestReading = new WeatherReading(DateTime.Parse("1/1/1900 12:00 AM"), 0, 0, 0); if (NoPhotoDate == false) { for (int i = 0; i < reading.Count; i++) { TimeSpan DiffTime = PhotoDate - reading[i].ReadingDate; if (Math.Abs(DiffTime.TotalMinutes) < MinDiffTime) { closestReading = reading[i]; MinDiffTime = Math.Abs(DiffTime.TotalMinutes); } } } Console.WriteLine("------ File " + (q + 1).ToString() + " of " + ImageFiles.Count() + " ------"); if (MinDiffTime < 30) { string ConsoleOutput = ""; if (closestReading.AmbientTemperature != 99999) { ConsoleOutput = ConsoleOutput + " " + closestReading.AmbientTemperature.ToString() + "°C "; } else { ConsoleOutput = ConsoleOutput + " -- °C "; } if (closestReading.Humidity != 99999) { ConsoleOutput = ConsoleOutput + " " + closestReading.Humidity.ToString() + " %"; } else { ConsoleOutput = ConsoleOutput + " -- % "; } if (closestReading.Pressure != 99999) { ConsoleOutput = ConsoleOutput + " " + closestReading.Pressure.ToString() + " hPa"; } else { ConsoleOutput = ConsoleOutput + " -- hPa "; } Console.WriteLine(ImageFiles[q].ToString().Replace(Directory.GetCurrentDirectory(), "").Trim() + " - " + ConsoleOutput); if (WriteToFile == true) { string WriteStatus = WriteFileInfo(ImageFiles[q], closestReading); Console.WriteLine(WriteStatus); } } else { if (NoPhotoDate == true) { Console.WriteLine(ImageFiles[q].ToString().Replace(Directory.GetCurrentDirectory(), "").Trim() + " - Photo file has no date and time."); } else { Console.WriteLine(ImageFiles[q].ToString().Replace(Directory.GetCurrentDirectory(), "").Trim() + " - No reading found."); } } } Console.WriteLine(); }
public bool GetHistory(DateTime date, IList <WeatherReading> weatherReadings, IList <WeatherSummary> summaryReadings) { string queryDate = string.Format("{0:yyyyMMdd}", date); string url = $"history_{queryDate}/q/{settings.Country}/{settings.City}.json"; bool success = true; var data = MakeRestRequest <WUGPayload>(url); if (data != null && data.history != null) { if (data.history.observations.Count > 0) { foreach (var obs in data.history.observations) { string fullDate = $"{obs.date.year}/{obs.date.mon}/{obs.date.mday} {obs.date.hour}:{obs.date.min}:00"; var parsedDate = DateTime.ParseExact(fullDate, "yyyy/MM/dd HH:mm:ss", CultureInfo.InvariantCulture); WeatherReading reading = new WeatherReading { timestamp = parsedDate, rainfall = obs.rain == "1" ? safeParseDouble(obs.precipm) : 0, snowfall = obs.snow == "1" ? safeParseDouble(obs.precipm) : 0, temperature = safeParseDouble(obs.tempm), humidity = safeParseDouble(obs.hum), windspeed = safeParseDouble(obs.wspdm), windDirection = obs.wdire, hail = (obs.hail == "1"), thunder = (obs.thunder == "1"), fog = (obs.fog == "1"), }; weatherReadings.Add(reading); } } if (data.history.dailysummary.Count > 0) { foreach (var summary in data.history.dailysummary) { string fullDate = $"{summary.date.year}/{summary.date.mon}/{summary.date.mday} 00:00:00"; var parsedDate = DateTime.ParseExact(fullDate, "yyyy/MM/dd HH:mm:ss", CultureInfo.InvariantCulture); WeatherSummary summaryReading = new WeatherSummary() { timestamp = parsedDate, rainfallMM = safeParseDouble(summary.precipm), snowfallMM = safeParseDouble(summary.snowfallm), maxTempC = safeParseDouble(summary.maxtempm), minTempC = safeParseDouble(summary.mintempm), maxRH = safeParseDouble(summary.maxhumidity), minRH = safeParseDouble(summary.minhumidity), maxWindSpeedKMH = safeParseDouble(summary.maxwspdm), minWindSpeedKMH = safeParseDouble(summary.minwspdm) }; summaryReadings.Add(summaryReading); } } } else { Utils.Log("No data returned from WUG API - possible API limit breach."); success = false; } return(success); }
private WeatherCollection Do(StationYearRequest stationYearRequest) { var stationYear = stationYearRequest.StationYear; string url = String.Format(@"http://www1.ncdc.noaa.gov/pub/data/noaa/isd-lite/{2}/{0:D6}-{1:D5}-{2:D4}.gz" , stationYear.StationIdentifier.UsafId , stationYear.StationIdentifier.WbanId , stationYear.Year); var request = (HttpWebRequest)WebRequest.Create(url); //request.Method = "HEAD"; if (stationYearRequest.LastRun != default(WeatherCollection)) { request.Headers.Add(HttpRequestHeader.CacheControl, "max-age=0"); if (!String.IsNullOrWhiteSpace(stationYearRequest.LastRun.ETag)) { request.Headers.Add(HttpRequestHeader.IfNoneMatch, stationYearRequest.LastRun.ETag); } request.IfModifiedSince = (stationYearRequest.LastRun.LastUpdated ?? stationYearRequest.LastRun.RunTime); } List <WeatherReading> list = new List <WeatherReading>(); var collection = new WeatherCollection { RunTime = DateTime.Now }; try { using (WebResponse webResponse = request.GetResponse()) using (Stream stream = webResponse.GetResponseStream()) if (stream != null) { using (var decompress = new GZipStream(stream, CompressionMode.Decompress)) using (var reader = new StreamReader(decompress)) //using (MemoryStream ms = new MemoryStream()) { string line; while ((line = reader.ReadLine()) != null) { WeatherReading weatherReading = ProcessWeatherLine(line); if (weatherReading != default(WeatherReading)) { list.Add(weatherReading); } } collection.ETag = webResponse.Headers["ETag"]; DateTime tempDateTime; if (DateTime.TryParse(webResponse.Headers["Last-Modified"], out tempDateTime)) { collection.LastUpdated = tempDateTime; } } } } catch (WebException e) { HttpStatusCode httpStatusCode = ((HttpWebResponse)e.Response).StatusCode; if (stationYearRequest.LastRun != default(WeatherCollection) && httpStatusCode == HttpStatusCode.NotModified) { collection = stationYearRequest.LastRun; collection.RunTime = DateTime.Now; return(collection); } WebExceptionStatus webExceptionStatus = e.Status; } // ReSharper disable EmptyGeneralCatchClause catch (Exception e) // ReSharper restore EmptyGeneralCatchClause { } WeatherReading[] weatherReadings = list.ToArray(); weatherReadings.EnusureSorted(); collection.WeatherReading = weatherReadings; return(collection); }
public void AddWeatherReading(WeatherReading weatherReading) { context.WeatherReadings.Add(weatherReading); context.SaveChanges(); }
/** * @param weatherReading */ public JSONWeatherReading(WeatherReading weatherReading) { this.weatherReading = weatherReading; }