Example #1
0
        public async Task <WeatherInfo[]> GetForecast(string city, int dayCount)
        {
            var client   = new OpenWeatherMapClient(_options.OpenWeatherApiKey);
            var forecast = await client.Forecast.GetByName(city, true, MetricSystem.Metric, count : dayCount).ConfigureAwait(false);

            return(forecast.Forecast.Select(s => ToWeatherInfo(s, false)).ToArray());
        }
Example #2
0
        public async Task <WeatherInfo[]> GetForecastForDay(string city, DateTime fromDate, int marksCount)
        {
            var client   = new OpenWeatherMapClient(_options.OpenWeatherApiKey);
            var forecast = await client.Forecast.GetByName(city, false, MetricSystem.Metric).ConfigureAwait(false);

            var startingHour = 7;

            if (marksCount > 5)
            {
                startingHour = 6;
            }
            if (marksCount > 6)
            {
                startingHour = 3;
            }
            if (marksCount > 7)
            {
                startingHour = 0;
            }

            var result = forecast.Forecast.Where(f =>
            {
                var from = DateTime.SpecifyKind(f.From, DateTimeKind.Utc);
                return(from >= fromDate && from < fromDate.Date.AddDays(1) && (from.Hour >= startingHour && from.Hour <= 22));
            });

            return(result.Select(s => ToWeatherInfo(s, true)).ToArray());
        }
Example #3
0
        public WeatherReport GetWeather(string city)
        {
            var weatherClient = new OpenWeatherMapClient();
            var weatherObject = weatherClient.GetWeather(city);

            WeatherReport report = new WeatherReport();

            Temperature tempatureInfo = new Temperature
            {
                Current = weatherObject.Result.main.temp,
                Low     = weatherObject.Result.main.temp_min,
                High    = weatherObject.Result.main.temp_max
            };

            report.Temperatures = tempatureInfo;

            report.Pressure = weatherObject.Result.main.pressure;
            report.Humidity = weatherObject.Result.main.humidity;

            Winds wind = new Winds
            {
                Speed     = weatherObject.Result.wind.speed,
                Direction = weatherObject.Result.wind.deg
            };

            report.Winds = wind;

            report.Description = "Here is today's weather data for " + city + "!";

            return(report);
        }
        public static async void Run([TimerTrigger("0 */15 * * * *")] TimerInfo AlertTimer, TraceWriter log)
        {
            storageAccount = CloudStorageAccount.Parse(storageAcct);
            tableClient    = storageAccount.CreateCloudTableClient();  // Create the table client.
            table          = tableClient.GetTableReference(weatherTable);
            client         = new OpenWeatherMapClient(owmKey);

            log.Info($"Open Weather Map Timer trigger function executed at: {DateTime.Now}");

            var result = await client.CurrentWeather.GetByName(owmLocation, MetricSystem.Metric);

            weatherEntity.Temperature   = result.Temperature.Value;
            weatherEntity.Pressure      = result.Pressure.Value;
            weatherEntity.Humidity      = result.Humidity.Value;
            weatherEntity.Precipitation = result.Precipitation.Value;
            weatherEntity.WindSpeed     = result.Wind.Speed.Value;
            weatherEntity.Clouds        = result.Clouds.Value;
            weatherEntity.Weather       = result.Weather.Value;

            weatherEntity.PartitionKey = appId;
            weatherEntity.RowKey       = owmLocation;

            TableOperation insertOperation = TableOperation.InsertOrReplace(weatherEntity);

            table.Execute(insertOperation);
        }
Example #5
0
        private async void GetWeather(BasicGeoposition?position)
        {
            if (!position.HasValue)
            {
                Weather.Messages = "Can't find your location";
                return;
            }

            var hasApiContract = ApiInformation
                                 .IsApiContractPresent("Windows.Phone.PhoneContract", 1);

            Weather.Messages = hasApiContract
                                ? $"{Battery.GetDefault().RemainingDischargeTime.TotalHours:0.0} hours remaining"
                                : "";

            var client  = new OpenWeatherMapClient();
            var weather = await client.GetCurrentWeatherAsync(position.Value.Latitude, position.Value.Longitude);

            Weather.Current = new CurrentWeatherViewModel(weather);

            var forecast = await client.GetSevenDayForecastAsync(position.Value.Latitude, position.Value.Longitude);

            Weather.Forecast = forecast.List
                               .Select(f => new ForecastViewModel(f))
                               .ToList();
        }
Example #6
0
        public override bool Init()
        {
            var pollTime = GetPropertyValueInt("poll");
            var apiKey   = GetPropertyValueString("api-key");

            _timer.Elapsed += _timer_Elapsed;
            _timer.Interval = pollTime * 1000;

            _client = new OpenWeatherMapClient("17cd16005872728916a7475b71d6050e");

            var latitude  = DriverContext.NodeTemplateFactory.GetSetting("Latitude").ValueDouble;
            var longitude = DriverContext.NodeTemplateFactory.GetSetting("Longitude").ValueDouble;

            _cords = new Coordinates()
            {
                Latitude  = latitude.Value,
                Longitude = longitude.Value
            };

            _logger.LogInformation($"Using longitude {longitude} latitude {latitude} refresh rate {_timer.Interval}ms");



            return(base.Init());
        }
Example #7
0
 public ShellViewModel()
 {
     client = new OpenWeatherMapClient();
     // Variant 1: with delegate command.
     GetCurrentWeatherCommand = new DelegateCommand(GetCurrentWeatherCommandExecute);
     // Variant 2: with cancellable async command.
     //GetCurrentWeatherCommand = new AsyncCancellableCommand(GetCurrentWeatherCommandExecuteAsync);
 }
        public async Task <string> getWeather()
        {
            var client         = new OpenWeatherMapClient("68b8644b93b1b90aec47e87b59f8612d");
            var currentWeather = await client.CurrentWeather.GetByName("Tampa");

            //Console.WriteLine(currentWeather.Weather.Value);
            return(currentWeather.Temperature.Value.ToString());
        }
Example #9
0
 /// <summary>
 /// Get OpenWeatherMap connection
 /// </summary>
 /// <returns></returns>
 OpenWeatherMapClient GetWeatherServiceClient()
 {
     if (weatherClient == null)
     {
         weatherClient = new OpenWeatherMapClient(APIkey);
     }
     return(weatherClient);
 }
Example #10
0
        public void GetCurrentWeatherByZip_ArgumentNullException_NullZipCode(string zip)
        {
            // Arrange
            var client = new OpenWeatherMapClient(_apiKey);

            // Assert
            Assert.ThrowsAsync <ArgumentNullException>(async() => await client.GetCurrentWeatherByZip(zip));
        }
Example #11
0
        //Get the current temperature
        public async Task <Temperature> GetCurrentTemperature(string city, string country)
        {
            var client = new OpenWeatherMapClient(this.applicationId);

            var currentWeather = await client.CurrentWeather.GetByName(city, MetricSystem.Metric);

            return(currentWeather.Temperature);
        }
Example #12
0
        public void Ctor_Instantiates_NonEmptyApiKey()
        {
            // Act
            var result = new OpenWeatherMapClient(_apiKey);

            // Assert
            Assert.IsInstanceOf <OpenWeatherMapClient>(result);
        }
Example #13
0
        protected override async Task OnMessageActivityAsync(ITurnContext <IMessageActivity> turnContext, CancellationToken cancellationToken)
        {
            var client         = new OpenWeatherMapClient("47d4faed8ac5819xxxxxxxxxx");
            var CloudImage     = "http://messagecardplayground.azurewebsites.net/assets/Mostly%20Cloudy-Square.png";
            var DizzleImage    = "http://messagecardplayground.azurewebsites.net/assets/Drizzle-Square.png";
            var rainImage      = "https://raw.githubusercontent.com/zayedrais/WeatherBot/master/rain.png";
            var stormImage     = "https://raw.githubusercontent.com/zayedrais/WeatherBot/master/storm.png";
            var sunImage       = "https://raw.githubusercontent.com/zayedrais/WeatherBot/master/sun.png";
            var currentWeather = await client.CurrentWeather.GetByName(turnContext.Activity.Text);

            var search = await client.Search.GetByName("Chennai");

            var forcast = await client.Forecast.GetByName("Chennai");

            var    curtTemp        = currentWeather.Temperature.Value - 273.15;
            var    MaxTemp         = currentWeather.Temperature.Max - 273.15;
            var    MinTemp         = currentWeather.Temperature.Min - 273.15;
            var    updateCard      = readFileforUpdate_jobj(_cards[0]);
            JToken cityName        = updateCard.SelectToken("body[0].text");
            JToken tdyDate         = updateCard.SelectToken("body[1].text");
            JToken curTemp         = updateCard.SelectToken("body[2].columns[1].items[0].text");
            JToken maxTem          = updateCard.SelectToken("body[2].columns[3].items[0].text");
            JToken minTem          = updateCard.SelectToken("body[2].columns[3].items[1].text");
            JToken weatherImageUrl = updateCard.SelectToken("body[2].columns[0].items[0].url");


            cityName.Replace(currentWeather.City.Name);
            curTemp.Replace(curtTemp.ToString("N0"));
            tdyDate.Replace(DateTime.Now.ToString("dddd, dd MMMM yyyy"));
            maxTem.Replace("Max" + " " + MaxTemp.ToString("N0"));
            minTem.Replace("Min" + " " + MinTemp.ToString("N0"));
            var n = currentWeather.Clouds.Name;

            if (n == "overcast clouds")
            {
                weatherImageUrl.Replace(rainImage);
            }
            else if (n.Contains("clouds"))
            {
                weatherImageUrl.Replace(CloudImage);
            }
            else if (n.Contains("sky"))
            {
                weatherImageUrl.Replace(sunImage);
            }
            else if (n.Contains("rain"))
            {
                weatherImageUrl.Replace(rainImage);
            }
            else if (n.Contains("storm") || n.Contains("thunder"))
            {
                weatherImageUrl.Replace(stormImage);
            }

            var updateWeatherTem = UpdateAdaptivecardAttachment(updateCard);

            await turnContext.SendActivityAsync(MessageFactory.Attachment(updateWeatherTem), cancellationToken);
        }
        public static async Task Run([TimerTrigger("0 0 18 * * *")] TimerInfo myTimer, TraceWriter log)
        {
            log.Info($"C# Timer trigger function executed at: {DateTime.Now}");
            DependencyInjection.ConfigureInjection(log);

            using (var scope = DependencyInjection.Container.BeginLifetimeScope())
            {
                FreezingAlgorithme  algorithme          = scope.Resolve <FreezingAlgorithme>();
                DeviceService       deviceService       = scope.Resolve <DeviceService>();
                NotificationService notificationService = scope.Resolve <NotificationService>();
                FreezeService       freezeService       = scope.Resolve <FreezeService>();
                AlarmService        alarmService        = scope.Resolve <AlarmService>();

                OpenWeatherMapClient weatherClient = scope.Resolve <OpenWeatherMapClient>();

                IList <Alarm> alarms = new List <Alarm>();

                try
                {
                    log.Info("Get latest telemtry");
                    Dictionary <Device, Telemetry> telemetries = deviceService.GetLatestTelemetryByDevice();
                    foreach (var item in telemetries)
                    {
                        OwmCurrentWeather current = await weatherClient.GetCurrentWeather(item.Key.Position.Latitude, item.Key.Position.Longitude);

                        OwmForecastWeather forecast = await weatherClient.GetForecastWeather(item.Key.Position.Latitude, item.Key.Position.Longitude);

                        log.Info($"Execute Algorithme (device {item.Key.Id})");
                        FreezeForecast freeze = await algorithme.Execute(item.Value, item.Key, current.Weather, forecast.Forecast, forecast.StationPosition);

                        if (freeze == null)
                        {
                            log.Error($"Unable to calculate the freeze probability (no forecast)");
                            continue;
                        }
                        // TODO : complete process
                        Dictionary <DateTime, FreezingProbability> averageFreezePrediction12h = freezeService.CalculAverageFreezePrediction12h(freeze.FreezingProbabilityList);
                        log.Info($"Create alarms");
                        alarmService.CreateFreezeAlarm(item.Key.Id, item.Key.SiteId, averageFreezePrediction12h);
                        log.Info($"Insert Freeze in Db");
                        freezeService.CreateFreezeAndThawByDevice(item.Key.Id, averageFreezePrediction12h);
                    }

                    notificationService.SendNotifications(alarms);
                    log.Info($"Notifications sent at: {DateTime.Now}");
                }
                catch (AlgorithmeException)
                {
                    throw;
                }
                catch (Exception e)
                {
                    log.Error(e.Message, e);
                    throw;
                }
            }
        }
Example #15
0
 public Weather2Base(string cityName)
 {
     this.NotesContext     = new WeatherNotesContext();
     this.WeatherMapClient = new OpenWeatherMapClient()
     {
         AppId = "aaed34ba968cee384865edc13f38c775"
     };
     this.CityName = cityName;
 }
Example #16
0
        async void GetWeatherData()
        {
            var client         = new OpenWeatherMapClient("d912e2792e6814cb36463f2b39ee4f66");
            var currentWeather = await client.CurrentWeather.GetByName("Hamburg");

            int Temperatur = Convert.ToInt16(currentWeather.Temperature.Value / 32);

            lbl_weather.Text = Convert.ToString(currentWeather.Weather.Value);
            lbl_temp.Text    = Temperatur + " Grad Celsius";
        }
Example #17
0
        private async void BotTelegram_OnMessage(object sender, MessageEventArgs e)
        {
            var message = e.Message;

            if (message == null || message.Type != MessageType.TextMessage)
            {
                return;
            }
            var client  = new OpenWeatherMapClient("7574caa56a934eb3b27c54904c019e03");
            var weather = client.CurrentWeather.GetByName(message.Text);
            var temp    = "\uD83C\uDF21";
            var degree  = "\u00B0";

            //if (/*weather.Status == TaskStatus.WaitingForActivation*/ weather.Exception == null && !message.Text.StartsWith("/start"))
            //{
            //var clouds = Icons.getIcon(weather.Result.Clouds.Name);
            //await botTelegram.SendTextMessageAsync(message.Chat.Id,
            //    "City: " + weather.Result.City.Name + "\n" +
            //    "Temperature: " + temp + Math.Round((Convert.ToInt32(weather.Result.Temperature.Value) - 273.15), 1) + degree + "\n" +
            //    "Clouds: " + clouds + weather.Result.Clouds.Name + "\n" +
            //    "Pressure: " + Math.Round((Convert.ToDouble(weather.Result.Pressure.Value) / 1.333220000000039), 2));
            //}
            //else
            //{
            //    if (message.Text.StartsWith("/start"))
            //    {
            //        await botTelegram.SendTextMessageAsync(message.Chat.Id, "Hello to WeatherBot!!!");
            //    }
            //    else
            //    {
            //        await botTelegram.SendTextMessageAsync(message.Chat.Id, "Error city");
            //    }
            //}
            if (message.Text.StartsWith("/start"))
            {
                await botTelegram.SendTextMessageAsync(message.Chat.Id, "Hello to WeatherBot!!!");
            }
            else
            {
                try
                {
                    var clouds = Icons.getIcon(weather.Result.Clouds.Name);
                    await botTelegram.SendTextMessageAsync(message.Chat.Id,
                                                           "City: " + weather.Result.City.Name + "\n" +
                                                           "Temperature: " + temp + Math.Round((Convert.ToInt32(weather.Result.Temperature.Value) - 273.15), 1) + degree + "\n" +
                                                           "Clouds: " + clouds + weather.Result.Clouds.Name + "\n" +
                                                           "Pressure: " + Math.Round((Convert.ToDouble(weather.Result.Pressure.Value) / 1.333220000000039), 2));
                }
                catch (AggregateException)
                {
                    botTelegram.SendTextMessageAsync(message.Chat.Id, "Error city");
                    // await botTelegram.SendTextMessageAsync(message.Chat.Id, "Error city");
                }
            }
        }
Example #18
0
        async void OnSelection(object sender, SelectedItemChangedEventArgs e)
        {
            if (e.SelectedItem == null)
            {
                return;
            }
            var cidade = e.SelectedItem as Cidade;
            var clima  = OpenWeatherMapClient.BuscarClima(cidade.id);

            await Navigation.PushAsync(new DetalheCidadePage(clima));
        }
Example #19
0
        private async Task <RainStatus> GetRainStatus(Geoposition pos)
        {
            var client  = new OpenWeatherMapClient("YourApiKey");
            var weather = await client.CurrentWeather.GetByCoordinates(new Coordinates()
            {
                Latitude  = pos.Coordinate.Point.Position.Latitude,
                Longitude = pos.Coordinate.Point.Position.Longitude
            });

            return(weather.Precipitation.Mode == "no" ? RainStatus.Sun : RainStatus.Rain);
        }
Example #20
0
        async void GetWeather()
        {
            var    client         = new OpenWeatherMapClient("");               // Hier muss man den eigenen API Key von GetWeatherMap.com eingeben, den man nach dem LogIn bekommt
            String ort            = "Rastatt";
            var    currentWeather = await client.CurrentWeather.GetByName(ort); // soll drauf warten auf die Antwort vom Client


            int Temperatur = Convert.ToInt16(currentWeather.Temperature.Value - 273.15); // Umrechung von Kelvin in Grad, da dies von CurrentWeather nicht in Celsius ausgegeben wird


            say("die aktuelle Temperatur beträgt in: " + ort + Temperatur + "Grad Celsius");
        }
Example #21
0
 public static Task <CurrentWeatherResponse> GetWeather(string city)
 {
     try
     {
         var client = new OpenWeatherMapClient("47db2e9d7bbbd1f32788194422b353b6");
         return(client.CurrentWeather.GetByName(city));
     }
     catch
     {
         throw;
     }
 }
Example #22
0
        async void GetWeather()
        {
            var client         = new OpenWeatherMapClient("d912e2792e6814cb36463f2b39ee4f66");
            var currentWeather = await client.CurrentWeather.GetByName("Hamburg");

            int Temperatur = Convert.ToInt16(currentWeather.Temperature.Value / 32);

            s.SpeakAsync("der himmel ist:" + currentWeather.Weather.Value);
            s.SpeakAsync("der himmel ist:" + currentWeather.Temperature.Value);
            lbl_weather.Text = currentWeather.Weather.Value;
            s.SpeakAsync("und die aktuelle Temperatur beträgt:" + Temperatur + "Grad Celsius");
            lbl_temp.Text = Temperatur + " Grad Celsius";
        }
        private async Task Run()
        {
            Weather.Text = "";

            var city    = "Lincoln, NE";
            var client  = new OpenWeatherMapClient();
            var weather = await client.GetCurrentWeatherByCityAsync(city);

            Weather.Text += $"Temp: {weather?.Main?.Temperature}\n";
            Weather.Text += $"Low: {weather?.Main?.MinTemperature}\n";
            Weather.Text += $"High: {weather?.Main?.MaxTemperature}\n";
            Icon.Source   = weather.WeatherIconUrl();
        }
Example #24
0
        public async Task <IList <WeatherClass> > GetWeatherAsync()
        {
            OpenWeatherMapClient client = new OpenWeatherMapClient(token);
            var currentWeather          = await client.Forecast.GetByCoordinates(new OpenWeatherMap.Coordinates()
            {
                Latitude = coordinates.Latitude, Longitude = coordinates.Longitude
            },
                                                                                 false,
                                                                                 MetricSystem.Metric,
                                                                                 OpenWeatherMapLanguage.RU);

            return(ConvertToWeatherClass(currentWeather.Forecast));
        }
Example #25
0
        // POST tables/CheckInItem
        public async Task <IHttpActionResult> PostCheckInItem(CheckInItem item)
        {
            if (item.Longitude != 0)
            {
                var client         = new OpenWeatherMapClient();
                var currentWeather = await client.CurrentWeather.GetByCoordinates(new Coordinates { Longitude = item.Longitude, Latitude = item.Latitude });

                item.Weather = currentWeather.ToWeatherCondition();
            }

            CheckInItem current = await InsertAsync(item);

            return(CreatedAtRoute("Tables", new { id = current.Id }, current));
        }
Example #26
0
        //Ließt die Temperatur aus der API aus
        public static async void LoadTemp(string cityname)
        {
            try
            {
                OpenWeatherMapClient client = new OpenWeatherMapClient(weathercode);
                var currentWeather          = await client.CurrentWeather.GetByName(cityname);

                temperatur = Convert.ToInt32(currentWeather.Temperature.Value - 273.15);
            }
            finally
            {
                Simon.WriteInLog("Temperatur geladen");
            }
        }
Example #27
0
        //Ließt die Wolkendaten aus der API aus
        public static async void LoadClouds(string cityname)
        {
            try
            {
                OpenWeatherMapClient client = new OpenWeatherMapClient(weathercode);
                var currentWeather          = await client.CurrentWeather.GetByName(cityname);

                clouds = currentWeather.Clouds.Value;
            }
            finally
            {
                Simon.WriteInLog("Wolcken geladen");
            }
        }
        private async void button_Click(object sender, RoutedEventArgs e)
        {
            var client         = new OpenWeatherMapClient("f106071d5c9f2a0f94eda7fb618ed294");
            var currentWeather = await client.CurrentWeather.GetByName(_city);

            // Celcius to Kelvin is -> -273.15

            textBlock.Text = string.Format("{0}- Humidity = {1} Temperature={2}-{3}  Weather = {4}",
                                           currentWeather.City.Name, currentWeather.Humidity.Value,
                                           currentWeather.Temperature.Value - 273.15, "Celcius", currentWeather.Weather.Value);
            var bitmapImage = new BitmapImage();

            if (currentWeather.Weather.Value.ToLower().Contains("few clouds"))
            {
                image.Source = new BitmapImage(new Uri("ms-appx:///Assets/cloudy1.png"));
            }
            else if (currentWeather.Weather.Value.ToLower().Contains("clear sky"))
            {
                image.Source = new BitmapImage(new Uri("ms-appx:///Assets/sunny.png"));
            }
            else if (currentWeather.Weather.Value.ToLower().Contains("scattered clouds"))
            {
                image.Source = new BitmapImage(new Uri("ms-appx:///Assets/cloudy3.png"));
            }
            else if (currentWeather.Weather.Value.ToLower().Contains("broken clouds"))
            {
                image.Source = new BitmapImage(new Uri("ms-appx:///Assets/cloudy5.png"));
            }
            else if (currentWeather.Weather.Value.ToLower().Contains("shower rain"))
            {
                image.Source = new BitmapImage(new Uri("ms-appx:///Assets/shower2.png"));
            }
            else if (currentWeather.Weather.Value.ToLower().Contains("rain"))
            {
                image.Source = new BitmapImage(new Uri("ms-appx:///Assets/shower3.png"));
            }
            else if (currentWeather.Weather.Value.ToLower().Contains("thunderstorm"))
            {
                image.Source = new BitmapImage(new Uri("ms-appx:///Assets/tstorm2.png"));
            }
            else if (currentWeather.Weather.Value.ToLower().Contains("mist"))
            {
                image.Source = new BitmapImage(new Uri("ms-appx:///Assets/mist.png"));
            }
            else if (currentWeather.Weather.Value.ToLower().Contains("smoke"))
            {
                image.Source = new BitmapImage(new Uri("ms-appx:///Assets/overcast.png"));
            }
        }
        public bool GetLocationData(City city)
        {
            int cityId;

            // Other grabbers store string IDs and this would fail here
            if (city.Grabber != GetServiceName() || !int.TryParse(city.Id, out cityId))
            {
                return(false);
            }
            var client         = new OpenWeatherMapClient(GetKey());
            var currentWeather = Task.Run(async() => await client.CurrentWeather.GetByCityId(cityId, _metricSystem, _language)).Result;

            city.Condition.Temperature   = FormatTemp(currentWeather.Temperature.Value, currentWeather.Temperature.Unit);
            city.Condition.Humidity      = string.Format("{0} {1}", currentWeather.Humidity.Value, currentWeather.Humidity.Unit);
            city.Condition.Pressure      = string.Format("{0:F0} {1}", currentWeather.Pressure.Value, currentWeather.Pressure.Unit);
            city.Condition.Precipitation = string.Format("{0} {1}", currentWeather.Precipitation.Value, currentWeather.Precipitation.Unit);
            city.Condition.Wind          = string.Format("{0} {1}", currentWeather.Wind.Speed.Name, currentWeather.Wind.Direction.Name);
            city.Condition.Condition     = currentWeather.Weather.Value;
            var  now     = DateTime.Now;
            bool isNight = now >= currentWeather.City.Sun.Set || now < currentWeather.City.Sun.Rise;

            city.Condition.BigIcon   = @"Weather\128x128\" + GetWeatherIcon(currentWeather.Weather.Number, isNight);
            city.Condition.SmallIcon = @"Weather\64x64\" + GetWeatherIcon(currentWeather.Weather.Number, isNight);

            var forecasts = Task.Run(async() => await client.Forecast.GetByCityId(cityId, true, _metricSystem, _language)).Result;

            foreach (var forecast in forecasts.Forecast)
            {
                DayForecast dayForecast = new DayForecast();
                dayForecast.High = FormatTemp(forecast.Temperature.Max, currentWeather.Temperature.Unit);
                dayForecast.Low  = FormatTemp(forecast.Temperature.Min, currentWeather.Temperature.Unit);

                dayForecast.Humidity = string.Format("{0} {1}", forecast.Humidity.Value, forecast.Humidity.Unit);
                // TODO:
                //dayForecast.Pressure = string.Format("{0} {1}", forecast.Pressure.Value, forecast.Pressure.Unit);
                dayForecast.Precipitation = string.Format("{0} {1}", forecast.Precipitation.Value, forecast.Precipitation.Unit);
                dayForecast.Wind          = string.Format("{0} {1}", forecast.WindSpeed.Mps, currentWeather.Wind.Direction.Name);
                dayForecast.Overview      = forecast.Symbol.Name;
                dayForecast.BigIcon       = @"Weather\128x128\" + GetWeatherIcon(forecast.Symbol.Number, false);
                dayForecast.SmallIcon     = @"Weather\64x64\" + GetWeatherIcon(forecast.Symbol.Number, false);
                string fomattedDate = forecast.Day.ToString(_dateFormat.ShortDatePattern, _dateFormat);
                string day          = _dateFormat.GetAbbreviatedDayName(forecast.Day.DayOfWeek);
                dayForecast.Day = String.Format("{0} {1}", day, fomattedDate);

                city.ForecastCollection.Add(dayForecast);
            }
            city.ForecastCollection.FireChange();
            return(true);
        }
Example #30
0
        public static async Task <MyWeather> GetWeather()
        {
            // Ключ доступа к OpenWeatherMap.
            const string owmApiKey = "7a29ddb27ed8939647a190357541d344";
            string       city      = String.Empty;

            try
            {
                // Запрашиваем коодинаты устройства, если они доступны, то отпределяем по координатам город,
                // по названию города определяем погоду.
                city = await GetCity(await Geolocate());
            }

            // Если запрещен доступ приложению к геоданным
            catch (UnauthorizedAccessException)
            {
                await new MessageDialog("Невозможно определить Ваши координаты").ShowAsync();

                // TODO: реализовать открытие окна настроек доступа к геоданным, чтобы открыть приложению доступ к ним.

                /*if (await Windows.System.Launcher.LaunchUriAsync(new Uri("ms-settings:privacy-location")))
                 * {
                 *  await GetWeather();
                 * }*/

                return(null);
            }

            // Другие исключения, например, отсуствие подключения к сети, требуемое для определения координат.
            catch (Exception)
            {
                return(null);
            }



            var weatherClient = new OpenWeatherMapClient(owmApiKey);

            // В качестве параметров задаем название города, и другие параметры. Также OWM клиент имеет метод для получения погоды по координатам
            // устройства. В данном конкретном примере определение названия города реализовано в учебных целях.
            var currentWeather = await weatherClient.CurrentWeather.GetByName(city, MetricSystem.Metric, OpenWeatherMapLanguage.RU);

            // Форматируем должным образом данные текущей погоды, в том числе задаем URI иконки, определенной OWM для текущей погоды.
            return(new MyWeather(
                       (Int32)currentWeather.Temperature.Value + "°C",
                       (Int32)currentWeather.Wind.Speed.Value + " м/с",
                       "http://openweathermap.org/img/w/" + currentWeather.Weather.Icon + ".png"));
        }