Пример #1
0
        public async Task FetchAndSyncWeather_StoresNewDataInCache_WhenNoneExistsInCache()
        {
            // Expire cache data, by making it older than 4 hours
            var weatherDto = FakerT <WeatherDto> .Generate();

            weatherDto.LocaleId = 3;
            var mockWeatherApi = new Mock <IWeatherApi>();

            mockWeatherApi.Setup(api => api.GetWeatherForLocation(3)).Returns(Task.FromResult(TestDataGenerator.LocationWeather(3)));

            var option     = new DbContextOptionsBuilder <WeatherDbContext>().UseInMemoryDatabase("WeatherInMemoryDatabase").Options;
            var dbContext  = new WeatherDbContext(option);
            var repository = new WeatherRepository(dbContext);

            // Act
            var sut = new FetchManager.FetchManager(mockWeatherApi.Object, repository, new OpenWeatherSettings()
            {
                CacheExpiryMinutes = 180
            });
            var result = (await sut.FetchAndSyncWeatherForLocationAsync(3)).FirstOrDefault();

            // Assert
            Assert.Equal(3, result.LocaleId);
            var insertedObject = await repository.GetWeatherById(3);

            Assert.Equal(3, insertedObject.Count);
        }
Пример #2
0
        public async Task AddWeatherInDbRecursively()
        {
            string     url    = "http://api.openweathermap.org/data/2.5/weather?q=Valletta&units=metric&appid=d12e761b653064784c9d028522c92fe9";
            HttpClient client = new HttpClient();
            string     result;
            JObject    currentWeather;

            while (true)
            {
                result = "\0";
                result = await client.GetStringAsync(url);  //waiting to receive required data asynchronously.

                //Storing json into JObject
                currentWeather = JObject.Parse(result);
                Weather w = new Weather();

                var weather = currentWeather["weather"] as JArray;
                foreach (JObject item in weather)
                {
                    w.Main = item["main"].Value <string>();
                    w.Desc = item["description"].Value <string>();
                }

                w.Temperature = currentWeather["main"]["temp"].Value <decimal>();
                w.Humidity    = currentWeather["main"]["humidity"].Value <int>();

                w.WindSpeed = currentWeather["wind"]["speed"].Value <decimal>();
                w.WindDirectionInDegrees = currentWeather["wind"]["deg"].Value <int>(); //returns wind direction in degrees

                w.W_Id      = Guid.NewGuid();
                w.TimeStamp = DateTime.Now;


                w.WindDirection = GetWindDirection(); //need to implement this to change from degrees to a wind direction.


                //addToDb
                WeatherRepository wr = new WeatherRepository();
                wr.InsertLatestWeatherUpdate(w);

                UsersController   uc    = new UsersController();
                RequestController rc    = new RequestController();
                EmailController   ec    = new EmailController();
                List <User>       users = uc.GetUsers();

                if (users != null)
                {
                    foreach (User u in users)
                    {
                        Request latestRequest = rc.GetLatestRequestByEmail(u.Email);
                        if (latestRequest != null)
                        {
                            ec.SendEmail(latestRequest);
                        }
                    }
                }

                await Task.Delay(new TimeSpan(0, 1, 0));
            }
        }
Пример #3
0
        // POST api/transfernumberapi
        public string Post([FromBody] string requestStr)
        {
            try
            {
                WeatherRequest requests = JsonConvert.DeserializeObject <WeatherRequest>(requestStr);
                string         output   = "";

                WeatherRepository repository = new WeatherRepository();
                WeatherResult     results    = repository.Check(requests);
                output = JsonConvert.SerializeObject(results);

                return(output);
            }
            catch (Exception ex)
            {
                //發生錯誤時,傳回HTTP 500及錯誤訊息
                var resp = new HttpResponseMessage()
                {
                    StatusCode   = HttpStatusCode.InternalServerError,
                    Content      = new StringContent(ex.Message),
                    ReasonPhrase = "Web API Error"
                };
                throw new HttpResponseException(resp);
            }
        }
        public void GetCountries()
        {
            IWeatherRepository _iWeatherRepository = null;

            _iWeatherRepository = new WeatherRepository();
            List <Country> expectedCountries = new List <Country>()
            {
                new Country(1, "Australia"),
                new Country(2, "America"),
                new Country(3, "England")
            };
            List <Country>    actualCountries = null;
            WeatherController wc = new WeatherController(_iWeatherRepository);

            wc.Request = new HttpRequestMessage()
            {
                Properties = { { HttpPropertyKeys.HttpConfigurationKey, new HttpConfiguration() } }
            };

            HttpResponseMessage response = wc.GetCountries();

            response.TryGetContentValue <List <Country> >(out actualCountries);

            Assert.AreEqual(expectedCountries, actualCountries);
        }
        public void GetWeatherDataByCity()
        {
            IWeatherRepository _iWeatherRepository = null;
            int cityID = 1;

            _iWeatherRepository = new WeatherRepository();
            tblTemperature expectedTempData = new tblTemperature();

            expectedTempData.CityID           = 1;
            expectedTempData.Location         = "Paramatta";
            expectedTempData.Preasure         = 30;
            expectedTempData.RelativeHumidity = 50;
            expectedTempData.SkyCondition     = "Good";
            expectedTempData.Visibility       = 1;
            expectedTempData.DewPoint         = 1;


            List <Country>    actualTempData = null;
            WeatherController wc             = new WeatherController(_iWeatherRepository);

            wc.Request = new HttpRequestMessage()
            {
                Properties = { { HttpPropertyKeys.HttpConfigurationKey, new HttpConfiguration() } }
            };
            HttpResponseMessage response = wc.GetWeatherDataByCity(cityID);

            response.TryGetContentValue <List <Country> >(out actualTempData);

            Assert.AreEqual(expectedTempData, actualTempData);
        }
        public async Task <Condition> GetCurrentAsync()
        {
            WeatherFacade weatherFacade = new WeatherFacade(API.Value);
            Condition     weather       = null;

            using (appDB){
                WeatherRepository repo = new WeatherRepository(appDB);
                var cons = await repo.LatestConditionAsync();

                if (cons.Count > 0)
                {
                    weather = cons[0];
                    TimeSpan span = (DateTime.Now - weather.timeStamp);
                    if (span.Minutes < 10)
                    {
                        Console.WriteLine("db");
                        return(weather);
                    }
                }
                Console.WriteLine("api");
                var w = weatherFacade.GetCurrentWeatherDetail();
                if (w != null)
                {
                    await repo.InsertAsync(w);

                    weather = w;
                }
            }
            return(weather);
        }
Пример #7
0
        public void GetCurrentWeatherByCityTestNotGood()
        {
            IRestClient restclient;

            restclient = Substitute.For <IRestClient>();
            IRestRequest  request  = new RestRequest();
            IRestResponse response = new RestResponse();

            response.StatusCode = System.Net.HttpStatusCode.BadRequest;

            response.Content = JsonConvert.SerializeObject(new WeatherModel
            {
                Current = new CurrentWeather {
                    Humidity = 3
                },
                Location = new Location {
                    Name = "test", Country = "test"
                }
            });

            restclient.Execute(request).Returns(response);
            IWeatherRepository repository = new WeatherRepository(restclient, request);
            var result = repository.GetCurrentWeatherByCity("test");

            Assert.Null(result);
        }
Пример #8
0
        public async Task GetWeather_ByZip()
        {
            var client = new Mock <IWeatherClient>();

            client
            .Setup(i => i.GetByZipCodeAsync(It.IsAny <int>()))
            .ReturnsAsync(SuccessResponse);

            var repository = new WeatherRepository(client.Object);

            var result = await repository.GetAsync(10117);

            Assert.IsNotNull(result);
            Assert.AreEqual("Berlin", result.Name);
            Assert.AreEqual(2950159, result.Id);
            Assert.IsNotNull(result.Weather);
            Assert.IsNotEmpty(result.Weather);
            Assert.IsTrue(result.Weather.Any(i => i.Date.Date == DateTime.Now.Date));

            foreach (var item in result.Weather)
            {
                Assert.Greater(item.Date, DateTime.MinValue);
                Assert.Greater(item.Temperature, 0);
                Assert.Greater(item.Pressure, 0);
                Assert.Greater(item.Humidity, 0);
                Assert.IsNotNull(item.WindSpeed);
            }
        }
Пример #9
0
        public void GetWeatherDataFromAPiWhenNoCacheExists()
        {
            // Arrange
            const int  zipCode               = 95661;
            const bool fromCache             = false;
            var        mockIWeatherService   = new Mock <IWeatherService>();
            var        mockIWeatherDataCache = new Mock <IWeatherDataCache>();
            var        mockIJsonParsor       = new Mock <IJsonParsor>();
            //var testWeatherAPISettings = GenerateTestAPISettings();
            var rawTestData   = GenerateTestJSONRawData();
            var finalTestData = GenerateTestJSONFinalData(fromCache, zipCode);

            mockIWeatherService.Setup(x => x.GetRawDataFromApi(zipCode)).Returns(Task.FromResult(rawTestData));
            mockIWeatherDataCache.Setup(p => p.RetrieveDataFromCache(zipCode)).Returns(string.Empty);
            mockIJsonParsor.Setup(y => y.ConvertJSONToModel(zipCode, rawTestData, fromCache)).Returns(finalTestData);
            WeatherRepository weatherRepo = new WeatherRepository(mockIWeatherService.Object, mockIWeatherDataCache.Object, mockIJsonParsor.Object);

            // Act
            var testWeatherData = weatherRepo.GetWeatherData(zipCode);

            // Assert
            Assert.IsNotNull(testWeatherData, "weatherRepo.GetWeatherData returned null!");
            Assert.AreEqual(zipCode.ToString(), testWeatherData.ZipCode);
            Assert.AreEqual(2, testWeatherData.ForcastInfo.Count);
            Assert.IsFalse(testWeatherData.FromCache);
        }
Пример #10
0
        public IActionResult Index()
        {
            var repository = new WeatherRepository();

            ViewBag.Result = repository.GetHourlyWeather();
            return(View());
        }
Пример #11
0
        public Weather GetRequestedInformation(string[] userInfo)
        {
            if (userInfo != null)
            {
                WeatherRepository wr            = new WeatherRepository();
                Weather           latestWeather = wr.getLatestWeatherFromDb();
                string            itemLowCase   = "\0";

                if (userInfo.Length == 0 || userInfo.Length > 6)
                {
                    return(null);
                }
                else
                {
                    Weather filteredWeather = new Weather();
                    filteredWeather.W_Id      = latestWeather.W_Id;
                    filteredWeather.TimeStamp = latestWeather.TimeStamp;

                    foreach (string item in userInfo)
                    {
                        if (item != null)
                        {
                            itemLowCase = item.ToLower();

                            if (itemLowCase.Equals("description"))
                            {
                                filteredWeather.Desc = latestWeather.Desc;
                            }

                            else if (itemLowCase.Equals("temperature"))
                            {
                                filteredWeather.Temperature = latestWeather.Temperature;
                            }

                            else if (itemLowCase.Equals("humidity"))
                            {
                                filteredWeather.Humidity = latestWeather.Humidity;
                            }

                            else if (itemLowCase.Equals("wind speed"))
                            {
                                filteredWeather.WindSpeed = latestWeather.WindSpeed;
                            }

                            else if (itemLowCase.Equals("wind direction"))
                            {
                                filteredWeather.WindDirectionInDegrees = latestWeather.WindDirectionInDegrees;
                            }
                        }
                    }

                    return(filteredWeather); //Ok(filteredWeather);
                }
            }
            else
            {
                return(null);
            }
        }
Пример #12
0
        public async System.Threading.Tasks.Task GetForecastInfo()
        {
            var rep = new WeatherRepository();

            var forecast = await rep.GetForecastInfo(2744819);

            forecast.Should().NotBeNull();
        }
Пример #13
0
        public async System.Threading.Tasks.Task GetWeatherInfo()
        {
            var rep = new WeatherRepository();

            var weather = await rep.GetWeatherInfo(2744819);

            weather.Should().NotBeNull();
        }
Пример #14
0
        public static async Task <HttpResponseMessage> GetMostRecentData(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "get-most-recent")] HttpRequestMessage req,
            ILogger log)
        {
            log.LogInformation("C# HTTP trigger function GetMostRecentData processed a request.");

            return(req.CreateResponse(HttpStatusCode.OK, await WeatherRepository.GetMostRecentFromAllPartitions()));
        }
Пример #15
0
        public void GetWeatherAsync()
        {
            WeatherRepository weatherrepo = new WeatherRepository();

            Task <String> result = weatherrepo.GetWeatherAsync("Sydney");

            Assert.IsNotNull(result);
        }
Пример #16
0
        public void WeatherRepositoryConstructorWithParameterTestGood()
        {
            IRestClient        resclient  = new RestClient();
            IRestRequest       request    = new RestRequest();
            IWeatherRepository repository = new WeatherRepository(resclient, request);

            Assert.NotNull(repository);
        }
        protected override bool Execute(T ruleContext)
        {
            var userIp = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];

            if (string.IsNullOrEmpty(userIp))
            {
                userIp = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
            }

            var location = ((ILocationRepository) new LocationRepository())
                           .GetLocationFromIp(userIp, GetLocationApi());

            var request = new WeatherRequestModel()
            {
                AppId       = DataSourceItem.Fields["AppId"].Value,
                BaseURL     = DataSourceItem.Fields["AppWeatherBaseUrl"].Value,
                location    = location,
                RelativeURL = DataSourceItem.Fields["SearchByDestinationRelativeUrl"].Value,
                Unit        = GetValueFromTargetItem(DataSourceItem, "TemperatureUnit", "Name")
            };

            IWeatherRepository weatherServiceRepository = new WeatherRepository();

            var weatherInfoString = weatherServiceRepository.GetWeatherByCity(request);
            var weatherCurrent    = Newtonsoft.Json.JsonConvert.DeserializeObject <WeatherCurrent>(weatherInfoString);

            switch (this.GetOperator())
            {
            case ConditionOperator.Equal:
                return(SpecifiedValue
                       == System.Convert.ToInt32(Math.Round(weatherCurrent.main.temp)));

            case ConditionOperator.GreaterThanOrEqual:
                return(SpecifiedValue
                       >= System.Convert.ToInt32(Math.Round(weatherCurrent.main.temp)));

            case ConditionOperator.GreaterThan:
                return(SpecifiedValue
                       > System.Convert.ToInt32(Math.Round(weatherCurrent.main.temp)));

            case ConditionOperator.LessThanOrEqual:
                return(SpecifiedValue
                       <= System.Convert.ToInt32(Math.Round(weatherCurrent.main.temp)));

            case ConditionOperator.LessThan:
                return(SpecifiedValue
                       < System.Convert.ToInt32(Math.Round(weatherCurrent.main.temp)));

            case ConditionOperator.NotEqual:
                return(SpecifiedValue
                       != System.Convert.ToInt32(Math.Round(weatherCurrent.main.temp)));

            default:
                throw new ArgumentOutOfRangeException();
            }
        }
Пример #18
0
        public TelegramModule(
            WeatherRepository weatherRepository,
            TelegramMessageRepository telegramMessageRepository,
            NominatimSearchRepository nominatimSearchRepository)
        {
            _weatherRepository         = weatherRepository;
            _telegramMessageRepository = telegramMessageRepository;

            _nominatimSearchRepository = nominatimSearchRepository;
        }
Пример #19
0
        /// <summary>
        /// Init new instance
        /// </summary>
        /// <param name="client">Http client</param>
        /// <param name="config">Configuration</param>
        /// <exception cref="ArgumentNullException">Throws exception if config is null</exception>
        public OpenWeatherDatabase(HttpClient client, IOpenWeatherConfig config)
        {
            if (config is null)
            {
                throw new ArgumentNullException(nameof(config));
            }

            Weather  = new WeatherRepository(new WeatherClient(client, config.ApiKey));
            Forecast = new ForecastRepository(new ForecastClient(client, config.ApiKey));
        }
        public dynamic GetWeatherConditionsByCity(int idCity)
        {
            try
            {
                WeatherRepository weatherRepository = new WeatherRepository();

                int partFromToday = ((int)DateTime.Now.DayOfWeek == 0) ? 7 : (int)DateTime.Now.DayOfWeek;

                var weatherConditionsList = weatherRepository.GetWeatherConditionsByCity(idCity, partFromToday);

                if (weatherConditionsList != null)
                {
                    Logger.Instance.WriteInLog(LogType.INFO, "Weather conditions successfully obtained");

                    WeatherConditionsResponse weatherConditionsResponse = new WeatherConditionsResponse();
                    weatherConditionsResponse.weatherConditions = new List <WeatherCondition>();

                    foreach (var weatherConditionTemp in weatherConditionsList)
                    {
                        WeatherCondition weatherCondition = new WeatherCondition();
                        weatherCondition.cityId                = weatherConditionTemp.IdCity;
                        weatherCondition.dayId                 = weatherConditionTemp.IdDay;
                        weatherCondition.weatherId             = weatherConditionTemp.IdWeather;
                        weatherCondition.dayName               = weatherConditionTemp.Days.Day;
                        weatherCondition.dayWeather            = weatherConditionTemp.Weathers.Weather;
                        weatherCondition.humidity              = weatherConditionTemp.Humidity;
                        weatherCondition.precipitation         = weatherConditionTemp.Precipitation;
                        weatherCondition.temperatureCelsius    = weatherConditionTemp.TemperatureCelsius;
                        weatherCondition.temperatureFahrenheit = weatherConditionTemp.TemperatureFahrenheit;
                        weatherCondition.wind = weatherConditionTemp.Wind;
                        weatherConditionsResponse.weatherConditions.Add(weatherCondition);
                    }

                    return(JObject.Parse(JsonConvert.SerializeObject(weatherConditionsResponse)));
                }
                else
                {
                    Logger.Instance.WriteInLog(LogType.WARNING, "Something wrong ocurred while getting the weather conditions");
                    return(JObject.Parse(JsonConvert.SerializeObject(new WeatherConditionsResponse
                    {
                        weatherConditions = new List <WeatherCondition>(),
                        errors = "Could not get the weather conditions"
                    })));
                }
            }
            catch (Exception ex)
            {
                Logger.Instance.WriteInLog(LogType.ERROR, "An error ocurred while getting the weather conditions", null, ex.Message);
                return(JObject.Parse(JsonConvert.SerializeObject(new WeatherConditionsResponse
                {
                    weatherConditions = new List <WeatherCondition>(),
                    errors = ex.Message.ToString()
                })));
            }
        }
        public void GetCountry_ForFakeCountry_ReturnsNull_Test()
        {
            // Arrange
            IWeatherRepository weatherRepository = new WeatherRepository();

            // Act
            Country country = weatherRepository.GetCountry("Moon");

            // Assert
            Assert.IsNull(country);
        }
Пример #22
0
 // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
 public void Configure(WeatherForecast weather, WeatherRepository weatherRepo, IApplicationBuilder app, IWebHostEnvironment env)
 {
     app.UseRouting();
     app.UseEndpoints(endpoints =>
     {
         endpoints.MapGet("/weatherforecast", async context =>
         {
             await context.Response.WriteAsJsonAsync(weather);
         });
     });
 }
        public void GetCountry_Test()
        {
            // Arrange
            IWeatherRepository weatherRepository = new WeatherRepository();

            // Act
            Country country = weatherRepository.GetCountry("Australia");

            // Assert
            Assert.AreEqual("Australia", country.Name);
            Assert.IsTrue(country.Cities.Where(c => c.Name.Equals("Sydney Airport")).Count() > 0);
        }
Пример #24
0
        // GET: api/Conditions?location=paris
        public string Get(string location, string days)
        {
            WeatherRepository weatherRepo = new WeatherRepository();
            WeatherModel      weather     = weatherRepo.GetWeatherData(location, days);

            ConditionRepository conditionRepo = new ConditionRepository();
            ConditionModel      condition     = conditionRepo.Map(weather);

            JavaScriptSerializer serializer = new JavaScriptSerializer();

            return(serializer.Serialize(condition));
        }
Пример #25
0
 public IHttpActionResult GetLatestWeatherUpdate()
 {
     try
     {
         WeatherRepository wr = new WeatherRepository();
         return(Ok(wr.getLatestWeatherFromDb()));
     }
     catch (Exception e)
     {
         return(InternalServerError(new Exception(e.Message)));
     }
 }
        public void GetWeather_Test()
        {
            // Arrange
            IWeatherRepository weatherRepository = new WeatherRepository();

            // Act
            Weather weather = weatherRepository.GetWeather("Australia", "Sydney Airport");

            // Assert
            Assert.AreEqual("Australia", weather.Country.Name);
            Assert.AreEqual("Sydney Airport", weather.City.Name);
            Assert.AreEqual("Sydney /Australia 28-34N 077-07E 233M", weather.Location);
        }
 public void Arrange()
 {
     _weatherRepo = new WeatherRepository();
     _weather     = new Weather
     {
         WeatherID       = 1,
         IsPrecipitating = true,
         WindSpeed       = 30,
         WindDirection   = WindDirection.East,
         Temperature     = 55,
         WeatherDate     = DateTimeOffset.Now
     };
     _weatherRepo.AddWeatherItemToList(_weather);
 }
Пример #28
0
        public async Task GetWeather_ByName_Null()
        {
            var client = new Mock <IWeatherClient>();

            client
            .Setup(i => i.GetByCityNameAsync(It.IsAny <string>()))
            .ReturnsAsync(null as WeatherResponse);

            var repository = new WeatherRepository(client.Object);

            var result = await repository.GetAsync("Berlin");

            Assert.IsNull(result);
        }
Пример #29
0
        public async Task GetWeather_ByZip_Null()
        {
            var client = new Mock <IWeatherClient>();

            client
            .Setup(i => i.GetByZipCodeAsync(It.IsAny <int>()))
            .ReturnsAsync(SuccessResponse);

            var repository = new WeatherRepository(client.Object);

            var result = await repository.GetAsync(10117);

            Assert.IsNotNull(result);
        }
Пример #30
0
        //-- TestInit (Arrange)
        public void Arrange()
        {
            _weatherRepo = new WeatherRepository();
            Weather newWeather = new Weather
            {
                WeatherID       = 1,
                IsPrecipitating = true,
                WindSpeed       = 30,
                WindDirection   = Direction.East,
                Temperature     = 55
            };

            _weatherRepo.AddWeatherToList(newWeather);
        }
Пример #31
0
        public void GetAll()
        {
            // Arrange
            _datasourceMock.Setup(x => x.BuildDataSource<Observations>())
                          .Returns(new Observations
                          {
                              Observation = new[] {new Observation {StationName = "Station Name 1",DateTime = new DateTime(2013,4,11)}}
                          });
            var weatherRepository = new WeatherRepository(_datasourceMock.Object);

            // Action
            var result = weatherRepository.GetAll();

            // Assert
            Assert.AreEqual(1, result.Count());
            Assert.AreEqual("Station Name 1", result.FirstOrDefault().StationName);
            Assert.AreEqual(new DateTime(2013, 4, 11), result.FirstOrDefault().DateTime);
        }
Пример #32
0
        public void GetByNamedAndDateFromAndDateToSpecification()
        {
            // Arrange
            _datasourceMock.Setup(x => x.BuildDataSource<Observations>())
                          .Returns(new Observations
                          {
                              Observation = new[] { new Observation { StationName = "Station Name 1", DateTime = new DateTime(2013, 4, 11) },
                                                  new Observation { StationName = "Station Name 1", DateTime = new DateTime(2013, 4, 10) },
                                                  new Observation { StationName = "Station Name 2", DateTime = new DateTime(2013, 4, 11) }}
                          });
            var weatherRepository = new WeatherRepository(_datasourceMock.Object);

            // Action
            var result = weatherRepository.Get(new StationNameContainsText("1").And(new WeatherDataRecordedFromDate(new DateTime(2013, 4, 10)).And(new WeatherDataRecordedToDate(new DateTime(2013, 4, 11)))));

            // Assert
            Assert.AreEqual(2, result.Count());
            Assert.AreEqual("Station Name 1", result.FirstOrDefault().StationName);
        }