Пример #1
0
        public async Task GetHTTPForex_Test()
        {
            var         url   = this.configuration.GetSection("OpenWeather:Url").Value;
            OpenWeather model = await weatherService.GetHTTPWeather(City.Sydney.ToString());

            Assert.IsTrue(true);
        }
Пример #2
0
 public Settings(MainForm main)
 {
     InitializeComponent();
     Weather           = new OpenWeather();
     Main              = main;
     City_textBox.Text = Properties.Settings.Default.City;
 }
Пример #3
0
        private async Task GetDayWeather()
        {
            OpenWeatherAccess access = new OpenWeatherAccess();

            if (File.Exists(OpenWeatherAccessPath))
            {
                using (StreamReader stream = File.OpenText(OpenWeatherAccessPath))
                {
                    string json = stream.ReadToEnd();
                    access = JsonConvert.DeserializeObject <OpenWeatherAccess>(json);
                }
            }

            string url = $"http://api.openweathermap.org/data/2.5/weather?" +
                         $"lat={access.Latitude}&" +
                         $"lon={access.Longitude}&" +
                         $"appid={access.AppID}&" +
                         $"lang={access.Language}";

            HttpClient          http        = new HttpClient();
            HttpResponseMessage httpRespond =
                await http.GetAsync(url);

            string httpResult = await httpRespond.Content.ReadAsStringAsync();

            OpenWeather openWeather = JsonConvert.DeserializeObject <OpenWeather>(httpResult);

            ConvertDayWeather(openWeather);
        }
Пример #4
0
        private async Task GetDayWeather()
        {
            string url = $"http://api.openweathermap.org/data/2.5/weather?" +
                         $"lat={DemonApp.Latitude}&" +
                         $"lon={DemonApp.Longitude}&" +
                         $"appid={DemonApp.AppID}&" +
                         $"lang={DemonApp.Language}";

            HttpClient          http        = new HttpClient();
            HttpResponseMessage httpRespond =
                await http.GetAsync(url);

            string httpResult = await httpRespond.Content.ReadAsStringAsync();

            OpenWeather openWeather = JsonConvert.DeserializeObject <OpenWeather>(httpResult);

            Log.Write($"Longitude: {openWeather.coord.lon}, Latitude: {openWeather.coord.lat}");
            if (httpRespond.StatusCode != System.Net.HttpStatusCode.OK)
            {
                Log.Write($"HttpRespond: {httpRespond}");
            }
            ConvertDayWeather(openWeather);

            SaveDayWeather();
        }
Пример #5
0
        public async Task <IActionResult> GetForecast(string city = "Dnipro")
        {
            string stringResult;

            try
            {
                stringResult = await OpenWeather.GetForecast(city, "forecast", _configuration["MyKey"]);
            }
            catch (HttpRequestException httpRequestException)
            {
                if (httpRequestException.Message.Contains("404 (Not Found)"))
                {
                    return(NotFound(httpRequestException.Message));
                }
                if (httpRequestException.Message.Contains("401 (Unauthorized)"))
                {
                    return(Unauthorized(httpRequestException.Message));
                }
                return(BadRequest(httpRequestException.Message));
            }
            catch (Exception exception)
            {
                return(BadRequest(exception.Message));
            }

            var rawWeather = JsonSerializer.Deserialize <OpenWeatherResponses>(stringResult);
            var forecasts  = rawWeather.Forecasts.Select(forecast => new ForecastModel(forecast)).ToList();

            return(Ok(forecasts));
        }
 public WeatherForecastViewModel(AppSecrets appSecrets, Location location)
 {
     OpenWeather    = new OpenWeather(appSecrets.ApiKey); // use the Logger event
     LocationSearch = new LocationSearch(OpenWeather);
     Location       = location;
     InitCommands();
 }
Пример #7
0
        private OpenWeather GetWeather(string cityname)
        {
            this.logger.LogWarning("GetWeather starts");
            HtmlNode main = GetMainNode();

            if (main != null)
            {
                this.logger.LogWarning("main != null");
                HtmlNodeCollection collection = GetCityNode(main, cityname);
                if (collection != null)
                {
                    this.logger.LogWarning("collection != null");
                    OpenWeather model = new OpenWeather();
                    model.City      = collection[0].InnerText;
                    model.IconTitle = collection[1].InnerText;
                    HtmlNodeCollection imageCollection = collection[1].SelectNodes("img");
                    if (imageCollection != null)
                    {
                        model.IconURL = url + imageCollection[0].Attributes["src"].Value;
                    }
                    var Temperature = Regex.Match(collection[3].InnerText, @"\d+");
                    model.Temperature = System.Convert.ToDecimal(Temperature.Value);
                    var Wind = Regex.Match(collection[9].InnerText, @"\d+");
                    model.WindSpeed = System.Convert.ToDecimal(Wind.Value ?? "0");
                    this.logger.LogWarning("GetWeather stops");
                    return(model);
                }
                this.logger.LogWarning("return null");
                return(null);
            }
            this.logger.LogWarning("return null");
            return(null);
        }
Пример #8
0
 private void Create(OpenWeather model)
 {
     this.logger.LogWarning("Create Starts");
     this.datacontext.OpenWeathers.Add(model);
     this.datacontext.SaveChanges();
     this.logger.LogWarning("Create Stops");
 }
Пример #9
0
        public void GetDataFromOpenWeatherTest()
        {
            var fakeSite = new Mock <IRequest>();

            fakeSite.Setup(r => r.Connected).Returns(true);
            fakeSite.Setup(r => r.Response).Returns("{\"coord\":{\"lon\":30.2642,\"lat\":59.8944},\"weather\":[{\"id\":800,\"main\":\"Clear\",\"description\":\"clear sky\",\"icon\":\"01n\"}],\"base\":\"stations\",\"main\":{\"temp\":275.93,\"feels_like\":273.93,\"temp_min\":273.8,\"temp_max\":275.96,\"pressure\":1019,\"humidity\":45},\"visibility\":10000,\"wind\":{\"speed\":2,\"deg\":200},\"clouds\":{\"all\":0},\"dt\":1651174866,\"sys\":{\"type\":2,\"id\":197864,\"country\":\"RU\",\"sunrise\":1651111556,\"sunset\":1651168004},\"timezone\":10800,\"id\":498817,\"name\":\"Saint Petersburg\",\"cod\":200}");
            OpenWeather openWeather = new OpenWeather(fakeSite.Object);
            Weather     data        = openWeather.GetData();
            var         correct     = new Weather(2.78, 37, 0, 45, 2, "S", "Clear");

            Assert.AreEqual(correct.TemperatureCelsius, data.TemperatureCelsius);
            Assert.AreEqual(correct.Humidity, data.Humidity);
            Assert.AreEqual(correct.TemperatureFahrenheit, data.TemperatureFahrenheit);
            Assert.AreEqual(correct.CloudCover, data.CloudCover);
            Assert.AreEqual(correct.WindSpeed, data.WindSpeed);
            Assert.AreEqual(correct.WindDirection, data.WindDirection);
            Assert.AreEqual(correct.Precipitation, data.Precipitation);

            fakeSite.Setup(r => r.Connected).Returns(false);
            try
            {
                openWeather.GetData();
            }
            catch
            {
                Assert.Pass();
            }
            Assert.Fail();
        }
Пример #10
0
        /// <summary>
        /// Function to get current weather and update the elements. Comments work in case
        /// you want to keep that info, but at least in México is mostly empty
        /// </summary>
        protected void updateWeather()
        {
            try
            {
                //gets clients georeference
                string latitude  = this.latitude.Text;
                string longitude = this.longitude.Text;
                string unit      = this.dwlMeasureUnit.SelectedValue;

                //gets current weather via OpenWeather API
                OpenWeatherReponse weatherResponse = OpenWeather.GetOpenWeatherObjectAsync(latitude, longitude);

                //if (weatherResponse.Main.FeelsLike != 0)
                //{
                //    feels_like.InnerText = (weatherResponse.Main.FeelsLike - 273.15).ToString() + " °C";
                //}
                //else
                //{
                //    feels_like.InnerText = "No Data";
                //}
                //humidity.InnerText = (weatherResponse.Main.Humidity).ToString();
                //pressure.InnerText = (weatherResponse.Main.Pressure).ToString();

                //Updates the aspx elements
                if (weatherResponse.Main.Temp != 0)
                {
                    temp.InnerText = GeneralFunctions.convertTemperatureAndFormat(weatherResponse.Main.Temp, unit); //(weatherResponse.Main.Temp - 273.15).ToString() + " °C";
                }
                else
                {
                    temp.InnerText = "No Data";
                }
                //if (weatherResponse.Main.TempMax != 0)
                //{
                //    temp_max.InnerText = GeneralFunctions.convertTemperature(weatherResponse.Main.TempMax, unit); //(weatherResponse.Main.TempMax - 273.15).ToString() + " °C";
                //}
                //else
                //{
                //    temp_max.InnerText = "No Data";
                //}
                //if (weatherResponse.Main.TempMin != 0)
                //{
                //    temp_min.InnerText = GeneralFunctions.convertTemperature(weatherResponse.Main.TempMin, unit); //(weatherResponse.Main.TempMin - 273.15).ToString() + " °C";
                //}
                //else
                //{
                //    temp_min.InnerText = "No Data";
                //}
                name.InnerText = weatherResponse.Name;
                CultureInfo cultureInfo = Thread.CurrentThread.CurrentCulture;
                TextInfo    textInfo    = cultureInfo.TextInfo;
                weatherDescription.InnerText = textInfo.ToTitleCase(weatherResponse.Weather[0].Description);
                weatherIcon.Src   = "http://openweathermap.org/img/wn/" + weatherResponse.Weather[0].Icon + ".png";
                country.InnerText = weatherResponse.Sys.Country;
            }
            catch (Exception e)
            {
                throw e;
            }
        }
Пример #11
0
        public async Task SetLocation(string location, double latitude, double longitude, RemoteViews widgetView)
        {
            var weather = Settings.Settings.Instance.GetWeather(latitude, longitude);

            if (weather is null)
            {
                try
                {
                    weather = await OpenWeather.GetWeather(latitude, longitude, OpenWeather.Units.Metric);

                    Settings.Settings.Instance.UpdatePlace(latitude, longitude, weather);
                }
                catch (Exception)
                {
                    weather = Settings.Settings.Instance.GetWeatherFull(latitude, longitude);
                    if (weather is null)
                    {
                        return;
                    }
                }
            }
            widgetView.SetTextViewText(Resource.Id.Temperature, FormatTemperature(weather.Current.Temperature));
            widgetView.SetTextViewText(Resource.Id.Sunrise, string.Format(Resources.Translations.GetSunriseText(),
                                                                          UnixTimeStampToDateTimeConverter.Convert(weather.Current.Sunrise).ToString("t")));
            widgetView.SetTextViewText(Resource.Id.Sunset, string.Format(Resources.Translations.GetSunsetText(),
                                                                         UnixTimeStampToDateTimeConverter.Convert(weather.Current.Sunset).ToString("t")));
            widgetView.SetTextViewText(Resource.Id.Pressure, weather.Current.Pressure.ToString("F0") + "hPa");
            widgetView.SetTextViewText(Resource.Id.WindSpeed, FormatWindSpeed(weather.Current.WindSpeed));

            if (weather.Current.WeatherList.Count > 0)
            {
                SetWeatherIcon(widgetView, weather.Current.WeatherList[0].Icon);
                widgetView.SetTextViewText(Resource.Id.Description, weather.Current.WeatherList[0].Description.FirstCharToUpper());
            }
        }
Пример #12
0
        public OpenWeather ConvertOpenWeatherDtoInOpenWeather(OpenWeatherDto weatherDto)
        {
            OpenWeatherCoordinate coordinate = new OpenWeatherCoordinate(
                weatherDto.Coord.Lon,
                weatherDto.Coord.Lat);

            OpenWeatherMain weatherMain = new OpenWeatherMain(
                weatherDto.Main.Temp,
                weatherDto.Main.FeelsLike,
                weatherDto.Main.TempMin,
                weatherDto.Main.TempMax,
                weatherDto.Main.Pressure,
                weatherDto.Main.Humidity);

            OpenWeather openWeather = new OpenWeather(
                weatherDto.Base,
                weatherDto.Visibility,
                weatherDto.Dt,
                weatherDto.Timezone,
                weatherDto.Name,
                weatherDto.Cod);

            openWeather.AddCoordinate(coordinate);
            openWeather.AddWeatherMain(weatherMain);

            return(openWeather);
        }
Пример #13
0
        public IActionResult Index()
        {
            OpenWeather openWeather = new OpenWeather();
            var         weather     = openWeather.JsonToObject(openWeather.Get()).main;

            return(View(weather));
        }
        public void GetCurrentWeatherByCityName_GetData_Returns_EmptyOpenWeather()
        {
            //Arrange
            var         logger      = new Mock <ILogger <IWeatherProvider> >();
            OpenWeather openWeather = new OpenWeather();

            var uriProvider = new Mock <IExternalApiUriProvider>();
            Uri uri         = new Uri("http://someuri");

            uriProvider.Setup(m => m.GetCurrentWeatherByCityUri(It.IsAny <string>(), It.IsAny <string>())).Returns(uri);

            var weatherApiRetriever = new Mock <IApiDataRetriever <OpenWeather> >();

            weatherApiRetriever.Setup(m => m.GetData(It.IsAny <Uri>(), It.IsAny <string>()))
            .ReturnsAsync(openWeather);

            var weatherResponseConverter = new Mock <IExternalApiResponseConverter <OpenWeather, CurrentWeatherModel> >();

            weatherResponseConverter.Setup(m => m.Convert(It.IsAny <OpenWeather>())).Throws(new Exception("Invalid input parameter."));

            var weatherProvider = new WeatherProvider(logger.Object, weatherApiRetriever.Object, uriProvider.Object, weatherResponseConverter.Object);

            //Act
            //Assert
            Assert.ThrowsAsync <HttpResponseWithStatusCodeException>(
                () => weatherProvider.GetCurrentWeatherByCityName("berlin", "de"), "Invalid input parameters.");
        }
        public void GetCurrentWeatherByZipcode_InvalidRequestUri()
        {
            //Arrange
            var         logger      = new Mock <ILogger <IWeatherProvider> >();
            OpenWeather openWeather = new OpenWeather();

            var weatherApiRetriever = new Mock <IApiDataRetriever <OpenWeather> >();

            weatherApiRetriever.Setup(m => m.GetData(It.IsAny <Uri>(), It.IsAny <string>()))
            .ReturnsAsync(openWeather);

            var uriProvider = new Mock <IExternalApiUriProvider>();
            Uri invalidUri  = new Uri("http://invaliduri");

            uriProvider.Setup(m => m.GetCurrentWeatherByZipCodeUri(It.IsAny <string>(), It.IsAny <string>())).Returns(invalidUri);

            var weatherResponseConverter = new Mock <IExternalApiResponseConverter <OpenWeather, CurrentWeatherModel> >();

            var weatherProvider = new WeatherProvider(logger.Object, weatherApiRetriever.Object, uriProvider.Object, weatherResponseConverter.Object);

            //Act
            var result = weatherProvider.GetCurrentWeatherByZipCode("10247", "de"); //10247 - Berlin Friedrichshain

            //Assert
            Assert.ThrowsAsync <HttpResponseWithStatusCodeException>(
                () => weatherProvider.GetCurrentWeatherByZipCode("berlin", "de"), "Invalid input parameters.");
        }
Пример #16
0
        public void GetCityWeatherForecastWeekTest()
        {
            var request = new Mock <IRequest>();
            var jsonDay = "{\"temp\": {\"day\":8.4},\"humidity\":70,\"wind_speed\":6.21,\"wind_deg\":290,\"clouds\":50},";
            var temp    = string.Concat(Enumerable.Repeat(jsonDay, 7));

            temp = temp.Remove(temp.LastIndexOf(','), 1);
            var jsonWeekString = "{\"daily\":[" + temp + "]}";

            request.Setup(x => x.Get()).Returns(jsonWeekString);
            request.Setup(x => x.Connected).Returns(true);

            var site   = new OpenWeather(WeatherParameter.Week);
            var result = site.GetCityWeatherForecast(request.Object);

            Assert.IsNotNull(result);
            Assert.IsTrue(result.Source == "OpenWeather");
            Assert.IsTrue(result.ErrorMessage == "No errors");

            foreach (var todayWeather in result.Forecast)
            {
                Assert.IsTrue(todayWeather.CelsiusTemperature == "8,4");
                Assert.IsTrue(todayWeather.FahrenheitTemperature == "47,12");
                Assert.IsTrue(todayWeather.Humidity == "70");
                Assert.IsTrue(todayWeather.CloudCover == "50");
                Assert.IsTrue(todayWeather.WindSpeed == "6,21");
                Assert.IsTrue(todayWeather.WindDirection == "290");
            }
        }
Пример #17
0
        public async Task <bool> Update(OpenWeather model)
        {
            this.logger.LogWarning("Update Starts");
            this.logger.LogWarning("model.City => " + model.City);
            bool result  = false;
            bool isEmpty = await isEmptyTable(model.City);

            if (isEmpty)
            {
                Create(model);
            }
            this.logger.LogWarning("isEmpty => " + isEmpty.ToString());
            OpenWeather temp = this.datacontext.OpenWeathers.Where(w => w.City.ToUpper().Trim() == model.City.ToUpper().Trim()).FirstOrDefault();

            this.logger.LogWarning("temp == null => " + (temp == null).ToString());
            if (temp != null)
            {
                temp.City        = model.City;
                temp.IconTitle   = model.IconTitle;
                temp.IconURL     = model.IconURL;
                temp.Temperature = model.Temperature;
                temp.WindSpeed   = model.WindSpeed;
                temp.LastUpdate  = DateTime.Now;

                this.datacontext.OpenWeathers.Update(temp);
                this.datacontext.SaveChanges();
                result = true;
            }
            this.logger.LogWarning("result => " + result.ToString());
            this.logger.LogWarning("Update Stops");
            return(result);
        }
Пример #18
0
        public async Task <OpenWeather> Read(string city)
        {
            this.logger.LogWarning("Read Starts");
            OpenWeather openWeather = await this.datacontext.OpenWeathers.Where(w => w.City.Trim().ToUpper() == city.Trim().ToUpper()).FirstOrDefaultAsync();

            this.logger.LogWarning("Read Stops");
            return(openWeather);
        }
Пример #19
0
        public void ChangeParameterTest()
        {
            var site = new OpenWeather(WeatherParameter.Current);

            site.ChangeParameter(WeatherParameter.Week);

            Assert.AreEqual(site.Parameter, WeatherParameter.Week);
        }
Пример #20
0
 // метод викликається при створенні форми (перед відображенням)
 private void MainForm_Load(object sender, EventArgs e)
 {
     SetProxy();
     weather = new OpenWeather(Properties.Settings.Default.OWID, Properties.Settings.Default.OWCity, language, Fed.Weather.Scale.Celsius, proxy);
     UpdateData();
     SetTimer();
     timerForVisible.Start();
 }
Пример #21
0
        private OneCallResponse OneCallDesignData()
        {
            string sampleLocation = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, _designJsonPath);
            string sampleJson     = File.ReadAllText(sampleLocation);

            // deserialize and return the resulting object
            return(OpenWeather.DeserializeJson <OneCallResponse>(sampleJson));
        }
Пример #22
0
        public void ThenVerifyTheDetailsFromWebAndApi(int offset)
        {
            var isInragne = OpenWeather.VerifyResultsRange(ApiResult, WebResult - offset, WebResult + offset);

            Assert.IsTrue(isInragne,
                          string.Format("Humidity value from web and rest are not same. Web: {0} and Api: {1}",
                                        WebResult, ApiResult));
        }
Пример #23
0
 private void ConvertDayWeather(OpenWeather openWeather)
 {
     DayWeather.Time        = openWeather.dt.ConvertUnixTimeToDate();
     DayWeather.Temperature = openWeather.main.temp.ToCelsius();
     DayWeather.Pressure    = openWeather.main.pressure;
     DayWeather.Humidity    = openWeather.main.humidity;
     DayWeather.Visibility  = openWeather.visibility;
     DayWeather.WindSpeed   = openWeather.wind.speed.ToKmPerHour();
 }
Пример #24
0
 private void GetOpenWeaterDetails()
 {
     appId = ConfigurationManager.AppSettings["OpenWeather"];
     OpenWeather _weather = new OpenWeather(appId, SelectedCity.Name);
     string url = _weather.BuildUrl();
     OpenWeatherDetails weatherDetails = _weather.GetOpenWeatherDetails(url);
     _weatherDetails = weatherDetails;
     LoadOpenWeatherDates(weatherDetails);
 }
Пример #25
0
 private OpenWeather GetOpenWeather()
 {
     using (WebClient client = new WebClient())
     {
         string      json    = client.DownloadString(Url);
         OpenWeather weather = JsonConvert.DeserializeObject <OpenWeather>(json);
         return(weather);
     }
 }
Пример #26
0
        static void Main(string[] args)
        {
            ProcessArgs(args);
            deviceClient = DeviceClient.CreateFromConnectionString(config.IoTHubDeviceConnectionString);
            openWeather  = new OpenWeather(config.OpenWeatherMapApiKey, config.OpenWeatherMapLocationId);
            telemetry    = new Telemetry(config.OpenWeatherMapLocationId, Measure, 5);

            Console.WriteLine("Streaming Open Weather Map Sensor Data to Azure IoT Hub.\n\nPress any key to cancel");
            Console.Read();
        }
Пример #27
0
        public void CurrentTempAsync__SpecifiesTheUnits()
        {
            var handlerMock = SetupBackend(x => x.RequestUri.Query.Contains($"units=metric"));

            var client  = new HttpClient(handlerMock.Object);
            var weather = new OpenWeather(client, apiKey);

            Func <Task> act = async() => await weather.CurrentTempAsync(new Coord(0d, 0d));

            act.Should().NotThrow();
        }
Пример #28
0
        public void CurrentTempAsync__ThrowsExceptionWhenApiFails()
        {
            var handlerMock = SetupBackend(response: FailedResponse);

            var client  = new HttpClient(handlerMock.Object);
            var weather = new OpenWeather(client, apiKey);

            Func <Task> act = async() => await weather.CurrentTempAsync(new Coord(0d, 0d));

            act.Should().Throw <ApiException>().WithMessage($"*{failedMessage}");
        }
Пример #29
0
        public void CurrentTempAsync__CallsOpenWeather()
        {
            var handlerMock = SetupBackend(x => x.RequestUri.AbsoluteUri.StartsWith("http://api.openweathermap.org/data/2.5/weather"));

            var client  = new HttpClient(handlerMock.Object);
            var weather = new OpenWeather(client, apiKey);

            Func <Task> act = async() => await weather.CurrentTempAsync(new Coord(0d, 0d));

            act.Should().NotThrow();
        }
Пример #30
0
        public void CurrentTempAsync__CallsOpenWithGet()
        {
            var handlerMock = SetupBackend(x => x.Method == HttpMethod.Get);

            var client  = new HttpClient(handlerMock.Object);
            var weather = new OpenWeather(client, apiKey);

            Func <Task> act = async() => await weather.CurrentTempAsync(new Coord(0d, 0d));

            act.Should().NotThrow();
        }