Exemplo n.º 1
0
        public IEnumerable <DailyForecast> LoadDailyForecasts(Location location)
        {
            XmlDocument xmldoc = GetForecastDocument(location);

            foreach (XmlElement forecast in xmldoc.SelectNodes("response/forecast/simpleforecast/forecastdays/forecastday").OfType <XmlElement>())
            {
                DailyForecast daily = null;
                try
                {
                    DateTime day = new DateTime(Int32.Parse(forecast.SelectSingleNode("date/year").InnerText),
                                                Int32.Parse(forecast.SelectSingleNode("date/month").InnerText),
                                                Int32.Parse(forecast.SelectSingleNode("date/day").InnerText));
                    WeatherCondition low = new WeatherCondition(day,
                                                                Int32.Parse(forecast.SelectSingleNode("low/fahrenheit").InnerText),
                                                                forecast.SelectSingleNode("conditions").InnerText);
                    WeatherCondition high = new WeatherCondition(day,
                                                                 Int32.Parse(forecast.SelectSingleNode("high/fahrenheit").InnerText),
                                                                 forecast.SelectSingleNode("conditions").InnerText);
                    daily = new DailyForecast(high, low);
                }
                catch (XmlException)
                {
                }

                if (daily != null)
                {
                    yield return(daily);
                }
            }
        }
Exemplo n.º 2
0
        public async Task ProcessRecords()
        {
            await GetSQLRecords();
            await fetchPoissonAsync(lamba, Forecasts.Count());

            var CurrentForecasts = Forecasts.Where(pr => Forecasts.Any(p => pr.fdate >= DateTime.Today)).ToList();

            List <DailyForecast> finalRecords = new List <DailyForecast>();

            foreach (var item in CurrentForecasts)
            {
                DailyForecast newItem = new DailyForecast(per_loc, per_admit, per_vent);

                newItem.EstimatedGloveSurgical         = GloveSurgical;
                newItem.EstimatedGloveExamNitrile      = GloveExamNitrile;
                newItem.EstimatedGloveExamVinyl        = GloveExamVinyl;
                newItem.EstimatedMaskFaceAntiFog       = MaskFaceAntiFog;
                newItem.EstimatedMaskFluidResistant    = MaskFluidResistant;
                newItem.EstimatedGownIsolationXLYellow = GownIsolationXLYellow;
                newItem.EstimatedMaskAntiFogWFilm      = MaskAntiFogWFilm;
                newItem.EstimatedShieldFaceFullAntiFog = ShieldFaceFullAntiFog;
                newItem.EstimatedRespPartFilterReg     = RespPartFilterReg;

                newItem.fdate          = item.fdate;
                newItem.ForecastValues = item.ForecastValues;
                newItem.NewCases       = item.NewCases;
                newItem.Total_cc       = item.Total_cc;
                newItem.Total_nc       = item.Total_nc;
                finalRecords.Add(newItem);
            }


            data = Tricks.ToDataTable(finalRecords);
        }
Exemplo n.º 3
0
        private List <DailyForecastModel> FiveDayForecast(DailyForecast fiveDaysForecast)
        {
            List <DailyForecastModel> list = new List <DailyForecastModel>();

            for (int i = 1; i < 5; i++)
            {
                DailyForecastModel dailyForecast = new DailyForecastModel();

                dailyForecast.Id = i;
                if (i == 1)
                {
                    dailyForecast.Date = string.Format("Tomorrow, {0} {1}",
                                                       fiveDaysForecast.DailyForecasts[i].Date.Date.Day,
                                                       CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(fiveDaysForecast.DailyForecasts[i].Date.Date.Month));
                }
                else
                {
                    dailyForecast.Date = string.Format("{0}, {1} {2}",
                                                       fiveDaysForecast.DailyForecasts[i].Date.Date.DayOfWeek,
                                                       fiveDaysForecast.DailyForecasts[i].Date.Date.Day,
                                                       CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(fiveDaysForecast.DailyForecasts[i].Date.Date.Month));
                }

                dailyForecast.ImageResource = ImageHelper.ImagePicker(fiveDaysForecast.DailyForecasts[i].Day.LongPhrase);
                dailyForecast.DegreesMin    = "/" + Math.Ceiling(fiveDaysForecast.DailyForecasts[i].Temperature.Minimum.Value) + "\u00B0";
                dailyForecast.Degrees       = Math.Ceiling(fiveDaysForecast.DailyForecasts[i].Temperature.Maximum.Value) + "\u00B0";

                list.Add(dailyForecast);
            }
            ;

            return(list);
        }
Exemplo n.º 4
0
        public void TestTomorrowWeatherNoMatchFailure()
        {
            Dictionary <String, String> input = new Dictionary <string, string>
            {
                { "Command", "weather" },
                { "Location", "here" },
                { "Time", "DayOfWeek=tomorrow;" },
            };
            IConfigurationManager configMan = GetConfigurationManager();

            Mock <IWeatherSensor> weatherSensor = new Mock <IWeatherSensor>(MockBehavior.Strict);

            weatherSensor.Setup(s => s.Name).Returns("Mock Weather Sensor");
            weatherSensor.Setup(s => s.IsValid).Returns(true);
            DateTime         today    = DateTime.Now;
            WeatherCondition high     = new WeatherCondition(today, 90, "Sunny");
            WeatherCondition low      = new WeatherCondition(today, 70, "Rainy");
            DailyForecast    forecast = new DailyForecast(high, low);

            weatherSensor.Setup(s => s.LoadDailyForecasts(new Location("Austin", "Texas", 78759))).Returns(new List <DailyForecast> {
                forecast
            });
            AddComponentToConfigurationManager(weatherSensor.Object);

            Assert.AreEqual("That forecast is not currently available.", RunSingleConversation <WeatherConversation>(input));

            weatherSensor.Verify(s => s.LoadDailyForecasts(new Location("Austin", "Texas", 78759)), Times.Exactly(1));
        }
Exemplo n.º 5
0
        public void TestTomorrowWeatherSuccess()
        {
            Dictionary <String, String> input = new Dictionary <string, string>
            {
                { "Command", "weather" },
                { "Location", "here" },
                { "Time", "DayOfWeek=tomorrow;" },
            };
            IConfigurationManager configMan = GetConfigurationManager();

            Mock <IWeatherSensor> weatherSensor = new Mock <IWeatherSensor>(MockBehavior.Strict);

            weatherSensor.Setup(s => s.Name).Returns("Mock Weather Sensor");
            weatherSensor.Setup(s => s.IsValid).Returns(true);
            DateTime         tomorrow = DateTime.Now.AddDays(1);
            WeatherCondition high     = new WeatherCondition(tomorrow, 90, "Sunny");
            WeatherCondition low      = new WeatherCondition(tomorrow, 70, "Rainy");
            DailyForecast    forecast = new DailyForecast(high, low);

            weatherSensor.Setup(s => s.LoadDailyForecasts(new Location("Austin", "Texas", 78759))).Returns(new List <DailyForecast> {
                forecast
            });
            AddComponentToConfigurationManager(weatherSensor.Object);

            String expectedResult = String.Format("According to Mock Weather Sensor. On {0}, it will be between 70 and 90 degrees and Rainy..", tomorrow.ToString("m", CultureInfo.InvariantCulture));

            Assert.AreEqual(expectedResult, RunSingleConversation <WeatherConversation>(input));

            weatherSensor.Verify(s => s.LoadDailyForecasts(new Location("Austin", "Texas", 78759)), Times.Exactly(1));
        }
Exemplo n.º 6
0
        private WeatherDaily MapWeatherDaily(DailyForecast daily, int latitude, int longitude)
        {
            return(new WeatherDaily()
            {
                ApparentTemperatureMax = daily.apparentTemperatureMax,
                ApparentTemperatureMaxTime = daily.apparentTemperatureMaxTime,
                ApparentTemperatureMin = daily.apparentTemperatureMin,
                ApparentTemperatureMinTime = daily.apparentTemperatureMinTime,
                CloudCover = daily.cloudCover,
                DewPoint = daily.dewPoint,
                Humidity = daily.humidity,
                Icon = daily.icon,
                MoonPhase = daily.moonPhase,
                Ozone = daily.ozone,
                PrecipIntensity = daily.precipIntensity,
                PrecipIntensityMax = daily.precipIntensityMax,
                PrecipProbability = daily.precipProbability,
                Pressure = daily.pressure,
                Summary = daily.summary,
                SunriseTime = daily.sunriseTime,
                SunsetTime = daily.sunsetTime,
                TemperatureMax = daily.temperatureMax,
                TemperatureMaxTime = daily.temperatureMaxTime,
                TemperatureMin = daily.temperatureMin,
                TemperatureMinTime = daily.temperatureMinTime,
                Time = daily.time,
                Visibility = daily.visibility,
                WindBearing = daily.windBearing,
                WindSpeed = daily.windSpeed,

                Latitude = latitude,
                Longitude = longitude
            });
        }
        public List <DailyForecast> GetDailyForecasts(ParkModel park)
        {
            try
            {
                List <DailyForecast> fiveDayForecast = new List <DailyForecast>();
                using (SqlConnection connection = new SqlConnection(connectionString))
                {
                    connection.Open();
                    SqlCommand cmd = new SqlCommand(SQL_GetDailyForecasts, connection);
                    cmd.Parameters.AddWithValue("@parkCode", park.ParkCode);
                    SqlDataReader reader = cmd.ExecuteReader();

                    while (reader.Read())
                    {
                        DailyForecast forecast = new DailyForecast();
                        forecast.Day        = Convert.ToInt16(reader["fiveDayForecastValue"]);
                        forecast.Low        = Convert.ToInt16(reader["low"]);
                        forecast.High       = Convert.ToInt16(reader["high"]);
                        forecast.Conditions = Convert.ToString(reader["forecast"]);
                        fiveDayForecast.Add(forecast);
                    }
                }
                return(fiveDayForecast);
            }
            catch (SqlException ex)
            {
                throw;
            }
        }
Exemplo n.º 8
0
        private void GetDailyForecast(string cityCode = "sb")
        {
            ObservableCollection <DailyForecast> dailyForecastCollection = new ObservableCollection <DailyForecast>();

            dailyForecastCollection = DailyForecast.GetForecast(cityCode);
            DailyForecastCollection = new ObservableCollection <DailyForecast>(dailyForecastCollection);
            RaisePropertyChanged(() => DailyForecastCollection);
        }
        /// <summary>
        /// Get the seven day weather forecast.
        /// </summary>
        public async void GetWeatherForecast()
        {
            List <double> geocoding = await GetGeocode();

            var dailyForecast = await _weatherService.GetWeatherForecast(geocoding[0], geocoding[1]);

            dailyForecast.Daily.ForEach(d => DailyForecast.Add(d));
        }
Exemplo n.º 10
0
        public async Task <DailyForecast> UpdateDailyForecastCache(int cityId)
        {
            var dailyForecastFromJson = await _weatherApiService.GetDailyForecastAsync(cityId);

            var dailyForecastToReplace = new DailyForecast(dailyForecastFromJson.DailyForecast);

            return(ReplaceAndRetrunIfExpiredOrMissing <DailyForecast>(_dailyForecast, cityId, dailyForecastToReplace));
        }
Exemplo n.º 11
0
 public static DailyForecastDto ToDto(this DailyForecast source, string imageUrlTemplate, string type)
 {
     return(new DailyForecastDto
     {
         ApplicableDate = source.ApplicableDate.ToShortDateString(),
         Created = source.Created,
         WeatherStateAbbreviation = source.WeatherStateAbbreviation,
         WeatherStateName = source.WeatherStateName,
         WeatherStateImageUrl = $"{imageUrlTemplate}{source.WeatherStateAbbreviation}.{type}"
     });
 }
        /// <summary>
        /// Set the Daily forecast for the next week
        /// </summary>
        private void SetDailyForecast()
        {
            DailyForecast.Clear();

            for (int i = 0; i < 7; i++)
            {
                var dailyWeather = new DailyWeatherViewModel(OneCallResponse.DailyWeather[i], Options);
                DailyForecast.Add(dailyWeather);
            }

            OnProperyChanged("DailyForecast");
        }
Exemplo n.º 13
0
    public void Fill(DailyForecast forecast)//method for UI filling with getting data
    {
        scale = 1.0F;
        UIMain main = FindObjectOfType <UIMain>();

        picture.sprite = main.Pictures[forecast.Code];
        this.day.text  = forecast.Date.Day + " " + forecast.Date.DayOfWeek;

        string temp   = (forecast.Temp.HasValue) ? string.Format("{0:#} \u00B0C\n", forecast.Temp) : string.Empty;
        string result = string.Format("{0}\n{1}Min: {2:#} \u00B0C\nMax: {3:#} \u00B0C", forecast.Text, temp, forecast.Low, forecast.High);

        this.weatherInfo.text = result;
    }
Exemplo n.º 14
0
        public ForecastViewModel(DailyForecast forecast)
        {
            var time = GetTimeFromUnixTime(forecast.Date);

            Day = $"{time:ddd MM/dd}";

            var max = forecast.Temp.Max;
            var min = forecast.Temp.Min;

            Temperature = $"{max:0}° / {min:0}°";

            IconUrl = forecast.Weathers[0]?.IconUrl;
        }
Exemplo n.º 15
0
        private async Task GetSQLRecords()
        {
            string    sqlQuery = "Select *  from CovId19 Where ProvinceState = '" + State + "' and model = '" + Model + "'";
            DataTable data     = DataObject.GetDataTable(sqlQuery);

            foreach (DataRow row in data.Rows)
            {
                DailyForecast item = new DailyForecast(per_loc, per_admit, per_vent);
                item.fdate          = DateTime.Parse(row["fdates"].ToString());
                item.ForecastValues = int.Parse(row["forecast_vals"].ToString());
                item.NewCases       = int.Parse(row["newcases"].ToString());
                Forecasts.Add(item);
            }
        }
        public async Task Update()
        {
            var city = db.city.Include(c => c.currentWeather).ToList();

            foreach (var c in city)
            {
                WeatherRoot w = await getCityWeather(c);

                CurrentWeather currentWeather = new CurrentWeather
                {
                    clouds              = w.current.clouds,
                    sunrise             = w.current.sunrise,
                    sunset              = w.current.sunset,
                    temp                = w.current.temp,
                    humidity            = w.current.humidity,
                    feels_like          = w.current.feels_like,
                    pressure            = w.current.pressure,
                    uvi                 = w.current.uvi,
                    dew_point           = w.current.dew_point,
                    dt                  = w.current.dt,
                    wind_deg            = w.current.wind_deg,
                    wind_speed          = w.current.wind_speed,
                    weather_main        = w.current.weather[0].main,
                    weather_description = w.current.weather[0].description,
                    weather_icon        = w.current.weather[0].icon,
                    weather_id          = w.current.weather[0].id,
                    visibility          = w.current.visibility
                };

                if (c.currentWeather == null)
                {
                    c.currentWeather = currentWeather;
                    db.SaveChanges();
                }
                else
                {
                    db.Entry(c.currentWeather).State = EntityState.Modified;
                    c.currentWeather = currentWeather;
                    db.SaveChanges();
                }

                foreach (var dailyForecast in w.daily)
                {
                    DailyForecast dailyForecast1 = new DailyForecast
                    {
                        dt                  = dailyForecast.dt,
                        sunrise             = dailyForecast.sunrise,
                        sunset              = dailyForecast.sunset,
                        temp_day            = dailyForecast.temp.day,
                        temp_min            = dailyForecast.temp.min,
                        temp_max            = dailyForecast.temp.max,
                        temp_night          = dailyForecast.temp.night,
                        temp_eve            = dailyForecast.temp.eve,
                        morn                = dailyForecast.temp.morn,
                        feels_like_day      = dailyForecast.feels_like.day,
                        feels_like_night    = dailyForecast.feels_like.night,
                        feels_like_eve      = dailyForecast.feels_like.eve,
                        feels_like_morn     = dailyForecast.feels_like.morn,
                        pressure            = dailyForecast.pressure,
                        humidity            = dailyForecast.humidity,
                        dew_point           = dailyForecast.dew_point,
                        wind_speed          = dailyForecast.wind_speed,
                        wind_deg            = dailyForecast.wind_deg,
                        weather_id          = dailyForecast.weather[0].id,
                        weather_main        = dailyForecast.weather[0].main,
                        weather_description = dailyForecast.weather[0].description,
                        weather_icon        = dailyForecast.weather[0].icon,
                        clouds              = dailyForecast.clouds,
                        uvi                 = dailyForecast.uvi
                    };

                    c.dailyForcasts.Add(dailyForecast1);
                    db.SaveChanges();
                }
            }
        }
Exemplo n.º 17
0
        public ObservableCollection <DailyForecast> GetForecasts(string city)
        {
            string    resultApi;
            WebClient client = new WebClient();

            try
            {
                resultApi = client.DownloadString($"{webApiF}{city}&appid={token}");

                ForecastsInfo result = JsonConvert.DeserializeObject <ForecastsInfo>(resultApi);

                ForecastsInfo root = result;

                ObservableCollection <DailyForecast> df = new ObservableCollection <DailyForecast>();

                string  aDaysUV = client.DownloadString($"{webApiUVI}{token}&lat={root.city.coord.lat.ToString().Replace(',', '.')}&lon={root.city.coord.lon.ToString().Replace(',', '.')}&cnt=5");
                dynamic uvJson  = JsonConvert.DeserializeObject(aDaysUV);

                IEnumerable <ForecastsInfo.list> lists;

                int i = 0; //UVIndexCNTr
                for (DateTime day = DateTime.Now; ; day = day.AddDays(1))
                {
                    if (day.Day <= 9)
                    {
                        lists = from l in root.List where l.dt_txt.Split('-').Last().Split(' ').First() == ("0" + day.Day.ToString()) select l;
                    }
                    else
                    {
                        lists = from l in root.List where l.dt_txt.Split('-').Last().Split(' ').First() == day.Day.ToString() select l;
                    }

                    if (lists.Count() != 0)
                    {
                        DailyForecast d = new DailyForecast
                        {
                            deg      = Convert.ToInt32(lists.First().wind.deg),
                            wind     = Convert.ToInt32(lists.First().wind.speed),
                            humidity = Convert.ToInt32(lists.First().main.humidity),
                            Day      = day.DayOfWeek.ToString() + " " + day.Day.ToString(),
                            descr    = lists.First().Weather[0].description.Substring(0, 1).ToUpper() + lists.First().Weather[0].description.Remove(0, 1),
                            icon     = "/Images/WeatherStatuss/" + lists.First().Weather[0].icon + ".png"
                        };

                        #region Get UVIndex
                        if (day.ToShortDateString() == DateTime.Now.ToShortDateString())
                        {
                            string  todayuv = client.DownloadString($"http://api.openweathermap.org/data/2.5/uvi?appid={token}&lat={root.city.coord.lat.ToString().Replace(',', '.')}&lon={root.city.coord.lon.ToString().Replace(',', '.')}");
                            dynamic uv1json = JsonConvert.DeserializeObject(todayuv);
                            d.uvindex = uvJson[0]["value"];
                        }
                        else
                        {
                            d.uvindex = uvJson[i]["value"];
                        }
                        i++;
                        #endregion

                        foreach (ForecastsInfo.list list in lists)
                        {
                            HourlyForecast h = new HourlyForecast
                            {
                                time     = list.dt_txt.Split(' ').Last(),
                                temp     = Convert.ToInt32(WeatherConvertor.KelvinToCelsius(list.main.temp)),
                                wind     = Convert.ToInt32(WeatherConvertor.MsToKh(list.wind.speed)),
                                deg      = Convert.ToInt32(list.wind.deg),
                                icon     = "/Images/WeatherStatuss/" + list.Weather[0].icon + ".png",
                                descr    = list.Weather[0].description.Substring(0, 1).ToUpper() + list.Weather[0].description.Remove(0, 1),
                                humidity = Convert.ToInt32(list.main.humidity)
                            };

                            d.Hourlies.Add(h);
                        }

                        #region Get min/max
                        d.temp_max = d.Hourlies.OrderBy(x => x.temp).Last().temp;
                        d.temp_min = d.Hourlies.OrderBy(x => x.temp).First().temp;
                        #endregion

                        df.Add(d);
                    }
                    else if (lists.Count() == 0)
                    {
                        break;
                    }
                }


                return(df);
            }
            catch { throw; }
        }
Exemplo n.º 18
0
        private void DrawForecast(SKCanvas canvas, SKRect rect, DailyForecast forecast)
        {
            // background
            using (var paint = new SKPaint())
            {
                var colors = new[] { WeatherColors.LightBlue, WeatherColors.Blue };

                paint.Color = SKColors.Black;
                canvas.DrawRect(rect, paint);

                rect        = new SKRect(rect.Left + 2, rect.Top + 2, rect.Right - 2, rect.Bottom - 2);
                paint.Color = SKColors.Gray;
                canvas.DrawRect(rect, paint);

                rect        = new SKRect(rect.Left + 4, rect.Top + 4, rect.Right - 4, rect.Bottom - 4);
                paint.Color = SKColors.Black;
                canvas.DrawRect(rect, paint);

                rect = new SKRect(rect.Left + 2, rect.Top + 2, rect.Right - 2, rect.Bottom - 2);
                var grad = WeatherBitmapCache.Get("gradient.png");
                canvas.DrawBitmap(grad, rect);
            }

            var w = (rect.Right - rect.Left);

            // day of week
            using (var paint = new SKPaint())
            {
                paint.Color     = WeatherColors.Yellow;
                paint.TextSize  = 36;
                paint.Typeface  = WeatherTypeface.Standard;
                paint.TextAlign = SKTextAlign.Center;

                var forecastTime =
                    new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc).AddSeconds(forecast.time).ToLocalTime();
                DrawShadowedText(canvas, forecastTime.ToString("ddd").ToUpper(), rect.Left + w / 2, rect.Top + 30, paint);
            }

            // forecast icon

            var icon     = WeatherBitmapCache.Get($"{forecast.icon}.gif");
            var paddingW = (w - icon.Width) / 2;
            var paddingH = (128 - icon.Height) / 2;
            var imgRect  = new SKRect(rect.Left + paddingW, 140 + paddingH, rect.Right - paddingW,
                                      140 + 128 - paddingH);

            canvas.DrawBitmap(icon, imgRect);

            // hi/lo
            using (var paint = new SKPaint())
            {
                paint.TextSize  = 36;
                paint.Typeface  = WeatherTypeface.Standard;
                paint.TextAlign = SKTextAlign.Center;

                paint.Color = WeatherColors.TealAlso;
                DrawShadowedText(canvas, "Lo", rect.Left + w / 4, rect.Bottom - 50, paint);

                paint.Color = WeatherColors.Yellow;
                DrawShadowedText(canvas, "Hi", rect.Left + (w / 4) * 3, rect.Bottom - 50, paint);

                paint.Color    = SKColors.White;
                paint.Typeface = WeatherTypeface.Large;
                paint.TextSize = 32;
                DrawShadowedText(canvas, $"{Math.Round(forecast.temperatureMin)}", rect.Left + w / 4, rect.Bottom - 5,
                                 paint);
                DrawShadowedText(canvas, $"{Math.Round(forecast.temperatureMax)}", rect.Left + (w / 4) * 3, rect.Bottom - 5,
                                 paint);
            }

            // condition
            using (var paint = new SKPaint())
            {
                paint.Color     = SKColors.White;
                paint.TextSize  = 36;
                paint.Typeface  = WeatherTypeface.Standard;
                paint.TextAlign = SKTextAlign.Center;

                var description = forecast.icon.Split('-');

                DrawShadowedText(canvas, TextUtils.UppercaseFirst(description[0]), rect.Left + w / 2,
                                 rect.Bottom - 110 - 50, paint);
                if (description.Length >= 2)
                {
                    DrawShadowedText(canvas, TextUtils.UppercaseFirst(description[1]), rect.Left + w / 2,
                                     rect.Bottom - 110,
                                     paint);
                }
            }
        }
Exemplo n.º 19
0
        /// <summary>
        /// Adds a day panel into the forecast grid
        /// </summary>
        /// <param name="day"></param>
        /// <param name="col"></param>
        private void AddDayPanel(DailyForecast day, int col)
        {
            //Get day name from epoch time
            System.DateTime dtDateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc);
            dtDateTime = dtDateTime.AddSeconds(day.EpochDate).ToLocalTime();
            //Create day name
            TextBlock tbn = new TextBlock
            {
                Text = dtDateTime.DayOfWeek.ToString(),
                HorizontalAlignment = HorizontalAlignment.Center,
                VerticalAlignment   = VerticalAlignment.Center,
                FontSize            = 20,
                Foreground          = new SolidColorBrush(Colors.White),
                FontWeight          = FontWeights.Bold
            };

            grdForecastDays.Children.Add(tbn);
            Grid.SetColumn(tbn, col);
            Grid.SetRow(tbn, 0);

            //Create stackpanels for day/night pictures
            StackPanel panel    = new StackPanel();
            StackPanel dayPanel = new StackPanel
            {
                Orientation         = Orientation.Horizontal,
                HorizontalAlignment = HorizontalAlignment.Center
            };
            StackPanel nightPanel = new StackPanel
            {
                Orientation         = Orientation.Horizontal,
                HorizontalAlignment = HorizontalAlignment.Center
            };

            panel.Children.Add(dayPanel);
            panel.Children.Add(nightPanel);
            grdForecastDays.Children.Add(panel);
            Grid.SetColumn(panel, col);
            Grid.SetRow(panel, 1);
            //Day
            TextBlock tbd = new TextBlock
            {
                Text = "Day  ",
                HorizontalAlignment = HorizontalAlignment.Center,
                VerticalAlignment   = VerticalAlignment.Center,
                FontSize            = 18,
                Foreground          = new SolidColorBrush(Colors.White),
                FontWeight          = FontWeights.Bold
            };

            dayPanel.Children.Add(tbd);
            //Day Picture
            Image img = new Image
            {
                Source = new BitmapImage(new System.Uri("ms-appx:///Assets/icons/" + day.Day.Icon + ".png")),
                Width  = 60,
                Height = 60
            };

            dayPanel.Children.Add(img);
            //Night
            TextBlock tbni = new TextBlock
            {
                Text = "Night",
                HorizontalAlignment = HorizontalAlignment.Center,
                VerticalAlignment   = VerticalAlignment.Center,
                FontSize            = 18,
                Foreground          = new SolidColorBrush(Colors.White),
                FontWeight          = FontWeights.Bold
            };

            nightPanel.Children.Add(tbni);
            //DayPicture
            Image img2 = new Image();

            img2.Source = new BitmapImage(new System.Uri("ms-appx:///Assets/icons/" + day.Night.Icon + ".png"));
            img2.Width  = 60;
            img2.Height = 60;
            nightPanel.Children.Add(img2);

            //Min/Max temperatures
            //Add temperature
            TextBlock tbt = new TextBlock
            {
                Text = "Min " + Math.Round(day.Temperature.Minimum.Value) + "°C / Max " + Math.Round(day.Temperature.Maximum.Value) + "°C",
                HorizontalAlignment = HorizontalAlignment.Center,
                FontSize            = 15,
                Foreground          = new SolidColorBrush(Colors.White),
                FontWeight          = FontWeights.Bold
            };

            grdForecastDays.Children.Add(tbt);
            Grid.SetColumn(tbt, col);
            Grid.SetRow(tbt, 2);
        }
Exemplo n.º 20
0
        private static bool TryStateForecastForSensor(SamiDateTime time, Location location, IWeatherSensor sensor, out String message)
        {
            if (time.Range == DateTimeRange.Now)
            {
                WeatherCondition condition = sensor.LoadConditions(location);
                if (condition == null)
                {
                    message = "Weather conditions are not available right now.";
                    return(false);
                }
                message = String.Format("Right now, it is {0} degrees and {1}.",
                                        condition.Temperature,
                                        condition.ConditionDescription);
                return(true);
            }
            else if (time.Range == DateTimeRange.Day)
            {
                // We are asking about a specific day, not a specific time.
                IEnumerable <DailyForecast> forecasts = sensor.LoadDailyForecasts(location);
                if (forecasts == null)
                {
                    message = "That forecast is not currently available.";
                    return(false);
                }
                DailyForecast forecast = forecasts.SingleOrDefault(f => f.High.Time.Date.Equals(time.Time.Date));
                if (forecast == null)
                {
                    message = "That forecast is not currently available.";
                    return(false);
                }
                message = String.Format("On {0}, it will be between {2} and {1} degrees and {3}.",
                                        time.Time.ToString("m", CultureInfo.InvariantCulture),
                                        forecast.High.Temperature,
                                        forecast.Low.Temperature,
                                        forecast.Low.ConditionDescription);
                return(true);
            }
            else if (time.Range == DateTimeRange.SpecificTime)
            {
                // Make sure we're not trying to get the time in the past
                if (time.Time < DateTime.Now)
                {
                    message = "I'm sorry, I can not get a forcast for the past.";
                    return(false);
                }

                // We want a specific time.
                WeatherCondition condition = sensor.LoadHourlyForecasts(location).SingleOrDefault(c => c.Time.Equals(new DateTime(time.Time.Year, time.Time.Month, time.Time.Day, time.Time.Hour, 0, 0)));
                if (condition == null)
                {
                    message = "That forecast is not available currently.";
                    return(false);
                }
                if (time.Time.Day == DateTime.Today.Day)
                {
                    message = String.Format("Today at {0}, it will be {1} degrees and {2}.",
                                            time.Time.ToString("hh:mm tt", CultureInfo.InvariantCulture),
                                            condition.Temperature,
                                            condition.ConditionDescription);
                    return(true);
                }
                else
                {
                    message = String.Format("On {0} at {1}, it will be {2} degrees and {3}.",
                                            time.Time.ToString("m", CultureInfo.InvariantCulture),
                                            time.Time.ToString("hh:mm tt", CultureInfo.InvariantCulture),
                                            condition.Temperature,
                                            condition.ConditionDescription);
                    return(true);
                }
            }
            else if (time.Range == DateTimeRange.EarlyMorning ||
                     time.Range == DateTimeRange.Morning ||
                     time.Range == DateTimeRange.Afternoon ||
                     time.Range == DateTimeRange.Evening ||
                     time.Range == DateTimeRange.Night)
            {
                DateTime firstTime  = time.GetMinTime();
                DateTime secondTime = time.GetMaxTime();

                // Make sure we're not trying to get the time in the past
                if (secondTime < DateTime.Now)
                {
                    message = "I'm sorry, I can not get a forcast for the past.";
                    return(false);
                }

                double firstTemp, secondTemp;

                if (firstTime < DateTime.Now)
                {
                    // We are already in the time span requested.
                    WeatherCondition condition = sensor.LoadConditions(location);
                    IEnumerable <WeatherCondition> forecasts = sensor.LoadHourlyForecasts(location);
                    WeatherCondition forecast = forecasts == null ? null : forecasts.SingleOrDefault(c => c.Time.Equals(new DateTime(secondTime.Year, secondTime.Month, secondTime.Day, secondTime.Hour, 0, 0)));

                    if (condition == null || forecast == null)
                    {
                        message = "That forecast is not available currently.";
                        return(false);
                    }

                    firstTemp  = condition.Temperature;
                    secondTemp = forecast.Temperature;

                    String temperatureCompare;

                    if (firstTemp < secondTemp)
                    {
                        temperatureCompare = "warm up to";
                    }
                    else if (firstTemp > secondTemp)
                    {
                        temperatureCompare = "cool down to";
                    }
                    else
                    {
                        temperatureCompare = "stay at";
                    }

                    message = String.Format("Currently, it is {0} degrees and {1}. It will {2} {3} degrees by {4} and {5}.",
                                            firstTemp,
                                            condition.ConditionDescription,
                                            temperatureCompare,
                                            secondTemp,
                                            secondTime.ToString("hh:mm tt", CultureInfo.InvariantCulture),
                                            forecast.ConditionDescription);
                    return(true);
                }
                else
                {
                    // We want a specific time.
                    IEnumerable <WeatherCondition> forecasts = sensor.LoadHourlyForecasts(location);
                    WeatherCondition firstForecast           = forecasts == null ? null : forecasts.SingleOrDefault(c => c.Time.Equals(new DateTime(firstTime.Year, firstTime.Month, firstTime.Day, firstTime.Hour, 0, 0)));
                    WeatherCondition secondForecast          = forecasts == null ? null : forecasts.SingleOrDefault(c => c.Time.Equals(new DateTime(secondTime.Year, secondTime.Month, secondTime.Day, secondTime.Hour, 0, 0)));

                    if (firstForecast == null || secondForecast == null)
                    {
                        message = "That forecast is not currently available.";
                        return(false);
                    }

                    // "At (time) (nothing|tomorrow|on day), it will be (firsttemp) degrees and (firstcondition). It will (warm up to|cool down to|stay at) (secondtemp) degrees and be (secondcondition)."
                    // Deturmine how to say the day
                    String day;
                    if (time.Time.Date == DateTime.Today.Date)
                    {
                        // Today
                        day = "today";
                    }
                    else if (time.Time.Date == DateTime.Today.AddDays(1).Date)
                    {
                        // Tomorrow
                        day = "tomorrow";
                    }
                    else
                    {
                        // Some other day
                        day = "on " + time.Time.ToString("m", CultureInfo.InvariantCulture);
                    }
                    firstTemp  = firstForecast.Temperature;
                    secondTemp = secondForecast.Temperature;

                    String temperatureCompare;

                    if (firstTemp < secondTemp)
                    {
                        temperatureCompare = "warm up to";
                    }
                    else if (firstTemp > secondTemp)
                    {
                        temperatureCompare = "cool down to";
                    }
                    else
                    {
                        temperatureCompare = "stay at";
                    }


                    message = String.Format("At {0} {1}, it will be {2} degrees and {3}. It will {4} {5} degrees by {6} and {7}.",
                                            firstTime.ToString("hh:mm tt", CultureInfo.InvariantCulture),
                                            day,
                                            firstTemp,
                                            firstForecast.ConditionDescription,
                                            temperatureCompare,
                                            secondTemp,
                                            secondTime.ToString("hh:mm tt", CultureInfo.InvariantCulture),
                                            secondForecast.ConditionDescription);
                    return(true);
                }
            }
            message = "Not Supported";
            return(false);
        }
Exemplo n.º 21
0
        static TileNotification CreateTileDaily(DailyForecast dailyForecast)
        {
            var content = new TileContent()
            {
                Visual = new TileVisual()
                {
                    TileMedium = GetMediumVisual(),
                    TileWide   = GetWideVisual(),
                    TileLarge  = GetLargeVisual()
                }
            };

            TileBinding GetMediumVisual()
            {
                return(new TileBinding()
                {
                    Content = new TileBindingContentAdaptive()
                    {
                        Children =
                        {
                            new AdaptiveGroup()
                            {
                                Children =
                                {
                                    CreateDailySubGroup(dailyForecast.Days[1]),
                                    CreateDailySubGroup(dailyForecast.Days[2])
                                }
                            }
                        }
                    }
                });
            }

            TileBinding GetWideVisual()
            {
                return(new TileBinding()
                {
                    Content = new TileBindingContentAdaptive()
                    {
                        Children =
                        {
                            new AdaptiveGroup()
                            {
                                Children =
                                {
                                    CreateDailySubGroup(dailyForecast.Days[1]),
                                    CreateDailySubGroup(dailyForecast.Days[2]),
                                    CreateDailySubGroup(dailyForecast.Days[3]),
                                    CreateDailySubGroup(dailyForecast.Days[4]),
                                    CreateDailySubGroup(dailyForecast.Days[5])
                                }
                            }
                        }
                    }
                });
            }

            TileBinding GetLargeVisual()
            {
                return(new TileBinding()
                {
                    Content = new TileBindingContentAdaptive()
                    {
                        Children =
                        {
                            new AdaptiveGroup()
                            {
                                Children =
                                {
                                    CreateDailySubGroup(dailyForecast.Days[1]),
                                    CreateDailySubGroup(dailyForecast.Days[2]),
                                    CreateDailySubGroup(dailyForecast.Days[3]),
                                    CreateDailySubGroup(dailyForecast.Days[4]),
                                }
                            },
                            //new AdaptiveText(), // for spacing
                            new AdaptiveGroup()
                            {
                                Children =
                                {
                                    CreateDailySubGroup(dailyForecast.Days[5]),
                                    CreateDailySubGroup(dailyForecast.Days[6]),
                                    CreateDailySubGroup(dailyForecast.Days[7])
                                }
                            }
                        }
                    }
                });
            }

            return(new TileNotification(content.GetXml()));
        }