public IActionResult Tempo()
        {
            HttpClient          client   = MyHTTPClient.Client;
            string              path     = "v1/current.json?key=A_SUA_CHAVE&q=Albufeira";
            HttpResponseMessage response = client.GetAsync(path).Result;
            WeatherApiResponse  wr       =
                response.Content.ReadAsAsync <WeatherApiResponse>().Result;

            return(View(wr));
        }
        public async Task <IActionResult> Tempo(WeatherApiResponse objCidade)
        {
            string cidade = objCidade.Location.Name;
            string path   = "current?access_key=08d9721c9f4a140a938f7325c3402e41&query=" + cidade;
            HttpResponseMessage response = MyHTTPClient.clientes.GetAsync(path).Result;
            string myJsonResponse        = await response.Content.ReadAsStringAsync();

            WeatherApiResponse apiResponse = JsonConvert.DeserializeObject <WeatherApiResponse>(myJsonResponse);

            return(View(apiResponse));
        }
        public async Task <IActionResult> Tempo(string cidade)
        {
            //criar e configurar o cliente HTTP
            HttpClient client = MyHTTPClient.Client;
            string     path   = "v1/current.json?key=2aef87f6723e417fad095040172704&q=" + cidade;

            //fazer o pedido HTTP, receber a resposta, guardar JSON
            HttpResponseMessage response = client.GetAsync(path).Result;
            string json = await response.Content.ReadAsStringAsync();

            //converter JSON para um objeto do tipo WeatherApiResponse
            WeatherApiResponse wc = JsonConvert.DeserializeObject <WeatherApiResponse>(json);

            return(View(wc));
        }
Ejemplo n.º 4
0
        public async Task <IActionResult> Tempo(string cidade)
        {
            //Criar e configurar o cliente HTTP
            HttpClient client = MyHTTPClient.Client;
            string     path   = "v1-+/current.json?key=45e3ca0ce8b54abcb9b85027180705&q=" + cidade;


            //Fazer o pedido HTTP, receber a resposta, guardar JSON
            HttpResponseMessage response = client.GetAsync(path).Result;
            string json = await response.Content.ReadAsStringAsync();

            //Converter JSON para um objeto do tipo WeatherApiResponse
            WeatherApiResponse wc = JsonConvert.DeserializeObject <WeatherApiResponse>(json);


            return(View(wc));
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Creates the embed used for displaying the weather data to the end user
        /// </summary>
        /// <param name="weatherData">The weather data as a <see cref="WeatherApiResponse"/> object</param>
        /// <returns>A discord <see cref="Embed"/> object</returns>
        private Embed CreateWeatherEmbed(WeatherApiResponse weatherData)
        {
            var weatherEmbed = new EmbedBuilder()
                               .WithTitle($"Current weather for {weatherData.CityName} ({weatherData.RegionInfo.CountryCode})")
                               .WithImageUrl($"{weatherIconUrl}{weatherData.Weather.FirstOrDefault().WeatherConditionIcon}.png")
                               .AddField("Temperature", (int)weatherData.TemperatureAndPressure.Temperature, true)
                               .AddField("Condition", weatherData.Weather.FirstOrDefault().WeatherCondition, true)
                               .AddField("Humidity", $"{weatherData.TemperatureAndPressure.Humidity}%", true)
                               .AddField("High", (int)weatherData.TemperatureAndPressure.MaximumTemperature, true)
                               .AddField("Low", (int)weatherData.TemperatureAndPressure.MinimumTemperature, true)
                               .AddField("Cloud Coverage", $"{weatherData.CloudInfo.CloudCoveragePercent}%", true)
                               .WithFooter(new EmbedFooterBuilder {
                Text = DateTime.Now.ToString("f")
            })
                               .Build();

            return(weatherEmbed);
        }
        public async Task <IActionResult> Tempo()
        {
            //criar e configurar o cliente HTTP
            string baseAddress = "http://api.weatherstack.com/";

            HttpClient cliente = new HttpClient();

            cliente.BaseAddress = new Uri(baseAddress);
            cliente.DefaultRequestHeaders.Accept.Clear();
            cliente.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            string path = "current?access_key=08d9721c9f4a140a938f7325c3402e41&query=Almada";
            HttpResponseMessage response = cliente.GetAsync(path).Result;
            string myJsonResponse        = await response.Content.ReadAsStringAsync();

            WeatherApiResponse apiResponse = JsonConvert.DeserializeObject <WeatherApiResponse>(myJsonResponse);

            return(View(apiResponse));
        }
Ejemplo n.º 7
0
        public async Task <WeatherApiResponse> GetWeatherAsync(string q)
        {
            try
            {
                var finalResult = new WeatherApiResponse();
                var client      = new HttpClient();
                client.BaseAddress = new Uri(BaseURL);
                var res = await client.GetAsync($"forecast?q={q}&appid={appID}");

                if (res.IsSuccessStatusCode)
                {
                    var results = res.Content.ReadAsStringAsync().Result;
                    finalResult = JsonConvert.DeserializeObject <WeatherApiResponse>(results, jsonOptions);
                }

                return(finalResult);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Ejemplo n.º 8
0
        public WeatherApiResponse GetWeather(WeatherRequest request)
        {
            var weatherApiResponse = new WeatherApiResponse
            {
                ErrorMessage = string.Empty
            };

            var response = _communicationService
                           .Get <WeatherApiResponse>(
                $"forecast?q={request.CityName}" +
                $"&units=metric" +
                $"&APPID={appID}");

            if (response.Exception != null)
            {
                weatherApiResponse.ErrorMessage = response.Exception.InnerException.Message;
            }
            else
            {
                weatherApiResponse = response.Result;
            }

            return(weatherApiResponse);
        }
Ejemplo n.º 9
0
 public FetchWeatherNotification(FetchWeatherQuery fetchWeatherQuery, WeatherApiResponse weatherApiResponse)
 {
     FetchWeatherQuery  = fetchWeatherQuery;
     WeatherApiResponse = weatherApiResponse;
 }
Ejemplo n.º 10
0
        public async Task <IActionResult> Index()
        {
            var resApi        = new WeatherApiResponse();
            var displayResApi = new WeatherApiResponse();

            try {
                if (SignInManager.IsSignedIn(User))
                {
                    var                       loggedInUser            = HttpContext.Session.GetString(ApplicationVariables.SessionVariables.UserEmail);
                    List <string>             listOfCities            = new List <string>();
                    List <WeatherApiResponse> weatherApiResponsesList = new List <WeatherApiResponse>();
                    List <Employee>           listOfEmployees         = _userRepositoriesInterface.GetEmployees();
                    //Fetch cities stored in database
                    var cities = _userRepositoriesInterface.GetCities();

                    //populatelist of cities
                    if (listOfEmployees != null && listOfEmployees.Count > 0)
                    {
                        foreach (var emp in listOfEmployees)
                        {
                            listOfCities.Add(_userRepositoriesInterface.GetEmployeeByEmail(emp.Email).City.CityName);
                        }
                    }

                    //checks if city list is empty
                    if (listOfCities != null && listOfEmployees.Count > 0)
                    {
                        List <string> cityDataFetched = new List <string>();
                        //populate list of weatherdata responses per city
                        foreach (var city in listOfCities)
                        {
                            //Fetch data from api
                            if (!cityDataFetched.Contains(city))
                            {
                                resApi = await _weatherInterface.GetWeatherAsync(city);

                                if (resApi.list != null)
                                {
                                    weatherApiResponsesList.Add(resApi);
                                    cityDataFetched.Add(city);
                                }
                            }
                        }
                    }

                    //checks if weatherlist is empty
                    if (weatherApiResponsesList != null && weatherApiResponsesList.Count > 0)
                    {
                        //populate weather data to be displayed for current users city
                        foreach (var emp in listOfEmployees)
                        {
                            if (emp.Email.ToLower().Trim() == loggedInUser.ToLower().Trim())
                            {
                                foreach (var weather in weatherApiResponsesList)
                                {
                                    int cityID = -1;
                                    cityID = cities.Where(x => x.CityName.Contains(weather.city.name.Trim()))
                                             .FirstOrDefault().ID;

                                    if (emp.CityID == cityID && emp.Email.ToLower().Trim() == loggedInUser.ToLower().Trim())
                                    {
                                        displayResApi.list = new List <List>();
                                        //Use data from db
                                        foreach (var item in weather.list)
                                        {
                                            if (Convert.ToDateTime(item.dt_txt).Date >= DateTime.Now.Date)
                                            {
                                                displayResApi.city      = new City();
                                                displayResApi.city.name = weather.city.name;
                                                List list = new List();
                                                list.dt_txt  = item.dt_txt;
                                                list.weather = new List <Weather>();
                                                Weather weatherForList = new Weather();
                                                weatherForList.main        = item.weather[0].main;
                                                weatherForList.description = item.weather[0].description;
                                                list.weather.Add(weatherForList);
                                                displayResApi.list.Add(list);
                                            }
                                        }
                                        break;
                                    }
                                }
                                break;
                            }
                        }

                        foreach (var weather in weatherApiResponsesList)
                        {
                            int cityID = -1;
                            cityID = cities.Where(x => x.CityName.Contains(weather.city.name.Trim()))
                                     .FirstOrDefault().ID;

                            //Fetch Weather Data from db
                            var resFromDB = _weatherRepositoryInterface.GetWeatherDataByCityID(cityID);
                            if (resFromDB != null && resFromDB.Count > 0)
                            {
                                var todaysDate     = DateTime.Now.Date;
                                var tommorrowsDate = DateTime.Now.AddDays(1).Date;
                                //checks to se if there is a record of weather data in db for today
                                var hasTodayWData = resFromDB.Find(x => x.Day.Date == todaysDate);
                                //checks to se if there is a record of weather data in db for the next day
                                var hasTomorrowsWData = resFromDB.Find(x => x.Day.Date == tommorrowsDate);
                                //if there is no data in db for today and tomorrow fetch data from api
                                if (hasTodayWData == null && hasTomorrowsWData == null)
                                {
                                    //Fetch Weather Data from api
                                    resApi = await _weatherInterface.GetWeatherAsync(weather.city.name);

                                    //populate weather info to store in db
                                    foreach (var wData in resApi.list)
                                    {
                                        WeatherInfo weatherInfo = new WeatherInfo();
                                        weatherInfo.Day = Convert.ToDateTime(wData.dt_txt);
                                        if (weatherInfo.Day.Hour == 6)
                                        {
                                            weatherInfo.WeatherDesc = wData.weather[0].main + ": " + wData.weather[0].description;

                                            weatherInfo.CityID = cityID;
                                            //Store Weather data
                                            _weatherRepositoryInterface.StoreWeatherData(weatherInfo);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }catch (Exception ex)
            {
                _logger.LogError("Error:" + ex.Message);
            }
            return(View(displayResApi));
        }