コード例 #1
0
ファイル: HomeController.cs プロジェクト: Awiprogs/WeatherApp
        public async Task <ViewResult> Index(WeatherInputModel inputModel)
        {
            if (ModelState.IsValid)
            {
                HttpResponseMessage reponse = await _openWeatherHttpService.SendRequest(_serviceUrl, inputModel.Country, inputModel.City);

                if (reponse.StatusCode == HttpStatusCode.BadRequest)
                {
                    return(View("Error", new ErrorModel {
                        Input = inputModel, Message = Resources.InvalidInputData
                    }));
                }

                if (!reponse.IsSuccessStatusCode)
                {
                    return(View("Error", new ErrorModel {
                        Input = inputModel, Message = Resources.UnexpectedError
                    }));
                }

                WeatherDetails weather = await _openWeatherHttpService.GetData(reponse.Content);

                WeatherDetailsModel model = Mapper.Map <WeatherDetailsModel>(weather);
                model.ShowDetails = true;

                return(View("Details", model));
            }

            return(View(inputModel));
        }
コード例 #2
0
 private City ConvertFromWeatherDetailsToCity(string cityKey, WeatherDetails wd)
 {
     return(new City()
     {
         Key = cityKey,
     });
 }
コード例 #3
0
        public async Task <IActionResult> Post([FromBody] Coordinates coordinates)
        {
            var location = coordinates;

            using (var client = new HttpClient())
            {
                try
                {
                    client.BaseAddress = new Uri("http://api.openweathermap.org");
                    string key      = configuration.GetValue <string>("APIKeys:OpenWeatherMap");
                    var    response = await client.GetAsync($"/data/2.5/weather?lat={location.Latitude}&lon={location.Longitude}&appid={key}&units=metric");

                    response.EnsureSuccessStatusCode();
                    var stringResult = await response.Content.ReadAsStringAsync();

                    var rawWeatherData = JsonConvert.DeserializeObject <OpenWeatherResponse>(stringResult);

                    WeatherDetails weather = new WeatherDetails()
                    {
                        City        = rawWeatherData.Name,
                        Temperature = rawWeatherData.Main.Temp,
                        Description = rawWeatherData.Weather.FirstOrDefault().Description
                    };

                    return(Ok(weather));
                }
                catch (HttpRequestException httpRequestException)
                {
                    return(BadRequest($"Error getting weather from OpenWeather: {httpRequestException.Message}"));
                }
            }
        }
コード例 #4
0
        public async Task <IActionResult> PutWeatherDetails(string id, WeatherDetails weatherDetails)
        {
            if (id != weatherDetails.City)
            {
                return(BadRequest());
            }

            _context.Entry(weatherDetails).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!WeatherDetailsExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(NoContent());
        }
コード例 #5
0
        /// <summary>
        /// Getting weather Information
        /// </summary>
        /// <param name="city"></param>
        /// <returns></returns>
        public ActionResult GetWeather(string city)
        {
            WeatherDetails weatherDetails = new WeatherDetails();
            WeatherModel   weatherModel   = weatherDetails.GetWeather(city);

            return(PartialView("Weather", weatherModel));
        }
コード例 #6
0
        public async Task <WeatherDetails> GetData(HttpContent httpResponseContent)
        {
            string stringResult = await httpResponseContent.ReadAsStringAsync();

            WeatherDetails weather = JsonConvert.DeserializeObject <WeatherDetails>(stringResult);

            return(weather);
        }
コード例 #7
0
 private WeatherInfo ConvertDetailsToInfo(WeatherDetails wd)
 {
     return(new WeatherInfo()
     {
         Temprature = wd.Temperature.Metric.Value,
         WeatherText = wd.WeatherText
     });
 }
コード例 #8
0
        /// <summary>
        /// Get the weather information
        /// </summary>
        /// <param name="city"></param>
        /// <returns></returns>
        public WeatherDetails GetWeatherInfo(string city)
        {
            WeatherDetails weatherDetails = new WeatherDetails();

            weatherPage.PinCity(city).Click();
            weatherDetails.humidity      = Convert.ToDouble((String.Join("", weatherPage.WeatherDetails("Humidity").GetAttribute("innerText").Where(char.IsDigit))));
            weatherDetails.TempInDegrees = Convert.ToDouble((String.Join("", weatherPage.WeatherDetails("Temp in Degrees").GetAttribute("innerText").Where(char.IsDigit))));
            return(weatherDetails);
        }
コード例 #9
0
        private WeatherDetails ConvertDalCityToWeatherDetails(FavoritesCity city)
        {
            WeatherDetails wd = new WeatherDetails();

            wd.Temperature              = new Temperature();
            wd.Temperature.Metric       = new TempratureDetails();
            wd.Temperature.Metric.Value = (double)city.CelsiusTemprature;
            wd.WeatherText              = city.WeatherText;
            return(wd);
        }
コード例 #10
0
        public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath)
        {
            var cell = DequeCell(tableView, indexPath);

            var detail = WeatherDetails.GetDetail(indexPath.Row, Location, Settings.UomTemperature, Settings.UomSpeed, Settings.UomLength, Settings.UomDistance, Settings.UomPressure);

            cell.SetData(detail);

            return(cell);
        }
コード例 #11
0
 public async void GetCurrentWeather()
 {
     WeatherStruct = await Weather.GetWeather(global.pref.WeatherLocation);
     if (global.HTMLerror == false)
     {
         CurrentWeather = WeatherStruct[0];
         TommorowsWeather = WeatherStruct[1];
         TommorowssWeather = WeatherStruct[2];
     }
     SetAllWeatherValues();
 }
コード例 #12
0
        public async void ThenIReceiveTheTemperatureAndHumidityAccordingToTheOfficialWeatherReports()
        {
            //Check result
            WeatherDetails weather = await _weatherService.GetData(_response.Content);

            Assert.IsNotNull(weather);
            Assert.IsNotNull(weather.Temperature);
            Assert.IsNotNull(weather.Location);
            Assert.Equals(weather.Location.Country, _country);
            Assert.Equals(weather.Location.City, _city);
        }
コード例 #13
0
        public static WeatherModel FromObject(WeatherDetails obj)
        {
            var ret = new WeatherModel();

            ret.Date                = obj.TimeStamp;
            ret.Humidity            = obj.Humidity;
            ret.Temperature         = obj.Temperature;
            ret.WeaherConditionIcon = obj.Condition[0].IconCode;

            return(ret);
        }
コード例 #14
0
        public static async Task <WeatherDetails> GetWeatherAsync(string zipCode)
        {
            //Sign up for a free API key at http://openweathermap.org/appid
            string queryString = Helper.api + zipCode + "&appid=" + Helper.key;

            //RESPONSE
            //{"coord":{"lon":-74,"lat":40.75},"weather":[{"id":800,"main":"Clear","description":"clear sky","icon":"01n"}],"base":"stations","main":{"temp":283.3,"pressure":1025,"humidity":53,"temp_min":281.15,"temp_max":285.15},"visibility":16093,"wind":{"speed":4.1,"deg":340,"gust":7.7},"clouds":{"all":1},"dt":1509771360,"sys":{"type":1,"id":2121,"message":0.0106,"country":"US","sunrise":1509795025,"sunset":1509832089},"id":0,"name":"New York","cod":200}
            var results = await DataService.getDataFromService(queryString).ConfigureAwait(false);

            #region Commented
            //IEnumerable<RootObject> results = (IEnumerable<RootObject>)Task.Run(async () => { return await DataService.GetResult(queryString); });
            //Synchronous call
            //var results = DataService.GetResult(queryString);
            //var results = await DataService.getDataFromService(queryString);
            #endregion
            if (results[Helper.weather] != null)
            {
                WeatherDetails weather = new WeatherDetails();

                weather.Title       = (string)results[Helper.name];
                weather.Temperature = (string)results[Helper.main][Helper.temp] + " f";
                double cel = 0;
                //T(°C) = (T(°F) - 32) / 1.8
                try
                {
                    string farStr = (results[Helper.main][Helper.temp]).ToString();
                    double far    = Convert.ToDouble(farStr);
                    cel = (far - 32) / (1.8);
                }
                catch (Exception ex)
                {
                    ExceptionFileWriter.ToLogUnhandledException(ex);
                    //throw ex;
                }
                weather.Celsius    = String.Format("{0:0.00}", cel);
                weather.Wind       = (string)results[Helper.wind][Helper.speed] + " " + Helper.mph;
                weather.Humidity   = (string)results[Helper.main][Helper.humidity] + " %";
                weather.Visibility = (string)results[Helper.weather][0][Helper.main];

                DateTime time    = new System.DateTime(1970, 1, 1, 0, 0, 0, 0);
                DateTime sunrise = time.AddSeconds((double)results[Helper.sys][Helper.sunrise]);
                DateTime sunset  = time.AddSeconds((double)results[Helper.sys][Helper.sunset]);
                //weather.Sunrise = sunrise.ToString() + " UTC";
                weather.Sunrise = sunrise.TimeOfDay.ToString() + " " + Helper.UTC;
                weather.Sunset  = sunset.ToString() + " " + Helper.UTC;
                return(weather);
            }
            else
            {
                return(null);
            }
        }
コード例 #15
0
        WeatherDetails GetWeatherDetails(DateTime utcDate, SqlConnection weatherConnection)
        {
            var startTime = utcDate.AddMinutes(-5);
            var endTime   = utcDate.AddMinutes(5);


            var startSQLFormattedDate = startTime.ToString(Constants.DATE_TIME_FORMAT);
            var endSQLFormattedDate   = endTime.ToString(Constants.DATE_TIME_FORMAT);

            SqlCommand weatherCmd = new SqlCommand("SELECT * FROM Weather where TimeStamp >= @startTime AND TimeStamp <= @endTime", weatherConnection);

            string query = "SELECT * FROM Weather where TimeStamp >= " + startSQLFormattedDate + " AND TimeStamp <= " + endSQLFormattedDate;

            //log.Debug(query);
            // Console.WriteLine(query);
            weatherCmd.Parameters.Add("@startTime", SqlDbType.DateTime);
            weatherCmd.Parameters["@startTime"].Value = startSQLFormattedDate;
            weatherCmd.Parameters.Add("@endTime", SqlDbType.DateTime);
            weatherCmd.Parameters["@endTime"].Value = endSQLFormattedDate;
            SqlDataReader weatherReader = weatherCmd.ExecuteReader();

            WeatherDetails weatherDetails = new WeatherDetails();

            while (weatherReader.Read())
            {
                if (weatherReader["Temperature"] != DBNull.Value)
                {
                    weatherDetails.Temperature = Convert.ToInt32(weatherReader["Temperature"]);
                }
                if (weatherReader["Pressure"] != DBNull.Value)
                {
                    weatherDetails.Pressure = Convert.ToInt32(weatherReader["Pressure"]);
                }
                if (weatherReader["Relative Humidity"] != DBNull.Value)
                {
                    weatherDetails.RelativeHumidity = Convert.ToInt32(weatherReader["Relative Humidity"]);
                }
                if (weatherReader["visibility"] != DBNull.Value)
                {
                    weatherDetails.Visibility = Convert.ToInt32(weatherReader["visibility"]);
                }

                if (weatherDetails.Temperature == 0)
                {
                    continue;
                }

                break;
            }
            weatherReader.Close();
            return(weatherDetails);
        }
コード例 #16
0
 private void UpdateFavorites(string cityKey, WeatherDetails wd)
 {
     using (var ctx = new MyFavoritesWeatherEntities())
     {
         var city = ctx.FavoritesCities.Where(x => x.CityKey == cityKey).First();
         if (city != null)
         {
             city.CelsiusTemprature = wd.Temperature.Metric.Value;
             city.WeatherText       = wd.WeatherText;
         }
         ctx.SaveChanges();
     };
 }
コード例 #17
0
        public static CurrentWeatherModel FromObject(WeatherDetails obj)
        {
            var ret = new CurrentWeatherModel();

            ret.Date = obj.TimeStamp;
            ret.Humidity = obj.Humidity;
            ret.Temperature = obj.Temperature;
            ret.WeaherConditionIcon = obj.Condition[0].IconCode;
            ret.Clouds = obj.Clouds;
            ret.WindDirection = obj.WindDirection;
            ret.WindSpeed = obj.WindSpeed;

            return ret;
        }
コード例 #18
0
        public async Task <IHttpActionResult> GetWeatherDetails(string country, string city)
        {
            try
            {
                WeatherDetails result = await _openWeatherService.GetWeather(country, city);

                _logger.LogSuccess(nameof(GetWeatherDetails));

                return(Ok(result));
            }
            catch (HttpRequestException httpRequestException)
            {
                _logger.LogError(httpRequestException.Message);
                return(BadRequest($"Error getting weather from OpenWeather: {httpRequestException.Message}"));
            }
        }
コード例 #19
0
		public WeatherDetails GetWeather(DateTime dt)
		{
			var result = new WeatherDetails();
			var val = this.GetWeatherAsFloat(dt);

			if (val < 1.0f)
				result.Type = WeatherType.Clear;
			else if (val < 1.95f)
				result.Type = WeatherType.Clouds;
			else
			{
				result.Type = WeatherType.Rain;
				result.RainStrength = (int)((val - 1.95f) * 40);
			}

			return result;
		}
コード例 #20
0
 private string GetUrl(ref WeatherDetails _weather)
 {
     string Url = null;
     switch (SelectedWeatherSource)
     {
         case "Open Weather":
             appId = ConfigurationManager.AppSettings["OpenWeather"];
             _weather = new OpenWeather(appId, SelectedCity.Name);
             Url = _weather.BuildUrl();
             break;
         case "Yahoo":
             _weather = new YahooWeather(SelectedCity.Name);
             Url = _weather.BuildUrl();
             break;
     }
     return Url;
 }
コード例 #21
0
        public void When_GetWeatherForCitiesCalled_Returns_Data()
        {
            var dummyWeatherDetails = new WeatherDetails()
            {
                Name    = "Cairns",
                Weather = new Weather[]
                {
                    new Weather()
                    {
                        Id          = 802,
                        Main        = "Clouds",
                        Description = "scattered clouds",
                        Icon        = "03n"
                    }
                }
            };

            _mockCityWeatherService.Setup(x => x.GetWeatherForCityAsync(It.IsAny <Int32>(), It.IsAny <string>(), It.IsAny <string>()))
            .Returns(Task.FromResult(dummyWeatherDetails));
            var           formFile  = new Mock <IFormFile>();
            StringBuilder sbContent = new StringBuilder();

            sbContent.AppendLine("CityId,CityName");
            sbContent.AppendLine("2643741,City of London");
            sbContent.AppendLine("5128581,New York");
            sbContent.AppendLine("1273294,Delhi");
            sbContent.AppendLine("1275339,Mumbai");

            var fileName = "test.csv";
            var ms       = new MemoryStream();
            var writer   = new StreamWriter(ms);

            writer.Write(sbContent.ToString());
            writer.Flush();
            ms.Position = 0;

            formFile.Setup(_ => _.OpenReadStream()).Returns(ms);
            formFile.Setup(_ => _.FileName).Returns(fileName);
            formFile.Setup(_ => _.Length).Returns(ms.Length);

            var file   = formFile.Object;
            var result = _cityWeatherController.GetWeatherForCitiesAsync(file);

            Assert.NotNull(result);
        }
コード例 #22
0
        public async Task <WeatherDetails> GetWeatherForCityAsync(int cityid, string apiKey, string uriWeather)
        {
            WeatherDetails weatherDetails = null;

            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri(uriWeather);
                var response = await client.GetAsync($"/data/2.5/weather?id=" + cityid.ToString() + "&appid=" + apiKey);

                response.EnsureSuccessStatusCode();

                var stringResult = await response.Content.ReadAsStringAsync();

                weatherDetails = JsonConvert.DeserializeObject <WeatherDetails>(stringResult);
            }

            return(weatherDetails);
        }
コード例 #23
0
        private async void Get_Weather()
        {
            List <WeatherDetails> weathers = await WeatherHelper.GetWeather();

            WeatherDetails weatherDetails = weathers.First();

            BitmapImage bi3 = new BitmapImage();

            bi3.BeginInit();
            bi3.UriSource = new Uri(weatherDetails.WeatherIcon, UriKind.Relative);
            bi3.EndInit();
            ImgWeather.Stretch = Stretch.Fill;
            ImgWeather.Source  = bi3;

            CurrentTemp.Text = weatherDetails.Temperature;
            MaxTemp.Text     = weatherDetails.MaxTemperature;
            MinTemp.Text     = weatherDetails.MinTemperature;
            Wind.Text        = weatherDetails.WindSpeed;
            Dayofweek.Text   = weatherDetails.WeatherDay;
        }
コード例 #24
0
        private async void GetWeatherButton_Clicked(object sender, EventArgs e)
        {
            var cityName = weatherEntry.Text;

            using (HttpClient client = new HttpClient())
            {
                using (HttpResponseMessage response = await client.GetAsync("http://kams-weather-api.herokuapp.com/" + cityName))
                {
                    using (HttpContent content = response.Content)
                    {
                        var myContent = await content.ReadAsStringAsync();

                        WeatherDetails details     = JsonConvert.DeserializeObject <WeatherDetails>(myContent);
                        float          celTemp     = returnTemperatureInCelsius(details.temperature);
                        string         tempDetails = "Currently the temperature is at " + details.temperature + " in " + details.city + " ." + details.summary;
                        await DisplayAlert("Weather details", tempDetails, "Okay!");
                    }
                }
            }
        }
コード例 #25
0
        private void DownloadWeatherDetailsOffline(string city)
        {
            WeatherDetails _weather = null;
            string url = GetUrl(ref _weather);
            string weatherDetails = _weather.DownloadWeatherDetails(url);

            string dirPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory.Replace("bin\\Debug\\", "Offline Datas\\"), SelectedWeatherSource);
            if (!Directory.Exists(dirPath))
                Directory.CreateDirectory(dirPath);

            string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory.Replace("bin\\Debug\\", "Offline Datas\\"), string.Format("{0}\\{1}.txt", SelectedWeatherSource, city));
            if (File.Exists(path))
                File.Delete(path);
            using (StreamWriter writer = new StreamWriter(path))
            {
                writer.WriteLine(weatherDetails);
                writer.Close();
            }
            MessageBox.Show("Downloaded Successfully !!!");
        }
コード例 #26
0
        public void Setup()
        {
            _mockWeatherRepository = new Mock <ICityWeatherRepository>();
            _weatherService        = new CityWeatherService(_mockWeatherRepository.Object);
            var dummyWeatherDetails = new WeatherDetails()
            {
                Name    = "Cairns",
                Weather = new Weather[]
                {
                    new Weather()
                    {
                        Id          = 802,
                        Main        = "Clouds",
                        Description = "scattered clouds",
                        Icon        = "03n"
                    }
                }
            };

            _mockWeatherRepository.Setup(x => x.GetWeatherForCityAsync(It.IsAny <Int32>(), It.IsAny <string>(), It.IsAny <string>())).Returns(Task.FromResult(dummyWeatherDetails));
        }
コード例 #27
0
        public async Task <ActionResult <WeatherDetails> > PostWeatherDetails(WeatherDetails weatherDetails)
        {
            _context.WeatherForecast.Add(weatherDetails);
            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateException)
            {
                if (WeatherDetailsExists(weatherDetails.City))
                {
                    return(Conflict());
                }
                else
                {
                    throw;
                }
            }

            return(CreatedAtAction("GetWeatherDetails", new { id = weatherDetails.City }, weatherDetails));
        }
コード例 #28
0
        public WeatherDetails GetWeather(DateTime dt)
        {
            var result = new WeatherDetails();
            var val    = this.GetWeatherAsFloat(dt);

            if (val < 1.0f)
            {
                result.Type = WeatherType.Clear;
            }
            else if (val < 1.95f)
            {
                result.Type = WeatherType.Clouds;
            }
            else
            {
                result.Type         = WeatherType.Rain;
                result.RainStrength = (int)((val - 1.95f) * 40);
            }

            return(result);
        }
コード例 #29
0
        public async Task <WeatherDetails> GetWeather(string country, string city)
        {
            using (HttpClient client = new HttpClient())
            {
                client.BaseAddress = new Uri(_openWeatherUrl);
                HttpResponseMessage response = await client.GetAsync($"data/2.5/weather?q={city},{country}&appid={_apiKey}&units=metric");

                response.EnsureSuccessStatusCode();

                string stringResult = await response.Content.ReadAsStringAsync();

                OpenWeatherResponse weather = JsonConvert.DeserializeObject <OpenWeatherResponse>(stringResult);

                WeatherDetails wd = Mapper.Map <WeatherDetails>(weather);
                wd.Location = new Location {
                    City = city, Country = country
                };

                return(wd);
            }
        }
コード例 #30
0
        private WeatherDetails GetWeatherInfo(XElement xEl)
        {
            IEnumerable <WeatherViewModel> w = xEl.Descendants("time").Select((el) =>
                                                                              new WeatherViewModel
            {
                Humidity       = el.Element("humidity").Attribute("value").Value + "%",
                MaxTemperature = el.Element("temperature").Attribute("max").Value + "°",
                MinTemperature = el.Element("temperature").Attribute("min").Value + "°",
                Temperature    = el.Element("temperature").Attribute("day").Value + "°",
                Weather        = el.Element("symbol").Attribute("name").Value,
                WeatherDay     = DayOfTheWeek(el),
                WeatherIcon    = WeatherIconPath(el),
                WindDirection  = el.Element("windDirection").Attribute("name").Value,
                WindSpeed      = el.Element("windSpeed").Attribute("mps").Value + "mps"
            });

            var weatherDetails = new WeatherDetails();

            weatherDetails.WeatherData = w.ToList();

            return(weatherDetails);
        }
コード例 #31
0
        public async void GetDataFromHttpContentTest()
        {
            //Arrange
            IWeatherHttpClientService weatherHttpClient = new WeatherHttpClientService();

            string json = "{\"location\":{\"city\":\"Warsaw\",\"country\":\"PL\"}," +
                          "\"temperature\":{\"format\":\"Celsius\",\"value\":10.5}," +
                          "\"humidity\":76.0}";

            HttpContent content = new StringContent(json);

            //Act
            WeatherDetails wd = await weatherHttpClient.GetData(content);

            //Assert
            Assert.NotNull(wd);
            Assert.NotNull(wd.Location);
            Assert.NotNull(wd.Temperature);
            Assert.True(wd.Location.City == "Warsaw");
            Assert.True(wd.Location.Country == "PL");
            Assert.True(wd.Temperature.Value == 10.5);
            Assert.True(wd.Humidity == 76);
        }
コード例 #32
0
        public async void weatherService()
        {
            //Arrange
            var mockEnvironment = new Mock <IHostingEnvironment>();

            //...Setup the mock as needed
            mockEnvironment
            .Setup(m => m.WebRootPath)
            .Returns("D:\\WeatherData\\WeatherData\\WeatherData\\wwwroot");
            IOptions <WeatherConfiguration> iWeatherConfiguration = Options.Create <WeatherConfiguration>(new WeatherConfiguration());

            iWeatherConfiguration.Value.AppId  = Appid;
            iWeatherConfiguration.Value.WebUrl = appurl;
            IFileOperations file    = new FileOperations();
            IWeatherDetails weather = new WeatherDetails(iWeatherConfiguration);

            WeatherData.Controllers.WeatherController w = new WeatherData.Controllers.WeatherController(mockEnvironment.Object, file, weather);
            bool response = await w.Get();

            if (response)
            {
                Assert.True(true);
            }
        }