Exemplo n.º 1
0
        /// <summary> Get the Forecast of the Weather of the next 5 days of the selected location </summary>
        /// <param name="location">Use the format CITY,CITY_CODE,COUNTRY</param>
        /// <returns>An instance of the class CityWeather </returns>
        public CityWeather getWeather(string location)
        {
            try
            {
                // Create the URL to make the request
                string url = getUrl(location);

                // Create the new request using the location and the API Key
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;

                // Store the API result as JSON String
                string resultJsonString = "";

                // Execute the request
                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                    // Read the result as an Stream
                    using (Stream stream = response.GetResponseStream())
                        // Reader to get the result as String
                        using (StreamReader reader = new StreamReader(stream))
                        {
                            // String as JSON
                            resultJsonString = reader.ReadToEnd();
                        }

                // Parse the JSON String to a WeatherResult class
                var weatherResult = JsonConvert.DeserializeObject <WeatherResult>(resultJsonString);

                // Create a new instace of CityWeather to return the result
                CityWeather result = new CityWeather();

                // Use LINQ to extract and calculate the forecast per days
                // The API return entries for 5 days, in a range of 3 hours
                // First the list is sorted by date ASC
                // The WHERE clause remove the current day
                // The LINQ group the data per date (without taking consideration the time)
                // The SELECT return the date, the average temp, and if exists or not chance of precipitation
                // TAKE will only return the first 5 days
                var stats = weatherResult
                            .list
                            .OrderBy(measure => measure.date)
                            .Where(measure => measure.date >= DateTime.Today.AddDays(1))
                            .GroupBy(measure => measure.date.ToString("MM/dd/yyyy"))
                            .Select(daily => new CityWeatherPerDay()
                {
                    Date                  = daily.Key,
                    AverageTemp           = Math.Round(daily.Average(m => m.main.temp_average), 2),
                    ChanceOfPrecipitation = daily.Average(m => m.pop) > 0
                })
                            .Take(5);

                result.Id       = weatherResult.city.id;       // Add the City ID
                result.Location = location.Replace(",", ", "); // Beautify the string for final display
                result.WeatherStats.AddRange(stats);           // Add 5 days

                // Return the result
                return(result);
            }
            catch { throw; }
        }
Exemplo n.º 2
0
 private static void printResult(CityWeather res)
 {
     Console.WriteLine("-----------------------------");
     Console.WriteLine(String.Format("{0} ({1})", res.Location, res.Id));
     Console.WriteLine("");
     Console.WriteLine("Date \t\t Avg Temp (F)");
     Console.WriteLine("-----------------------------");
     res.WeatherStats.ForEach(stat =>
     {
         string precipitation = stat.ChanceOfPrecipitation ? "*" : " ";
         Console.WriteLine(String.Format("{0}{1} \t {2}°", stat.Date, precipitation, stat.AverageTemp.ToString("#,##0.00")));
     });
     Console.WriteLine("");
 }
Exemplo n.º 3
0
        public static void Main()
        {
            GetWeather api = new GetWeather(API_KEY);

            Console.WriteLine("Current datetime: " + DateTime.Now.ToString("g") + "/n");

            foreach (var location in LOCATIONS)
            {
                try
                {
                    CityWeather result = api.getWeather(location);
                    printResult(result);
                }
                catch (Exception)
                {
                    Console.WriteLine("Something goes wrong when the application search the location: " + location);
                }
            }
        }