/// <summary>
        /// Get the weather for a location.
        /// </summary>
        /// <param name="latitude"></param>
        /// <param name="longitude"></param>
        /// <returns></returns>
        public async Task <Weather> GetWeather(float latitude, float longitude)
        {
            var cachedWeather = await _weatherCache.GetForecast(latitude, longitude);

            if (cachedWeather != null)
            {
                Debug.WriteLine("Fetched from cache: " + cachedWeather.ToString());
                return(cachedWeather);
            }

            Debug.WriteLine("Fall back to DarkSky api");

            var uri = string.Format
                      (
                "{0}{1}/{2},{3}?units={4}",
                _darkSkySettings.Url,
                _darkSkySettings.Token,
                latitude,
                longitude,
                _weatherUnit
                      );
            GetWeather weather = null;

            using (_httpClient)
            {
                var response = await _httpClient.GetAsync(uri);

                if (!response.IsSuccessStatusCode)
                {
                    throw new Exception(string.Format("DarkSky returned with code {0}", response.StatusCode));
                }
                weather = await _httpMapper.ParseResponse <GetWeather>(response);
            }

            var weatherCollection = new List <Weather>();

            for (int i = 0; i < weather.Hourly.Data.Length; i++)
            {
                var now = weather.Hourly.Data[i];
                weatherCollection.Add(new Weather
                {
                    Condition         = DarkSkyConditionMapper.GetCondition(now.Icon),
                    Temperature       = now.Temperature,
                    Latitude          = latitude,
                    Longitude         = longitude,
                    Date              = now.Time,
                    PrecipProbability = now.PrecipProbability,
                    Humidity          = now.Humidity,
                    Pressure          = now.Pressure,
                    WindSpeed         = now.WindSpeed,
                    CloudCover        = now.CloudCover,
                    UVIndex           = now.UVIndex
                }
                                      );
            }

            await _weatherCache.CacheForecasts(weatherCollection.ToArray());

            return(weatherCollection[2]);
        }
Beispiel #2
0
        private void button1_Click(object sender, EventArgs e)
        {
            while (true)
            {
                try
                {
                    panel2.Controls.RemoveAt(0);
                }
                catch (Exception exce)
                {
                    break;
                }
            }

            string searchString = textBox1.Text;

            int count = 0;

            foreach (var item in GetWeather.Search(searchString))
            {
                count++;
                Button newButton = new Button();
                newButton.Location = new Point(13, 25 * count + 13);
                newButton.Text     = item.title;
                newButton.Click   += (s, EventArgs) => { dynamicButton_click(s, EventArgs, item.woeid); };

                panel2.Controls.Add(newButton);
                if (count == 5)
                {
                    break;
                }
            }
        }
Beispiel #3
0
        private void dynamicButton_click(object sender, EventArgs e, int par = 0)
        {
            var res = GetWeather.GetLocation(par);

            label1.Text = res.parent.title;
            label2.Text = res.title;
            label3.Text = res.location_type;
            int count = 0;

            while (true)
            {
                try
                {
                    panel1.Controls.RemoveAt(0);
                }
                catch (Exception exce)
                {
                    break;
                }
            }
            foreach (var location in res.consolidated_weather)
            {
                var lb = new Label();
                lb.Width    = 300;
                lb.Text     = $"{location.applicable_date}:Minima:{location.min_temp},Maxima: {location.max_temp}";
                lb.Location = new Point(13, 25 * count + 13);
                count++;
                panel1.Controls.Add(lb);
            }
        }
        static async Task Main(string[] args)
        {
            GetWeather weather    = new GetWeather();
            string     weatherNow = await weather.GetWeatherAsync();

            Console.WriteLine(weatherNow);
        }
Beispiel #5
0
 public void gibberishSearch()
 {
     //Arange
     string input = "aslrgo23q590q3ngbg";
     //Act
     List <Search> searchResult = GetWeather.Search(input);
     //Assert
 }
Beispiel #6
0
 public void emptySearch()
 {
     //Arange
     string input = "";
     //Act
     List <Search> searchResult = GetWeather.Search(input);
     //Assert
 }
Beispiel #7
0
 public void UrlInjectionSearch()
 {
     //Arange
     string input = "buc/ro";
     //Act
     List <Search> searchResult = GetWeather.Search(input);
     //Assert
 }
Beispiel #8
0
 public void invalidWoeid()
 {
     //Arange
     string input = "Bucharest";
     //Act
     RootobjectLocation location = GetWeather.GetLocation(99999999);
     //Assert
 }
        public HomeViewModel()
        {
            Interval           = "15";
            Title              = "Homepage";
            _weatherService    = Locator.Current.GetService <IWeatherService>();
            _dataRepository    = Locator.Current.GetService <IDataRepository>();
            _backgroundService = Locator.Current.GetService <IBackgroundService>();

            GetWeather = ReactiveCommand.CreateFromTask <string, WeatherRoot>(
                city => {
                if (string.IsNullOrEmpty(city))
                {
                    return(GetWeatherUsingGps());
                }
                return(_weatherService.GetWeather(city));
            });

            GetWeather.Subscribe(data => { Output = data; });

            _weatherService.NewWeatherUpdate.Subscribe(data => { Output = data; });

            _isLoading = GetWeather
                         .IsExecuting
                         .ToProperty(this, x => x.IsLoading);

            this.WhenValueChanged(x => x.Interval)
            .Skip(1)     // Skip initial value assignment
            .Throttle(TimeSpan.FromSeconds(2))
            .Where(x => !string.IsNullOrEmpty(x))
            .Subscribe(interval =>
            {
                _backgroundService.StopJob();
                _backgroundService.RunJob(int.Parse(interval));
            });

            GetWeather.IsExecuting
            .Skip(1)                            // IsExecuting has an initial value of false.  We can skip that first value
            .Where(isExecuting => !isExecuting) // filter until the executing state becomes false
            .Subscribe(_ => {
                if (!_backgroundService.IsJobRunning)
                {
                    _backgroundService.RunJob(int.Parse(string.IsNullOrEmpty(Interval) ? "0" : Interval));
                }
            });

            this.WhenValueChanged(x => x.Output)
            .Skip(1)     // Skip initial value assignment
            .DistinctUntilChanged()
            .Throttle(TimeSpan.FromSeconds(2))
            .Subscribe(data =>
            {
                var h = data.ToHistory();
                h.Id  = 1;
                _dataRepository.SaveItemAsync(h);
            });
        }
Beispiel #10
0
        public void SearchCity()
        {
            //Arange
            string input = "yo";
            //Act
            List <Search> searchResult = GetWeather.Search(input);

            //Assert
            Assert.AreEqual("Yokohama", searchResult[2].title);
            Assert.AreEqual("York", searchResult[6].title);
            Assert.AreEqual(7, searchResult.Count);
        }
Beispiel #11
0
        public void CheckDeserialization()
        {
            //Arange
            string input = "Bucharest";
            //Act
            Search             searchResult = GetWeather.Search(input)[0];
            RootobjectLocation location     = GetWeather.GetLocation(searchResult.woeid);

            //Assert
            Assert.AreEqual("Romania", location.parent.title);
            Assert.AreEqual("Bucharest", location.title);
        }
Beispiel #12
0
        public async Task <IActionResult> Index([Bind("Location,Model")] GetWeather weather)
        {
            Log.Information("GetWeather object passed to \"weather/index\" method");
            Log.Information("Mode " + weather.Mode);
            Log.Information("Location " + weather.Location);

            if (ModelState.IsValid)
            {
                return(RedirectToAction(nameof(Weather), new { location = weather.Location }));
            }
            return(View());
        }
Beispiel #13
0
        public void CheckConnection()
        {
            //Arrange
            string input   = "https://www.metaweather.com/api/location/search/?query=Bucharest";
            string content = "[{\"title\":\"Bucharest\",\"location_type\":\"City\",\"woeid\":868274,\"latt_long\":\"44.434200,26.102970\"}]";
            //Act
            string output = GetWeather.FetchWebsite(input).Replace(" ", "");

            //Assert
            if (!content.Equals(output))
            {
                Assert.Warn("API structure may have changed!");
            }
        }
Beispiel #14
0
        private async Task <IList <WeatherForecast> > CurrentOrPreviousFiveDayWeatherForecast(string zip)
        {
            if (string.IsNullOrWhiteSpace(zip))
            {
                return(null);
            }

            var utcNow           = DateTimeOffset.UtcNow;
            var weatherForecasts = new List <WeatherForecast>();
            var cachedWeather    = await ActivityDbContext.CachedWeathers
                                   .AsNoTracking()
                                   .Include(cachedWeather0 => cachedWeather0.WeatherForecasts)
                                   .SingleOrDefaultAsync(cachedWeather0 => cachedWeather0.ZipCode == zip && cachedWeather0.DateCached.LocalDateTime.ToShortDateString() == utcNow.LocalDateTime.ToShortDateString());

            if (cachedWeather == null)
            {
                weatherForecasts = GetWeather.FiveDayAround1500Forecast(zip).ToList();

                cachedWeather = new CachedWeather
                {
                    ZipCode          = zip,
                    DateCached       = utcNow,
                    WeatherForecasts = weatherForecasts
                };

                var previousCachedWeathersForZipcodeQuery = ActivityDbContext.CachedWeathers
                                                            .AsNoTracking()
                                                            .Where(previousCachedWeather => previousCachedWeather.ZipCode == zip);

                if (previousCachedWeathersForZipcodeQuery.Count() > 0)
                {
                    ActivityDbContext.CachedWeathers.RemoveRange(previousCachedWeathersForZipcodeQuery);
                }

                ActivityDbContext.CachedWeathers.Add(cachedWeather);
                await ActivityDbContext.SaveChangesAsync();

                return(weatherForecasts);
            }
            else
            {
                return(cachedWeather.WeatherForecasts);
            }
        }
        public static void Main(string[] args)
        {
            GetWeather myWeather = new GetWeather(getWeather);

            Console.Write("Enter the city: ");
            string userInput = Console.ReadLine();

            IAsyncResult result = myWeather.BeginInvoke(userInput, null, null);

            do
            {
                Console.WriteLine("Fetching..");
                Thread.Sleep(1000);
            } while (!result.IsCompleted);


            string data = myWeather.EndInvoke(result);

            Console.WriteLine(data);

            Console.ReadKey();
        }
        public async Task GetWeather()
        {
            String sentUrl     = null;
            String expectedUrl = string.Format
                                 (
                "{0}{1}/{2},{3}?units={4}",
                settings.Url,
                settings.Token,
                1,
                1,
                "si"
                                 );

            var        serialisedWeather = File.ReadAllText(@"../../../Resources/weather.json");
            GetWeather weather           = JsonConvert.DeserializeObject <GetWeather>(serialisedWeather);
            var        expectedFirst     = weather.Hourly.Data[2];

            _mockHttpClient.Setup(cli => cli.GetAsync(It.IsAny <string>()))
            .Callback <string>(url => sentUrl = url)
            .ReturnsAsync(new HttpResponseMessage {
                StatusCode = HttpStatusCode.OK
            });
            _mockHttpResponseMapper.Setup(mpr => mpr.ParseResponse <GetWeather>(It.IsAny <HttpResponseMessage>()))
            .ReturnsAsync(weather);

            var darkSkyWeatherService = new DarkSkyWeatherService
                                        (
                settings,
                _mockHttpClient.Object,
                _mockHttpResponseMapper.Object,
                _mockCache.Object,
                new LoggerFactory().CreateLogger <DarkSkyWeatherService>()
                                        );
            var fetchedWeather = await darkSkyWeatherService.GetWeather(1, 1);

            Assert.Equal(expectedFirst.Time, fetchedWeather.Date);
            Assert.Equal(expectedUrl, sentUrl);
        }
Beispiel #17
0
 public IEnumerable <WeatherForecast> FiveDayWeatherForecast(double latitude, double longitude)
 {
     return(GetWeather.FiveDayAround1500Forecast(latitude, longitude));
 }
 public void FiveDayAround1500Forecast_84037()
 {
     GetWeather.FiveDayAround1500Forecast(GetWeather.GetWeatherForecastsForZip("84103"));
 }
 public void GetWeatherDatesForZip_84037_WeatherForecasts()
 {
     var weather = GetWeather.GetWeatherForecastsForZip("84103");
 }
 public void GetWeatherForZip_84037_JSONString()
 {
     var weatherString = GetWeather.GetWeatherForZip("84103");
 }
 public void GetWeatherForGeolocation_40_And_N111_JSONString()
 {
     var weatherString = GetWeather.GetWeatherForGeolocation(40, -111, true);
 }
 public void SaveWeather_WeatherSavedToMyDocuments()
 {
     JSONSave.SaveWeatherToAppData(GetWeather.GetWeatherForecastsForZip("84103", true));
 }
Beispiel #23
0
 private void Window_Loaded(object sender, RoutedEventArgs e)
 {
     GetWeather?.Invoke(this, EventArgs.Empty);
     CurrentMoney?.Invoke(this, EventArgs.Empty);
 }