Ejemplo n.º 1
0
 public TemperatureLookupFacade
     (WeatherService weatherService, GeoLookupService geoLookupService, EnglishMetricsConverter converter)
 {
     this.weatherService   = weatherService;
     this.geoLookupService = geoLookupService;
     this.converter        = converter;
 }
Ejemplo n.º 2
0
        public Object GetHourlyReportWeatherBit(string lat, string lon, string start_date, string end_date)
        {
            Console.WriteLine(lat);
            Console.WriteLine(lon);
            Console.WriteLine(start_date);
            Console.WriteLine(end_date);

            WeatherService obj = new WeatherService();
            IDatabase      db  = AppConstant.rediscon.GetDatabase();


            var projectData = db.StringGet("WeatherBitHourly" + lat + lon + start_date + end_date);

            if (!string.IsNullOrEmpty(projectData))
            {
                Console.WriteLine("Get Data From Cache");
                return(JsonConvert.DeserializeObject(projectData));
            }
            else
            {
                Console.WriteLine("Set Data in Cache");
                db.StringSet("WeatherBitHourly" + lat + lon + start_date + end_date, obj.GetHourlyReportWeatherBit(lat, lon, start_date, end_date));
                Console.WriteLine("Set Data in Cache");
                projectData = db.StringGet("WeatherBitHourly" + lat + lon + start_date + end_date);
                Console.WriteLine("Set Data in Cache");
                return(JsonConvert.DeserializeObject(projectData));
            }
        }
Ejemplo n.º 3
0
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            var appConfiguration = Configuration.Get <AppConfiguration>();

            var httpClient        = new HttpClient();
            var zWayService       = new ZWayService(httpClient, LoggerFactory.CreateLogger <ZWayService>());
            var weatherService    = new WeatherService(httpClient, LoggerFactory.CreateLogger <WeatherService>());
            var sunService        = new SunService(httpClient, LoggerFactory.CreateLogger <SunService>());
            var virtualService    = new DeviceGroupService(zWayService);
            var aggregatedService = new AggregatedDeviceService(zWayService, virtualService, weatherService, sunService);
            var statisticsService = new StatisticsService(LoggerFactory.CreateLogger <StatisticsService>(), aggregatedService, appConfiguration.Statistics);


            zWayService.InitAsync(appConfiguration.ZWay).Wait();
            weatherService.InitAsync(appConfiguration.Weather).Wait();
            sunService.InitAsync(appConfiguration.Sun).Wait();
            virtualService.Init(appConfiguration.DeviceGroups);
            aggregatedService.Init(appConfiguration.ToggleAutomationRules);
            statisticsService.Init();

            services.AddMvc();
            services.AddSingleton <HttpClient>(new HttpClient());
            services.AddSingleton <IDeviceService>(aggregatedService);
            services.AddSingleton <VersionService>(new VersionService());
            services.AddSingleton <StatisticsService>(statisticsService);
            //services.AddSignalR();
        }
Ejemplo n.º 4
0
        public static void TestTimeExecution()
        {
            var weatherService = new WeatherService();

            var path = "Data/62318.30.11.2010.30.11.2020.1.0.0.en.utf8.00000000.csv";

            var csvMappingResults = weatherService.GroupByOneMonth(CsvReader.readFile(path));

            var watch = new System.Diagnostics.Stopwatch();

            watch.Start();
            weatherService.CalculateMediumTemperature(csvMappingResults);
            watch.Stop();
            Console.WriteLine($"Simple; Execution time: {watch.ElapsedMilliseconds} ms");

            watch.Restart();
            weatherService.CalculateMediumTemperatureByTasks(csvMappingResults).GetAwaiter().GetResult();
            watch.Stop();
            Console.WriteLine($"Tasks (ThreadPool); Execution time: {watch.ElapsedMilliseconds} ms");

            watch.Restart();
            weatherService.CalculateMediumTemperatureByActors(csvMappingResults).GetAwaiter().GetResult();
            watch.Stop();
            Console.WriteLine($"Actors (1); Execution time: {watch.ElapsedMilliseconds} ms");


            watch.Restart();
            weatherService.CalculateMediumTemperatureByActors(csvMappingResults, 3).GetAwaiter().GetResult();
            watch.Stop();
            Console.WriteLine($"Actors (3); Execution time: {watch.ElapsedMilliseconds} ms");
        }
        public async Task WhenErrorOnRetrievingWeatherData_PassResponseOn()
        {
            var locationData = new List <WeatherLocation>
            {
                new WeatherLocation
                {
                    Title          = "Place",
                    WhereOnEarthId = 123456
                }
            };

            var moqClient = new Mock <IWeatherServiceClient>();

            moqClient
            .Setup(m => m.GetLocation(It.IsAny <string>()))
            .ReturnsAsync(new ProcessResponse <List <WeatherLocation> >(locationData).Success());
            moqClient
            .Setup(m => m.GetWeatherData(It.IsAny <int>()))
            .ReturnsAsync(new ProcessResponse <WeatherData>().Error("Something happened"));

            var service = new WeatherService(moqClient.Object);
            var result  = await service.GetWeatherData("Test");

            result.Should().BeEquivalentTo(new ProcessResponse <WeatherData>().Error("Something happened"));
        }
Ejemplo n.º 6
0
        public async void FetchWeatherData_ReturnShouldContainDataFromAPI()
        {
            var data = await WeatherService.FetchWeatherData();

            Assert.NotNull(data?.Temperature);
            Assert.NotNull(data?.Humidity);
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Populates the page with data.
        /// </summary>
        /// <param name="item">Item containing data.</param>
        /// <returns></returns>
        public async Task SelectItemAsync(object item)
        {
            SelectedItem = item;
            var pos = (SelectedItem as MapElementItem).GetPosition();

            weatherControl.Weather = await WeatherService.GetWeatherAsync(pos.Latitude, pos.Longitude);
        }
Ejemplo n.º 8
0
        public async Task Getting_weather_for_valid_city_should_return_proper_data()
        {
            // Arrange
            var response = new CurrentWeather
            {
                Name = "London",
                Main = new Main {
                    Temp = 30
                },
                Weather = new List <Api.Models.Weather>
                {
                    new Api.Models.Weather {
                        Main = "Dizzy", Icon = "01d"
                    }
                }
            };

            var service = new WeatherService(GetClientWithResponse(response));

            // Act
            var data = await service.GetCurrentWeather("London");

            // Assert
            data.CityName = "London";
            data.Description.Should().Be("Dizzy");
            data.Icon.Should().Be("01d");
            data.Temperature.Should().Be(30);
        }
Ejemplo n.º 9
0
        static void Main(string[] args)
        {
            WeatherService ws = new WeatherService();

            currentWind = ws.GetCurrentWeather().wind;

            Console.WriteLine("Harbor Control Console System");
            Console.WriteLine("------------------------------------------");
            Console.WriteLine($"Current wind speed is : {currentWind.speed}");

            //2 speedboats, 1 sailboat, 1 cargo
            generateInitialBoats();

            //Get boat into the perimeter     GetAllowedBoat();
            var allowBoat = GetAllowedBoat();

            while (!allowBoat)
            {
                allowBoat = GetAllowedBoat();
            }
            getAllowedBoat();
            var boatWithinPerimeter = boats.Dequeue();

            BoatInPerimeter(boatWithinPerimeter);
            var timeToDock = GetTime(boatWithinPerimeter.speed);

            Task.Delay(timeToDock).Wait();
            displayBoatDocked(boatWithinPerimeter);
            ScheduleBoats();

            // TODO: Random boat generator method to be called. Could not be completed due to time constraint
        }
        public Basic_WeatherObservablePage()
        {
            InitializeComponent();

            var cities = new string[] { "Brussels", "Mechelen", "Hasselt" };

            IObservable <WeatherCondition> weatherFeed =
                WeatherService.GetCurrentConditions(cities);

            #region Observer
            var weatherObserver = weatherFeed
                                  .ObserveOn(SynchronizationContext.Current)
                                  .Subscribe(

                wc => Output += $"{wc.City}: {wc.Text}\n",

                e => new MessageDialog(e.Message, "Oops, an error").ShowAsync(),
                () => new MessageDialog("Completed").ShowAsync());
            #endregion

            #region alternatives
            //LoadWeather(cities);
            //WeatherService.StreamWeatherConditions(cities, (wc) => Output += $"{wc.City}: {wc.Text}\n");
            #endregion
        }
Ejemplo n.º 11
0
        private async Task RefreshWeatherData()
        {
            await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async() =>
            {
                var weather             = new WeatherService(ApplicationDataController.GetValue(KeyNames.OpenWeatherMapApiKey, string.Empty), new CultureInfo(ApplicationLanguages.PrimaryLanguageOverride));
                WeatherData weatherData = null;
                try
                {
                    //weatherData = await weather.GetWeatherDataForCity(ApplicationDataController.GetValue(KeyNames.WeatherZip, string.Empty), ApplicationDataController.GetValue(KeyNames.WeatherCountry, string.Empty));
                    weatherData = await weather.GetWeatherDataForCity(ApplicationDataController.GetValue(KeyNames.WeatherCityName, string.Empty));
                }
                catch (WeatherServiceException weatherServiceException)
                {
                    await ShowMessageDialogIfSupported(weatherServiceException.Message, "Error");
                }

                if (weatherData == null)
                {
                    await ShowMessageDialogIfSupported(Strings.UnableToConnectToWeatherService, Strings.Error);
                }
                else
                {
                    WeatherIcon.Source = GetImageSourceFromUri(weatherData.WeatherIconUri.AbsolutePath);
                    LocationTxb.Text   = Strings.Get(weatherData.Location);
                    if (string.IsNullOrEmpty(LocationTxb.Text))
                    {
                        LocationTxb.Text = weatherData.Location;
                    }
                    TemperatureTxb.Text        = Math.Round(weatherData.Temp) + "°";
                    WeatherDescirptionTxb.Text = string.IsNullOrEmpty(weatherData.Description) ? string.Empty : weatherData.Description.ToLower();
                }
            });
        }
Ejemplo n.º 12
0
        //ActionResult<APixuWeatherReport>
        public Object GetAccuWeatherReportCurrent(ApiRequest apirequest)
        {
            if ((apirequest.lat == null) || (apirequest.lon == null))
            {
                return(NotFound());
            }
            WeatherService obj = new WeatherService();
            IDatabase      db  = AppConstant.rediscon.GetDatabase();

            var projectData = db.StringGet("ACCUCurrent" + apirequest.Place + apirequest.RequestDate.date);

            if (!string.IsNullOrEmpty(projectData))
            {
                Console.WriteLine("Get Data From Cache");
                return(JsonConvert.DeserializeObject(projectData));
            }
            else
            {
                Console.WriteLine("Set Data in Cache");
                db.StringSet("ACCUCurrent" + apirequest.Place + apirequest.RequestDate.date, obj.GetAccuWeatherReportLocID(apirequest.lat + "," + apirequest.lon));

                projectData = db.StringGet("ACCUCurrent" + apirequest.Place + apirequest.RequestDate.date);

                var projectData1 = JsonConvert.DeserializeObject <Accu>(projectData);
                Console.WriteLine(projectData1.Key);

                db.StringSet("ACCUCurrent" + apirequest.Place + apirequest.RequestDate.date, obj.GetAccuWeatherReport(projectData1.Key));

                projectData = db.StringGet("ACCUCurrent" + apirequest.Place + apirequest.RequestDate.date);

                return(JsonConvert.DeserializeObject(projectData));
            }
        }
        public WeatherServiceTests()
        {
            var weatherRepository = Substitute.For <IWeatherRepository>();

            weatherRepository.GetWeather(Arg.Any <string>(), Arg.Any <string>()).Returns(new WeatherModel());
            this.weatherService = new WeatherService(weatherRepository);
        }
Ejemplo n.º 14
0
        public async Task  TestForNotNullData(string country, string city)
        {
            WeatherService weatherService = MockData.GetService(false, country, city);
            var            response       = await weatherService.GetAsync(country, city);

            Assert.NotNull(response);
        }
Ejemplo n.º 15
0
        public IActionResult Weather(string city)
        {
            var service = new WeatherService();
            var result  = service.GetWeather(city).Result;

            return(View(result));
        }
Ejemplo n.º 16
0
        public async Task Getting_weather_for_city_with_many_weather_elements_should_return_icon_and_description_from_first()
        {
            // Arrange
            var response = new CurrentWeather
            {
                Weather = new List <Api.Models.Weather>
                {
                    new Api.Models.Weather {
                        Main = "Rainy", Icon = "02d"
                    },
                    new Api.Models.Weather {
                        Main = "Dizzy", Icon = "01d"
                    },
                }
            };

            var service = new WeatherService(GetClientWithResponse(response));

            // Act
            var data = await service.GetCurrentWeather("London");

            // Assert
            data.Description.Should().Be("Rainy");
            data.Icon.Should().Be("02d");
        }
Ejemplo n.º 17
0
 public async Task GetWeather_InvalidParameters_OneOfParametersIsInvalidExceptionThrown(
     string country, string city)
 {
     IWeatherService weatherService = new WeatherService();
     await Assert.ThrowsAsync <InvalidParameters>(
         (async() => await weatherService.GetWeather(country, city)));
 }
        /// <summary>
        /// Handle the user selecting a zone to populate the views for desired weather conditions
        /// </summary>
        public void ZoneSelected(object sender, AdapterView.ItemSelectedEventArgs args)
        {
            var spinner = (Spinner)sender;
            var item    = spinner.GetItemAtPosition(args.Position);

            var weatherOptions = new List <string>();

            if (args.Position != 0)
            {
                weatherOptions = WeatherService.GetWeatherOptionsForZone(item.ToString());
                weatherOptions.Insert(0, "Any");
            }

            var desiredElement  = _view.FindViewById <MultiSelectionSpinner>(Resource.Id.DesiredSpinner);
            var previousElement = _view.FindViewById <MultiSelectionSpinner>(Resource.Id.PreviousSpinner);
            var weatherTable    = _view.FindViewById <TableLayout>(Resource.Id.resultsTable);

            desiredElement.Items  = weatherOptions;
            previousElement.Items = weatherOptions;
            weatherTable.RemoveAllViews();

            desiredElement.RequestLayout();
            previousElement.RequestLayout();
            weatherTable.RequestLayout();
        }
Ejemplo n.º 19
0
        public Object GetSunRiseSunSetData(ApiRequest apirequest)
        {
            //ActionResult<SunRiseSunSet>
            if (apirequest.RequestDate.date == null)
            {
                apirequest.RequestDate.date = DateTime.Now.ToString("yyyy-MM-dd");
            }
            WeatherService obj = new WeatherService();
            IDatabase      db  = AppConstant.rediscon.GetDatabase();


            var projectData = db.StringGet("SunRiseSunSet" + apirequest.Place + apirequest.RequestDate.date);

            if (!string.IsNullOrEmpty(projectData))
            {
                Console.WriteLine("Get Data From Cache");
                return(JsonConvert.DeserializeObject(projectData));
            }
            else
            {
                Console.WriteLine("Set Data in Cache");
                db.StringSet("SunRiseSunSet" + apirequest.Place + apirequest.RequestDate.date, obj.GetSunRiseSunSet(apirequest.RequestDate.date, apirequest.lat, apirequest.lon));

                projectData = db.StringGet("SunRiseSunSet" + apirequest.Place + apirequest.RequestDate.date);
                return(JsonConvert.DeserializeObject(projectData));
            }
        }
Ejemplo n.º 20
0
        public void GetCityNames_When_city_entities_Then_city_names_correctly_returned()
        {
            var cityRepository = A.Fake <IRepository <CityEntity> >();

            A.CallTo(() => cityRepository.GetAll()).Returns(new[]
            {
                new CityEntity {
                    Id = 1, Name = "city 1"
                },
                new CityEntity {
                    Id = 2, Name = "city 2"
                },
                new CityEntity {
                    Id = 3, Name = "city 3"
                }
            }.AsEnumerable());

            var uow = A.Fake <IUnitOfWork>();

            A.CallTo(() => uow.Repository <CityEntity>()).Returns(cityRepository);

            var weatherService = new WeatherService(uow);

            var expectedResult = new List <string> {
                "city 1", "city 2", "city 3"
            };
            var gainedResult = weatherService.GetCityNamesAsync();

            CollectionAssert.AreEqual(expectedResult, gainedResult.Result);
        }
Ejemplo n.º 21
0
        public async Task InitializeAsync()
        {
            var service  = new WeatherService();
            var forecast = await service.GetForecast();

            Forecast = new ObservableCollection <WeatherForecast>(forecast);
        }
Ejemplo n.º 22
0
 public WeatherForecastController(
     WeatherService weatherService,
     ILogger <WeatherForecastController> logger)
 {
     _weatherService = weatherService;
     _logger         = logger;
 }
Ejemplo n.º 23
0
 public SearchPage()
 {
     InitializeComponent();
     _tidalService   = new TidalService();
     _weatherService = new WeatherService();
     howManyDays     = "0";
 }
Ejemplo n.º 24
0
        static void Main(string[] args)
        {
            string pathToData;

            if (!args.Any())
            {
                Console.WriteLine("No arguents passed assuming weather.dat file is in same directory as execcutable.");
                pathToData = "./weather.dat";
            }
            else
            {
                pathToData = args[0];
            }

            if (!File.Exists(pathToData))
            {
                Console.WriteLine($"Could not find data: {pathToData}");
                return;
            }

            var weatherData = new WeatherFileReader(pathToData).GetAll();
            var dayWithSmallestTempSread = new WeatherService(weatherData).GetDayWithSmallestTempSpread();

            Console.WriteLine($"The day with the samllest temperature spread is: {dayWithSmallestTempSread.Day}");

            Console.ReadKey();
        }
        public Form2(IImagePathRepository imagePathRepository, IDayWeatherRepository dayWeatherRepository)
        {
            InitializeComponent();
            _imagePathRepository  = imagePathRepository;
            _dayWeatherRepository = dayWeatherRepository;
            Import();

            tabControl1.TabPages.Clear();
            foreach (UserControl uc in _controls)
            {
                TabPage tp = new TabPage();
                var     displayNameAttribute = uc.GetType().GetCustomAttribute(typeof(DisplayNameAttribute)) as DisplayNameAttribute;
                if (displayNameAttribute != null)
                {
                    tp.Text = displayNameAttribute.DisplayName;
                }

                if (uc is AddDayWeather addDayWeather)
                {
                    addDayWeather.InitAll(_imagePathRepository, _dayWeatherRepository);
                }

                if (uc is WeatherView weatherView)
                {
                    var weatherService = new WeatherService(_imagePathRepository, _dayWeatherRepository);
                    weatherView.ResourcesPath = weatherService.GetImagePathList();
                    weatherView.Items         = weatherService.GetDayWeatherList();
                }

                uc.Dock = DockStyle.Fill;
                tp.Controls.Add(uc);
                tabControl1.TabPages.Add(tp);
            }
        }
        public void Should_get_weather_DI()
        {
            IRestRequest myRequest      = null;
            var          httpHelperMock = Mock.Create <IHttpHelper>();

            Mock.Arrange(() => httpHelperMock.Execute <Weather>(Arg.IsAny <IRestRequest>()))
            .DoInstead((IRestRequest request) => { myRequest = request; })
            .Returns(() => new Weather {
                ZipCode = "12345", TemperaturInFahrenheit = 68, WindSpeed = 8
            })
            .OccursOnce();

            Mock.Arrange(() => httpHelperMock.GetRestRequest(Arg.AnyString, Arg.IsAny <Method>(), Arg.IsAny <DataFormat>()))
            .Returns((string resource, Method method, DataFormat dataFormat) =>
            {
                var httpHelper = new HttpHelper("http://Foo/");
                return(httpHelper.GetRestRequest(resource, method, dataFormat));
            });

            var ws = new WeatherService(httpHelperMock);

            var weather = ws.GetWeatherForZip("04103");

            Assert.AreEqual("12345", weather.ZipCode);
            Assert.AreEqual(68, weather.TemperaturInFahrenheit);
            Assert.AreEqual(8, weather.WindSpeed);

            Assert.AreEqual("GET", myRequest.Method.ToString());
            Assert.AreEqual("CurrentWeather/04103", myRequest.Resource);
        }
Ejemplo n.º 27
0
        public async void TestGetWeather()
        {
            var openForecast = Option <OpenWeathermapForecast>
                               .Some(new OpenWeathermapForecast { list = new WeatherList[] {} });

            openWeathermapService.GetCurrentWeather(Arg.Any <int>())
            .Returns(Task.FromResult(Option <OpenWeathermapCurrent> .Some(new OpenWeathermapCurrent())));

            openWeathermapService.GetWeatherforecast(Arg.Any <int>())
            .Returns(Task.FromResult(openForecast));

            mapper.Map <OpenWeathermapCurrent, Backend.Weatherforecast.Service.Weather>(Arg.Any <OpenWeathermapCurrent>())
            .Returns(new Backend.Weatherforecast.Service.Weather());

            mapper.Map <WeatherList[], Backend.Weatherforecast.Service.Weather[]>(Arg.Any <WeatherList[]>())
            .Returns(new Backend.Weatherforecast.Service.Weather[]
                     { new Backend.Weatherforecast.Service.Weather {
                           Humidity = 42, Temperature = 13
                       } });

            IWeatherService service = new WeatherService(logger, mapper, openWeathermapService,
                                                         TestUtilities.ZipcodeToCitiesProvider, citynamesIds);
            var resultOpt = await service.GetWeather(TestUtilities.CityIdHamburg).ConfigureAwait(false);

            resultOpt
            .Some(result =>
            {
                Assert.NotNull(result);
                Assert.Equal(42f, result.AverageHumidity);
                Assert.Equal(13f, result.AverageTemperature);
            })
            .None(() => Assert.False(true, "Test Failed"));
        }
Ejemplo n.º 28
0
        public void GetRecipeDetails_CanLoadFromContext()
        {
            var connection = new SqliteConnection("DataSource=:memory:");

            connection.Open();

            var options = new DbContextOptionsBuilder <AppDbContext>()
                          .UseSqlite(connection)
                          .Options;

            using (var context = new AppDbContext(options))
            {
                context.Database.EnsureCreated();
                context.Weathers.AddRange(
                    new Weather {
                    Id = 1, Name = "Snow"
                },
                    new Weather {
                    Id = 2, Name = "Summer"
                },
                    new Weather {
                    Id = 3, Name = "Spring"
                });
                context.SaveChanges();
            }

            using (var context = new AppDbContext(options))
            {
                var service = new WeatherService(context);
                var weather = service.GetRecipe(id: 2);
                Assert.NotNull(weather);
                Assert.Equal(2, weather.Id);
                Assert.Equal("Summer", weather.Name);
            }
        }
Ejemplo n.º 29
0
        public MainPage()
        {
            InitializeComponent();
            WeatherService weatherService = new WeatherService();

            weatherService.Get();
        }
Ejemplo n.º 30
0
        public async Task CalculatePointTyreDegradationTest_Invalid()
        {
            //e.g. Silverstone|Towcester|14,57
            const double trackDegradationPoint = 57;
            var          dataManager           = new DataManager();
            await dataManager.LoadAndParseData();

            var tyreDetailsViewModel = new TyreDetailsViewModel(dataManager.Tyres[0]);

            var    tyreCoefficient = tyreDetailsViewModel.TyreCoefficient;
            double temperature     = 0.0;
            var    weatherService  = new WeatherService(new OpenWeatherMapApiConsumer(new WebClientConsumer()));

            weatherService.GetTemperatureForLocationAsync("Towcester",
                                                          (object sender, EventArgs e) =>
            {
                if (e is TemperatureUpdatedEventArgs temperatureArgs)
                {
                    temperature = temperatureArgs.NewTemperature;
                }
            });

            var pointTyreDegradataion = TyrePlacementViewModel.CalculatePointTyreDegradation(trackDegradationPoint, tyreCoefficient, temperature);
            var manualCalculation     = (14 + temperature) / tyreCoefficient;

            Assert.AreNotEqual(manualCalculation, pointTyreDegradataion);
        }
Ejemplo n.º 31
0
 //异步的方法完成以后触发wwsc_getWeatherbyCityNameCompleted事件。
 void wwsc_getWeatherbyCityNameCompleted(object sender, WeatherService.getWeatherbyCityNameCompletedEventArgs e)
 {
     string[] strs = e.Result;
     foreach (string str in strs)
     {
         Response.Write(str + "<br/>");
     }
 }
        public void InteractsWithExternalWeatherService()
        {
            IWeatherDao wDao = new StubWeatherDao();
            IAuditDBDao auditDbDao = new StubAuditDao();
            WeatherService service = new WeatherService(wDao, auditDbDao);

            Assert.AreEqual(80, service.GetCurrentWeather());
        }
Ejemplo n.º 33
0
 public UpdateTileTask()
 {
     userService = UserService.GetInstance();
     weatherService = WeatherService.GetInstance();
     userRespose = new GetUserRespose();
     userCityRespose = new GetUserCityRespose();
     weatherTypeRespose = new GetWeatherTypeRespose();
 }
Ejemplo n.º 34
0
		/// <summary>
		/// Gets the updated weather and store it as a new record in the database
		/// Further implementation to consdier:
		/// 	- Depends on the scenario, you could choose async or sync database save
		/// 	- Check last updated date time, prior to web service calls.
		/// </summary>
		/// <returns>The updated weather.</returns>
		/// <param name="uri">URI.</param>
		public async Task<Weather> GetUpdatedWeather (string uri)
		{
			var service = new WeatherService ();
			var response = await service.FetchWeatherAsync (uri);

//			// You could choose to save async as well, and return the response object directly to the front-end
			var savedId = Save (response);
			return response;
		}
        public void CanCallTheWeatherDao()
        {
            // arrange
            StubWeatherDao stub = new StubWeatherDao();
            WeatherService service = new WeatherService(stub);

            // act
            int result = service.CurrentTemp();

            // assert
            Assert.AreEqual(75, result);
        }
        public void UseMock()
        {
            Mock<IWeatherDao> mockWeatherDao = new Mock<IWeatherDao>();
            Mock<IAuditDBDao> auditDbMock = new Mock<IAuditDBDao>();
            WeatherService service = new WeatherService(mockWeatherDao.Object, auditDbMock.Object);

            // Setting expectations
            mockWeatherDao.Setup(x => x.getCurrent()).Returns(75);
            Assert.AreEqual(75, service.GetCurrentWeather());

            auditDbMock.Verify(x => x.LogRequest());
        }
        public void CanCallTheWeatherDao_WithMock()
        {
            // Arrange
            Mock<IWeatherDao> mock = new Mock<IWeatherDao>();
            WeatherService service = new WeatherService(mock.Object);
            mock.Setup(x => x.GetCurrentTemperature()).Returns(32);

            // Act
            int result = service.CurrentTemp();

            // Assert
            Assert.AreEqual(32, result);
        }
        public IEnumerable<WeatherData> It_Try_Get_Xml_Temperature()
        {
            var location = new GeoLocation() { Latitude = (float)33.481048, Longitude = (float)-86.704159 };
            var start = new DateTime(2004, 01, 01, 0, 0, 0);
            var end = new DateTime(2016, 09, 24, 0, 0, 0);

            var client = new WeatherServiceClient();
            var dataXml = client.GetRelativeHumidity(location.Latitude, location.Longitude, start, end);

            var data = new WeatherService().RelativeHumidity(location, start, end);

            Assert.IsNotNullOrEmpty(dataXml);
            return data;
        }
Ejemplo n.º 39
0
        static void Main(string[] args)
        {
            //var client = new WeatherServiceClient();
            //var result = client.GetTemperature((float) 33.481048, (float) -86.704159, new DateTime(2012, 1, 1),
            //                                   DateTime.Now);
            //Console.WriteLine(result);
            //Console.ReadKey();

            GeoLocation location = new GeoLocation() { Latitude = (float)33.481048, Longitude = (float)-86.704159 };
            var start = new DateTime(2004, 01, 01, 0, 0, 0);
            var end = new DateTime(2016, 09, 24, 0, 0, 0);

            var data = new WeatherService().GetTemperature(location, start, end);

            data = new WeatherService().RelativeHumidity(location, start, end);
        }
        public void CanConvertTemperature_ToString()
        {
            // arrange
            Mock<IWeatherDao> mock = new Mock<IWeatherDao>();
            WeatherService service = new WeatherService(mock.Object);
            Temperature temp = new Temperature()
                                   {
                                       temp = 75,
                                       scale = "F"
                                   };
            mock.Setup(x => x.ConvertToString(It.IsAny<Temperature>())).Returns("75 F");

            // act
            string result = service.convert(temp);

            // assert
            Assert.AreEqual("75 F", result);
        }
Ejemplo n.º 41
0
        public PivotPage()
        {
            this.InitializeComponent();

            this.navigationHelper = new NavigationHelper(this);
            this.navigationHelper.LoadState += this.NavigationHelper_LoadState;
            this.navigationHelper.SaveState += this.NavigationHelper_SaveState;
            this.NavigationCacheMode = Windows.UI.Xaml.Navigation.NavigationCacheMode.Required;

            userService = UserService.GetInstance();
            weatherService = WeatherService.GetInstance();
            settingService = SettingService.GetInstance();
            userRespose = new GetUserRespose();
            userCityRespose = new GetUserCityRespose();
            weatherRespose = new GetWeatherRespose();
            weatherTypeRespose = new GetWeatherTypeRespose();
            settingAutoUpdateTimeRepose = new GetSettingAutoUpdateTimeRepose();
        }
Ejemplo n.º 42
0
        public MyCityPage()
        {
            this.InitializeComponent();

            this.navigationHelper = new NavigationHelper(this);
            this.navigationHelper.LoadState += this.NavigationHelper_LoadState;
            this.navigationHelper.SaveState += this.NavigationHelper_SaveState;

            userService = UserService.GetInstance();
            weatherService = WeatherService.GetInstance();
            userRespose = new GetUserRespose();
            userCityRespose = new GetUserCityRespose();
            weatherTypeRespose = new GetWeatherTypeRespose();
            weatherRespose = new GetWeatherRespose();
            myCityPage = new ViewModel.MyCityPage();
            myCityPageModelList = new List<ViewModel.MyCityPageModel>();

        }
        public async Task<WeatherForecast> GetCurrentWeatherByCityAsync(City city)
        {
            var u = new Uri("http://api.openweathermap.org/data/2.5/weather?q=" + city.Name + "," + city.Country + "&appid=" + API_KEY + "&lang=fr&units=metric");
            //throw new NotImplementedException();
            WeatherService s = new WeatherService();
            HttpClient client = new HttpClient();
            var json = await client.GetStringAsync(u);
            var response = JsonConvert.DeserializeObject<CurrentWeatherModel.RootObject>(json);
            WeatherForecast forecast = null;

            DateTime dtDateTime = GetDateTime(response.dt);

            return new WeatherForecast()
            {
                City = city,
                Date = dtDateTime,
                Description = response.weather.First().description,
                MaxTemperature = response.main.temp_max,
                MinTemperature = response.main.temp_min,
            };

        }
Ejemplo n.º 44
0
        public MainPage()
        {
            this.navigationHelper = new NavigationHelper(this);
            this.NavigationCacheMode = Windows.UI.Xaml.Navigation.NavigationCacheMode.Required;

            userService = UserService.GetInstance();
            weatherService = WeatherService.GetInstance();
            settingService = SettingService.GetInstance();
            colorService = ColorService.GetInstance();

            userRespose = new GetUserRespose();
            userCityRespose = new GetUserCityRespose();
            weatherRespose = new GetWeatherRespose();
            weatherTypeRespose = new GetWeatherTypeRespose();
            settingAutoUpdateTimeRepose = new GetSettingAutoUpdateTimeRepose();
            colorResponse = new GetColorRespose();
            homePageModel = new HomePageModel();


            this.InitializeComponent();
            Loaded += MainPage_Loaded;
        }
Ejemplo n.º 45
0
        public void WeatherServiceGetLocationTest()
        {
            var webService = new Domain.WebServices.Fakes.StubIWeatherWebService
            {
                GetLocationString = s => new Location
                {
                    Latitude = 11.1f,
                    Longitude = 22.2f,
                    LocationId = 1,
                    LocationText = "Göteborg",
                    PlaceCode = "abc"
                }
            };

            var repo = new Domain.Repositories.Fakes.StubIWeatherRepository();

            var w = new WeatherService(repo, webService);

            var actual = w.GetLocation("Göteborg");

            Assert.AreEqual(actual.LocationText, "Göteborg");
        }
Ejemplo n.º 46
0
 public void Init()
 {
     _weatherService = new WeatherService();
 }
Ejemplo n.º 47
0
        public void LookupWeather(string zipCode)
        {
            if (String.IsNullOrEmpty(zipCode) || (zipCode == _zipCode)) {
                return;
            }

            _zipCode = zipCode;

            WeatherService weatherService = new WeatherService();
            _currentAsyncResult = weatherService.BeginGetWeather(zipCode, LookupWeatherCallback, weatherService);

            RaisePropertyChanged("Weather", "IsLoading", "Status", "ZipCode");
        }