コード例 #1
0
        /// <summary>
        /// Connect weather data api and get data
        /// </summary>
        private WeatherDataViewModel ConnectAndDeserilizeWeatherData(string ApiUrl, WeatherDataViewModel weatherDataViewModel)
        {
            using (HttpClient weatherClient = new HttpClient())
            {
                weatherClient.BaseAddress = new Uri(ApiUrl);
                weatherClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                try
                {
                    using (HttpResponseMessage weatherDataResponse = weatherClient.GetAsync(ApiUrl).Result)
                    {
                        if (weatherDataResponse.IsSuccessStatusCode)
                        {
                            var       dataContentResult    = weatherDataResponse.Content.ReadAsStringAsync().Result;
                            var       deserilizeJsonObject = JsonConvert.DeserializeObject <RootModel>(dataContentResult.ToString());
                            RootModel root = deserilizeJsonObject;
                            MapWeatherDataModel(root, weatherDataViewModel);
                        }
                        else
                        {
                            weatherDataViewModel.ErrorMessage = exceptionService.UserFriendlyExceptionMessage(weatherDataResponse);
                        }
                    }
                }
                catch (Exception exception)
                {
                    weatherDataViewModel.ErrorMessage         = UserFriendlyMessages.DefaultMessage;
                    weatherDataViewModel.ErrorDetails         = exception.StackTrace.ToString();
                    weatherDataViewModel.DisplayWeatherReport = false;
                }

                return(weatherDataViewModel);
            }
        }
コード例 #2
0
        public void ExtractingEmptyWeatherDataUnitTest()
        {
            RootModel            root = null;
            WeatherDataViewModel weatherDataViewModel = new WeatherDataViewModel();

            string jsonFileLocation = @"";

            if (!string.IsNullOrWhiteSpace(jsonFileLocation))
            {
                using (StreamReader reader = new StreamReader(jsonFileLocation))
                {
                    string json   = reader.ReadToEnd();
                    var    result = JsonConvert.DeserializeObject <RootModel>(json);

                    root = result;
                }

                weatherDataViewModel.Location           = root.Name;
                weatherDataViewModel.CurrentTemperature = string.Format("{0} C\u00B0", root.Main.Temp);
                weatherDataViewModel.MaximumTemperature = string.Format("{0} C\u00B0", root.Main.Temp_max);
                weatherDataViewModel.MinimumTemperature = string.Format("{0} C\u00B0", root.Main.Temp_min);
                weatherDataViewModel.Pressure           = string.Format("{0}", root.Main.Pressure);
                weatherDataViewModel.Humidity           = string.Format("{0} %", root.Main.Humidity);
                weatherDataViewModel.Sunrise            = ConvertUnixToTime(root.Sys.Sunrise);
                weatherDataViewModel.Sunset             = ConvertUnixToTime(root.Sys.Sunset);

                string ConvertUnixToTime(double unixTime)
                {
                    DateTime dt = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);

                    return(dt.AddSeconds(unixTime).ToLocalTime().ToShortTimeString());
                }
            }
            Assert.AreEqual(weatherDataViewModel.DisplayWeatherReport, false);
        }
コード例 #3
0
        public ActionResult GetWeatherReport(WeatherDataViewModel weatherDataViewModel)
        {
            WeatherDataService weatherDataService = new WeatherDataService(new ExceptionService());
            var weatherDataResult = weatherDataService.GetWeatherDataFromApi(weatherDataViewModel);

            return(View("Index", weatherDataResult));
        }
コード例 #4
0
        public WeatherPage(WeatherDataViewModel viewModel)
        {
            BindingContext = viewModel;
            WeatherDataViewModelInstance = viewModel;

            InitializeUIElements();
            InitializeUIGrid();
        }
コード例 #5
0
        public async Task <WeatherDataViewModel> GetWeatherDataAsync(int hours)
        {
            DateTime timebegin = DateTime.Now.Subtract(new TimeSpan(hours, 0, 0));
            IEnumerable <MonitorData> values = await _context.SensorsData.Where <MonitorData>(Data => Data.Timestamp > timebegin).ToArrayAsync();

            WeatherDataViewModel model = new WeatherDataViewModel();

            model.WeatherDataPoints = values;
            return(model);
        }
コード例 #6
0
        public void WeatherDataApiUnitTest()
        {
            WeatherDataViewModel weatherViewModel = new WeatherDataViewModel();

            weatherViewModel.Location = "Cambridge";

            WeatherDataService weatherDataService = new WeatherDataService(new ExceptionService());
            var weatherDataResult = weatherDataService.GetWeatherDataFromApi(weatherViewModel);

            Assert.IsNotNull(weatherDataResult);
        }
コード例 #7
0
 /// <summary>
 /// Mapping the root model into weather data view model.
 /// </summary>
 private void MapWeatherDataModel(RootModel root, WeatherDataViewModel weatherDataViewModel)
 {
     weatherDataViewModel.Location             = root.Name ?? string.Empty;
     weatherDataViewModel.CurrentTemperature   = string.Format("{0} C\u00B0", root.Main.Temp) ?? string.Empty;
     weatherDataViewModel.MaximumTemperature   = string.Format("{0} C\u00B0", root.Main.Temp_max) ?? string.Empty;
     weatherDataViewModel.MinimumTemperature   = string.Format("{0} C\u00B0", root.Main.Temp_min) ?? string.Empty;
     weatherDataViewModel.Pressure             = string.Format("{0}", root.Main.Pressure) ?? string.Empty;
     weatherDataViewModel.Humidity             = string.Format("{0} %", root.Main.Humidity) ?? string.Empty;
     weatherDataViewModel.Sunrise              = ConvertUnixToTime(root.Sys.Sunrise) ?? string.Empty;
     weatherDataViewModel.Sunset               = ConvertUnixToTime(root.Sys.Sunset) ?? string.Empty;
     weatherDataViewModel.DisplayWeatherReport = true;
 }
コード例 #8
0
        public async Task <IActionResult> GetWeatherData(int weatherDataId)
        {
            var weatherData = await _unitOfWork.WeatherDatas.GetAsync(weatherDataId);

            if (weatherData == null)
            {
                return(NotFound(new { error = String.Format("Weather Data with id {0} has not been found.", weatherDataId) }));
            }

            WeatherDataViewModel vmWeatherData = new WeatherDataViewModel(weatherData, false);

            return(Ok(vmWeatherData));
        }
コード例 #9
0
        public async Task <IActionResult> GetLatestWeatherData()
        {
            try {
                var weatherData = _unitOfWork.WeatherDatas.GetLatest();
                if (weatherData == null)
                {
                    return(NotFound(new { error = String.Format("Weather Data has not been found.") }));
                }

                WeatherDataViewModel vmWeatherData = new WeatherDataViewModel(weatherData, true);
                return(Ok(vmWeatherData));
            } catch (Exception e) {
                return(BadRequest(new { error = e.Message }));
            }
        }
コード例 #10
0
        /// <summary>
        /// Get weather data from api
        /// </summary>
        public override WeatherDataViewModel GetWeatherDataFromApi(WeatherDataViewModel weatherDataViewModel)
        {
            if (string.IsNullOrWhiteSpace(weatherDataViewModel.Location) || weatherDataViewModel.Location.Contains(","))
            {
                weatherDataViewModel.ErrorMessage = UserFriendlyMessages.ValidLocationMessage;
                return(weatherDataViewModel);
            }

            string ApiUrl = ApiConfiguration.GenerateApiUrl(weatherDataViewModel.Location);

            if (!string.IsNullOrWhiteSpace(ApiUrl))
            {
                return(ConnectAndDeserilizeWeatherData(ApiUrl, weatherDataViewModel));
            }

            weatherDataViewModel.ErrorMessage         = UserFriendlyMessages.DefaultMessage;
            weatherDataViewModel.DisplayWeatherReport = false;
            return(weatherDataViewModel);
        }
コード例 #11
0
        public string GenerateWeatherTrendsReport(string filePath)
        {
            // Validate filepath and throw an exception if it is null or empty
            if (string.IsNullOrEmpty(filePath.Trim()))
            {
                throw new Exception("File path cannot be null or empty");
            }

            WeatherDataMap map = new WeatherDataMap();

            var weatherData = _csvHelper.ParseCSVFile <WeatherData>(filePath, map);

            var reportData = new WeatherDataViewModel
            {
                WeatherDataForYears = GetWeatherDataForYears(weatherData)
            };

            return(_jsonHelper.ConvertToJson(reportData));
        }
コード例 #12
0
        public async Task <IActionResult> CreateWeatherData([FromBody] WeatherDataViewModel vmWeatherData)
        {
            if (vmWeatherData == null)
            {
                return(BadRequest(new { error = "No Weather Data object in request body." }));
            }
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            try {
                // create new WeatherData
                var newWeatherData = new WeatherData.Models.WeatherData
                {
                    Temperature = vmWeatherData.Temperature,
                    Weather     = vmWeatherData.Weather,
                    Humidity    = vmWeatherData.Humidity,
                    WindSpeed   = vmWeatherData.WindSpeed,
                    PrecipitationProbability = vmWeatherData.PrecipitationProbability,
                    DateTime  = DateTime.Now,
                    AddressId = vmWeatherData.AddressId // if Address doesn't exists it throws error
                };

                // Add new WeatherData to DBContext and Save Changes
                await _unitOfWork.WeatherDatas.AddAsync(newWeatherData);

                _unitOfWork.Complete();

                vmWeatherData.WeatherDataId = newWeatherData.WeatherDataId;
                return(CreatedAtAction(nameof(GetWeatherData), new { weatherDataId = vmWeatherData.WeatherDataId }, vmWeatherData));
            } catch (Exception e)
            {
                return(BadRequest(new { error = e.Message }));
            }
        }
コード例 #13
0
        public ActionResult Index()
        {
            WeatherDataViewModel model = new WeatherDataViewModel();

            model.Countries = _weatherDataService.GetCountryList().
                              Select(country => new SelectListItem()
            {
                Text = country, Value = country
            }).ToList();

            model.Cities = _weatherDataService.GetCityList(model.Countries[0].Value).
                           Select(City => new SelectListItem()
            {
                Text = City, Value = City
            }).ToList();


            model.Country = model.Countries[0].Value;
            model.City    = model.Cities[0].Value;

            model.CityWeatherData = _weatherDataService.GetWeather(model.Countries[0].Value, model.Cities[0].Value);

            return(View(model));
        }
コード例 #14
0
 /// <summary>
 /// Get weather data from open map weather Api.
 /// </summary>
 public abstract WeatherDataViewModel GetWeatherDataFromApi(WeatherDataViewModel weatherDataViewModel);