コード例 #1
0
        public async Task <ActionResult> Index(WeatherVM weatherVM)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    var request = String.Format("http://api.openweathermap.org/data/2.5/weather?q={0}&appid=c3023616e1b1e2324a9f56882b12e779", weatherVM.Query);

                    var client = new HttpClient();

                    //var response = await client.GetStringAsync(request);
                    var response = await client.GetAsync(request);

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

                        extractWeatherDataFromJson(weatherVM, responseMessage);
                    }
                    else
                    {
                        weatherVM.ResponseCode = 404;
                    }
                }
                catch (WebException e)
                {
                    Console.WriteLine("Error message: {0}", e.Message);
                }
            }



            return(View(weatherVM));
        }
        public WeatherVM GetWeather(GetCityWeatherVM vm)
        {
            WeatherVM weatherVM = new WeatherVM();
            DatabaseProvider <WeatherVM> dataBaseProvider = new DatabaseProvider <WeatherVM>();

            base.command.CommandText = "GetCityWeather";
            base.command.Parameters.AddWithValue("@p_CityKey", vm.CityKey);
            var result = dataBaseProvider.Get(base.command);

            if (result.Count == 0)
            {
                ServiceProvider <WeatherModel> dataServiceProvider = new ServiceProvider <WeatherModel>();
                string apiCurrentConditions = "Accuweather.Api.CurrentConditions".GetWebConfigValue <string>();
                apiCurrentConditions += vm.CityKey + "?apikey=" + base.apiKey;
                WeatherModel weatherModel = dataServiceProvider.Get(apiCurrentConditions).Single();
                weatherVM = new WeatherVM
                {
                    CityKey     = vm.CityKey,
                    WeatherText = weatherModel.WeatherText,
                    Temperature = weatherModel.Temperature.Metric.Value
                };
                base.command.CommandText = "InsertCityWeather";
                base.command.Parameters.Clear();
                base.command.Parameters.AddWithValue("@p_CityKey", weatherVM.CityKey);
                base.command.Parameters.AddWithValue("@p_WeatherText", weatherVM.WeatherText);
                base.command.Parameters.AddWithValue("@p_Temperature", weatherVM.Temperature);
                dataBaseProvider.Insert(base.command);
            }
            else
            {
                weatherVM = result.FirstOrDefault();
            }
            return(weatherVM);
        }
コード例 #3
0
        // GET: Weathers
        public ActionResult GetWeatherData(int?year, int?month, int page = 1)
        {
            int pageSize = int.Parse(WebConfigurationManager.AppSettings["PageSize"]);

            #region Mapper
            var config = new MapperConfiguration(map =>
            {
                map.CreateMap <Weather, MoscowWeather.Models.WeatherModel>();
                map.CreateMap <PageModel, PageVM>();
                map.CreateMap <DataLayer.Model.WeatherModel, WeatherVM>()
                .ForMember("PageViewModel", opt => opt.MapFrom(c => c.PageModel));
            });
            var mapper = new Mapper(config);
            #endregion

            DataLayer.Model.WeatherModel weatherViewModel
                = weatherService.GetWeatherData(year, year == null ? null: month, page, pageSize);

            DateVM dateViewModel = new DateVM
            {
                Year  = year,
                Month = month
            };

            WeatherVM weatherVM = mapper.Map <WeatherVM>(weatherViewModel);
            weatherVM.DateViewModel = dateViewModel;

            return(View("Weather", weatherVM));
        }
コード例 #4
0
        public void Post([FromBody] WeatherVM weather)
        {
            if (ModelState.IsValid)
            {
                if (weather.key >= 0 && weather.weatherText != String.Empty && weather.temperature != null)
                {
                    // Make sure current location is not exists in DB.
                    Locations locationFromDB = db.Locations.FirstOrDefault(i => i.LocationId == weather.key);

                    // Important !!!
                    // We are not supposed to get here.
                    // Check if we found location in DB --> Do nothing
                    if (locationFromDB != null)
                    {
                        return;
                    }


                    // Add location to favorites
                    db.Locations.Add(new Locations()
                    {
                        LocationId  = weather.key,
                        Name        = weather.name,
                        Temperature = (int)weather.temperature,
                        WeatherText = weather.weatherText
                    });


                    db.SaveChanges();
                }
            }
        }
        // Detail Page for selected park
        public IActionResult Detail(string parkCode)
        {
            WeatherVM vm = new WeatherVM();

            vm.Park     = nationalParkDAO.GetPark(parkCode);
            vm.Weathers = weatherDAO.GetWeather(parkCode);
            return(View(vm));
        }
コード例 #6
0
        public City CheckWeather(WeatherVM weather)
        {
            City City = new City();

            City = Check(weather.AskedCity.Name);

            return(City);
        }
コード例 #7
0
        public async Task <IActionResult> GetWeather(decimal lat, decimal lon)
        {
            string lons = Decimal.Round(lon, 3).ToString(new CultureInfo("en"));
            string lats = Decimal.Round(lat, 3).ToString(new CultureInfo("en"));

            var locname = await _locationService.LocationName(lats, lons);

            var weatherList = _context.Weathers.ToList();
            var position    = new LoactionCoord
            {
                CityName  = locname,
                Latitude  = lats,
                Longitude = lons
            };

            if (weatherList.Any(x => x.Updated <= DateTime.UtcNow.AddHours(2).AddMinutes(10)) || weatherList.Count == 0)
            {
                _context.Forecasts.RemoveRange(_context.Forecasts);
                _context.Weathers.RemoveRange(_context.Weathers);



                var openWeatherWeather = await _weatherService.OpenWeatherWeather(position);

                var yrWeather = await _weatherService.YRWeather(position);

                var smhiWeather = await _weatherService.SMHIWeather(position);

                weatherList = new List <Weather> {
                    openWeatherWeather, yrWeather, smhiWeather
                };

                foreach (var weather in weatherList)
                {
                    _context.Weathers.Add(weather);
                }
                _context.SaveChanges();
            }
            else
            {
                weatherList = _context.Weathers.ToList();
            }
            var sortedWeather = SortWeathers(weatherList);

            foreach (var item in sortedWeather)
            {
                item.Updated = DateTime.UtcNow.AddHours(2);
            }

            allWeathers = new WeatherVM
            {
                Weathers = sortedWeather,
                City     = position.CityName,
                Date     = DateTime.UtcNow.AddHours(2).ToString("dddd, dd MMMM HH:mm")
            };

            return(View("Like", allWeathers));
        }
コード例 #8
0
        async void weatherButton_ClickedAsync(object sender, System.EventArgs e)
        {
            WeatherVM weatherVM = new WeatherVM();
            await weatherVM.InitializeGetWeatherAsync();

            fahren.Text          = "Fahrenheit:- " + weatherVM.Fahrenheit;
            cel.Text             = "Celsius:- " + weatherVM.Celsius;
            tm.Text              = "Recorded Time:- " + weatherVM.Time;
            alertPopup.IsVisible = true;
        }
コード例 #9
0
        /// <summary>
        /// Default constructor
        /// </summary>
        public WidgetWeather()
        {
            _fullWidget      = new WeatherWidgetFull();
            _rightLeftWidget = new WeatherWidgetReduce();
            _topBotWidget    = new WeatherWidgetReduce();

            _dataContext = (WeatherVM)_fullWidget.DataContext;

            _topBotWidget.DataContext    = _dataContext;
            _rightLeftWidget.DataContext = _dataContext;
        }
コード例 #10
0
        public async Task <WeatherVM> GetWeatherForCity(string cityName)
        {
            var response = await _openWeatherClient.GetWeather(cityName);

            var weather = new WeatherVM();

            weather.Description = response.weather[0].description;
            weather.Icon        = response.weather[0].icon;
            weather.Temp        = (int)response.main.temp;

            weather.Name = response.name;
            return(weather);
        }
コード例 #11
0
        public WeatherVM CheckLocalWeather()
        {
            WeatherVM weathervm = new WeatherVM();

            using (WebClient klient = new WebClient())
            {
                string json      = klient.DownloadString("https://api.ipgeolocation.io/getip");
                var    GetIpApi  = JsonConvert.DeserializeObject <GetIp>(json);
                string json2     = klient.DownloadString($"https://api.ipgeolocation.io/ipgeo?apiKey=05061dc94ff04170b61d064708615c71&ip={GetIpApi.ip}");
                var    GetLocApi = JsonConvert.DeserializeObject <GetLoc>(json2);
                weathervm.LocalCity = Check(GetLocApi.city);
            };
            return(weathervm);
        }
コード例 #12
0
 public IActionResult CheckWeather(WeatherVM weathervm)
 {
     try
     {
         weathervm.LocalCity = _cityService.CheckLocalWeather().LocalCity;
         weathervm.AskedCity = _cityService.CheckWeather(weathervm);
     }
     catch
     {
         ModelState.AddModelError("CityError", "Invalid city name!");
         weathervm.AskedCity.Name = null;
         return(View("Index", weathervm));
     }
     return(View("Index", weathervm));
 }
コード例 #13
0
        public void QueryLengthTest()
        {
            //arrange
            int       expectedQueryLength = 10;
            string    longquery           = "abcdefghijkl";
            WeatherVM weatherVM           = new WeatherVM();

            //act
            weatherVM.Query = longquery;

            //assert
            int actualQueryLength = weatherVM.Query.Length;

            Assert.AreEqual(actualQueryLength, expectedQueryLength, "Query not cuting strings correctly");
        }
コード例 #14
0
        public void EmptyQueryTest()
        {
            //arrange
            int       expectedForecastLength = 0;
            string    query     = "";
            WeatherVM weatherVM = new WeatherVM();

            //act
            weatherVM.Query = query;

            //assert
            int actualForecastLength = weatherVM.Forecasts.Count;

            Assert.AreEqual(actualForecastLength, expectedForecastLength, "Empty query not being handled correctly");
        }
コード例 #15
0
        private void extractWeatherDataFromJson(WeatherVM weatherVM, string response)
        {
            JObject json = JObject.Parse(response);

            weatherVM.ResponseCode = int.Parse(json["cod"].ToString());

            weatherVM.Weather = new WeatherInfo()
            {
                Temp       = kelvinToCelsius(float.Parse(json["main"]["temp"].ToString())),
                Pressure   = json["main"]["pressure"].ToString(),
                WindSpeed  = json["wind"]["speed"].ToString(),
                Humidity   = json["main"]["humidity"].ToString(),
                Cloudiness = json["clouds"]["all"].ToString(),
                CityName   = json["name"].ToString()
            };
        }
コード例 #16
0
        public void ErasingQueryTest()
        {
            //arrange
            int       expectedForecastLength = 0;
            string    firstQuery             = "r";
            string    secondQuery            = "";
            WeatherVM weatherVM = new WeatherVM();

            //act
            weatherVM.Query = firstQuery;
            weatherVM.Query = secondQuery;

            //assert
            int actualForecastLength = weatherVM.Forecasts.Count;

            Assert.AreEqual(actualForecastLength, expectedForecastLength, "Forecast list not erasing correctly");
        }
コード例 #17
0
ファイル: HomeController.cs プロジェクト: cbm-ts/MvcWeather
        public ActionResult FindWeather(WeatherVM model)
        {
            model.Date = DateTime.Now;
            using (Context ctx = new Context())
            {
                LocationDA locationDA = new LocationDA(ctx);
                model.Location = locationDA.GetLocationByZip(model.ZipCode);
                WeatherDA weatherDA = new WeatherDA(ctx);
                model.TodaysWeather = weatherDA.GetTodaysWeatherByZip(model.ZipCode, model.Date);
            }

            //model.ZipCode = 30809;
            //model.Location = "Evans, GA";
            //model.TodaysWeather = new List<Weather>();
            //model.TodaysWeather.Add(
            //    new Weather
            //    {
            //        Temperature = 70,
            //        Status = WeatherType.Sunny,
            //        TimePeriod = TimePeriod.Morning
            //    }
            //);
            //model.TodaysWeather.Add(
            //    new Weather
            //    {
            //        Temperature = 95,
            //        Status = WeatherType.Rainy,
            //        TimePeriod = TimePeriod.Afternoon
            //    }
            //);
            //model.TodaysWeather.Add(
            //    new Weather
            //    {
            //        Temperature = 75,
            //        Status = WeatherType.Cloudy,
            //        TimePeriod = TimePeriod.Night
            //    }
            //);
            return(PartialView("_TodaysWeather", model));
        }
 public RefreshCommand(WeatherVM vm)
 {
     VM = vm;
 }
コード例 #19
0
 public SearchCommand(WeatherVM vm)
 {
     VM = vm;
 }
コード例 #20
0
 public RefreshCommand(WeatherVM vm)         // passing the ViewModel Object so that the system does not generate a new view madel
                                             // every time button is clicked
 {
     VM = vm;
 }
コード例 #21
0
 public DetailsCommand(WeatherVM vm)
 {
     VM = vm;
 }
コード例 #22
0
 public SearchCommand(WeatherVM vm)
 {
     _vm = vm;
 }
コード例 #23
0
 public SearchCommand(WeatherVM viewModel)
 {
     ViewModel = viewModel;
 }
コード例 #24
0
 public SearchCommand(WeatherVM weatherVM)
 {
     this.weatherVM = weatherVM;
 }
コード例 #25
0
 public SearchCommand(WeatherVM vM)
 {
     VM = vM;
 }
コード例 #26
0
 public IActionResult Index(WeatherVM weathervm)
 {
     weathervm.LocalCity = _cityService.CheckLocalWeather().LocalCity;
     return(View(weathervm));
 }