Example #1
0
        public static CityWeatherInfo Parse(JObject data)
        {
            var cityResult = data.SelectToken(@"$.name").ToObject <string>();

            var mainTokenResult = data.SelectToken(@"$.main");
            var tempResult      = mainTokenResult.SelectToken(@".temp").ToObject <string>();
            var humidityResult  = mainTokenResult.SelectToken(@".humidity").ToObject <int>();

            var weatherTokenResult = data.SelectToken(@"$.weather");
            var stateResult        = weatherTokenResult[0].SelectToken(@"description").ToObject <string>();
            var iconResult         = weatherTokenResult[0].SelectToken(@"icon").ToObject <string>();

            var cloudsResult = data.SelectToken(@"$.clouds.all").ToObject <int>();

            var result = new CityWeatherInfo()
            {
                Name         = cityResult,
                Temperature  = tempResult,
                Humidity     = humidityResult,
                WeatherState = stateResult,
                Icon         = iconResult,
                Clouds       = cloudsResult
            };

            return(result);
        }
Example #2
0
 public static void Update(CityWeatherInfo item, CityWeatherInfo result)
 {
     result.Clouds       = item.Clouds;
     result.Humidity     = item.Humidity;
     result.Icon         = item.Icon;
     result.Temperature  = item.Temperature;
     result.WeatherState = item.WeatherState;
 }
        public IActionResult AddCity(CityWeatherInfo cityname)
        {
            var userId = this.userManager.GetUserId(this.HttpContext.User);

            if (this.manager.AddCity(userId, cityname.Name))
            {
                return(this.RedirectToAction((nameof(WeatherController.Index))));
            }

            this.ModelState.AddModelError("Name", this.localizer["No city found"]);
            return(this.View(cityname));
        }
        public void SaveWeatherInfo(CityWeatherInfo info)
        {
            var lang = CultureInfo.CurrentCulture.Name;

            this.logger.LogTrace($"TRACE - {DateTime.Now} - Entered SaveWeatherInfo method");

            var cacheEntryOptions = new MemoryCacheEntryOptions()
                                    .SetAbsoluteExpiration(TimeSpan.FromHours(1));

            this.cache.Set(info.Name + lang, info, cacheEntryOptions);

            this.logger.LogDebug($"DEBUG - {DateTime.Now} - Added info about {info.Name} to cache");
            this.logger.LogTrace($"TRACE - {DateTime.Now} - Ended SaveWeatherInfo method");
        }
        private void GetCityWeather()
        {
            CityWeatherInfo data = new CityWeatherInfo()
            {
                City        = "Chandler",
                State       = "Az",
                FeelsLike   = "Nice",
                Temperature = 82,
                Id          = 1
            };

            cityInfos.Add(data);
            data = new CityWeatherInfo()
            {
                City        = "Odessa",
                State       = "Tx",
                FeelsLike   = "Windy",
                Temperature = 68,
                Id          = 2
            };
            cityInfos.Add(data);
            data = new CityWeatherInfo()
            {
                City        = "San Diego",
                State       = "Ca",
                FeelsLike   = "Beaching",
                Temperature = 74,
                Id          = 3
            };
            cityInfos.Add(data);
            data = new CityWeatherInfo()
            {
                City        = "Shemya",
                State       = "Ak",
                FeelsLike   = "Bad",
                Temperature = 35,
                Id          = 4
            };
            cityInfos.Add(data);
            data = new CityWeatherInfo()
            {
                City        = "Gilbert",
                State       = "Az",
                FeelsLike   = "Nicer",
                Temperature = 84,
                Id          = 5
            };
            cityInfos.Add(data);
        }
        public async Task <string> AddAsync(CityWeatherInfo entity)
        {
            string result = "";

            //validate the object
            if (entity.Id == 0 && CityNotAdded(entity.City))
            {
                var newId = (from a in cityInfos
                             select a.Id).Max() + 1;
                entity.Id = newId;
                //add to the collection
                cityInfos.Add(entity);
            }
            else
            {
                result = "City is already is in use.";
            }
            await Task.CompletedTask;

            return(result);
        }
Example #7
0
 public void Update(Domain.Models.CityWeatherInfo item)
 {
     try
     {
         using (var context = new CityWeatherInfoContext())
         {
             var daoModel = new CityWeatherInfo
             {
                 CityId         = item.CityId,
                 Name           = item.Name,
                 TempDay        = item.TempDay,
                 TempNight      = item.TempNight,
                 WeatherComment = item.WeatherComment
             };
             context.Entry(daoModel).State = EntityState.Modified;
             context.SaveChanges();
         }
     }
     catch (Exception e)
     {
         throw new Domain.Exceptions.CityWeatherInfoRepositoryException(e.Message, e);
     }
 }
        public async Task <string> UpdateAsync(CityWeatherInfo entity)
        {
            string result = "";
            var    t      = from a in cityInfos
                            where a.Id == entity.Id
                            select a;

            if (t.Any())
            {
                CityWeatherInfo old = t.FirstOrDefault();
                old.City        = entity.City;
                old.State       = entity.State;
                old.Temperature = entity.Temperature;
                old.FeelsLike   = entity.FeelsLike;
            }
            else
            {
                result = "Unable to find city to update";
            }
            await Task.CompletedTask;

            return(result);
        }
Example #9
0
 public async Task <IViewComponentResult> InvokeAsync(CityWeatherInfo data)
 {
     return(this.View(data));
 }
        public void Setup()
        {
            _moockLogger = new Mock <ILogger <WeatherInfoController> >();
            _mockinsurwaveWeatherInfoService = new Mock <IInsurwaveWeatherInfoService>();
            _mockmapper = new Mock <IMapper>();

            _current = new Current
            {
                TempC = "11.0",
                TempF = "54.3"
            };

            _location = new Location
            {
                Name      = "London",
                Country   = "United Kingdom",
                Localtime = "2020-11-16 13:02",
                Region    = "City of London, Greater London"
            };

            _currentDetail = new CurrentDetail
            {
                Current  = _current,
                Location = _location
            };

            _astronomyDetail = new AstronomyDetail {
                Astronomy = new Astronomy
                {
                    Astro = new Astro {
                        Sunrise = "07:21 AM",
                        Sunset  = "04:09 PM"
                    }
                },
                Location = _location
            };

            _city = "London";
            _date = DateTime.UtcNow;

            _cityWeatherInfo = new CityWeatherInfo
            {
                City        = _currentDetail.Location.Name,
                Country     = _currentDetail.Location.Country,
                LocalTime   = _currentDetail.Location.Localtime,
                Region      = _currentDetail.Location.Region,
                Temperature = _currentDetail.Current.TempC
            };

            _cityDetailWithTempUnit = new CityDetailWithTempUnit
            {
                City      = _currentDetail.Location.Name,
                Country   = _currentDetail.Location.Country,
                LocalTime = _currentDetail.Location.Localtime,
                Region    = _currentDetail.Location.Region
            };



            WeatherApiHttpClientResponse = new WeatherApiHttpClientResponse
            {
                Data          = JsonConvert.SerializeObject(_currentDetail),
                IsSuccessFull = true,
                StatusCode    = HttpStatusCode.OK
            };

            AstronomyWeatherApiHttpClientResponse = new WeatherApiHttpClientResponse
            {
                Data          = JsonConvert.SerializeObject(_astronomyDetail),
                IsSuccessFull = true,
                StatusCode    = System.Net.HttpStatusCode.OK
            };

            _mockinsurwaveWeatherInfoService.Setup(x => x.GetLocalWeatherInfo(_city)).Returns(Task.FromResult(WeatherApiHttpClientResponse));

            _mockinsurwaveWeatherInfoService.Setup(x => x.GetAstronomyInfo(_city, _date)).Returns(Task.FromResult(AstronomyWeatherApiHttpClientResponse));
            _mockinsurwaveWeatherInfoService.Setup(x => x.GetAstronomyInfo(_city, null)).Returns(Task.FromResult(AstronomyWeatherApiHttpClientResponse));
            //  _moockLogger.Setup(x => x.LogError(It.IsAny<string>(), It.IsAny<Object>()));
            _mockmapper.Setup(x => x.Map <CityWeatherInfo>(It.IsAny <CurrentDetail>())).Returns(_cityWeatherInfo);
            _mockmapper.Setup(x => x.Map <CityDetailWithTempUnit>(It.IsAny <CurrentDetail>())).Returns(_cityDetailWithTempUnit);

            SUT = new WeatherInfoController(_moockLogger.Object, _mockinsurwaveWeatherInfoService.Object, _mockmapper.Object);
        }
Example #11
0
        private async Task RunAsync(CancellationToken ct)
        {
            var sleepPeriod = new TimeSpan(0, 0, 10);

            while (true)
            {
                int addedCities = 0, updatedCities = 0;
                var weatherDate = DateTime.Now.AddDays(1);

                try
                {
                    if (ct.IsCancellationRequested)
                    {
                        ct.ThrowIfCancellationRequested();
                    }

                    var cities = await _weatherProvider.GetCitiesAsync();

                    var localWeatherData = _weatherRepository.GetAll();
                    foreach (var city in cities)
                    {
                        var weatherForCity = localWeatherData.FirstOrDefault(w => w.Name.Equals(city.Name));
                        var weatherOnDate  = await GetWeatherOnDate(city, weatherDate);

                        if (weatherForCity == null)
                        {
                            var newCity = new CityWeatherInfo
                            {
                                Name           = city.Name,
                                TempDay        = weatherOnDate.TempDay,
                                TempNight      = weatherOnDate.TempNight,
                                WeatherComment = weatherOnDate.WeatherComment
                            };
                            _weatherRepository.Create(newCity);
                            addedCities++;
                            continue;
                        }

                        if (weatherForCity.TempDay == weatherOnDate.TempDay &&
                            weatherForCity.TempNight == weatherOnDate.TempNight &&
                            weatherForCity.WeatherComment == weatherOnDate.WeatherComment)
                        {
                            continue;
                        }

                        weatherForCity.TempDay        = weatherOnDate.TempDay;
                        weatherForCity.TempNight      = weatherOnDate.TempNight;
                        weatherForCity.WeatherComment = weatherOnDate.WeatherComment;
                        _weatherRepository.Update(weatherForCity);
                        updatedCities++;
                    }

                    Console.WriteLine($"Added: {addedCities}, Updated:{updatedCities}");
                    ct.WaitHandle.WaitOne(sleepPeriod);
                }
                catch (CityWeatherInfoRepositoryException e)
                {
                    Console.WriteLine("Database Error");
                    Console.WriteLine(e.ToString());
                    break;
                }
                catch (WeatherProviderServiceException e)
                {
                    Console.WriteLine("Weather provider Error");
                    Console.WriteLine(e.ToString());
                    break;
                }
                catch (OperationCanceledException)
                {
                    break;
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.ToString());
                    throw;
                }
            }
        }