private WeatherResponse GetWeatherData()
        {
            var rnd = new Random();

            var res = new WeatherResponse
            {
                Temperature = (float)(rnd.NextDouble() * 100.0),
                WindSpeed   = (float)(rnd.NextDouble() * 50.0),
                RainAmount  = (float)(rnd.NextDouble() * 10.0)
            };

            return(res);
        }
        private WeatherResponse Transform(string Daily, string Hourly)
        {
            WeatherResponse response = new WeatherResponse();
            string          shortDescription;
            JObject         item = JObject.Parse(Hourly);
            var             X    = item["properties"]["periods"][0];

            shortDescription            = X.Value <string>("shortForecast");
            response.Temp               = X.Value <int>("temperature");
            response.ForcastDescription = DetailedForcast(Daily);
            response.WType              = convert(shortDescription);
            response.OptionalLink       = $"https://forecast.weather.gov/MapClick.php?lat={LatLong.Latitude}&lon={LatLong.Longitude}";
            return(response);
        }
        private void UpdateForm(WeatherResponse weatherResponse)
        {
            City.Text = weatherResponse.Location;
            WeatherIcon.Load(weatherResponse.WeartherUri);
            Temperature.Text = (weatherResponse.Temperature == -432) ? "9K" : weatherResponse.Temperature.ToString();
            WeatherText.Text = weatherResponse.WeatherText;
            Pressure.Text    = $"{weatherResponse.Pressure.ToString()} in";
            Wind.Text        = $"{weatherResponse.WindSpeed.ToString()} mph";
            Humidity.Text    = $"{weatherResponse.RelativeHumidity.ToString()} %";
            UVIndex.Text     = weatherResponse.UVIndex.ToString();
            var localTime = weatherResponse.RetrievedDateTimeOffset.ToLocalTime();

            Updated.Text = $"Updated at {localTime.ToString("h:mm:ss tt")}";
        }
Beispiel #4
0
 public WeatherViewModel(WeatherResponse weather)
 {
     Coord   = weather.Coord;
     Weather = new ObservableCollection <Weather>(weather.Weather);
     Base    = weather.Base;
     Main    = weather.Main;
     Wind    = weather.Wind;
     Clouds  = weather.Clouds;
     Dt      = weather.Dt;
     Sys     = weather.Sys;
     Id      = weather.Id;
     Name    = weather.Name;
     Cod     = weather.Cod;
 }
        public async Task <IActionResult> GetColdestCity()
        {
            WeatherResponse weatherResponse = await _weatherServiceRepository.GetForecastForAllCities();

            var queryLowest  = weatherResponse.Data.OrderByDescending(c => c.TMin).FirstOrDefault();
            var queryLowest2 = weatherResponse.Data.FirstOrDefault(m => m.TMin == weatherResponse.Data.Min(a => a.TMin));

            UserViewModel vmObject = new UserViewModel();

            vmObject.Query             = new Query();
            vmObject.Query.querySingle = queryLowest;

            return(RedirectToAction("(PartialView)", "IpmaWeatherService", vmObject));
        }
Beispiel #6
0
        public async Task <WeatherResponse> GetWeatherByCityBl(string city)
        {
            WeatherResponse response = null;

            try
            {
                response = await _weatherDataService.GetWeatherByCityAsync(city);
            }
            catch (Exception)
            {
                // ignored
            }
            return(response);
        }
        public void GetWeather(string zipCode)
        {
            // assemble
            WeatherRequest req = new WeatherRequest {
                ZipCode = zipCode
            };
            WeatherWorker worker = new WeatherWorker();

            // act
            WeatherResponse response = worker.GetWeather(req);

            // assert
            Assert.IsNotNull(response);
        }
 private void Initialization(WeatherResponse result)
 {
     CompleteWeatherList = result.list.ToList();
     Lat     = result.city.coord.lat.ToString();
     Long    = result.city.coord.lon.ToString();
     Country = result.city.country;
     foreach (var item in CompleteWeatherList)
     {
         Dates.Add(new DateList()
         {
             Date_Time = item.dt_txt
         });
     }
 }
Beispiel #9
0
        public async Task Write(WeatherResponse weatherResponse)
        {
            string filePath = fileOptions.Path.Replace("{date}", DateTime.Now.ToShortDateString());

            string text = "Температура:" + weatherResponse.Temperature.ToString() + ", " +
                          "Скорость ветра:" + weatherResponse.WindSpeed.ToString() + ", " +
                          "Направление ветра:" + weatherResponse.WindDirection.ToString() + ", " +
                          "Сервис:" + weatherResponse.WheatherService.ToString();

            using (StreamWriter streamWriter = new StreamWriter(filePath, true, Encoding.UTF8))
            {
                await streamWriter.WriteLineAsync(text);
            }
        }
Beispiel #10
0
    internal async Task <WeatherResponse> GetWeatherByCityNameAsObject(string city)
    {
        WeatherResponse result   = null;
        string          apiQuery = $"/data/2.5/weather?q={city}&appid={_apiKey}";

        HttpResponseMessage response = await client.GetAsync(apiQuery);

        if (response.IsSuccessStatusCode)
        {
            result = await response.Content.ReadAsAsync <WeatherResponse>();
        }

        return(result);
    }
Beispiel #11
0
 public WeatherViewModel Build(WeatherResponse weatherResponse)
 {
     return(new WeatherViewModel()
     {
         LocationName = weatherResponse.Name,
         Humidity = weatherResponse.main.Humidity,
         Maximum = weatherResponse.main.TempMax,
         Minimum = weatherResponse.main.TempMin,
         Pressure = weatherResponse.main.Pressure,
         Temperature = weatherResponse.main.Temp,
         Sunrise = weatherResponse.sys.Sunrise,
         Sunset = weatherResponse.sys.Sunset,
     });
 }
        static void Main(string[] args)
        {
            //Configure the client by setting the API Key. Get yours at http://www.wunderground.com
            WUnderground.Client.WUndergroundClient.Config.ApiKey = ConfigurationSettings.AppSettings["ApiKey"];

            //Get the current weather conditions for the specified location
            WeatherResponse current = WUndergroundClient.GetConditionsForLocationAsync(51.4800, 0.0).Result;

            Debug.WriteLine(current.current_observation.feelslike_string);

            //Get the weather forecast for the specified location
            WeatherResponse forecast = WUndergroundClient.GetConditionsAndForecastForLocationAsync(51.4800, 0.0).Result;

            Debug.WriteLine(forecast.forecast.txt_forecast.forecastday[0].fcttext);
        }
        private static WeatherResponse ToWeatherResponse(Weather weather)
        {
            var weatherResponse = new WeatherResponse
            {
                Location = weather.Location,
                LocalObservationDateTime = Timestamp.FromDateTimeOffset(weather.LocalObservationDateTime),
                WeatherText           = weather.WeatherText,
                WeatherIconUrl        = weather.WeatherIconUrl,
                Temperature           = weather.Temperature,
                PastDayMaxTemperature = weather.PastDayMaxTemperature,
                PastDayMinTemperature = weather.PastDayMinTemperature
            };

            return(weatherResponse);
        }
Beispiel #14
0
        ISharedResponse ISharedInterface.Invoke()
        {
            WeatherResponse response = new WeatherResponse();

            try
            {
                httpResponseHourly = SharedObjects.CompressedCallSite($"https://api.weather.gov/gridpoints/{StationID}/{Grid.Latitude.ToString()},{Grid.Longitude.ToString()}/forecast/hourly", Gov_User);
                httpResponseDaily  = SharedObjects.CompressedCallSite($"https://api.weather.gov/gridpoints/{StationID}/{Grid.Latitude.ToString()},{Grid.Longitude.ToString()}/forecast", Gov_User);
                response           = Transform(httpResponseDaily, httpResponseHourly);
                LastUpdated        = DateTime.Now;
                _ThrownException   = null;
            }
            catch (Exception x) { _ThrownException = x; _errors = x.ToString(); }
            return(response);
        }
Beispiel #15
0
        public void GetWthBy_CtName_StateCode(string strUrl)
        {
            //string strUrl = String.Format("http://api.openweathermap.org/data/2.5/weather?q=Ha Noi&appid=2f45ec1571c6451311ed3c4b5937678b");

            HttpClientUtils httpClient   = new HttpClientUtils();
            var             httpResponse = httpClient.SendGetRequest(strUrl);

            //convert response to String
            string responseBody = new StreamReader(httpResponse.GetResponseStream()).ReadToEnd().Replace("base", "baseAtt");

            //convert response from string to Json
            WeatherResponse response = JsonConvert.DeserializeObject <WeatherResponse>(responseBody);

            Console.WriteLine();
        }
        public ActionResult Index()
        {
            WeatherWidgetProperties properties = GetProperties();
            var model = new WeatherWidgetViewModel();


            if (String.IsNullOrEmpty(properties.City))
            {
                model.IsCitySelected = false;
                model.Error_msg      = "Please select the City";
            }
            else
            {
                try
                {
                    model.IsCitySelected = true;
                    model.Units          = properties.Units;
                    model.City           = properties.City;
                    string URL = String.Format("http://api.openweathermap.org/data/2.5/weather?q={0}&units={1}&APPID={2}", model.City, model.Units, API_ID);


                    var client = new WebClient();
                    client.Encoding = Encoding.UTF8;
                    string jsonData = client.DownloadString(URL);

                    WeatherResponse response = JsonConvert.DeserializeObject <WeatherResponse>(jsonData);

                    model.City         = response.name;
                    model.Temp         = (int)Math.Round(response.main.temp);
                    model.Pressure     = "Pressure: " + response.main.pressure.ToString() + " kPa";
                    model.Humidity     = "Humidity: " + response.main.humidity.ToString() + " %";
                    model.Temp_max     = (int)Math.Round(response.main.temp_max);
                    model.Temp_min     = (int)Math.Round(response.main.temp_min);
                    model.Weather_Icon = response.weather[0].icon + ".png";

                    // private method -> Gets unitType string and sets model to (°C / °K / °F)
                    model.Unit_Type = Get_Unit_Type(properties.Units);
                }
                catch (Exception e) // in case of wrong input (non-existing city)
                {
                    model.IsCitySelected = false;
                    model.Error_msg      = e.Message;
                }
            }


            return(PartialView("Widgets/_WeatherWidget", model));
        }
Beispiel #17
0
        public async Task <WeatherResponse> GetWeather(string cityName)
        {
            WeatherResponse result = null;

            var url      = BaseUrl + cityName + UrlQueryString;
            var response = await _httpClient.GetAsync(url);

            if (response.IsSuccessStatusCode)
            {
                var responseBody = await response.Content.ReadAsStringAsync();

                result = JsonConvert.DeserializeObject <WeatherResponse>(responseBody);
            }

            return(result);
        }
Beispiel #18
0
        private void GetWeatherItems(WeatherResponse data)
        {
            WeatherItems.Add(new WeatherItem("Wind", $"{data.Wind.Speed} km/h "));
            WeatherItems.Add(new WeatherItem("Cloudiness", $"{data.Clouds.All} %"));
            WeatherItems.Add(new WeatherItem("Pressure", $"{data.Main.Pressure} hpa"));
            WeatherItems.Add(new WeatherItem("Humidity", $"{data.Main.Humidity} %"));
            WeatherItems.Add(new WeatherItem("Sunrise", DateTimeHelper.GetDateString(data.Sys.Sunrise, DateTimeHelper.DateTimeFormat.Time, true)));
            WeatherItems.Add(new WeatherItem("Sunset", DateTimeHelper.GetDateString(data.Sys.Sunset, DateTimeHelper.DateTimeFormat.Time, true)));
            WeatherItems.Add(new WeatherItem("Coords", $"{data.Coord.Lon}, {data.Coord.Lat}"));

            for (var i = 0; i < WeatherItems.Count; i++)
            {
                var isOdd = !(i % 2 == 0);
                WeatherItems[i].OddColor = isOdd;
            }
        }
        public void WeatherResponseShouldCreateCorrectIconSrc()
        {
            var response = new WeatherResponse
            {
                Country            = "NO",
                Description        = "aaa",
                Icon               = "test",
                MainWeather        = "bbb",
                Name               = "ccc",
                TemperatureCurrent = 22.2,
                TemperatureMaximum = 24,
                TemperatureMinimum = 19,
            };

            Assert.Equal("http://openweathermap.org/img/wn/[email protected]", response.IconSrc);
        }
Beispiel #20
0
        public async Task <string> Get(string lat, string lon)
        {
            var coords = new GeoCoordinate(lat, lon);

            var geoTask      = _geoQueryService.ReverseQuery(coords);
            var forecastTask = _weatherQueryService.Query(coords);

            await Task.WhenAll(new Task[] { geoTask, forecastTask });

            var geo      = await geoTask;
            var forecast = await forecastTask;

            var resp = new WeatherResponse(geo, forecast);

            return(JsonConvert.SerializeObject(resp));
        }
Beispiel #21
0
        private async Task <WeatherResponse> GetWeather(string arg)
        {
            WeatherResponse weatherResponse = null;

            // `units=metric` faz com que a resposta siga o sistema de métrica internacional.
            var response = await _client.GetAsync($"weather?{arg}&units=metric&appid={_apiKey}");

            if (response.IsSuccessStatusCode)
            {
                var json = await response.Content.ReadAsStringAsync();

                weatherResponse = JsonConvert.DeserializeObject <WeatherResponse>(json);
            }

            return(weatherResponse);
        }
Beispiel #22
0
        // GET: ForecastApp/City
        public IActionResult City(string city)
        {
            WeatherResponse weatherResponse = _weatherForecastRepository.GetForecast(city);
            City            viewModel       = new City();

            if (weatherResponse != null)
            {
                viewModel.Name     = weatherResponse.Name;
                viewModel.Humidity = weatherResponse.Main.Humidity;
                viewModel.Pressure = weatherResponse.Main.Pressure;
                viewModel.Temp     = weatherResponse.Main.Temp;
                viewModel.Weather  = weatherResponse.Weather[0].Main;
                viewModel.Wind     = weatherResponse.Wind.Speed;
            }
            return(View(viewModel));
        }
        public async Task <IActionResult> Weather(string city)
        {
            WeatherResponse weatherResponse = null;

            try
            {
                HttpClient          client          = _httpClientFactory.CreateClient("weather");
                HttpResponseMessage responseMessage = await client.GetAsync($"/data/2.5/weather?q={city}&units=metric&appid={AppId}");

                responseMessage.EnsureSuccessStatusCode();
                string result = await responseMessage.Content.ReadAsStringAsync();

                weatherResponse = JsonConvert.DeserializeObject <WeatherResponse>(result);
            }
            catch (HttpRequestException)
            {
                return(View("Error"));
            }
            DateTime      now    = DateTime.Now;
            CookieOptions option = new CookieOptions
            {
                Expires = now.AddDays(1)
            };

            Response.Cookies.Append("LastCity", city, option);
            WeatherViewModel weatherViewModel = new WeatherViewModel()
            {
                Precipitation = string.Join(", ", weatherResponse.Weather.Select(w => w.Main)),
                HighestTemp   = weatherResponse.Main.Temp_max,
                LowestTemp    = weatherResponse.Main.Temp_min,
            };

            ViewData["LastCity"] = city;

            if (!Request.Cookies.ContainsKey($"{city}WarningMessage"))
            {
                foreach (Weather weather in weatherResponse.Weather)
                {
                    if (weather.Main == "Rain")
                    {
                        Response.Cookies.Append($"{city}WarningMessage", city, option);
                        ViewData["WarningMessage"] = "Today is rainy!";
                    }
                }
            }
            return(View(weatherViewModel));
        }
Beispiel #24
0
        public ActionResult Index()
        {
            var reddit = new Reddit();
            //var user = reddit.LogIn("EddieValiantsRabbit", "camaro");
            var all = reddit.GetSubreddit("/r/news");

            var listOfPosts = all.Hot.Take(25);

            ViewBag.Posts = new List <RedditSharp.Things.Post>();
            ViewBag.Posts = listOfPosts;

            ViewBag.Greeting = "Good " + SpareParts.DeterminePartOfDay();
            WebRequest weatherRequest = WebRequest.Create(@"http://api.openweathermap.org/data/2.5/weather?zip=94040,us&appid=8b3de9d1132f5c7199d2650d858cef68");

            weatherRequest.ContentType = "application/json; charset=utf-8";

            WeatherResponse jsonResponse = new WeatherResponse();

            using (HttpWebResponse weatherResponse = weatherRequest.GetResponse() as HttpWebResponse)
            {
                if (weatherResponse.StatusCode != HttpStatusCode.OK)
                {
                    throw new Exception(String.Format(
                                            "Server error (HTTP {0}: {1}).",
                                            weatherResponse.StatusCode,
                                            weatherResponse.StatusDescription));
                }
                DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof(WeatherResponse));
                object objResponse = jsonSerializer.ReadObject(weatherResponse.GetResponseStream());
                jsonResponse
                    = objResponse as WeatherResponse;
            }


            ViewBag.CurrentMonth       = SpareParts.GetCurrentMonth(DateTime.Now.Month);
            ViewBag.CurrentDayOfMonth  = DateTime.Now.Day;
            ViewBag.CurrentDayOfWeek   = DateTime.Now.DayOfWeek;
            ViewBag.CurrentHour        = DateTime.Now.Hour;
            ViewBag.CurrentMinute      = DateTime.Now.Minute;
            ViewBag.CurrentSecond      = DateTime.Now.Second;
            ViewBag.CurrentTemp        = (jsonResponse.main.Temp - 273.15) * 1.8 + 32;
            ViewBag.WeatherDescription = jsonResponse.weather[0].Description;



            return(View());
        }
Beispiel #25
0
        public ActionResult Index()
        {
            HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url);

            HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();

            string response;

            using (StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream()))
            {
                response = streamReader.ReadToEnd();
            }

            WeatherResponse weatherResponse = JsonConvert.DeserializeObject <WeatherResponse>(response);

            return(View(weatherResponse));
        }
Beispiel #26
0
        public async Task <WeatherResponse> GetWeatherData(string query)
        {
            WeatherResponse weatherData = null;

            var response = await _client.GetAsync(query);

            if (response.IsSuccessStatusCode)
            {
                var content = await response.Content.ReadAsStringAsync();

                weatherData = JsonConvert.DeserializeObject <WeatherResponse>(content);
            }



            return(weatherData);
        }
        public void Weather()
        {
            string          url             = "http://api.openweathermap.org/data/2.5/weather?q=Minsk&units=metric&appid=1d6de5c626ed1f4cef6c29a6e70b6944";
            HttpWebRequest  httpWebRequest  = (HttpWebRequest)WebRequest.Create(url);
            HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
            string          response;

            using (StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream()))
            {
                response = streamReader.ReadToEnd();
            }
            WeatherResponse weatherResponse = JsonConvert.DeserializeObject <WeatherResponse>(response);

            Console.ForegroundColor = ConsoleColor.Yellow;
            Console.WriteLine("Temperature in {0}: {1} °C", weatherResponse.Name, weatherResponse.Main.Temp);
            Console.ResetColor();
        }
Beispiel #28
0
        private static void Request()
        {
            string url = "http://api.openweathermap.org/data/2.5/weather?q=Astana&units=metric&appid=[your_app_id]";

            HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url);

            HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();

            string response;

            using (StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream()))
            {
                response = streamReader.ReadToEnd();
            }

            WeatherResponse weatherResponse = JsonConvert.DeserializeObject <WeatherResponse>(response);
        }
Beispiel #29
0
        // GET: ForecastApp/City .  se o estado acima for valido, o return vai chamar este get.
        public IActionResult City(string city)
        {
            // Consume the OpenWeatherAPI in order to bring Forecast data in our page.
            WeatherResponse weatherResponse = _forecastRepository.GetForecast(city);
            City            viewModel       = new City();

            if (weatherResponse != null)
            {
                viewModel.Name     = weatherResponse.Name;
                viewModel.Humidity = weatherResponse.Main.Humidity;
                viewModel.Pressure = weatherResponse.Main.Pressure;
                viewModel.Temp     = weatherResponse.Main.Temp;
                viewModel.Weather  = weatherResponse.Weather[0].Main;
                viewModel.Wind     = weatherResponse.Wind.Speed;
            }
            return(View(viewModel));
        }
Beispiel #30
0
        public IEnumerable <string> OpenWeatherMap()
        {
            string url = "http://api.openweathermap.org/data/2.5/weather?q=Kharkiv&units=metric&appid=4beac4fe0313cea3e96ed0ad0fa10244";

            HttpWebRequest  httpWebRequest  = (HttpWebRequest)WebRequest.Create(url);
            HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();

            string response;

            using (StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream()))
            {
                response = streamReader.ReadToEnd();
            }
            WeatherResponse weatherResponse = JsonConvert.DeserializeObject <WeatherResponse>(response);

            return(new string[] { weatherResponse.Name, weatherResponse.Main.Temp.ToString() });
        }