Beispiel #1
0
        // creates forecasts controls dynamically
        private async Task <bool> CreateForecastFrames(ForecastList forecasts)
        {
            try
            {
                _forecastControlsList.Clear();
                RaisePropertyChanged("ForecastControlsList");
                var forecastsItems = forecasts.list;

                foreach (var forecastItem in forecastsItems)
                {
                    var forecastControl = new SingleForecastControl();
                    forecastControl.Margin = new Xamarin.Forms.Thickness(10, 5, 10, 0);
                    var forecastViewModel = new SingleForecastItemViewModel(forecastItem);
                    forecastControl.BindingContext = forecastViewModel;
                    _forecastControlsList.Add(forecastControl);
                }

                RaisePropertyChanged("ForecastControlsList");
            }

            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
                return(false);
            }

            return(true);
        }
        private async void GetWeather()
        {
            var weatherData = await DependencyService.Get <IWeatherDataBusiness>().Get();

            if (weatherData.Count == 0)
            {
                await Application.Current.MainPage.DisplayAlert("Alerta", "Nenhum item salvo nos favoritos.", "OK");
            }

            foreach (var item in weatherData)
            {
                ForecastList.Add(item);
            }
        }
        private void ReceiveForecast(string json)
        {
            try
            {
                forecastList = JsonConvert.DeserializeObject <ForecastList>(json);
                IList <ForecastDTO> forecasts = new List <ForecastDTO>();
                foreach (Forecast forecast in forecastList.Forecasts)
                {
                    forecasts.Add(mapper.MapForecast(forecast));
                }

                IDictionary <DayOfWeek, List <ForecastDTO> > sortedForecasts = forecasts.GroupBy(f => f.DateOfCalculation.DayOfWeek)
                                                                               .ToDictionary(g => g.Key, g => g.ToList());
                OnForecastsReady(sortedForecasts);
            }
            catch (Exception ex)
            {
                Log.Error(ex.Message);
            }
        }
        public override void SetupBindings()
        {
            SetContentView(Resource.Layout.Weather);
            _bindings.Add(this.SetBinding(
                              () => Vm.SearchLocation,
                              () => LocationTextView.Text));
            _bindings.Add(this.SetBinding(
                              () => Vm.CurrentWeather.Description,
                              () => DescriptionTextView.Text));
            _bindings.Add(this.SetBinding(
                              () => Vm.CurrentWeather.Temp,
                              () => TempTextView.Text));

            //TODO: This needs to happen as a binding
            ImageDownloader.AssignImageAsync(IconImageView, Vm.CurrentWeather.Icon, this);

            _adapter = Vm.Forecasts.GetRecyclerAdapter(
                BindViewHolder,
                Resource.Layout.ForecastTemplate);

            ForecastList.SetLayoutManager(new LinearLayoutManager(this));
            ForecastList.SetAdapter(_adapter);
        }
Beispiel #5
0
        public string GetForecastInstanceMsg(string prefix, string weatherChangePhrase, ForecastList forecastInstance)
        {
            var readableLaterTime = _readableDateTimeService.Get(forecastInstance.DateTimePst);

            return($"{prefix} {readableLaterTime.Time} It will {weatherChangePhrase} {forecastInstance.Main.Temp} degrees with {forecastInstance.Weather.FirstOrDefault().Description}. ");
        }
        /// <summary>
        /// Handle the information returned from the async request
        /// </summary>
        /// <param name="asyncResult"></param>
        private void HandleForecastResponse(IAsyncResult asyncResult)
        {
            // get the state information
            ForecastUpdateState forecastState   = (ForecastUpdateState)asyncResult.AsyncState;
            HttpWebRequest      forecastRequest = (HttpWebRequest)forecastState.AsyncRequest;

            // end the async request
            forecastState.AsyncResponse = (HttpWebResponse)forecastRequest.EndGetResponse(asyncResult);

            Stream streamResult;

            string newCredit   = "";
            string newCityName = "";
            int    newHeight   = 0;

            // create a temp collection for the new forecast information for each
            // time period
            ObservableCollection <ForecastPeriod> newForecastList =
                new ObservableCollection <ForecastPeriod>();

            try
            {
                // get the stream containing the response from the async call
                streamResult = forecastState.AsyncResponse.GetResponseStream();

                // load the XML
                XElement xmlWeather = XElement.Load(streamResult);

                // start parsing the XML.  You can see what the XML looks like by
                // browsing to:
                // http://forecast.weather.gov/MapClick.php?lat=44.52160&lon=-87.98980&FcstType=dwml

                // find the source element and retrieve the credit information
                XElement xmlCurrent = xmlWeather.Descendants("source").First();
                newCredit = (string)(xmlCurrent.Element("credit"));

                // find the source element and retrieve the city and elevation information
                xmlCurrent  = xmlWeather.Descendants("location").First();
                newCityName = (string)(xmlCurrent.Element("city"));
                newHeight   = (int)(xmlCurrent.Element("height"));

                // find the first time layout element
                xmlCurrent = xmlWeather.Descendants("time-layout").First();

                int timeIndex = 1;

                // search through the time layout elements until you find a node
                // contains at least 12 time periods of information. Other nodes can be ignored
                while (xmlCurrent.Elements("start-valid-time").Count() < 12)
                {
                    xmlCurrent = xmlWeather.Descendants("time-layout").ElementAt(timeIndex);
                    timeIndex++;
                }

                ForecastPeriod newPeriod;

                // For each time period element, create a new forecast object and store
                // the time period name.
                // Time periods vary depending on the time of day the data is fetched.
                // You may get "Today", "Tonight", "Monday", "Monday Night", etc
                // or you may get "Tonight", "Monday", "Monday Night", etc
                // or you may get "This Afternoon", "Tonight", "Monday", "Monday Night", etc
                foreach (XElement curElement in xmlCurrent.Elements("start-valid-time"))
                {
                    try
                    {
                        newPeriod          = new ForecastPeriod();
                        newPeriod.TimeName = (string)(curElement.Attribute("period-name"));
                        newForecastList.Add(newPeriod);
                    }
                    catch (FormatException)
                    {
                    }
                }

                // now read in the weather data for each time period
                GetMinMaxTemperatures(xmlWeather, newForecastList);
                GetChancePrecipitation(xmlWeather, newForecastList);
                GetCurrentConditions(xmlWeather, newForecastList);
                GetWeatherIcon(xmlWeather, newForecastList);
                GetTextForecast(xmlWeather, newForecastList);


                // copy the data over
                Deployment.Current.Dispatcher.BeginInvoke(() =>
                {
                    // copy forecast object over
                    Credit   = newCredit;
                    Height   = newHeight;
                    CityName = newCityName;

                    ForecastList.Clear();

                    // copy the list of forecast time periods over
                    foreach (ForecastPeriod forecastPeriod in newForecastList)
                    {
                        ForecastList.Add(forecastPeriod);
                    }
                });
            }
            catch (FormatException)
            {
                // there was some kind of error processing the response from the web
                // additional error handling would normally be added here
                return;
            }
        }
        static async Task GetMessage(string TOKEN, string key)
        {
            TelegramBotClient bot = new TelegramBotClient(TOKEN);
            int offset            = 0;
            int timeout           = 0;

            Console.WriteLine("Старт получения сообщений");
            try
            {
                await bot.SetWebhookAsync("");

                while (flag_exit)
                {
                    var updates = await bot.GetUpdatesAsync(offset, timeout);

                    foreach (var update in updates)
                    {
                        string[] command = { };
                        var      message = update.Message;
                        try
                        {
                            command = filterMessage(message.Text);
                            Console.WriteLine($"Получено сообщение от " + message.From.FirstName + " " + message.From.LastName + ":" + message.Text);
                            if (command != null)
                            {
                                if (command.Length == 1)
                                {
                                    switch (command[0])
                                    {
                                    case "/start":
                                        await bot.SendTextMessageAsync(message.Chat.Id, "Вас приветствует MyBotWeather. Моя цель оповещать тебя о погоде по быстрому набору команд" +
                                                                       "для получения доступных команд набери /help");

                                        break;

                                    case "/help":
                                        await bot.SendTextMessageAsync(message.Chat.Id, "Weather_bot предоставляет информацию о погоде. Команды:\n" +
                                                                       "-Погода ГОРОД\n" +
                                                                       "-Прогноз ГОРОД\n");

                                        break;


                                    default:
                                        await bot.SendTextMessageAsync(message.Chat.Id, $"Команда {command[0]} отсутствует.");

                                        break;
                                    }
                                }
                                else
                                {
                                    try
                                    {
                                        string city = command[1];

                                        switch (command[0])
                                        {
                                        case "Погода":

                                            OpenWeatherAPI openWeatherAPI = new OpenWeatherAPI(key);

                                            WeatherResponse weatherResponse = openWeatherAPI.Weather(command[1]);
                                            if (weatherResponse != null)
                                            {
                                                await bot.SendTextMessageAsync(message.Chat.Id, $"Температура:{weatherResponse.Main.Temp}\n" +
                                                                               $"Давление:{weatherResponse.Main.Pressure}mm\n" +
                                                                               $"Ветер:{weatherResponse.Wind.Speed}м/c\n" +
                                                                               $"Влажность:{weatherResponse.Main.humidity}%");

                                                await bot.SendStickerAsync(message.Chat.Id, StickerWeather.GetSticker(weatherResponse.Weather[0].icon));
                                            }
                                            else
                                            {
                                                await bot.SendTextMessageAsync(message.Chat.Id, $"Ошибка запроса");
                                            }

                                            break;

                                        case "Прогноз":

                                            openWeatherAPI = new OpenWeatherAPI(key);

                                            ForecastList forecastList = openWeatherAPI.forecastList(command[1]);
                                            if (forecastList != null)
                                            {
                                                foreach (var s in forecastList.List)
                                                {
                                                    await bot.SendTextMessageAsync(message.Chat.Id, $"{s.dt_txt}\n" +
                                                                                   $"Температура:{s.Main.Temp},\n" +
                                                                                   $"Давление:{s.Main.Pressure}кПа,\n" +
                                                                                   $"Ветер:{s.Wind.Speed}м/c\n" +
                                                                                   $"Влажность:{s.Main.humidity}%");

                                                    await bot.SendStickerAsync(message.Chat.Id, StickerWeather.GetSticker(s.Weather[0].icon));
                                                }
                                            }
                                            else
                                            {
                                                await bot.SendTextMessageAsync(message.Chat.Id, $"Ошибка запроса");
                                            }

                                            break;

                                        default:
                                            await bot.SendTextMessageAsync(message.Chat.Id, $"Команда {command[0]} отсутствует.");

                                            break;
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        await bot.SendTextMessageAsync(message.Chat.Id, $"Ошибка обработки команды");
                                    }
                                }
                            }
                        }
                        catch
                        {
                            Console.WriteLine("Ошибка фильтра");
                        }

                        offset = update.Id + 1;
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Err:" + ex);
            }
        }
 public override void OnNavigatedTo(NavigationParameters parameters)
 {
     ForecastList.Clear();
     GetWeather();
     base.OnNavigatedTo(parameters);
 }