Esempio n. 1
0
        public ActionResult GeoLocation(double?latitude, double?longitude)
        {
            if (string.IsNullOrWhiteSpace(Settings.Default.ApiKey))
            {
#if DEBUG
                return(Json(WeatherSummaryViewModel.GetFailed("[Debug Build] Error details: 'ApiKey' setting is not configured. Please specify API Key in Web.config.")));
#else
                return(Json(WeatherSummaryViewModel.GetFailed()));
#endif
            }

            if (!latitude.HasValue || !longitude.HasValue)
            {
                return(Json(WeatherSummaryViewModel.GetFailed()));
            }

            try
            {
                using (ForecastClient client = new ForecastClient())
                {
                    string         url            = BuildUrl(Settings.Default.BaseUrl, Settings.Default.ApiKey, latitude.Value, longitude.Value);
                    WeatherSummary weatherSummary = client.Load(url);
                    return(Json(new WeatherSummaryViewModel(weatherSummary, HttpContext, new IconRepository())));
                }
            }
            catch (Exception ex)
            {
#if DEBUG
                return(Json(WeatherSummaryViewModel.GetFailed("[Debug Build] Error details: " + ex.Message)));
#else
                return(Json(WeatherSummaryViewModel.GetFailed()));
#endif
            }
        }
Esempio n. 2
0
        public void saveWeatherSummary(DailyData dailyData)
        {
            WeatherSummary weatherSummary = new WeatherSummary();
            int            humidityAvg    = 0;
            int            humidityHigh   = 0;
            int            humidityLow    = 0;
            int            cont           = 0;
            DateTime       date           = DateTime.MinValue;

            foreach (Observation item in dailyData.observations)
            {
                humidityAvg  = humidityAvg + item.humidityHigh;
                humidityHigh = humidityHigh + item.humidityHigh;
                humidityLow  = humidityLow + item.humidityLow;
                date         = item.obsTimeUtc;
                cont++;
            }
            weatherSummary.humidityAvg  = humidityAvg / cont;
            weatherSummary.humidityHigh = humidityHigh / cont;
            weatherSummary.humidityLow  = humidityLow / cont;
            weatherSummary.obsTimeUtc   = date;
            dbase.WeatherSummaries.Add(weatherSummary);
            Response res = new Response();

            res = DbHelper.Save(dbase);
        }
Esempio n. 3
0
 public WeatherSummaryViewModel UpdateWeather(WeatherSummary weatherSummary)
 {
     OpenWeatherIcon = OpenWeatherConfiguration.GetIconURL(weatherSummary.OpenWeatherIcon);
     Temperature     = GetShortTemperature(weatherSummary.Temperature);
     Time            = ToTimeAtLocation(weatherSummary);
     return(this);
 }
Esempio n. 4
0
        public object Convert(object value, Type targetType, object parameter, string language)
        {
            WeatherSummary summary   = (WeatherSummary)value;
            int            id        = summary.Id;
            TimeOfDay      timeOfDay = summary.Icon.Contains("d") ? TimeOfDay.Day : TimeOfDay.Night;

            string filename = null;

            if (id >= 200 && id <= 232)
            {
                filename = "thunderstorm.png";
            }
            else if (id >= 300 && id <= 321)
            {
                filename = "drizzle.png";
            }
            else if (id == 500 || id == 520 || id == 531)
            {
                filename = "drizzle.png";
            }
            else if (id == 501 || id == 521 || id == 522)
            {
                filename = "rain.png";
            }
            else if (id >= 502 && id <= 504)
            {
                filename = "extreme.png";
            }
            else if (id == 511)
            {
                filename = "cold.png";
            }
            else if (id >= 600)
            {
                filename = "snow.png";
            }
            else if (id >= 700)
            {
                filename = "atmosphere.png";
            }
            else if (id == 801)
            {
                filename = $"{AppendTimeOfDay("few_clouds", timeOfDay)}.png";
            }
            else if (id == 802 || id == 803)
            {
                filename = $"{AppendTimeOfDay("broken_clounds", timeOfDay)}.png";
            }
            else if (id == 804)
            {
                filename = $"overcast_clouds.png";
            }
            else
            {
                filename = null;
            }
            return($"Assets/WeatherIcons/{filename}");
        }
Esempio n. 5
0
 public WeatherSummaryViewModel(WeatherSummary weatherSummary, int ordering)
 {
     Name            = weatherSummary.Location;
     Temperature     = GetShortTemperature(weatherSummary.Temperature);
     OpenWeatherIcon = OpenWeatherConfiguration.GetIconURL(weatherSummary.OpenWeatherIcon);
     Id       = weatherSummary.Id;
     Ordering = ordering;
     Time     = ToTimeAtLocation(weatherSummary);
 }
Esempio n. 6
0
        public void ForecastJsonReaderTest()
        {
            WeatherSummary weatherSummary = _jsonData.ReadForecastJson();

            Assert.AreEqual(weatherSummary.Timezone, "Australia/Melbourne");
            Assert.AreEqual(weatherSummary.Temperature, ForecastJsonReader.CelsiusToFahrenheit(75.81));
            Assert.AreEqual(weatherSummary.ApparentTemperature, ForecastJsonReader.CelsiusToFahrenheit(75.81));
            Assert.AreEqual(weatherSummary.Summary, "Clear");
            Assert.AreEqual(weatherSummary.Icon, "clear-day");
        }
        public async Task <IEnumerable <WeatherSummary> > GetWeatherSummaryFor(long[] ids)
        {
            if (ids == null || ids.Length == 0)
            {
                throw new ArgumentException("Specify at least one location id", nameof(ids));
            }

            if (ids.Length == 1)
            {
                return(new [] { await GetWeatherSummaryFor(ids[0]) });
            }

            var results = new ConcurrentBag <WeatherSummary>();
            await ids.ParallelForEachAsync(async id =>
            {
                var weatherSummary = await GetWeatherSummaryFor(id);
                results.Add(weatherSummary);
            }, 0);

            return(results);

            async Task <WeatherSummary> GetWeatherSummaryFor(long id)
            {
                if (id <= 0)
                {
                    throw new ArgumentException("Specify a valid location id.", nameof(id));
                }

                return(await GetOrSet(id,
                                      GetWeatherSummary,
                                      new MemoryCacheEntryOptions { AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(10) }));

                async Task <WeatherSummary> GetWeatherSummary()
                {
                    var url = string.Format(openWeatherConfiguration.OpenWeatherURL, id);
                    var openWeatherForecast = await httpClient.GetAsync <Forecast>(url);

                    var weather        = openWeatherForecast.Weather.First();
                    var weatherSummary = new WeatherSummary(openWeatherForecast.Name,
                                                            Math.Round(openWeatherForecast.Main.Temp, 1),
                                                            weather.Icon,
                                                            openWeatherForecast.Id,
                                                            DateTimeOffset.FromUnixTimeSeconds(openWeatherForecast.Dt).UtcDateTime,
                                                            openWeatherForecast.Timezone,
                                                            openWeatherForecast.Clouds.All);

                    return(weatherSummary);
                }
            }
        }
Esempio n. 8
0
        public void DisplayWeatherSummary(WeatherSummary weatherSummary)
        {
            var inputFilePathParts  = _inputFilePath.Split('/');
            var outputFilePathParts = inputFilePathParts.Take(inputFilePathParts.Length - 1);
            var outputFilePath      = String.Join('/', outputFilePathParts) + "/WeatherOutput.txt";

            using (File.Create(outputFilePath)) { };
            File.AppendAllLines(outputFilePath, new string[]
            {
                "Weather Summary:\n",
                $"Temperature: {weatherSummary.Temperature}",
                $"Wind speed: {weatherSummary.WindSpeed}",
                $"Chance of rain: {weatherSummary.ChanceOfRain}"
            });
        }
Esempio n. 9
0
        public static Task <IEnumerable <WeatherForecastDTO> > Handle()
        {
            Random         randomTemperature    = new Random();
            Array          values               = Enum.GetValues(typeof(WeatherSummary));
            WeatherSummary randomWeatherSummary = (WeatherSummary)values.GetValue(randomTemperature.Next(values.Length));

            IEnumerable <WeatherForecastDTO> weatherForecasts = Enumerable.Range(1, 5).Select(index => new WeatherForecastDTO
            {
                Date = DateTime.Now.AddDays(index),
                TemperatureInCelcius = randomTemperature.Next(-20, 55),
                Summary = randomWeatherSummary.ToString()
            });

            return(Task.FromResult(weatherForecasts));
        }
Esempio n. 10
0
        private async Task deleteWeatherData(WeatherSummary weatherSummary)
        {
            foreach (var source in weatherSummary.Sources)
            {
                _sourceRepository.Delete(source);
            }

            foreach (var consolidatedWeatherObject in weatherSummary.ConsolidatedWeather)
            {
                _weatherRepository.Delete(consolidatedWeatherObject);
            }

            _locationRepository.Delete(weatherSummary.Parent);
            _weatherSummaryRepository.Delete(weatherSummary);

            await _weatherSummaryRepository.Save();
        }
Esempio n. 11
0
 public static WeatherSummary ReadForecastJson(this string json)
 {
     using (new StringReader(json))
     {
         WeatherSummary weather;
         using (new JsonTextReader(new StringReader(json)))
         {
             JObject jObject = JObject.Parse(json);
             weather = new WeatherSummary
             {
                 Timezone            = jObject.SelectToken("$.['timezone']").ToString(),
                 Summary             = jObject.SelectToken("$.currently['summary']").ToString(),
                 Icon                = jObject.SelectToken("$.currently['icon']").ToString(),
                 Temperature         = CelsiusToFahrenheit(double.Parse(jObject.SelectToken("$.currently['temperature']").ToString())),
                 ApparentTemperature = CelsiusToFahrenheit(double.Parse(jObject.SelectToken("$.currently['apparentTemperature']").ToString()))
             };
         }
         return(weather);
     }
 }
Esempio n. 12
0
        public void ThenTheSummersisedHourlyWeatherForcastIsDisplayedForEachDayRoundedDownToTheNearestValue(Table table)
        {
            foreach (var row in table.Rows)
            {
                var summary = new WeatherSummary();
                var home    = new WeatherForecastHomePage();

                string output;

                row.TryGetValue("Forecast Days", out output);

                if (output == "Tuesday")
                {
                    PageFactory.InitElements(driver, home);
                    var getDay = home.getTuesdaySummary;
                    getDay.Click();
                    Thread.Sleep(2000);

                    row.TryGetValue("Weather Condition", out output);
                    if (output == "Yes")
                    {
                        PageFactory.InitElements(driver, summary);
                        var Condition = summary.getDayMaxTemp.Text;

                        Assert.IsNotNull(Condition);
                        Console.WriteLine(Condition);
                        Assert.IsTrue(Condition.Length < 4);
                        Assert.IsFalse(Condition.Contains("."));
                    }

                    row.TryGetValue("Wind Speed and Direction", out output);
                    if (output == "Yes")
                    {
                        PageFactory.InitElements(driver, summary);
                        var WindDirection = summary.getSpeedWind.Text;

                        Console.WriteLine(WindDirection);

                        Assert.IsNotNull(WindDirection);


                        Assert.IsFalse(WindDirection.Contains("."));
                    }

                    row.TryGetValue("Aggregate Rainfall", out output);
                    if (output == "Yes")
                    {
                        PageFactory.InitElements(driver, summary);
                        var RainFall = summary.getAggregateRainFall.Text;
                        Console.WriteLine(RainFall);
                        Assert.IsNotNull(RainFall);
                        Assert.IsTrue(RainFall.Length < 4);
                        Assert.IsFalse(RainFall.Contains("."));
                    }
                }
                if (output == "Wednesday")
                {
                    PageFactory.InitElements(driver, home);
                    var getDay = home.getWednesdaySummary;
                    getDay.Click();
                    Thread.Sleep(2000);
                    row.TryGetValue("Weather Condition", out output);
                    if (output == "Yes")
                    {
                        PageFactory.InitElements(driver, summary);
                        var Condition = summary.getWedDayMaxTemp.Text;

                        Assert.IsNotNull(Condition);
                        Assert.IsFalse(Condition.Contains("."));
                    }

                    row.TryGetValue("Wind Speed and Direction", out output);
                    if (output == "Yes")
                    {
                        PageFactory.InitElements(driver, summary);
                        var WindDirection = summary.getWedSpeedWind.Text;

                        Console.WriteLine(WindDirection);
                        Assert.IsNotNull(WindDirection);
                        Assert.IsFalse(WindDirection.Contains("."));
                    }

                    row.TryGetValue("Aggregate Rainfall", out output);
                    if (output == "Yes")
                    {
                        PageFactory.InitElements(driver, summary);
                        var RainFall = summary.getWedAggregateRainFall.Text;
                        Console.WriteLine(RainFall);
                        Assert.IsNotNull(RainFall);

                        Assert.IsFalse(RainFall.Contains("."));
                    }
                }

                if (output == "Thursday")
                {
                    PageFactory.InitElements(driver, home);
                    var getDay = home.getThursdaySummary;
                    getDay.Click();
                    Thread.Sleep(2000);
                    row.TryGetValue("Weather Condition", out output);
                    if (output == "Yes")
                    {
                        PageFactory.InitElements(driver, summary);
                        var Condition = summary.getThursDayMaxTemp.Text;

                        Assert.IsNotNull(Condition);

                        Assert.IsFalse(Condition.Contains("."));
                    }
                    row.TryGetValue("Wind Speed and Direction", out output);
                    if (output == "Yes")
                    {
                        PageFactory.InitElements(driver, summary);
                        var WindDirection = summary.getThursSpeedWind.Text;

                        Console.WriteLine(WindDirection);

                        Assert.IsNotNull(WindDirection);

                        Assert.IsFalse(WindDirection.Contains("."));
                    }

                    row.TryGetValue("Aggregate Rainfall", out output);
                    if (output == "Yes")
                    {
                        PageFactory.InitElements(driver, summary);
                        var RainFall = summary.getThursAggregateRainFall.Text;
                        Console.WriteLine(RainFall);
                        Assert.IsNotNull(RainFall);

                        Assert.IsFalse(RainFall.Contains("."));
                    }
                }

                if (output == "Friday")
                {
                    PageFactory.InitElements(driver, home);
                    var getDay = home.getFridaySummary;
                    getDay.Click();
                    Thread.Sleep(2000);

                    row.TryGetValue("Weather Condition", out output);
                    if (output == "Yes")
                    {
                        PageFactory.InitElements(driver, summary);
                        var Condition = summary.getFridayDayMaxTemp.Text;

                        Console.WriteLine(Condition);

                        Assert.IsNotNull(Condition);

                        Assert.IsFalse(Condition.Contains("."));
                    }

                    row.TryGetValue("Wind Speed and Direction", out output);
                    if (output == "Yes")
                    {
                        PageFactory.InitElements(driver, summary);
                        var WindDirection = summary.getFriSpeedWind.Text;

                        Console.WriteLine(WindDirection);

                        Assert.IsNotNull(WindDirection);

                        Assert.IsFalse(WindDirection.Contains("."));
                    }

                    row.TryGetValue("Aggregate Rainfall", out output);
                    if (output == "Yes")
                    {
                        PageFactory.InitElements(driver, summary);
                        var RainFall = summary.getFriAggregateRainFall.Text;
                        Console.WriteLine(RainFall);
                        Assert.IsNotNull(RainFall);

                        Assert.IsFalse(RainFall.Contains("."));
                    }
                }

                if (output == "Saturday")
                {
                    PageFactory.InitElements(driver, home);
                    var getDay = home.getSaturdaySummary;
                    getDay.Click();
                    Thread.Sleep(2000);

                    row.TryGetValue("Weather Condition", out output);
                    if (output == "Yes")
                    {
                        PageFactory.InitElements(driver, summary);
                        var Condition = summary.getSatDayMaxTemp.Text;
                        Assert.IsNotNull(Condition);
                        Console.WriteLine(Condition);

                        Assert.IsFalse(Condition.Contains("."));
                    }

                    row.TryGetValue("Wind Speed and Direction", out output);
                    if (output == "Yes")
                    {
                        PageFactory.InitElements(driver, summary);
                        var WindDirection = summary.getSatSpeedWind.Text;

                        Console.WriteLine(WindDirection);

                        Assert.IsNotNull(WindDirection);

                        Assert.IsFalse(WindDirection.Contains("."));
                    }

                    row.TryGetValue("Aggregate Rainfall", out output);
                    if (output == "Yes")
                    {
                        PageFactory.InitElements(driver, summary);
                        var RainFall = summary.getSatAggregateRainFall.Text;
                        Console.WriteLine(RainFall);
                        Assert.IsNotNull(RainFall);

                        Assert.IsFalse(RainFall.Contains("."));
                    }
                }
            }
        }
Esempio n. 13
0
 public IViewComponentResult Invoke(WeatherSummary weatherSummary)
 {
     return(View(weatherSummary));
 }
        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);
        }
Esempio n. 15
0
        public IActionResult Index(double longitude, double latitude)
        {
            IpStackClient ipClient = new IpStackClient(_config["Keys:IPStack"]);

            string ipAddress = AppCode.Projects.Weather.GetRequestIP(_httpContextAccessor);

            IpStack.Models.IpAddressDetails location = ipClient.GetIpAddressDetails(ipAddress);

            GeoCoordinate coordinate = new GeoCoordinate();

            // If location is provided then use over IP address
            if (longitude == 0 && latitude == 0)
            {
                coordinate.Longitude = location.Longitude;
                coordinate.Latitude  = location.Latitude;
            }
            else
            {
                coordinate.Longitude = longitude;
                coordinate.Latitude  = latitude;
            }

            MetOfficeDataPointClient metClient = new MetOfficeDataPointClient(_config["Keys:MetOfficeDataPoint"]);

            MetOfficeDataPoint.Models.Location site             = metClient.GetClosestSite(coordinate).Result;
            ForecastResponse3Hourly            forecastResponse = metClient.GetForecasts3Hourly(null, site.ID).Result;

            // Create list containing 5 days of forecasts for midday
            List <WeatherSummary> weatherSummaries = new List <WeatherSummary>();

            // Get current minutes after midnight
            int minutes = (int)(DateTime.Now.TimeOfDay.TotalSeconds / 60);

            foreach (ForecastLocation3Hourly forecastLocation in forecastResponse.SiteRep.DV.Location)
            {
                foreach (Period3Hourly period in forecastLocation.Period)
                {
                    if (DateTime.Parse(period.Value).Date == DateTime.Today.Date)
                    {
                        WeatherSummary weatherSummary = new WeatherSummary();
                        weatherSummary.ForecastDay = DateTime.Parse(period.Value);

                        // Find closest forecast to now
                        Rep3Hourly forecast = period.Rep.Aggregate((x, y) => Math.Abs(x.MinutesAfterMidnight - minutes) < Math.Abs(y.MinutesAfterMidnight - minutes) ? x : y);
                        weatherSummary.Icon = AppCode.Projects.Weather.GetWeatherIcon(forecast.WeatherType);
                        // Find min temperature
                        weatherSummary.MinTemperature = (int)period.Rep.Where(x => x.MinutesAfterMidnight >= forecast.MinutesAfterMidnight).Min(x => x.Temperature);
                        // Find current temperature
                        weatherSummary.MaxTemperature = (int)period.Rep.Where(x => x.MinutesAfterMidnight >= forecast.MinutesAfterMidnight).Max(x => x.Temperature);
                        // Get remaing forecasts
                        weatherSummary.Forecasts = period.Rep.Where(x => x.MinutesAfterMidnight >= forecast.MinutesAfterMidnight).ToList();

                        weatherSummaries.Add(weatherSummary);
                    }
                    else
                    {
                        WeatherSummary weatherSummary = new WeatherSummary();
                        weatherSummary.ForecastDay = DateTime.Parse(period.Value);

                        // Get icon for midday
                        weatherSummary.Icon = AppCode.Projects.Weather.GetWeatherIcon(period.Rep.First(x => x.MinutesAfterMidnight == 720).WeatherType);
                        // Find min temperature
                        weatherSummary.MinTemperature = (int)period.Rep.Min(x => x.Temperature);
                        // Find max temperature
                        weatherSummary.MaxTemperature = (int)period.Rep.Max(x => x.Temperature);
                        // Get forecasts
                        weatherSummary.Forecasts = period.Rep;

                        weatherSummaries.Add(weatherSummary);
                    }
                }
            }

            ViewData["WeatherSummaries"] = weatherSummaries;
            ViewData["Location"]         = location;
            ViewData["Site"]             = site;

            return(View("~/Views/Projects/Weather/Index.cshtml"));
        }
Esempio n. 16
0
 public void NameFromValue(Int32 value, String expectedName)
 {
     Assert.Equal(expectedName, WeatherSummary.FromValue(value).Name);
 }
Esempio n. 17
0
 public void ValueFromName(String name, Int32 expectedValue)
 {
     Assert.Equal(expectedValue, WeatherSummary.FromName(name).Value);
 }
Esempio n. 18
0
 private string ToTimeAtLocation(WeatherSummary weatherSummary) =>
 (weatherSummary.Date + TimeSpan.FromSeconds(weatherSummary.Timezone)).ToString("HH:mm");