Beispiel #1
0
        public async Task <WeatherDto> GetCurrentForecast()
        {
            var key        = new DateTime(DateTime.UtcNow.Year, DateTime.UtcNow.Month, DateTime.UtcNow.Day, DateTime.UtcNow.Hour, 0, 0).ToString();
            var weatherDto = await this.MemoryCacheService.GetAsync <WeatherDto>(key);

            if (weatherDto == null)
            {
                var forecastList = await this.GetCurrentTromsForecast();

                var forecast = forecastList.First();

                weatherDto = new WeatherDto
                {
                    DateTime            = DateTime.Now,
                    RealFeelTemperature = forecast.RealFeelTemperature.Metric.Value,
                    Temperature         = forecast.Temperature.Metric.Value,
                    Wind    = forecast.Wind.Speed.Value,
                    Ceiling = forecast.Ceiling.Metric.Value,
                    PrecipitationProbability = forecast.HasPrecipitation ? 100 : 0,
                    SkyCoverage            = this.DataAgregator.GetSkyCoverage(forecast.CloudCover),
                    PrecipitationCondition = this.DataAgregator.GetPrecipitation(forecast),
                    WeatherCondition       = this.DataAgregator.GetWeatherCondition(forecast),
                    Others        = this.DataAgregator.GetOthers(forecast),
                    Probabilities = this.DataAgregator.GetProbabilities(forecast),
                    WindCondition = this.DataAgregator.GetWindCondition(forecast),
                    RoadCondition = forecast.HasPrecipitation ? RoadCondition.Wet : RoadCondition.Dry
                };

                await this.MemoryCacheService.SaveAsync(key, weatherDto);
            }

            return(weatherDto);
        }
Beispiel #2
0
        public WeatherDto Clima(int day)
        {
            var galaxy  = CreateGalaxy();
            var weather = new WeatherDto(day);

            galaxy.SetPositionToPlanets(day);

            if (WeatherCondition.IsDrought(galaxy))
            {
                weather.Weather = "Sequia";
            }
            else if (WeatherCondition.IsRaining(galaxy))
            {
                weather.Weather = "Lluvia";
            }
            else if (WeatherCondition.IsOptimal(galaxy))
            {
                weather.Weather = "Optimo";
            }
            else
            {
                weather.Weather = "Desconocido";
            }

            return(weather);
        }
Beispiel #3
0
        public void GetWeatherByLocation()
        {
            long ticks = long.Parse(DateTime.Now.ToString("yyyyMMddHHmmss"));
            // .Ticks;

            /***
             * Por una cuestion de tiempo, solo se puede probar la temperatura para la hora actual y el dia actual
             * Se utiliza Moq
             */

            // Arrange
            var lat      = -34.9214;
            var lon      = -57.9544;
            var expected = new WeatherDto
            {
                Currently = new CurrentlyDto
                {
                    time        = (int)DateTime.Now.Ticks,
                    temperature = 24.5d
                },
                Latitude  = lat,
                Longitude = lon
            };

            // Act
            var actual = _weatherService.GetWeatherByLocation(lat, lon).Result;

            // Assert
            Assert.AreEqual(expected.Currently.temperature, actual.Currently.temperature);
        }
        public async Task FetchAndSynceWeather_ReturnsNewData_WhenCachedOneHasExpired()
        {
            // Expire cache data, make it older than 4 hours
            var lastFetchTime      = DateTimeOffset.Now.AddHours(-4).ToUniversalTime();
            var cacheWeatherOutput = new WeatherDto()
            {
                TimeFetched = lastFetchTime
            };

            var mockWeatherApi = new Mock <IWeatherApi>();

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

            var mockRepo = new Mock <IWeatherRepository>();

            mockRepo.Setup(repo => repo.GetWeatherById(3)).Returns(Task.FromResult(new List <WeatherDto> {
                cacheWeatherOutput
            }));

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

            // Assert
            Assert.NotNull(result);
            Assert.Equal(4, (result.TimeFetched - lastFetchTime).Hours);
        }
        public static async Task <Weather> GetWeather(string zipCode)
        {
            // Sign up for api key of weather servic
            string key         = "69a500462ccf842f83f73c5b880a73d7"; // Problems with gettin key - only by VPN
            string queryString = "http://api.openweathermap.org/data/2.5/weather?zip="
                                 + zipCode + ",us&appid=" + key + "&units=imperial";

            WeatherDto results = await DataService.getWeatherDataFromService(queryString).ConfigureAwait(false);

            if (results != null)
            {
                Weather weather = new Weather();
                weather.Title       = results.name;
                weather.Temperature = results.main.temp + " F";
                weather.Wind        = results.wind.speed + " mph";
                weather.Humidity    = results.main.humidity + " %";
                weather.Visibility  = results.weather[0].main;

                DateTime time    = new System.DateTime(1970, 1, 1, 0, 0, 0, 0);
                DateTime sunrise = time.AddSeconds(Convert.ToDouble(results.sys.sunrise));
                DateTime sunset  = time.AddSeconds(Convert.ToDouble(results.sys.sunset));
                weather.Sunrise = sunrise.ToString() + " UTC";
                weather.Sunset  = sunset.ToString() + " UTC";

                return(weather);
            }
            else
            {
                return(null);
            }
        }
        public async Task FetchAndSyncWeather_ReturnsCachedData_WhenCachedVersionIsStillValid()
        {
            var lastFetchTime      = DateTimeOffset.Now.AddHours(-2).ToUniversalTime();
            var cacheWeatherOutput = new WeatherDto()
            {
                TimeFetched = lastFetchTime
            };

            ;
            // OpenWeather updates are three hours appart
            // Free API's are limited to a number of calls per hour
            // Goal is to create a cache that we only refresh when the data has expired.
            var mockWeatherApi = new Mock <IWeatherApi>();

            mockWeatherApi.Setup(api => api.GetWeatherForLocation(3)).Returns(Task.FromResult(TestDataGenerator.LocationWeather(3)));
            var mockRepo = new Mock <IWeatherRepository>();

            mockRepo.Setup(repo => repo.GetWeatherById(3)).Returns(Task.FromResult(new List <WeatherDto> {
                cacheWeatherOutput
            }));

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

            // Assert
            Assert.NotNull(result);
            Assert.True(result.TimeFetched.Equals(lastFetchTime));
        }
        async Task <WeatherDto> GetWeatherDtoInternal(string cityOrZip)
        {
            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri("http://api.openweathermap.org");
                var response = await client.GetAsync($"/data/2.5/forecast?q={cityOrZip},de&appid=fcadd28326c90c3262054e0e6ca599cd&units=metric");

                response.EnsureSuccessStatusCode();

                var stringResult = await response.Content.ReadAsStringAsync();

                dynamic rawWeather = JsonConvert.DeserializeObject(stringResult);

                var res = new WeatherDto
                {
                    City = rawWeather.city.name,
                };
                foreach (var wr in rawWeather.list)
                {
                    var weather = new WeatherMeasureDto()
                    {
                        DateFormatted = DateTimeStringFromUnixString(Convert.ToString(wr.dt)),
                        TemperatureC  = wr.main.temp,
                        Humidity      = wr.main.humidity,
                        WindSpeed     = wr.wind.speed,
                    };
                    res.Readings.Add(weather);
                }

                return(res);
            }
        }
        public async Task <WeatherDto> GetAsync(string city)
        {
            if (string.IsNullOrWhiteSpace(city))
            {
                throw new ArgumentException("City name can not be empty.", nameof(city));
            }
            var dto = _cache.Get <WeatherDto>($"weather:{city}");

            if (dto != null)
            {
                _logger.LogInformation($"Weather for: {city} was found in cache.");

                return(dto);
            }
            _logger.LogInformation($"Get weather for city: {city}");
            var response = await _httpClient.GetAsync($"current?city={city}&key={_apiKey}");

            var content = await response.Content.ReadAsStringAsync();

            var result = JsonConvert.DeserializeObject <Result>(content);

            dto = new WeatherDto
            {
                City        = result.Data.First().City,
                Temperature = result.Data.First().Temperature
            };
            // dto = new WeatherDto
            // {
            //     City = city,
            //     Temperature = 2
            // };
            _cache.Set($"weather:{city}", dto, TimeSpan.FromMinutes(5));

            return(dto);
        }
Beispiel #9
0
        public WeatherDto GetForecast(DateTime dateTime)
        {
            if (DateTime.Now.AddHours(12) < dateTime)
            {
                throw new Exception("Date too far in the future. Forecast unreliable.");
            }

            var longForecast = this.Get12HTromsWeather();
            var forecast     = longForecast.First(f => f.DateTime.Hour == dateTime.Hour);

            var weatherDto = new WeatherDto
            {
                DateTime            = dateTime,
                RealFeelTemperature = forecast.RealFeelTemperature.Value,
                Temperature         = forecast.Temperature.Value,
                Wind    = forecast.Wind.Speed.Value,
                Ceiling = forecast.Ceiling.Value,
                PrecipitationProbability = forecast.PrecipitationProbability,
                RoadCondition            = this.DataAgregator.GetRoadCondition(forecast),
                SkyCoverage            = this.DataAgregator.GetSkyCoverage(forecast.CloudCover),
                PrecipitationCondition = this.DataAgregator.GetPrecipitation(forecast),
                WeatherCondition       = this.DataAgregator.GetWeatherCondition(forecast),
                Others        = this.DataAgregator.GetOthers(forecast),
                Probabilities = this.DataAgregator.GetProbabilities(forecast),
                WindCondition = this.DataAgregator.GetWindCondition(forecast)
            };

            return(weatherDto);
        }
Beispiel #10
0
 static void DisplayWeatherInfo(WeatherDto weather)
 {
     Console.WriteLine($"City: {weather.City}");
     Console.WriteLine($"Weather: {weather.State}");
     Console.WriteLine($"Temparature: {weather.Temperature}");
     Console.WriteLine($"Precipitation: {weather.Precipitation}%");
     Console.WriteLine();
 }
Beispiel #11
0
 public WeatherModel GetFromDto(WeatherDto dto)
 {
     if (dto is null)
     {
         return(null);
     }
     return(new WeatherModel
     {
         Date = dto.Date,
         Summary = dto.Summary,
         TemperatureC = dto.TemperatureC
     });
 }
Beispiel #12
0
        public async Task <IHttpActionResult> GetWeather(int day)
        {
            WeatherDto weather = await db.Weathers
                                 .Where(b => b.DayNumber == day)
                                 .Select(AsWeatherDto)
                                 .FirstOrDefaultAsync();

            if (weather == null)
            {
                return(NotFound());
            }

            return(Ok(weather));
        }
Beispiel #13
0
        public async Task <WeatherDto> GetWeather(CancellationToken cancellationToken)
        {
            QueryStringParams["q"]     = City;
            QueryStringParams["units"] = Units;

            UriBuilder.Query = QueryStringParams.ToString();

            WeatherDto weather = null;

            try
            {
                using (var response = await HttpClient.GetAsync(UriBuilder.Uri, HttpCompletionOption.ResponseHeadersRead, cancellationToken))
                {
                    if (!response.IsSuccessStatusCode)
                    {
                        if (response.StatusCode == HttpStatusCode.UnprocessableEntity)
                        {
                            var errorStream = await response.Content.ReadAsStreamAsync(cancellationToken);

                            // Do something with errors here. The following code is just a guide and incomplete

                            using (var streamReader = new StreamReader(errorStream, Encoding.UTF8, true))
                            {
                                //using (var jsonTextReader = new JsonTextReader(streamReader))
                                {
                                    //var jsonSerializer = new JsonSerializer();
                                    //'var validationErrors = await JsonSerializer.DeserializeAsync(errorStream);
                                }
                            }
                        }
                    }

                    response.EnsureSuccessStatusCode();

                    var stream = await response.Content.ReadAsStreamAsync(cancellationToken);

                    weather = await DeserializeAsync <WeatherDto>(stream);
                }
            }
            catch (Exception exception)
            {
                _logger.LogError(EventIDs.EventIdHttpClient,
                                 exception,
                                 MessageTemplates.HttpClientGet,
                                 UriBuilder.Uri.AbsolutePath
                                 );
            }

            return(weather);
        }
        public async Task SaveAsync(WeatherDto weather)
        {
            await this.unitOfWork.Weather.AddAsync(new WeatherEntity
            {
                City          = weather.City,
                Precipitation = weather.Precipitation,
                Temperature   = weather.Temperature,
                State         = weather.State,
            });

            await this.unitOfWork.CommitAsync();

            this.logger.LogInformation($"Successfully saved weather item: \"{JsonConvert.SerializeObject(weather)}\".");
        }
Beispiel #15
0
        private void AddNudges(int nudgeCount)
        {
            var userIds = this.userService.GetAllUserIds();

            for (int i = 0; i < nudgeCount; i++)
            {
                var forecast = new WeatherDto()
                {
                };

                var trip = new TripDto();

                //   this.nudgeService.AddNudge(userIds[random.Next(userIds.Count)], (TransportationType)(random.Next(3)), forecast, trip);
            }
        }
Beispiel #16
0
        public WeatherResult GetCityWeather(string cityName)
        {
            try
            {
                var apiUrl           = string.Format("{0}?q={1}&APPID={2}", _openWeatherMapUrl, cityName, _openWeatherMapAppId);
                var weatherCondition = new WeatherDto();
                using (var client = new HttpClient())
                {
                    var json            = client.GetAsync(apiUrl).Result.Content.ReadAsStringAsync().Result;
                    var weatherResponse = JsonConvert.DeserializeObject <WeatherResponse>(json);
                    if (weatherResponse == null)
                    {
                        return new WeatherResult
                               {
                                   Exception = new InvalidDataException("Response to api call is not valid")
                               }
                    }
                    ;

                    weatherCondition.Location   = weatherResponse.Name;
                    weatherCondition.Wind       = weatherResponse.Wind.Speed;
                    weatherCondition.Visibility = weatherResponse.Visibility;
                    var skyCondition = weatherResponse.Weather.FirstOrDefault();
                    if (skyCondition != null)
                    {
                        weatherCondition.SkyConditions = skyCondition.Description;
                    }

                    weatherCondition.Temperature      = weatherResponse.Main.Temp;
                    weatherCondition.DewPoint         = weatherResponse.Main.Humidity;
                    weatherCondition.RelativeHumidity = weatherResponse.Main.Humidity;
                    weatherCondition.Pressure         = weatherResponse.Main.Pressure;
                }

                return(new WeatherResult
                {
                    Status = ServiceStatus.Success,
                    CityWeather = weatherCondition
                });
            }
            catch (Exception ex)
            {
                return(new WeatherResult
                {
                    Exception = ex
                });
            }
        }
Beispiel #17
0
        public async Task <IHttpActionResult> GetMaxRainDay()
        {
            int weatherTypeId = (int)Enum.Parse(typeof(WeatherEnum), "lluviaMaxima");

            WeatherDto weather = await db.Weathers
                                 .Where(w => (int)w.WeatherType == weatherTypeId)
                                 .Select(AsWeatherDto)
                                 .FirstOrDefaultAsync();

            if (weather == null)
            {
                return(NotFound());
            }

            return(Ok(weather));
        }
Beispiel #18
0
        public void GetFromDto_Should_Return_WeatherModel()
        {
            //Arrange
            WeatherDto dto = new WeatherDto {
                Date = DateTime.Now, Summary = "summary", TemperatureC = 10
            };

            //Act
            var result = sut.GetFromDto(dto);

            //Assert
            Assert.IsType <WeatherModel>(result);
            Assert.Equal(dto.Date, result.Date);
            Assert.Equal(dto.Summary, result.Summary);
            Assert.Equal(dto.TemperatureC, result.TemperatureC);
        }
Beispiel #19
0
        public static async Task <WeatherDto> getWeatherDataFromService(string queryString)
        {
            HttpClient client   = new HttpClient();
            var        response = await client.GetAsync(queryString);

            WeatherDto data = null;

            if (response != null)
            {
                string json = response.Content.ReadAsStringAsync().Result;
                // Deserialization = converting json to .Net object (WeatherDto type)
                // IF FIELDS R SAME
                data = JsonConvert.DeserializeObject <WeatherDto>(json);
                //data = JsonConvert.DeserializeObject(json); // to dynamic
            }
            return(data);
        }
        public async Task <WeatherDto> GetAsync(string cityname)
        {
            using (HttpClient client = new HttpClient())
            {
                WeatherDto CityWeather = new WeatherDto();
                using (var httpClient = new HttpClient())
                {
                    using (var response = await httpClient.GetAsync("http://api.openweathermap.org/data/2.5/weather?q=" + cityname + "&appid=31222ec700d66616e4e236f92631aae6"))
                    {
                        string apiResponse = await response.Content.ReadAsStringAsync();

                        CityWeather = JsonConvert.DeserializeObject <WeatherDto>(apiResponse);
                    }
                }
                return(CityWeather);
            }
        }
        public async Task <Result <WeatherDto> > GetCityWeather(string city)
        {
            using (HttpClient client = new HttpClient())
            {
                var url = string.Format(CultureInfo.InvariantCulture, AppSettings.AppOpenWeatherAPIRoute.ToString(), city, AppSettings.AppOpenWeatherAPISecretKey);
                HttpResponseMessage responseTask = await client.GetAsync(url);

                if (!responseTask.IsSuccessStatusCode)
                {
                    return(Result.NotFound <WeatherDto>(ResultErrorCodes.WeatherForecastNotFound));
                }

                var        json       = responseTask.Content.ReadAsStringAsync().Result;
                WeatherDto weatherDto = JsonConvert.DeserializeObject <WeatherDto>(json);

                return(Result.Ok(weatherDto));
            }
        }
Beispiel #22
0
        public ActionResult Index(string RequestedCity)
        {
            // assign API KEY from openweathermap
            string appId = "4d4257f81d5fb1ae4e9dcf1f73db071c";

            // API path with CITY parameter and api key parameter
            // units: standard(default)-Kelvin, metric-Celsius, imperial-Fahrenheit
            // cnt: Number of cities around the point that should be returned, default 5, max 50.
            string url = string.Format("http://api.openweathermap.org/data/2.5/weather?q={0}&units=metric&cnt=1&APPID={1}", RequestedCity, appId);


            using (WebClient client = new WebClient())
            {
                // get json by URL
                string jsonResult = client.DownloadString(url);

                /*"QuickWatch" can display result: text visualizer:
                 * { "coord":{ "lon":-79.4163,"lat":43.7001},"weather":[{ "id":803,"main":"Clouds","description":"broken clouds","icon":"04d"}],"base":"stations","main":{ "temp":0.74,"feels_like":-5.01,"temp_min":0.56,"temp_max":1.11,"pressure":1020,"humidity":55},"visibility":10000,"wind":{ "speed":7.11,"deg":339,"gust":8.85},"clouds":{ "all":76},"dt":1617293438,"sys":{ "type":1,"id":718,"country":"CA","sunrise":1617274716,"sunset":1617320637},"timezone":-14400,"id":6167865,"name":"Toronto","cod":200}
                 * "json formatter" can convert text into json*/

                //  Convert jsonResult string to OBJECT weatherDto(Data Transfer Object)
                WeatherDto weatherDto = (new JavaScriptSerializer()).Deserialize <WeatherDto>(jsonResult);

                //weatherviewmodel design to send only required fields not all fields which received from api
                WeatherViewModel rslt = new WeatherViewModel();
                rslt.RequestedCity  = RequestedCity;
                rslt.Country        = weatherDto.sys.country;
                rslt.City           = weatherDto.name;
                rslt.Lat            = Convert.ToString(weatherDto.coord.lat);
                rslt.Lon            = Convert.ToString(weatherDto.coord.lon);
                rslt.Description    = weatherDto.weather[0].description; //weather[0] -> Id
                rslt.Humidity       = Convert.ToString(weatherDto.main.humidity);
                rslt.Temp           = Convert.ToString(weatherDto.main.temp);
                rslt.TempFeels_like = Convert.ToString(weatherDto.main.feels_like);
                rslt.Temp_max       = Convert.ToString(weatherDto.main.temp_max);
                rslt.Temp_min       = Convert.ToString(weatherDto.main.temp_min);
                rslt.WeatherIcon    = weatherDto.weather[0].icon;
                return(View(rslt));


                // how to convert back from OBJECT to JSON string
                // ar jsonStr = new JavaScriptSerializer().Serialize(rslt);
            }
        }
Beispiel #23
0
        public void CalculateBeerPacks()
        {
            // real service

            IConfigurationBuilder configurationBuilder = new ConfigurationBuilder();

            configurationBuilder.AddJsonFile("appSettings.json");

            IConfiguration configuration = configurationBuilder.Build();

            IOptions <PaginationOptions> options = Options.Create(new PaginationOptions());

            var realMeetingService = new MeetingService(null, null, options);


            // calculara en base a 24.01 grados, o sea 2 por persona
            var weatherDto = new WeatherDto
            {
                Hourly = new HourlyDto
                {
                    data = new List <DatumDto>
                    {
                        new DatumDto
                        {
                            //solo necetiso la hora y la temp
                            time        = 1611183600, // representa el 20/01/201 20:00hs en EPOCH time
                            temperature = 24.01d      // deberia calcular 2 per cápita
                        }
                    }
                }
            };

            //meeting 2(mock) es para la plata, dentro de 1 dia
            var meeting2 = _meetingService.GetMeeting(2).Result;

            var totalDays = 1;// faltaria un dia para la meeting

            // cantidad de invitado qeu hicieron checkin, en este caso seran 10
            int attendes = _meetingService.GetAttendedCount(meeting2.MeetingId).Result;

            int result = realMeetingService.CalculateBeers(meeting2.Date, weatherDto, attendes, totalDays);

            Assert.AreEqual(4, result);
        }
Beispiel #24
0
        public async Task InsertWeather(string id, WeatherDto currentWeather)
        {
            using (var db = new OneContext(_connectionString))
            {
                await db.AddAsync(new Weather
                {
                    Key      = Guid.NewGuid().ToString(),
                    Date     = currentWeather.Date,
                    FeelLike = currentWeather.FeelLike,
                    Id       = id,
                    Humidity = currentWeather.Humidity,
                    Pressure = currentWeather.Pressure,
                    Temp     = currentWeather.Temp
                });

                await db.SaveChangesAsync();

                _logger.LogInformation($"parameters of weather is added");
            }
        }
Beispiel #25
0
        public void SetupWeatherMock()
        {
            var latitude   = -34.9214;
            var longitude  = -57.9544;
            var weatherDto = new WeatherDto
            {
                Currently = new CurrentlyDto
                {
                    time        = (int)DateTime.Now.Ticks,
                    temperature = 24.5d
                },
                Latitude  = latitude,
                Longitude = longitude
            };

            var mock = new Mock <IWeatherService>();

            mock.Setup(m => m.GetWeatherByLocation(latitude, longitude)).ReturnsAsync(weatherDto);
            _weatherService = mock.Object;
        }
Beispiel #26
0
        public async Task Should_ReturnSameWeatherAsProviderReturns()
        {
            WeatherResponse response = new WeatherResponse
            {
                City          = "test_city",
                Precipitation = 100,
                State         = "test_state",
                Temperature   = 77,
            };

            provider.GetWeatherByCityAsync(Arg.Any <string>()).ReturnsForAnyArgs(response);
            WeatherService service = new WeatherService(provider, unitOfWork, loggerFactory);

            WeatherDto weather = await service.GetAsync(response.City);

            Assert.Equal(response.City, weather.City);
            Assert.Equal(response.Precipitation, weather.Precipitation);
            Assert.Equal(response.State, weather.State);
            Assert.Equal(response.Temperature, weather.Temperature);
        }
Beispiel #27
0
        public Guid Insert(NudgeResult result, Guid userId, WeatherDto forecast, TripDto trip)
        {
            var entity = new NudgeEntity
            {
                UserId              = userId,
                Result              = result,
                TransportationType  = trip.TransportationType,
                Distance            = trip.Distance,
                Duration            = trip.Duration,
                SkyCoverage         = forecast.SkyCoverage,
                WeatherProbability  = forecast.Probabilities,
                ReafFeelTemperature = forecast.RealFeelTemperature,
                Temperature         = forecast.Temperature,
                RoadCondition       = forecast.RoadCondition,
                DateTime            = forecast.DateTime,
                WindCondition       = forecast.WindCondition
            };

            this.Insert(entity);
            return(entity.Id);
        }
Beispiel #28
0
        public async Task <WeatherDto> GetWeather(string lat, string lon)
        {
            WeatherDto WeatherObj = new WeatherDto();
            //Sign up for a free API key at http://openweathermap.org/appid
            string key         = "ab4311901e90daeca7b398c1806d56ab";
            string queryString = "http://api.openweathermap.org/data/2.5/weather?lat=" + lat + "&lon=" + lon
                                 + "&appid=" + key + "&units=imperial";

            WebRequest  request     = WebRequest.Create(queryString);
            WebResponse webResponse = await request.GetResponseAsync();

            using (Stream webStream = webResponse.GetResponseStream())
            {
                if (webStream != null)
                {
                    using (StreamReader responseReader = new StreamReader(webStream))
                    {
                        string response = responseReader.ReadToEnd();
                        var    results  = JObject.Parse(response);

                        if (results["weather"] != null)
                        {
                            WeatherObj.Title = (string)results["name"];
                            WeatherObj.Date  = DateTime.Now.ToString("dd/MM/yyyy");
                            var degrees = (Convert.ToDouble((string)results["main"]["temp"]) - 32) * 5 / 9;
                            WeatherObj.Temperature = string.Format("{0:0.00}\u00B0C", degrees);
                            WeatherObj.Wind        = (string)results["wind"]["speed"] + " mph";
                            WeatherObj.Humidity    = (string)results["main"]["humidity"] + " %";
                            WeatherObj.Visibility  = (string)results["weather"][0]["main"];
                            DateTime time    = new System.DateTime(1970, 1, 1, 0, 0, 0, 0);
                            DateTime sunrise = time.AddSeconds((double)results["sys"]["sunrise"]);
                            DateTime sunset  = time.AddSeconds((double)results["sys"]["sunset"]);
                            WeatherObj.Sunrise = sunrise.ToString() + " UTC";
                            WeatherObj.Sunset  = sunset.ToString() + " UTC";
                        }
                    }
                }
            }
            return(ObjectMapper.Map <WeatherDto>(WeatherObj));
        }
Beispiel #29
0
        public static List <WeatherDto> ToWeatherDtoList(this LocationWeather locationWeather)
        {
            if (locationWeather.list == null)
            {
                return(new List <WeatherDto>());
            }
            var grouped     = locationWeather.list.GroupBy(n => n.Day).Take(5);
            var weatherDtos = new List <WeatherDto>();
            var locale      = locationWeather.city.name;
            var localeId    = locationWeather.city.id;

            foreach (var list in grouped)
            {
                var rootItem   = list.First();
                var weatherDto = new WeatherDto
                {
                    WeatherDay  = rootItem.Day.ToString("ddd dd-MMM-yy"),
                    Locale      = locale,
                    LocaleId    = localeId,
                    TimeFetched = DateTimeOffset.Now
                };

                var details = list.Select(x => new TimedWeatherDetail()
                {
                    Temperature      = x.main.temp,
                    Humidity         = x.main?.humidity,
                    Wind             = x.wind?.speed,
                    WindDirection    = x.wind?.deg,
                    ShortDescription = x.weather?.FirstOrDefault()?.description,
                    DayTime          = x.DateTimeOffset,
                    Precipitation    = x.snow?.ThreeHourVolume,
                }).ToArray();

                weatherDto.TimedWeatherDetail = details;
                weatherDtos.Add(weatherDto);
            }

            return(weatherDtos);
        }
Beispiel #30
0
        public void AddNudge(Guid userId, NudgeResult nudgeResult, WeatherDto forecast, TripDto trip)
        {
            this.NudgeRepository.Insert(nudgeResult, userId, forecast, trip);

            try
            {
                this.AnonymousNudgeOracleRepository.Insert(new OracleNudgeEntity
                {
                    ActualTransportationType = trip.TransportationType,
                    PrecipitationProbability = forecast.PrecipitationProbability,
                    Result        = NudgeResult.Successful,
                    RoadCondition = forecast.RoadCondition,
                    SkyCoverage   = forecast.SkyCoverage,
                    Temperature   = forecast.Temperature,
                    Wind          = forecast.Wind
                });
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error while inserting into oracle database.");
                Console.WriteLine(ex.Message);
            }
        }