Esempio n. 1
0
        private async Task GetWeatherInfo()
        {
            //You apiKey
            string apiKey = "";
            string city   = "Daejeon";

            string url = string.Format("http://api.openweathermap.org/data/2.5/weather?q={0}&appid={1}", city, apiKey);

            var    httpClient = new HttpClient();
            string json       = await httpClient.GetStringAsync(url);

            OpenWeatherMap info = JsonConvert.DeserializeObject <OpenWeatherMap>(json);

            string iconFilename = GetCurrentWeatherIcon(info.weather[0].icon);
            string svgFile      = Path.Combine(_hostEnv.ContentRootPath, "climacons", iconFilename);

            CurrentWeatherIcon = System.IO.File.ReadAllText($"{svgFile}");

            DayWeatherSummary  = UppercaseFirst(info.weather[0].description);
            WeatherAttribution = "Powered by Open Weather";
            CurrentTemp        = Round(info.main.temp - 273.15).ToString() + "℃";
            CurrentMinTemp     = Round(info.main.temp_min - 273.15).ToString() + "℃";
            CurrentMaxTemp     = Round(info.main.temp_max - 273.15).ToString() + "℃";
            CurrentPressure    = info.main.pressure.ToString() + " aPh";
            CurrentHumidity    = info.main.humidity.ToString() + "%";
            CurrentWindSpeed   = info.wind.speed.ToString() + "m/s";
            CurrentWindDir     = info.wind.deg.ToString() + " degree";
            CurrentCloudiness  = info.clouds.all.ToString() + "%";
            CurrentSunrise     = ConvertUnixtimeToGMT(info.sys.sunrise).ToString("tt hh:mm:ss");
            CurrentSunset      = ConvertUnixtimeToGMT(info.sys.sunset).ToString("tt hh:mm:ss");

            DateTime ConvertUnixtimeToGMT(int unixTime)
            {
                DateTime dtDateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);

                dtDateTime = dtDateTime.AddSeconds(unixTime).ToLocalTime();

                return(dtDateTime);
            }

            string UppercaseFirst(string s)
            {
                char[] a = s.ToCharArray();
                a[0] = char.ToUpper(a[0]);
                return(new string(a));
            }
        }
Esempio n. 2
0
        public OpenWeatherMap WeatherApICall(OpenWeatherMap openWeatherMap, string cities)
        {
            if (cities != null)
            {
                try
                {
                    /*Calling API http://openweathermap.org/api */
                    string         apiKey     = "aa69195559bd4f88d79f9aadeb77a8f6";
                    HttpWebRequest apiRequest =
                        WebRequest.Create("http://api.openweathermap.org/data/2.5/weather?id=" +
                                          cities + "&appid=" + apiKey + "&units=metric") as HttpWebRequest;

                    string apiResponse = "";
                    using (HttpWebResponse response = apiRequest.GetResponse() as HttpWebResponse)
                    {
                        StreamReader reader = new StreamReader(response.GetResponseStream());
                        apiResponse = reader.ReadToEnd();
                    }
                    /*End*/

                    /*http://json2csharp.com*/
                    ResponseWeather rootObject = JsonConvert.DeserializeObject <ResponseWeather>(apiResponse);

                    StringBuilder sb = new StringBuilder();
                    sb.Append("<table class=\"col-md-4\" ><tr><th>Weather Description</th></tr>");
                    sb.Append("<tr><td>City:</td><td>" +
                              rootObject.name + "</td></tr>");
                    sb.Append("<tr><td>Country:</td><td>" +
                              rootObject.sys.country + "</td></tr>");
                    sb.Append("<tr><td>Wind:</td><td>" +
                              rootObject.wind.speed + " Km/h</td></tr>");
                    sb.Append("<tr><td>Current Temperature:</td><td>" +
                              rootObject.main.temp + " °C</td></tr>");
                    sb.Append("<tr><td>Humidity:</td><td>" +
                              rootObject.main.humidity + "</td></tr>");
                    sb.Append("<tr><td>Weather:</td><td>" +
                              rootObject.weather[0].description + "</td></tr>");
                    sb.Append("</table>");
                    openWeatherMap.apiResponse = sb.ToString();
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }
            return(openWeatherMap);
        }
        public static List <TempData> GetTempForecast()
        {
            List <TempData> temperatures = new List <Models.TempData>();

            OpenWeatherMap lWeather = GetLocalWeather();

            foreach (var item in lWeather.list)
            {
                temperatures.Add(new Models.TempData
                {
                    dt           = DateTime.Parse(item.dt_txt),
                    temperatureC = (Math.Round(item.main.temp)),
                    humidity     = (double)item.main.humidity
                });
            }
            return(temperatures);
        }
        private static List <WindData> GetWindForecast()
        {
            List <WindData> windSpeed = new List <WindData>();
            OpenWeatherMap  lWeather  = GetLocalWeather();

            foreach (var item in lWeather.list)
            {
                windSpeed.Add(new Models.WindData
                {
                    dt         = DateTime.Parse(item.dt_txt),
                    windSpeed  = (double)(item.wind.speed) * 3.6,
                    windDir    = (double)item.wind.deg,
                    cloudCover = (int)item.clouds.all
                });;
            }
            return(windSpeed);
        }
Esempio n. 5
0
        // Samtale med Kian hjalp med at udforme de næste to metoder
        public string GetTempatureBasedOnCity(string city)
        {
            OpenWeatherMap weatherMap = new OpenWeatherMap();

            weatherMap.AppId = "3654de113ecd4a2bf4e4144d9403491b";
            weatherMap.City  = city;
            double temp = 0.0;

            try
            {
                temp = weatherMap.GetTempature();
            }
            catch (WebException)
            {
                return("N/A");
            }
            return($"{temp}°");
        }
Esempio n. 6
0
        private List <WeatherForecast> GetAndMap(OpenWeatherMap model)
        {
            var res = new List <WeatherForecast>();

            foreach (var item in model.list.Where(i => i.Date > DateTime.Now).Take(6))
            {
                res.Add(new WeatherForecast
                {
                    DateFormatted = item.Date.ToLongTimeString(),
                    Description   = item.WeatherItem.description,
                    Temp          = item.main.temp,
                    TempMin       = item.main.temp_min,
                    TempMax       = item.main.temp_max,
                    City          = model.city.name,
                });
            }
            return(res);
        }
Esempio n. 7
0
        /*city data for each of the corresponding radio buttons
         * first value is going to display as the name
         * second value going to be what goes into the API, dont touch unless going to change API*/
        public OpenWeatherMap FillCity()
        {
            OpenWeatherMap openWeatherMap = new OpenWeatherMap();

            openWeatherMap.cities = new Dictionary <string, string>();
            openWeatherMap.cities.Add("Marlboro, MA", "Marlboro");
            openWeatherMap.cities.Add("San Diego, CA", "San Diego");
            openWeatherMap.cities.Add("Cheyenne, WY", "Cheyenne");
            openWeatherMap.cities.Add("Anchorage, AK", "Anchorage");
            openWeatherMap.cities.Add("Austin, TX", "Austin");
            openWeatherMap.cities.Add("Orlando, FL", "Orlando");
            openWeatherMap.cities.Add("Seattle, WA", "Seattle");
            openWeatherMap.cities.Add("Cleveland, OH", "Cleveland");
            openWeatherMap.cities.Add("Portland, ME", "Portland");
            openWeatherMap.cities.Add("Honolulu, HI", "Honolulu");

            return(openWeatherMap);
        }
Esempio n. 8
0
        public string GetWeatherIconBasedOnCity(string city)
        {
            OpenWeatherMap weatherMap = new OpenWeatherMap();

            weatherMap.AppId = "3654de113ecd4a2bf4e4144d9403491b";
            weatherMap.City  = city;
            string icon;

            try
            {
                icon = weatherMap.GetWeatherIcon();
            }
            catch (WebException)
            {
                return("N/A");
            }
            return($"{icon}");
        }
        public ActionResult Index(string cities)
        {
            OpenWeatherMap openWeatherMap = FillCity();

            if (cities != null)
            {
                /*Calling API http://openweathermap.org/api */
                string         apiKey     = "de6d52c2ebb7b1398526329875a49c57";
                HttpWebRequest apiRequest = WebRequest.Create("http://api.openweathermap.org/data/2.5/weather?q=" + cities + "&appid=" + apiKey) as HttpWebRequest;

                string apiResponse = "";
                using (HttpWebResponse response = apiRequest.GetResponse() as HttpWebResponse)
                {
                    StreamReader reader = new StreamReader(response.GetResponseStream());
                    apiResponse = reader.ReadToEnd();
                }
                /*End*/

                /*http://json2csharp.com*/
                ResponseWeather rootObject = JsonConvert.DeserializeObject <ResponseWeather>(apiResponse);

                StringBuilder sb = new StringBuilder();
                sb.Append("<table><tr><th>Weather Description</th></tr>");
                sb.Append("<tr><td>Location:</td><td>" + rootObject.name + "</td></tr>");
                sb.Append("<tr><td>Country:</td><td>" + rootObject.sys.country + "</td></tr>");
                sb.Append("<tr><td>Wind:</td><td>" + rootObject.wind.speed + " Km/h</td></tr>");
                sb.Append("<tr><td>Visibility:</td><td>" + rootObject.visibility + "</td></tr>");
                sb.Append("<tr><td>Sky Conditions:</td><td>" + rootObject.weather[0].description + "</td></tr>");
                sb.Append("<tr><td>Current Temperature:</td><td>" + rootObject.main.temp + "</td></tr>");
                sb.Append("<tr><td>Relative Humidity:</td><td>" + rootObject.main.humidity + "</td></tr>");
                sb.Append("<tr><td>Dew Point:</td><td>" + rootObject.dt + "</td></tr>");
                sb.Append("<tr><td>Pressure:</td><td>" + rootObject.main.pressure + "</td></tr>");
                sb.Append("</table>");
                openWeatherMap.apiResponse = sb.ToString();
            }
            else
            {
                if (Request.Form["submit"] != null)
                {
                    openWeatherMap.apiResponse = "Select City";
                }
            }
            return(View(openWeatherMap));
        }
        public OpenWeatherMap FillCity()
        {
            OpenWeatherMap openWeatherMap = new OpenWeatherMap
            {
                Cities = new Dictionary <string, string>()
            };

            openWeatherMap.Cities.Add("2643741", "City of London");
            openWeatherMap.Cities.Add("2988507", "Paris");
            openWeatherMap.Cities.Add("2964574", "Dublin");
            openWeatherMap.Cities.Add("4229546", "Washington");
            openWeatherMap.Cities.Add("5128581", "New York");
            openWeatherMap.Cities.Add("1273294", "Delhi");
            openWeatherMap.Cities.Add("1275339", "Mumbai");
            openWeatherMap.Cities.Add("6539761", "Rome");
            openWeatherMap.Cities.Add("2950159", "Berlin");
            openWeatherMap.Cities.Add("292223", "Dubai");
            return(openWeatherMap);
        }
Esempio n. 11
0
        static async Task <OpenWeatherMap> GetWeatherAsync(string path)
        {
            var client = new HttpClient();

            client.BaseAddress = new Uri("http://localhost:58617/");
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(
                new MediaTypeWithQualityHeaderValue("application/json"));

            OpenWeatherMap      weather  = null;
            HttpResponseMessage response = await client.GetAsync(path);

            if (response.IsSuccessStatusCode)
            {
                weather = await response.Content.ReadAsAsync <OpenWeatherMap>();
            }

            return(weather);
        }
Esempio n. 12
0
        public int ProcessWeatherInfo()
        {
            DirectoryInfo parentFolder;

            if (FileBeingProcessed.CitiesInFile != null & FileBeingProcessed.CitiesInFile.Count() > 0)
            {
                OpenWeatherMap openWeatherAPI = new OpenWeatherMap(new OpenWeatherAPIClient());
                parentFolder = FileUtility.CreaeFolderStructure(FileBeingProcessed.FileOutputDestination);
                Parallel.ForEach(FileBeingProcessed.CitiesInFile, (city) =>
                {
                    PresentWeather currentWeatherOfCity = openWeatherAPI.GetCurrentWeather(city.ZipCode);
                    FileUtility.WriteToJsonFile <PresentWeather>($"{parentFolder.FullName}\\{city.Name}.txt", currentWeatherOfCity);
                });
            }
            else
            {
                return(0);
            }
            return(FileBeingProcessed.CitiesInFile.Count());
        }
Esempio n. 13
0
            protected override void OnPostExecute(string result)
            {
                base.OnPostExecute(result);
                if (result.Contains("Error: Not found city"))
                {
                    pd.Dismiss();
                    return;
                }

                openWeatherMap = JsonConvert.DeserializeObject <OpenWeatherMap>(result);
                pd.Dismiss();

                //Control
                activity.txtCity        = activity.FindViewById <TextView>(Resource.Id.txtCity);
                activity.txtLastUpdate  = activity.FindViewById <TextView>(Resource.Id.txtLastUpdate);
                activity.txtDescription = activity.FindViewById <TextView>(Resource.Id.txtDescription);
                activity.txtHumidity    = activity.FindViewById <TextView>(Resource.Id.txtHumidity);
                activity.txtTime        = activity.FindViewById <TextView>(Resource.Id.txtTime);
                activity.txtCelsius     = activity.FindViewById <TextView>(Resource.Id.txtCelsius);
            }
        public ActionResult weatherForecast(OpenWeatherMap openWeatherMap, string cities)
        {
            openWeatherMap = FillCity();

            if (cities != null)
            {
                /*Calling API http://openweathermap.org/api */
                string         apiKey     = "c5ca5fc08600882248efe12926c6d411";
                HttpWebRequest apiRequest = WebRequest.Create("http://api.openweathermap.org/data/2.5/weather?id=" + cities + "&appid=" + apiKey + "&units=metric") as HttpWebRequest;

                string apiResponse = "";
                using (HttpWebResponse response = apiRequest.GetResponse() as HttpWebResponse)
                {
                    StreamReader reader = new StreamReader(response.GetResponseStream());
                    apiResponse = reader.ReadToEnd();
                }
                /*End*/

                /*http://json2csharp.com*/
                ResponseWeather rootObject = JsonConvert.DeserializeObject <ResponseWeather>(apiResponse);

                StringBuilder sb = new StringBuilder();
                sb.Append("<table><tr><th>Weather Description</th></tr>");
                sb.Append("<tr><td>City:</td><td>" + rootObject.name + "</td></tr>");
                sb.Append("<tr><td>Country:</td><td>" + rootObject.sys.country + "</td></tr>");
                sb.Append("<tr><td>Wind:</td><td>" + rootObject.wind.speed + " Km/h</td></tr>");
                sb.Append("<tr><td>Current Temperature:</td><td>" + rootObject.main.temp + " °C</td></tr>");
                sb.Append("<tr><td>Humidity:</td><td>" + rootObject.main.humidity + "</td></tr>");
                sb.Append("<tr><td>Weather:</td><td>" + rootObject.weather[0].description + "</td></tr>");
                sb.Append("</table>");
                openWeatherMap.apiResponse = sb.ToString();
            }
            else
            {
                if (Request.Form["submit"] != null)
                {
                    openWeatherMap.apiResponse = "► Select City";
                }
            }
            return(View(openWeatherMap));
        }
Esempio n. 15
0
        public IEnumerable <WeatherModel> Map(OpenWeatherMap instance)
        {
            var result = instance.List.GroupBy(
                t => Convert.ToDateTime(t.DT_txt).Date,
                (key, g) =>
            {
                var item = instance.List.Where(q => Convert.ToDateTime(q.DT_txt).Date == key).ToList();

                return(new WeatherModel
                {
                    DateTime = key,
                    City = instance.City.Name,
                    Coutnry = instance.City.Country,
                    Wind = (int)item.Max(s => s.Wind.Speed),
                    Humidity = item.Max(s => s.Main.Humidity),
                    MaxTemperature = item.Max(s => s.Main.TempMax),
                    MinTemperature = item.Max(s => s.Main.TempMin)
                });
            });

            return(result);
        }
            protected override void OnPostExecute(string result)
            {
                base.OnPostExecute(result);
                if (result.Contains("Error: Not found city"))
                {
                    pd.Dismiss();
                    return;
                }
                openWeatherMap = JsonConvert.DeserializeObject <OpenWeatherMap>(result);
                pd.Dismiss();

                //Control
                activity.txtCity        = activity.FindViewById <TextView>(Resource.Id.txtCity);
                activity.txtLastUpdate  = activity.FindViewById <TextView>(Resource.Id.txtLastUpdate);
                activity.txtDescription = activity.FindViewById <TextView>(Resource.Id.txtDescription);
                activity.txtHumidaty    = activity.FindViewById <TextView>(Resource.Id.txtHumidity);
                activity.txtTime        = activity.FindViewById <TextView>(Resource.Id.txtTime);
                activity.txtCelsius     = activity.FindViewById <TextView>(Resource.Id.txtCelsius);

                activity.imgView = activity.FindViewById <ImageView>(Resource.Id.imageView);


                //Add data
                activity.txtCity.Text        = $"{openWeatherMap.name},{openWeatherMap.sys.country}";
                activity.txtLastUpdate.Text  = $"Last Update: {DateTime.Now.ToString("dd MMMM yyyy HH:mm")}";
                activity.txtDescription.Text = $"{openWeatherMap.weather[0].description}";
                activity.txtHumidaty.Text    = $"Humidity: {openWeatherMap.main.humidity} %";
                activity.txtTime.Text        = $"{Common.Common.UnixTimeStampToDateTime(openWeatherMap.sys.sunrise).ToString("HH:mm")}/{Common.Common.UnixTimeStampToDateTime(openWeatherMap.sys.sunrise).ToString("HH:mm")}";

                activity.txtCelsius.Text = $"{openWeatherMap.main.temp} °C";

                if (!String.IsNullOrEmpty(openWeatherMap.weather[0].icon))
                {
                    Picasso.With(activity.ApplicationContext)
                    .Load(Common.Common.GetImage(openWeatherMap.weather[0].icon))
                    .Into(activity.imgView);
                }
            }
Esempio n. 17
0
        private static void Main(string[] args)
        {
            var openWeather = new OpenWeatherMap("TOKEN HERE", Units.Imperial);

            Console.WriteLine("Press any key to get forecast data...");
            Console.ReadKey();

            var currentWeather = openWeather.ByZipCode <CurrentWeather>("20439", "us").Result;

            Console.WriteLine(currentWeather.Weather[0].Description);
            Console.ReadKey();

            var forecast = openWeather.ByZipCode <Forecast>("20439", "us").Result;

            Console.WriteLine(forecast.ForecastCollection[0].Weather[0].Description);
            Console.ReadKey();

            var temp = currentWeather.DayMeasurements.Temp;

            Console.WriteLine(temp);


            Console.ReadKey();
        }
        public ActionResult Index(string zipcode)
        {
            OpenWeatherMap owm = new OpenWeatherMap(zipcode);

            return(View(owm));
        }
Esempio n. 19
0
 public GetWeather(MainActivity activity, OpenWeatherMap openWeatherMap)
 {
     this.activity       = activity;
     this.openWeatherMap = openWeatherMap;
 }
 public ActionResult Index(OpenWeatherMap openWeatherMap, string cities)
 {
     openWeatherMap = weatherBehaviour.GetDataFromOpenWeatherApi(cities);
     FileCreation.CreateFileByCityName(openWeatherMap.ApiResponse, cities);
     return(View(openWeatherMap));
 }
 // GET: OpenWeatherMapMvc
 public ActionResult Index()
 {
     OpenWeatherMap = weatherBehaviour.FillCity();
     return(View(OpenWeatherMap));
 }
Esempio n. 22
0
        public string Get([FromRoute] string ZipCode)
        {
            string CITY_NAME   = "";
            string TEMPERATURE = "";
            string TIMEZONE    = "";
            string Message     = "";

            string location = "";



            {
                try
                {
                    OpenWeatherMap OpenWeatherInfo = Common.CommonMethods.GetOpenWeatherInfo(ZipCode, _config);



                    if (OpenWeatherInfo != null)
                    {
                        CITY_NAME   = OpenWeatherInfo.name;
                        TEMPERATURE = OpenWeatherInfo.main.temp;
                        location    = $"{OpenWeatherInfo.coord.lat}, {OpenWeatherInfo.coord.lon}";

                        GoogleTimeZone GoogleInfo = Common.CommonMethods.GetGoogleInfo(location, _config);

                        if (GoogleInfo != null)
                        {
                            TIMEZONE = $"{GoogleInfo.timeZoneId} ({GoogleInfo.timeZoneName})";
                        }
                        else
                        {
                            TIMEZONE = Resources.MessagesRes.Unknown;
                        }
                    }
                    else
                    {
                        CITY_NAME   = Resources.MessagesRes.Unknown;
                        TEMPERATURE = Resources.MessagesRes.NotDefined;
                        TIMEZONE    = Resources.MessagesRes.Unknown;
                    }


                    Message = $"At the location {CITY_NAME}, \n the temperature is {TEMPERATURE}, \n and the timezone is {TIMEZONE}";
                }
                //catch (Exception ex)
                //{
                //    //Logging
                //    {
                //        CITY_NAME = Resources.MessagesRes.Unknown;
                //        TEMPERATURE = Resources.MessagesRes.NotDefined;
                //        TIMEZONE = Resources.MessagesRes.Unknown;
                //    }


                //    Message = $"At the location {CITY_NAME}, \n the temperature is {TEMPERATURE}, \n and the timezone is {TIMEZONE}";
                //}
                catch
                {
                    //Logging

                    {
                        CITY_NAME   = Resources.MessagesRes.Unknown;
                        TEMPERATURE = Resources.MessagesRes.NotDefined;
                        TIMEZONE    = Resources.MessagesRes.Unknown;
                    }


                    Message = $"At the location {CITY_NAME}, \n the temperature is {TEMPERATURE}, \n and the timezone is {TIMEZONE}";
                }
            }



            return(Message);
        }
        public void GetWeatherDataServiceTest()
        {
            OpenWeatherMap testWeather = OpenWeatherMap.Instance;

            Assert.AreEqual(WeatherDataServiceFactory.GetWeatherDataService(WeatherDataServiceFactory.OPEN_WEATHER_MAP).GetType().Name, testWeather.GetType().Name);
        }
        public ActionResult weatherForecast()
        {
            OpenWeatherMap openWeatherMap = FillCity();

            return(View(openWeatherMap));
        }
        public ActionResult Index()
        {
            OpenWeatherMap openWeatherMap = FillCity(); //Fill the city to call the API

            return(View(openWeatherMap));
        }
        public void OpenWeatherMapTest()
        {
            var site = new OpenWeatherMap();

            Assert.AreEqual("openweathermap.org", site.SiteAddress);
        }
Esempio n. 27
0
 public static async void CollectWeatherAsync()
 {
     Weather = await OpenWeatherMapInterface.GetWeatherAsync();
 }
        public ActionResult Index()
        {
            OpenWeatherMap localWeather = GetLocalWeather();

            return(View(localWeather));
        }
Esempio n. 29
0
        public IActionResult Index()
        {
            OpenWeatherMap openWeatherMap = FillCity();

            return(View(openWeatherMap));
        }
Esempio n. 30
0
 public GetWeather(WeatherSample activity, OpenWeatherMap openWeatherMap)
 {
     this.activity       = activity;
     this.openWeatherMap = openWeatherMap;
 }