Esempio n. 1
0
        public static Forecast GenerateForecast(string input)
        {
            var result   = JsonConvert.DeserializeObject <dynamic>(input);
            var list     = result["list"];
            var forecast = new Forecast()
            {
                City       = result["city"]["name"].ToString(),
                Latitude   = Convert.ToDouble(result["city"]["coord"]["lat"]),
                Longtitude = Convert.ToDouble(result["city"]["coord"]["lon"])
            };

            var reports = new List <ForecastReport>();

            for (int i = 0; i < 39; i++)
            {
                DateTime dtUTC = DateTime.SpecifyKind(DateTime.Parse(list[i]["dt_txt"].ToString()), DateTimeKind.Utc);

                var r = new ForecastReport()
                {
                    CurrentTemp = KtoF(Convert.ToDouble(list[i]["main"]["temp"])),
                    Humidity    = Convert.ToInt32(list[i]["main"]["humidity"]),
                    WeatherCode = Convert.ToInt32(list[i]["weather"][0]["id"]),
                    Icon        = "http://openweathermap.org/img/w/" + list[i]["weather"][0]["icon"].ToString() + ".png",
                    Description = list[i]["weather"][0]["description"].ToString(),
                    DateTime    = dtUTC.ToLocalTime()
                };

                reports.Add(r);
            }

            forecast.Reports = reports;

            return(forecast);
        }
        public void OneDayOfRainyForecast_GenerateReport_ReturnHeaviestDayOfRain()
        {
            var forecast = new List <Forecast>()
            {
                new Forecast(1, Weather.Rainy),
            };

            var report = new ForecastReport(forecast);

            report.HeaviestDayOfRain.Should().Be(1);
        }
        public void TenDaysOfRainyAndOneOfNormalForecast_GenerateReport_ReturnTwoPeriods()
        {
            List <Forecast> forecast = CreateTenDaysOfRain();

            forecast.Add(new Forecast(11, Weather.Normal));
            var report = new ForecastReport(forecast);

            report.Periods.Values.Any(value => value > 0).Should().BeTrue();
            report.Periods.Values.Count(value => value > 0).Should().Be(2);
            report.Periods[Weather.Rainy].Should().Be(1);
            report.Periods[Weather.Normal].Should().Be(1);
        }
        public async Task <ForecastReport> GetAreaForecast(int id)
        {
            string result = null;

            try
            {
                Debug.WriteLine("Getting Area Forecast from DataPoint Service...");
                result = await Task.Factory.StartNew <string>(()
                                                              => "{\"report\":{\"creating-authority\":\"Met Office\",\"creation-time\":\"2014-12-07T17:36:25\",\"title\":\"Mountain Forecasts\",\"location\":\"East Highland\",\"issue\":{\"date\":\"2014-12-07\",\"time\":\"1736\"},\"ValidFrom\":\"2014-12-07T17:00:00Z\",\"ValidTo\":\"2014-12-11T17:00:00Z\",\"Validity\":\"Monday\",\"IssuedDate\":\"Sunday, 07 December 2014\",\"Hazards\":{\"Hazard\":[{\"no\":\"1\",\"Element\":\"Blizzards\",\"Risk\":\"Medium\",\"Comments\":\"Frequent heavy snow showers at first\"},{\"no\":\"2\",\"Element\":\"Heavy snow\",\"Risk\":\"Low\",\"Comments\":\"Frequent heavy snow showers at first\"},{\"no\":\"3\",\"Element\":\"Storm force winds\",\"Risk\":\"High\",\"Comments\":\"Gust to 70 to 80mph overnight and at first on Monday with the risk of being blown over\"},{\"no\":\"4\",\"Element\":\"Gales\",\"Risk\":\"High\",\"Comments\":\"Winds falling below gale force later in the afternoon.\"},{\"no\":\"5\",\"Element\":\"Severe chill effect\",\"Risk\":\"High\",\"Comments\":\"Risk of hypothermia and frost bite, particularly overnight and Monday morning.\"},{\"no\":\"6\",\"Element\":\"Persistent extensive hill fog\",\"Risk\":\"Low\",\"Comments\":\"Temporary in snow showers\"},{\"no\":\"7\",\"Element\":\"Thunderstorms\",\"Risk\":\"Low\",\"Comments\":\"Not expected\"},{\"no\":\"8\",\"Element\":\"Heavy persistent rain\",\"Risk\":\"No Risk\",\"Comments\":\"\"},{\"no\":\"9\",\"Element\":\"Strong sunlight\",\"Risk\":\"Low\",\"Comments\":\"Low winter sun and glare off the snow.\"}]},\"Overview\":\"Snow showers will die out and winds will gradually ease on Monday as a ridge of high pressure builds in from the Atlantic\",\"Forecast_Day0\":{\"Weather\":\"Clear then sunny spells and snow showers. The snow showers heavy and frequent overnight and at first on Monday with temporary white out and blizzard conditions. The showers becoming confined to the Cairngorms and Eastern Grampians during the morning as the southern Highlands becoming dry and sunny. All ranges mainly dry with clear spells by dusk.\",\"Visibility\":\"Very good or excellent falling very poor in snow showers.\",\"HillFog\":\"Generally nil significant, but patches 700-900m, but much lower in showers\",\"MaxWindLevel\":\"600m\",\"MaxWind\":\"West or Northwest 40 to 50 gusts 70 to 80mph   over ridges and summits, decreasing 20 to 30 during the afternoon and evening.\",\"TempLowLevel\":\"Zero to plus 3 Celsius\",\"TempHighLevel\":\"Minus 3 Celsius\",\"FreezingLevel\":\"200 to 300m\",\"WeatherPPN\":{\"WxPeriod\":[{\"period\":\"1\",\"Period\":\"0000 to 0300\",\"Weather\":25,\"Probability\":\"60%\",\"Ppn_type\":\"\"},{\"period\":\"2\",\"Period\":\"0300 to 0600\",\"Weather\":25,\"Probability\":\"60%\",\"Ppn_type\":\"\"},{\"period\":\"3\",\"Period\":\"0600 to 0900\",\"Weather\":25,\"Probability\":\"60%\",\"Ppn_type\":\"\"},{\"period\":\"4\",\"Period\":\"0900 to 1200\",\"Weather\":26,\"Probability\":\"50%\",\"Ppn_type\":\"\"},{\"period\":\"5\",\"Period\":\"1200 to 1500\",\"Weather\":3,\"Probability\":\"30%\",\"Ppn_type\":\"\"},{\"period\":\"6\",\"Period\":\"1500 to 1800\",\"Weather\":0,\"Probability\":\"20%\",\"Ppn_type\":\"\"},{\"period\":\"7\",\"Period\":\"1800 to 2100\",\"Weather\":0,\"Probability\":\"10%\",\"Ppn_type\":\"\"},{\"period\":\"8\",\"Period\":\"2100 to 2400\",\"Weather\":0,\"Probability\":\"0%\",\"Ppn_type\":\"\"}]}},\"Forecast_Day1\":{\"Weather\":\"Dry during the early hours, but cloud thickening and low outbreaks of rain, sleet and snow by dawn. Snow soon confined to the highest tops and turning to rain at all levels during the morning. Rain then clearing back to snow showers in the evening.\",\"Visibility\":\"Very good falling moderate or poor at times and very poor in snow. Temporary blizzard and white out conditions.\",\"HillFog\":\"Nil significant at first. Becoming broken or overcast 300 to 600m at times during daylight hours. Lifting and breaking in the evening.\",\"MaxWindLevel\":\"600m\",\"MaxWind\":\"Increasing Southwest 50 to 60 during the morning, gusts 80mph or more over summits and ridges, veering westerly later\",\"TempLowLevel\":\"Zero to Minus 2 Celsius early and later. Rising to plus 6 during daylight hours.\",\"TempHighLevel\":\"Minus 3 Celsius early and later, rising Plus 3 around the middle of the day.\",\"FreezingLevel\":\"200-400m, rising above the summits for a time around the middle of the day.\"},\"Outlook_Day2\":\"Frequent snow showers with severe gale or storm force west or northwest winds over summits. Blizzard conditions.\",\"Outlook_Day3\":\"Frequent snow showers with severe gale or storm force west or northwest winds over summits. Blizzard conditions. Winds and snow showers gradually easing.\",\"Outlook_Day4\":\"Snow or snow showers. Strong to gale force west becoming north winds. Blizzard conditions at times.\"}}");
            }
            catch (Exception ex)
            {
                throw new Exception("Failed to get Area Forecast from service provider. The service maybe down. Retry or try again", ex);
            }

            ForecastReport forecastReport;

            try
            {
                var report = JObject.Parse(result)["report"];

                var issueDate = DateTime.Parse((string)report["creation-time"]);

                var forecastReport2 = new ForecastReport();
                forecastReport2.IssuedBy      = (string)report["creating-authority"];
                forecastReport2.IssueDateTime = issueDate;
                forecastReport2.Title         = (string)report["title"];
                forecastReport2.Location      = (string)report["title"];
                forecastReport2.ValidFrom     = DateTime.Parse((string)report["ValidFrom"]);
                forecastReport2.ValidTo       = DateTime.Parse((string)report["ValidTo"]);
                forecastReport2.Validity      = (string)report["Validity"];
                forecastReport2.IssuedDate    = (string)report["IssuedDate"];
                forecastReport2.Hazards       = report["Hazards"]["Hazard"].Select(hazard => new Hazard {
                    No       = (short)hazard["no"],
                    Element  = (string)hazard["Element"],
                    Risk     = (string)hazard["Risk"],
                    Comments = (string)hazard["Comments"]
                });
                forecastReport2.Overview     = (string)report["Overview"];
                forecastReport2.ForecastDay0 = ParseForecast(report["Forecast_Day0"], issueDate.Date.AddDays(1));
                forecastReport2.ForecastDay1 = ParseForecast(report["Forecast_Day1"], issueDate.Date.AddDays(2));
                forecastReport2.OutlookDay2  = (string)report["Outlook_Day2"];
                forecastReport2.OutlookDay3  = (string)report["Outlook_Day3"];
                forecastReport2.OutlookDay4  = (string)report["Outlook_Day4"];
                forecastReport = forecastReport2;
            }
            catch (Exception ex)
            {
                throw new FormatException("Failed to format the forecast report.", ex);
            }

            return(forecastReport);
        }
        public async void LoadForecast()
        {
            IsBusy          = true;
            _forecastReport = null;

            try
            {
                _forecastReport = await _mountainWeatherService.GetAreaForecast(_location.Id);

                if (_forecastReport == null)
                {
                    return;
                }

                var date = _forecastReport.ForecastDay0.Date;

                Items = new List <SelectableViewModel>
                {
                    new ForecastViewModel(_forecastReport.ForecastDay0)
                    {
                        IssuedDate = _forecastReport.IssueDateTime
                    },
                    new ForecastViewModel(_forecastReport.ForecastDay1)
                    {
                        IssuedDate = _forecastReport.IssueDateTime
                    },
                    new OutlookViewModel(_forecastReport.OutlookDay2, date.AddDays(2))
                    {
                        IssuedDate = _forecastReport.IssueDateTime
                    },
                    new OutlookViewModel(_forecastReport.OutlookDay3, date.AddDays(3))
                    {
                        IssuedDate = _forecastReport.IssueDateTime
                    },
                    new OutlookViewModel(_forecastReport.OutlookDay4, date.AddDays(4))
                    {
                        IssuedDate = _forecastReport.IssueDateTime
                    }
                };
            }
            catch (Exception ex)
            {
                _error = ex;
                if (_isVisible)
                {
                    ShowError();
                }
            }
            finally
            {
                IsBusy = false;
            }
        }
        public async Task <ForecastReport> GetAreaForecast(int id)
        {
            string result = null;

            try
            {
                Debug.WriteLine("Getting Area Forecast from DataPoint Service...");
                result = await Get(string.Format("txt/wxfcs/mountainarea/json/{0}", id));
            }
            catch (Exception ex)
            {
                throw new Exception("Failed to get Area Forecast from service provider. The service maybe down. Retry or try again", ex);
            }

            ForecastReport forecastReport;

            try
            {
                var report = JObject.Parse(result)["report"];

                var issueDate = DateTime.Parse((string)report["creation-time"], CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal);

                var forecastReport2 = new ForecastReport();
                forecastReport2.IssuedBy      = (string)report["creating-authority"];
                forecastReport2.IssueDateTime = issueDate;
                forecastReport2.Title         = (string)report["title"];
                forecastReport2.Location      = (string)report["title"];
                forecastReport2.ValidFrom     = DateTime.Parse((string)report["ValidFrom"], CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal);
                forecastReport2.ValidTo       = DateTime.Parse((string)report["ValidTo"], CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal);
                forecastReport2.Validity      = (string)report["Validity"];
                forecastReport2.IssuedDate    = (string)report["IssuedDate"];
                forecastReport2.Hazards       = report["Hazards"]["Hazard"].Select(hazard => new Hazard {
                    No       = (short)hazard["no"],
                    Element  = (string)hazard["Element"],
                    Risk     = (string)hazard["Risk"],
                    Comments = (string)hazard["Comments"]
                });
                forecastReport2.Overview     = (string)report["Overview"];
                forecastReport2.ForecastDay0 = ParseForecast(report["Forecast_Day0"], issueDate);
                forecastReport2.ForecastDay1 = ParseForecast(report["Forecast_Day1"], issueDate.AddDays(1));
                forecastReport2.OutlookDay2  = (string)report["Outlook_Day2"];
                forecastReport2.OutlookDay3  = (string)report["Outlook_Day3"];
                forecastReport2.OutlookDay4  = (string)report["Outlook_Day4"];
                forecastReport = forecastReport2;
            }
            catch (Exception ex)
            {
                throw new FormatException("Failed to format the forecast report.", ex);
            }

            return(forecastReport);
        }
        public void OneDayOfOtherForecast_GenerateReport_ReturnOnePeriod()
        {
            var forecast = new List <Forecast>()
            {
                new Forecast(1, Weather.Other),
            };

            var report = new ForecastReport(forecast);

            report.Periods.Values.Any(value => value > 0).Should().BeTrue();
            report.Periods.Values.Count(value => value > 0).Should().Be(1);
            report.Periods[Weather.Other].Should().Be(1);
        }
        public void OneDayOfRainyAndOneOfNormalForecast_GenerateReport_ReturnTwoPeriods()
        {
            var forecast = new List <Forecast>()
            {
                new Forecast(1, 325),
                new Forecast(2, Weather.Normal),
            };

            var report = new ForecastReport(forecast);

            report.Periods.Values.Any(value => value > 0).Should().BeTrue();
            report.Periods.Values.Count(value => value > 0).Should().Be(2);
            report.Periods[Weather.Rainy].Should().Be(1);
            report.Periods[Weather.Normal].Should().Be(1);
        }
Esempio n. 9
0
        static void Main(string[] args)
        {
            System.Console.WriteLine("Se generará el pronóstico para 3650 días para el sistema compuesto por: ");
            System.Console.WriteLine("- Ferengi, que se desplaza con una velocidad angular de 1 grados/día en sentido horario y su distancia con respecto al sol es de 500Km");
            System.Console.WriteLine("- Betasoide, que se desplaza con una velocidad angular de 3 grados/día en sentido horario y su distancia con respecto al sol es de 2000Km.");
            System.Console.WriteLine("- Vulcano, que se desplaza con una velocidad angular de 5 grados/día en sentido anti­horario y su distancia con respecto al sol es de 1000Km.");

            var report = new ForecastReport(new WeatherControlSystem(SolarSystemFactory.GenerateSolarSystem()).CalculateForecast(3650));

            System.Console.WriteLine("Se encontraron {0} períodos de sequía.", report.Periods[Weather.Drought]);
            System.Console.WriteLine("Se encontraron {0} períodos de lluvia.", report.Periods[Weather.Rainy]);
            System.Console.WriteLine("El día pico de lluvia será el {0}.", report.HeaviestDayOfRain);
            System.Console.WriteLine("Se encontraron {0} períodos de condiciones normales de presión y temperatura.", report.Periods[Weather.Normal]);
            System.Console.ReadLine();
        }
Esempio n. 10
0
        public void DateCountTest()
        {
            ForecastReport forecast = new ForecastReport(new DateTime(2017, 11, 20), new DateTime(2017, 12, 8));

            forecast.AddSale(new DateTime(2017, 10, 5), 10);
            forecast.AddSale(new DateTime(2017, 10, 8), 14);
            forecast.AddSale(new DateTime(2017, 10, 11), 9);
            forecast.AddSale(new DateTime(2017, 10, 15), 19);
            forecast.AddSale(new DateTime(2017, 10, 22), 18);
            forecast.AddSale(new DateTime(2017, 10, 26), 23);

            forecast.LoadReport("", "");

            NUnit.Framework.Assert.IsTrue(true);
        }
        public void TwoPeriodsOfRainyOneOfNormalOneOfDroughtAndOneOfOtherForecast_GenerateReport_ReturnPeriods()
        {
            List <Forecast> forecast = CreateTenDaysOfRain();

            forecast.Add(new Forecast(11, Weather.Normal));
            forecast.Add(new Forecast(12, 100));
            forecast.Add(new Forecast(13, Weather.Drought));
            forecast.Add(new Forecast(14, Weather.Other));
            var report = new ForecastReport(forecast);

            report.Periods.Values.Any(value => value > 0).Should().BeTrue();
            report.Periods.Values.Count(value => value > 0).Should().Be(4);
            report.Periods[Weather.Rainy].Should().Be(2);
            report.Periods[Weather.Normal].Should().Be(1);
            report.Periods[Weather.Drought].Should().Be(1);
            report.Periods[Weather.Other].Should().Be(1);
        }