Exemple #1
0
        public void Test1()
        {
            WeatherForecastService service = new WeatherForecastService();

            service.AddCity("Rennes");
            Assert.AreEqual(2, WeatherForecastService.Cities.Count);
        }
        public FetchDataViewModel(WeatherForecastService weatherForecastService)
        {
            _weatherForecastService = weatherForecastService;
            LoadForecasts           = ReactiveCommand.CreateFromTask(LoadWeatherForecastsAsync);

            _forecasts = LoadForecasts.ToProperty(this, x => x.Forecasts, scheduler: RxApp.MainThreadScheduler);
        }
        public void Should_Return_Forecasts()
        {
            var service   = new WeatherForecastService();
            var forecasts = service.Get();

            Assert.NotEmpty(forecasts);
        }
 public WeatherForecastController(
     WeatherForecastService weatherForecastService,
     IDistributedCache distributedCache)
 {
     _weatherForecastService = weatherForecastService;
     _distributedCache = distributedCache;
 }
Exemple #5
0
        private async void OnSearch(string city)
        {
            city   = city.Trim();
            Title  = $"Weather in {city}";
            Date   = DateTime.Now.ToString("D");
            IsBusy = true;

            try
            {
                var id = await GetCityId(city);

                var service  = new WeatherForecastService();
                var forecast = await service.FetchForecastAsync(id + "");

                Title = $"Weather in {forecast.CityName}, {forecast.CountryCode}";
                Publish(forecast);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error");
            }
            finally
            {
                IsBusy = false;
            }
        }
        public WeatherForecastController(
            ILogger <WeatherForecastController> logger,
            IOptionsSnapshot <DatabaseSettings> databaseSettingsAccessor,
            IOptions <UnvalidatedSettings> unvalidatedSettingsAccessor,
            IOptionsMonitor <MonitoredSettings> monitoredSettingsAccessor,
            IOptions <UnmonitoredButValidatedSettings> unmonitoredButValidatedSettingsAccessor,
            WeatherForecastService weatherForecastService
            )
        {
            _logger = logger;
            _weatherForecastService = weatherForecastService;

            /* If options-pattern validation fails, code will error out here.  However, it will error out on the
             * first object that fails to validate.  You could wrap a try-catch around all of the calls.
             *
             * example:
             *   - OptionsValidationException: Comment1 is required.; DatabaseType is required.; Comment2 is required.;
             *     SchemaNames.Schema1 is required.; SchemaNames.Schema2 is required.
             */

            // There's no validator for this one.
            _unvalidatedSettings = unvalidatedSettingsAccessor.Value;

            // IOptions<T> is a singleton that only validates on the first-use (anywhere).
            _unmonitoredButValidatedSettings = unmonitoredButValidatedSettingsAccessor.Value;

            // IOptionsMonitor<T> only runs when the underlying file has actually changed (still a singleton).
            _monitoredSettings = monitoredSettingsAccessor.CurrentValue;

            // IOptionsSnapshot<T> runs validation on every new request.
            _databaseSettings = databaseSettingsAccessor.Value;
        }
Exemple #7
0
        protected override async Task OnInitializedAsync()
        {
            WeatherForecastModel.UseAnnotations = true;
            weatherForecasts = await WeatherForecastService.GetForecastAsync(DateTime.Now);

            WeatherForecastModel.Rows = weatherForecasts;
        }
Exemple #8
0
 public WeatherForecastController(WeatherForecastService forecastService, ILogger <WeatherForecastController> logger = null)
 {
     if (logger != null)
     {
         _logger = logger;
     }
     _forecastService = forecastService ?? throw new ArgumentNullException(nameof(forecastService));
 }
        public void Setup()
        {
            logger            = new Mock <ILogger <WeatherForecastService> >().Object;
            randomizerService = new Mock <IRandomizerService>().Object;

            weatherForecastService = new WeatherForecastService(
                logger, randomizerService);
        }
        public async Task Fetch_forecast_should_succeed()
        {
            var          service  = new WeatherForecastService();
            const string cityId   = "2950159";
            var          forecast = await service.FetchForecastAsync(cityId);

            AssertForecastDocument(forecast);
        }
        public async Task GetForecastAsyncTest()
        {
            WeatherForecastService service = new WeatherForecastService();
            var result = await service.GetForecastAsync(DateTime.Now);

            Assert.NotNull(result);
            Assert.IsNotEmpty(result);
        }
        public FetchDataViewModel() : base("Fetch Data")
        {
            this.weatherForecastService = Locator.Current.GetService <WeatherForecastService>();

            forecastList.Connect().Bind(WeatherForecastItems).Subscribe();

            Initialize();
        }
 public WeatherForecastController(WeatherForecastService forecastService, CorrelationProviderAccessor correlationProviderAccessor, ILogger <WeatherForecastController> logger = null)
 {
     if (logger != null)
     {
         _logger = logger;
     }
     _forecastService = forecastService ?? throw new ArgumentNullException(nameof(forecastService));
     CorrelationProviderAccessorInstance = correlationProviderAccessor ?? throw new ArgumentNullException(nameof(correlationProviderAccessor));
 }
 public WeatherForecastViewModel(INavigationService navigationService)
 {
     _service           = new WeatherForecastService();
     _navigationService = navigationService;
     SearchWeather      = new RelayCommand(GetWeatherForecast);
     CityName           = "";
     Days = "1";
     GetSavedCities();
 }
Exemple #15
0
        public async Task SearchLocationAsync_ReturnLimaCity()
        {
            var weatherService = new WeatherForecastService(_settings, _httpClient);

            var weatherResponse = await weatherService.SearchLocationAsync("Lima");

            var weatherList = (List <Weather>)weatherResponse.Data;

            Assert.Equal("Lima", weatherList[0].Title);
        }
            public async Task <WeatherForecastState> UpdateAsync(
                ILiveState <Local, WeatherForecastState> liveState, CancellationToken cancellationToken)
            {
                var local     = liveState.Local;
                var forecasts = await WeatherForecastService.GetForecastAsync(local.StartDate, cancellationToken);

                return(new WeatherForecastState()
                {
                    Forecasts = forecasts
                });
            }
        public void GetWeatherForecast__ReturnsWindForecast()
        {
            // https://www.latlong.net/convert-address-to-lat-long.html
            // Roermond NL
            var locationKey            = "248715";
            var weatherForecastService = new WeatherForecastService();
            var forecast = weatherForecastService.GetWeatherForecast(locationKey, ApiKey, "de-de", true, true);

            Assert.True(!double.IsNaN(forecast.DailyForecasts[0].Day.Wind.Speed.Value));
            Assert.Equal("km/h", forecast.DailyForecasts[0].Day.Wind.Speed.Unit);
        }
Exemple #18
0
    static async Task Main()
    {
        var service   = new WeatherForecastService();
        var forecasts = await service.GetForecastAsync(DateTime.Now);

        Console.WriteLine("Date\tTemp. (C)\tTemp. (F)\tSummary");
        foreach (var f in forecasts)
        {
            Console.WriteLine($"{f.Date.ToShortDateString()}\t" +
                              $"{f.TemperatureC}\t{f.TemperatureF}\t{f.Summary}");
        }
    }
Exemple #19
0
        private static void Consumer_ReceivedAsync(object sender, BasicDeliverEventArgs e)
        {
            var body    = e.Body;
            var message = Encoding.UTF8.GetString(body);

            Console.WriteLine(" [Weater Forecast] Requets to Weather was received from Rabbit: {0}", message);

            if (!string.IsNullOrEmpty(message))
            {
                var response = new WeatherForecastService().GetOpenweatherForecast(message);
                messageService.Enqueue(response.Result);
            }
        }
Exemple #20
0
        public void Should_return_forecast_for_coords()
        {
            // Arrange
            var          service   = new WeatherForecastService();
            const double latitude  = 59.334415;
            const double longitude = 18.110103;

            // Act
            var forecast = service.GetForecastByCoords(latitude, longitude);

            // Assert
            Assert.IsNotNull(forecast);
        }
Exemple #21
0
        public async Task WeatherForecastService_ReturnsCollectionOfItems_WhenAmountOfItemsWasRequested()
        {
            //Arrange
            var numberOfRecords = 5;

            var sut = new WeatherForecastService(_summariesService);

            //Act
            var result = await sut.GetMultipleAsync(numberOfRecords, CancellationToken.None);

            //Assert
            result.Should().HaveCount(numberOfRecords);
        }
Exemple #22
0
        public async Task GetWeatherReport_invalidCity_Test()
        {
            var service = new WeatherForecastService();

            var            controller  = new HomeController(service);
            WeatherDataDTO weatherData = new WeatherDataDTO();

            var result = await controller.GetWeatherReport("InvalidCity") as JsonResult;

            weatherData = JsonConvert.DeserializeObject <WeatherDataDTO>(result.Data.ToString());

            Assert.AreEqual(weatherData.ErrorMessage, "Please specify a valid city name to get the weather forecast. Or the service is currently unavailable.");
        }
Exemple #23
0
        public async Task Test_GetForecastByCoordsAsync()
        {
            // Arrange
            var          service   = new WeatherForecastService();
            const double latitude  = 59.334415;
            const double longitude = 18.110103;

            // Act
            var forecast = await service.GetForecastByCoordsAsync(latitude, longitude);


            // Assert
            Assert.IsNotNull(forecast);
        }
        public void WeatherForecastService_ShouldReturnRequestedNumberOfForecasts_WhenWeatherForecastRepositoryReturnsData(int forecastLengthInDays)
        {
            var weatherForecastRepositoryMock = new Mock <IWeatherForecastRepository>();

            weatherForecastRepositoryMock.Setup(m => m.GetWeatherForecast(It.IsAny <int>()))
            .Returns(new WeatherForecast());
            var sut = new WeatherForecastService(Logger.None, weatherForecastRepositoryMock.Object);

            var actual = sut.GetWeatherForecast(forecastLengthInDays);

            actual.Should()
            .NotBeEmpty()
            .And.HaveCount(forecastLengthInDays);
        }
Exemple #25
0
        public void GetWeatherForecast__ReturnsWindForecast()
        {
            var dtOffset = new DateTimeOffset(DateTime.Now);
            var dt       = dtOffset.ToUnixTimeSeconds();

            // https://www.latlong.net/convert-address-to-lat-long.html
            // Roermond NL
            var lat = 51.192699;
            var lon = 5.992880;

            var weatherForecastService = new WeatherForecastService();
            var forecast = weatherForecastService.GetWeatherForecast(lat, lon, ApiKey, "metric", "de");

            Assert.True(!double.IsNaN(forecast.daily[0].wind_speed));
        }
Exemple #26
0
        public async Task GetWeatherReport_validCity_Test()
        {
            var service = new WeatherForecastService();

            var            controller  = new HomeController(service);
            WeatherDataDTO weatherData = new WeatherDataDTO();

            var result = await controller.GetWeatherReport("Basingstoke") as JsonResult;

            weatherData = JsonConvert.DeserializeObject <WeatherDataDTO>(result.Data.ToString());

            Assert.AreEqual(weatherData.ErrorMessage, "");
            Assert.IsTrue(weatherData.ForecastList.Count > 0);
            Assert.IsTrue(weatherData.CityName.Equals("Basingstoke"));
        }
Exemple #27
0
        public void TestAirPressureLow()
        {
            var wfs = new WeatherForecastService(new MockWeatherForecastRepo(), new MockAirpressuerServiceLow());
            var wf  = new WeatherForecast()
            {
                Id           = Guid.NewGuid(),
                Date         = DateTime.Now,
                PosX         = 1.0,
                PosY         = 1.0,
                TemperatureC = 30,
            };

            wfs.Add(wf);
            var nwf = wfs.GetForecast(wf.Id);

            Assert.True(nwf.Id == wf.Id);
            Assert.Contains("Lavtryk", nwf.Summary);
        }
Exemple #28
0
        public async Task Test_GetForecast_City_Async()
        {
            // Arrange
            var          service   = new WeatherForecastService();
            const double latitude  = 59.334415;
            const double longitude = 18.110103;
            var          city      = new City {
                X = latitude, Y = longitude, Name = "Stockholm"
            };


            // Act
            var forecast = await service.GetForecastAsync(city);


            // Assert
            Assert.AreEqual(forecast.CityName, city.Name);
        }
Exemple #29
0
        public IActionResult Get([FromServices] WeatherForecastService service, string nextDays)
        {
            int?days = null;

            try
            {
                if (nextDays != null)
                {
                    days = int.Parse(nextDays);
                }
                return(Ok(service.RetrieveForecast(days)));
            }
            catch (FormatException ex)
            {
                _logger.LogError(ex, "O valor informado {NextDays} não é um valor aceito.", nextDays);
                return(BadRequest());
            }
        }
        static void Main(string[] args)
        {
            WeatherForecastService a = new WeatherForecastService();

            var resultado = a.Get();

            foreach (var clima in resultado)
            {
                Console.WriteLine("Clima: " + clima.Summary
                                  + " Data: " + clima.Date
                                  + " Temperatura C " + clima.TemperatureC
                                  + " Temperatura F " + clima.TemperatureF);

                Console.WriteLine();
            }

            Console.ReadLine();
        }