Example #1
0
        private WeatherDTO MapFrom(OpenWeatherMap weather, OpenDailyWeatherMap dailyWeather)
        {
            var date       = FromUnixTime(weather.Dt);
            var weatherDto = new WeatherDTO
            {
                DayNumber          = date.ToString("dd"),
                DayName            = date.ToString("dddd"),
                MonthName          = date.ToString("MMMM"),
                Location           = weather.Name,
                Degree             = Math.Round(weather.Main.Temperature),
                Humidity           = weather.Main.Humidity,
                Pressure           = weather.Main.Pressure,
                WeatherName        = weather.Weather[0].Main,
                WeatherDescription = weather.Weather[0].Description,
                WindSpeed          = weather.Wind.Speed,
                Compass            = DegreesToCardinal(weather.Wind.Degrees)
            };

            for (int i = 0; i < Constants.MAXIMUN_NUMBER_OF_DAYS; i++)
            {
                var day = i + 1;
                date = FromUnixTime(dailyWeather.List[day].Dt);
                var weatherDayDto = new WeatherDayDTO
                {
                    Day = date.ToString("dddd"),
                    MaximumTemperature = Math.Round(dailyWeather.List[day].Temp.Maximum),
                    MinimumTemperature = Math.Round(dailyWeather.List[day].Temp.Minimum),
                    WeatherName        = dailyWeather.List[day].Weather[0].Main,
                    WeatherDescription = dailyWeather.List[day].Weather[0].Description,
                };
                weatherDto.DailyWeather[i] = weatherDayDto;
            }

            return(weatherDto);
        }
Example #2
0
        public void Get_ShouldReturnOk()
        {
            // Arrange
            var date     = DateTime.Now;
            var expected = new WeatherDTO()
            {
                data = new List <WeatherItem> {
                    new WeatherItem {
                        precision = 10, pressure = 23, value = 30
                    }
                },
                location = new Location {
                    latitude = 44, longitude = 50
                },
                time = date
            };
            var parameter = new WeatherParameter {
                Latitude = 44, Longitude = 50, Timestamp = date
            };
            var weatherServiceMock = new Mock <IWeatherService>();

            weatherServiceMock.Setup(p => p.GetWeather(parameter)).Returns(Task.FromResult(expected));
            // Act
            var controller = new WeatherController(weatherServiceMock.Object);

            // IHttpActionResult actionResult = controller.Get(44,50,date);
            //var actionResult = actionResult as OkNegotiatedContentResult<WeatherDTO>;

            //// Assert
            //Assert.IsType<OkNegotiatedContentResult<WeatherDTO>>(actionResult);
        }
        private void ReceiveWeather(string json)
        {
            currentWeather = JsonConvert.DeserializeObject <CurrentWeather>(json);
            WeatherDTO weatherDTO = mapper.MapCurrentWeather(currentWeather);

            OnWeatherReady(weatherDTO);
        }
Example #4
0
        private async void WeatherView_ItemTapped(object sender, ItemTappedEventArgs e)
        {
            WeatherDTO weatherDTO = e.Item as WeatherDTO;

            await DisplayAlert(weatherDTO.dayOfWeek, weatherDTO.ToString(), "OK");

            ((ListView)sender).SelectedItem = null;
        }
Example #5
0
        public WeatherEntity SendRequest()
        {
            WebrequestCore core    = new WebrequestCore();
            string         appLoad = core.Get(new Uri(this.requestUrl));
            WeatherEntity  wEntity = WeatherDTO.ParserJson(appLoad, Configuration);

            return(wEntity);
        }
Example #6
0
        private Weather GetWeather(WeatherDTO weatherDTO, TimeDTO timeDTO)
        {
            Weather weather = new Weather();

            weather.WeatherState = weatherDTO.WeatherState;
            weather.DayTime      = this._dayTimeService.GetDayTime(weatherDTO.SunriseTime, weatherDTO.SunsetTime, timeDTO.Time);

            return(weather);
        }
Example #7
0
        public WeatherDTO Map(OpenWeatherDTO openWeatherDTO)
        {
            WeatherDTO weatherDTO = new WeatherDTO();

            weatherDTO.SunsetTime   = DateTimeUtils.GetDateTimeFromUnixSeconds(openWeatherDTO.sys.sunset);
            weatherDTO.SunriseTime  = DateTimeUtils.GetDateTimeFromUnixSeconds(openWeatherDTO.sys.sunrise);
            weatherDTO.WeatherState = this.GetWeatherState(openWeatherDTO.weather[0].id);

            return(weatherDTO);
        }
 public static Weather ToWeather(this WeatherDTO input)
 {
     if (input == null)
     {
         return(null);
     }
     return(new Weather()
     {
         WeatherId = input.Id, Lon = input.Lon, Alert = input.Alert, Type = input.Type, Lat = input.Lat, IssueDate = input.IssueDate
     });
 }
        public async Task <IActionResult> Get(string loc)
        {
            Dictionary <string, string> query = new Dictionary <string, string>();

            query.Add("Location", loc);
            query.Add("APIKEY", _openWeatherSettings.APIKEY);

            string respAsString = await _weatherClient.GetWeatherAsync(query);

            var        obj = JsonSerializer.Deserialize <OpenWeatherResponse>(respAsString);
            WeatherDTO cleanWeatherDesiredObject = _mapper.Map <OpenWeatherResponse, WeatherDTO>(obj);

            return(Ok(cleanWeatherDesiredObject));
        }
Example #10
0
        public IHttpActionResult Create(WeatherDTO dto)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest());
            }

            var weather = Mapper.Map <WeatherDTO, Weather>(dto);

            context.Weather.Add(weather);
            context.SaveChanges();

            dto.id = weather.id;

            return(Created(new Uri($"{Request.RequestUri}/{weather.id}"), dto));
        }
        public void WeatherDetailsNull()
        {
            //Arrange
            string data = "{\r\n\"coord\": {\r\n \"lon\": 151.22,\r\n\"lat\": -33.85\r\n },\r\n \"weather\": [\r\n {\r\n      \"id\": 521,\r\n\"main\":\"Rain\",\r\n\"description\":\"shower rain\",\r\n\"icon\":\"09n\"\r\n}\r\n],\r\n\"base\": \"stations\",\r\n\"main\": {\r\n\"temp\": 289.29,\r\n\"pressure\": 1022,\r\n\"humidity\": 87,\r\n\"temp_min\":288.15,\r\n\"temp_max\": 290.15\r\n},\r\n\"visibility\": 8000,\r\n\"wind\": {\r\n\"speed\": 15.4,\r\n\"deg\": 190,\r\n\"gust\": 20.6\r\n},\r\n\"clouds\": {\r\n\"all\": 75\r\n},\r\n\"dt\":1526202420,\r\n\"sys\": {\r\n\"type\": 1,\r\n\"id\": 8233,\r\n\"message\": 0.0092,\r\n\"country\": \"AU\",\r\n\"sunrise\": 1526157519,\r\n\"sunset\": 1526195037\r\n},\r\n\"id\": 2147714,\r\n\"name\":\"Sydney\",\r\n\"cod\": 200\r\n}";


            var mockWeatherService = new Mock <IWeatherService>();


            string     city    = "Sydney";
            string     country = "AU";
            RequestDTO request = new RequestDTO()
            {
                country = country, city = city
            };
            var weatherDTO = new WeatherDTO()
            {
                cod = "200", clouds = new Clouds()
                {
                    all = "50"
                }, coord = new CoOrdinates()
                {
                    lat = "30", lon = "46"
                }, dt = "3242342", id = "1277333", main = new Conditions()
                {
                    humidity = "56", pressure = "565", temp = "34", temp_max = "46", temp_min = "29"
                }, name = "Sydney", wind = new Wind()
                {
                    deg = "46", speed = "45"
                }, visibility = "324", sys = new Event()
                {
                    country = "Australia", id = "3342", message = "dasfdsf"
                }
            };



            mockWeatherService.Setup(x => x.GetWeatherDetails(request)).Returns(data);

            var controller = new WeatherController(mockWeatherService.Object);

            //Act
            var result = controller.WeatherDetails(city, country);

            //Assert
            Assert.AreEqual(null, null);
        }
Example #12
0
        public List <Report> FetchWeather(WeatherDTO data)
        {
            string        WeatherAppId = ConfigurationManager.AppSettings["WeatherAppId"];
            string        apiResponse  = "";
            List <Report> reportList   = new List <Report>();

            try
            {
                foreach (var id in data.CityIds)
                {
                    try
                    {
                        HttpWebRequest apiRequest = (HttpWebRequest)WebRequest.Create(@"http://api.openweathermap.org/data/2.5/weather?id=" + id + "&appid=" + WeatherAppId + "&units=metric");
                        using (HttpWebResponse httpResponse = (HttpWebResponse)apiRequest.GetResponse())
                        {
                            using (Stream reader = httpResponse.GetResponseStream())
                            {
                                apiResponse = (new StreamReader(reader)).ReadToEnd();
                            }
                            var weatherResponse = JsonConvert.DeserializeObject <WeatherResponse>(apiResponse);
                            if (weatherResponse != null)
                            {
                                Report report = new Report
                                {
                                    City        = weatherResponse.name,
                                    Id          = id,
                                    Description = weatherResponse.weather.FirstOrDefault().description,
                                    Temp        = weatherResponse.main.temp,
                                    Max_Temp    = weatherResponse.main.temp_max,
                                    Min_Temp    = weatherResponse.main.temp_min
                                };
                                reportList.Add(report);
                            }
                        }
                    }
                    catch (Exception)
                    {
                        continue;
                    }
                }
            }
            catch (Exception)
            {
            }
            return(reportList);
        }
Example #13
0
        static void Main(string[] args)
        {
            string urlPrefix = string.Empty;

            if (args.Length > 0 && args[0].Equals("managerStartMode"))
            {
                urlPrefix = AppDomain.CurrentDomain.BaseDirectory.Replace("\\MyCodeKatas\\bin\\Debug\\", "\\Kata04_DataMunging\\bin\\Debug\\");
            }
            DatReader  datReader         = new DatReader(urlPrefix + "weather.dat");
            WeatherDTO morristownWeather = new WeatherDTO(datReader);

            morristownWeather.ShowDayWithSmallestTemperatureSpread();
            datReader = new DatReader(urlPrefix + "football.dat");
            FootballDTO premierLeagueResults = new FootballDTO(datReader);

            premierLeagueResults.ShowTeamWithSmallestGoalDifference();
            Console.ReadKey();
        }
        private static WeatherDTO invokeWeatherWebService(string url)
        {
            var request  = HttpWebRequest.Create(url);
            var response = request.GetResponse();

            using (var stream = response.GetResponseStream())
                using (var reader = new StreamReader(stream, System.Text.Encoding.GetEncoding("iso-8859-1")))
                {
                    string     contents    = reader.ReadToEnd();
                    var        obj         = (JObject)JsonConvert.DeserializeObject(contents);
                    var        tempC       = obj["data"]["current_condition"][0]["temp_C"];
                    var        weatherCode = obj["data"]["current_condition"][0]["weatherCode"];
                    WeatherDTO weather     = new WeatherDTO();
                    weather.Temperature = tempC.Value <float>();
                    weather.Condition   = (WeatherCondition)weatherCode.Value <int>();
                    return(weather);
                }
        }
Example #15
0
        public void FillWeatherBlock()
        {
            Controller controller = new Controller();

            WeatherDTO weatherDTO = controller.GetWeatherDTO();


            int count = 0;

            foreach (var elem in weatherDTO.forecastsDTO)
            {
                WeatherBlock weatherBlock = new WeatherBlock();
                weatherBlock.DataContext = elem;

                Grid.SetColumn(weatherBlock, count);
                gridWeatherBlocks.Children.Add(weatherBlock);
                count++;
            }
        }
Example #16
0
        public WeatherDTO MapCurrentWeather(CurrentWeather weather)
        {
            WeatherDTO weatherDTO = new WeatherDTO();

            weatherDTO.MainParameters = weather.MainParameters;

            weatherDTO.MainParameters.Temperature = Math.Round(weatherDTO.MainParameters.Temperature - 273.15);      // Get Temperature in Celsius
            weatherDTO.MainParameters.Pressure    = Math.Round(weatherDTO.MainParameters.Pressure * 0.750061561303); // hPa pressure to mmHg
            weatherDTO.MainParameters.Humidity    = Math.Round(weatherDTO.MainParameters.Humidity);

            weatherDTO.Weather = weather.Weather[0];
            weatherDTO.Wind    = weather.Wind;
            DateTimeOffset offset    = DateTimeOffset.FromUnixTimeSeconds(weather.TimeOfCalculation);
            TimeZone       localZone = TimeZone.CurrentTimeZone;

            weatherDTO.TimeOfCalculation = localZone.ToLocalTime(offset.UtcDateTime);

            return(weatherDTO);
        }
Example #17
0
        public ActionResult <WeatherDTO> Get(string id)
        {
            const int days = 5;
            var       ret  = new WeatherDTO();

            try
            {
                var weatherInfoList = _repository.LoadWeatherInfo(id, days);
                var last            = _sharedData.LastSensorData.Where(z => z.Key == id).FirstOrDefault();
                ret.SenderMAC   = id;
                ret.SenderName  = last.Value.SenderName ?? "";
                ret.Temperature = last.Value.Temperature;
                ret.Humidity    = last.Value.Humidity;
                ret.Date        = DateTime.Now.ToString("ddd, dd MMM");

                var weatherInfoHistory = new WeatherInfoDTO[days];

                int i = 0;
                foreach (var item in weatherInfoList)
                {
                    weatherInfoHistory[i]            = new WeatherInfoDTO();
                    weatherInfoHistory[i].Max        = item.Max;
                    weatherInfoHistory[i].Min        = item.Min;
                    weatherInfoHistory[i].DateISO    = item.Day;
                    weatherInfoHistory[i].DateOfWeek = DateTime.Parse(weatherInfoHistory[i].DateISO).ToString("ddd");
                    i++;
                }

                for (int y = i; y < days; y++)
                {
                    weatherInfoHistory[y] = new WeatherInfoDTO();
                }

                ret.WeatherInfo = weatherInfoHistory;
            }
            catch (Exception ex)
            {
                Logger.Error("ProcessData", "Error on execution. " + ex.Message);
            }

            return(ret);
        }
Example #18
0
        public void BeginLoadWeather(GPSPoint location)
        {
            string weatherUrl = "http://free.worldweatheronline.com/feed/weather.ashx?q={0},{1}&num_of_days=1&format=json&key={2}";
            double latitude   = location.Latitude;
            double longitude  = location.Longitude;
            //InvariantCulture is to force . (dot) for latitude and longitude
            string url = string.Format(weatherUrl, latitude.ToString(CultureInfo.InvariantCulture), longitude.ToString(CultureInfo.InvariantCulture), APIKey);

            var request = HttpWebRequest.Create(url);

            request.BeginGetResponse((iar) =>
            {
                try
                {
                    var response = request.EndGetResponse(iar);

                    using (var stream = response.GetResponseStream())
                        using (var reader = new StreamReader(stream, System.Text.Encoding.GetEncoding("iso-8859-1")))
                        {
                            string contents     = reader.ReadToEnd();
                            var obj             = (JObject)JsonConvert.DeserializeObject(contents);
                            var tempC           = obj["data"]["current_condition"][0]["temp_C"];
                            var weatherCode     = obj["data"]["current_condition"][0]["weatherCode"];
                            WeatherDTO weather  = new WeatherDTO();
                            weather.Temperature = tempC.Value <float>();
                            weather.Condition   = (WeatherCondition)weatherCode.Value <int>();
                            if (WeatherLoaded != null)
                            {
                                WeatherLoaded(this, new WeatherRetrievedEventArgs(weather));
                            }
                        }
                }
                catch (Exception)
                {
                    if (WeatherLoaded != null)
                    {
                        WeatherLoaded(this, new WeatherRetrievedEventArgs(new WeatherDTO()));
                    }
                }
            }, null);
        }
Example #19
0
        public Weather GetWeatherFromIp(string ip)
        {
            WeatherDTO weatherDTO = null;

            Task <LocationDTO> locationTask = this._locationFinder.FindLocationByIp(ip);
            Task <TimeDTO>     timeTask     = this._timeService.GetTimeFromIp(ip);

            Task weatherTask = locationTask.ContinueWith((task) =>
            {
                if (task.Exception == null)
                {
                    LocationDTO locationDTO = task.Result;

                    weatherDTO = this.GetWeatherDTO(locationDTO);
                }
            });

            try
            {
                Task.WaitAll(weatherTask, timeTask);
            }
            catch (AggregateException aggregateException)
            {
                Exception exception = aggregateException;

                while (exception is AggregateException && exception.InnerException != null)
                {
                    exception = exception.InnerException;
                }

                if (exception != null)
                {
                    throw exception;
                }
            }

            Weather weather = this.GetWeather(weatherDTO, timeTask.Result);

            return(weather);
        }
Example #20
0
        public async Task <WeatherDTO> GetWeatherStateFromLocation(LocationDTO locationDTO)
        {
            try
            {
                StringBuilder stringBuilder = new StringBuilder();
                stringBuilder.Append(_openWeatherApiUrl);
                stringBuilder.Append(locationDTO.CityName);
                stringBuilder.Append(_citySeparator);
                stringBuilder.Append(locationDTO.CountryCode);

                string fullUrl = stringBuilder.ToString();

                OpenWeatherDTO openWeatherDTO = await this._genericRestService.Get <OpenWeatherDTO>(fullUrl);

                WeatherDTO weatherDTO = this._weatherMapper.Map(openWeatherDTO);

                return(weatherDTO);
            }
            catch (NotFoundException)
            {
                throw new NoWeatherStateFoundException();
            }
        }
Example #21
0
        public ActionResult Report(HttpPostedFileBase UploadedFile)
        {
            BLL.WeatherService weatherService = new BLL.WeatherService();
            string             fileName       = Path.GetFileName(UploadedFile.FileName);
            var dto = new WeatherDTO();

            dto.CityIds = new List <string>();

            if (UploadedFile.ContentLength > 0 && !string.IsNullOrEmpty(fileName))
            {
                using (var package = new ExcelPackage(UploadedFile.InputStream))
                {
                    // get the first worksheet in the workbook
                    ExcelWorksheet worksheet = package.Workbook.Worksheets[1];
                    int            noOfRows  = worksheet.Dimension.End.Row;
                    for (int row = 2; row <= noOfRows; row++)
                    {
                        dto.CityIds.Add(worksheet.Cells[row, 1].Value.ToString());
                    }
                }
            }
            return(View(weatherService.FetchWeather(dto)));
        }
Example #22
0
        public Weather.Model.WeatherDTO GetWeatherInfo(double latitude, double longitude)
        {
            MapperConfiguration mapperConfig = new MapperConfiguration(cfg =>
            {
                cfg.CreateMap <DAL.Spatial, Model.Spatial>().MaxDepth(2);
                cfg.CreateMap <DAL.Weather, Model.Weather>().MaxDepth(2);
                cfg.CreateMap <DAL.Wind_Levels, Model.Wind_Levels>().MaxDepth(2);
                cfg.CreateMap <DAL.Wind_Directions, Model.Wind_Directions>().MaxDepth(2);
                cfg.CreateMap <DAL.Weather_Types, Model.Weather_Types>().MaxDepth(2);
                cfg.CreateMap <DAL.Air_Quality_Types, Model.Air_Quality_Types>().MaxDepth(2);
                cfg.CreateMap <DAL.Location_Aware_Message, Model.Location_Aware_Message>().MaxDepth(2);
            });
            var mapper      = mapperConfig.CreateMapper();
            var coord       = DbGeography.FromText($"Point({longitude} {latitude})", 4326);
            var nearestCity = mapper.Map <Model.Spatial>((from p in weatherEntities.Spatials

                                                          orderby p.GeoLocation.Distance(coord)
                                                          select p).FirstOrDefault());

            if (nearestCity != null)
            {
                var weatherOfCity = mapper.Map <Model.Weather>(weatherEntities.Weathers.Where(a => a.Spatial_Id == nearestCity.Spatial_Id).FirstOrDefault());
                if (weatherOfCity != null)
                {
                    weatherOfCity.Spatial         = nearestCity;
                    weatherOfCity.Weather_Types   = mapper.Map <Model.Weather_Types>(weatherEntities.Weather_Types.Where(a => a.Weather_Type_Id == weatherOfCity.Weather_Type_Id).FirstOrDefault());
                    weatherOfCity.Wind_Directions = mapper.Map <Model.Wind_Directions>(weatherEntities.Wind_Directions.Where(a => a.Wind_Direction_Id == weatherOfCity.Wind_Direction_Id).FirstOrDefault());
                    Model.Wind_Levels            windLevel  = mapper.Map <Model.Wind_Levels>(weatherEntities.Wind_Levels.Where(a => weatherOfCity.Wind_Speed != null && a.Speed_Start <= weatherOfCity.Wind_Speed && a.Speed_End > weatherOfCity.Wind_Speed).FirstOrDefault());
                    Model.Air_Quality_Types      airQuality = mapper.Map <Model.Air_Quality_Types>(weatherEntities.Air_Quality_Types.Where(a => weatherOfCity.Air_Quality_Num != null && a.Start <= weatherOfCity.Air_Quality_Num && a.End > weatherOfCity.Air_Quality_Num).FirstOrDefault());
                    Model.Location_Aware_Message msg        = mapper.Map <Model.Location_Aware_Message>(weatherEntities.Location_Aware_Message.Where(a => a.Spatial_Id == nearestCity.Spatial_Id).FirstOrDefault());
                    Model.WeatherDTO             weatherDto = new WeatherDTO(weatherOfCity, windLevel, airQuality, msg);

                    return(weatherDto);
                }
            }
            return(null);
        }
Example #23
0
        static void Main(string[] args)
        {
            #region test without pattern Factory Method

            /*
             * Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
             * Thread.CurrentThread.CurrentUICulture = new CultureInfo("ru-RU");
             *
             #region test weather block
             *
             * Currency currency = DataLoad.GetCurrencyFromXML("https://nationalbank.kz/rss/rates_all.xml?switch=russian", out message);
             * ShowMessage();
             *
             * Weather weather = DataLoad.GetWeatherFromXML("https://xml.meteoservice.ru/export/gismeteo/point/1.xml", out message);
             * ShowMessage();
             *
             * WeatherItemDescription description = new WeatherItemDescription();
             *
             * string strTod;
             * string strCloudiness;
             * string strPrecipitation;
             * string strRpower;
             * string strSpower;
             * string strDirection;
             *
             * Console.WriteLine($"\nПрогноз погоды в городе {weather.Sname}");
             * Console.WriteLine("По данным от " + DateTime.Now.ToString("F", new CultureInfo("ru")));
             * Console.WriteLine(new string('=', 90));
             *
             * foreach (Forecast forecast in weather.forecasts)
             * {
             *  description.tod.TryGetValue(forecast.Tod, out strTod);
             *  description.cloudiness.TryGetValue(forecast.phenomena.Cloudiness, out strCloudiness);
             *  description.precipitation.TryGetValue(forecast.phenomena.Precipitation, out strPrecipitation);
             *  description.rpower.TryGetValue(forecast.phenomena.Rpower, out strRpower);
             *  description.spower.TryGetValue(forecast.phenomena.Spower, out strSpower);
             *  description.direction.TryGetValue(forecast.wind.Direction, out strDirection);
             *
             *  //CultureInfo.GetCultureInfo("ru-RU");
             *  Enum.GetName(typeof(DayOfWeek), Convert.ToInt32(forecast.Weekday));
             *
             *  Console.WriteLine(
             *      forecast.GetDateTime().ToShortDateString() + "\n" +
             *      //forecast.GetDateTime().DayOfWeek + "\n" +
             *      Enum.GetName(typeof(DayOfWeekRU), Convert.ToInt32(forecast.Weekday) - 1) + "\n" +
             *      strTod + "\n" +
             *      strCloudiness + "\n" +
             *      strPrecipitation + "\n" +
             *      //strRpower + "\n" +
             *      //strSpower + "\n" +
             *      //strDirection + " " + forecast.wind.Min + " - " + forecast.wind.Max + " м/с" + "\n" +
             *      forecast.wind.ToString() + "\n" +
             *      forecast.temperature.ToString() + "\n" +
             *      forecast.heat.ToString() + "\n" +
             *      forecast.relwet.ToString() + "\n");
             *
             *  Console.WriteLine(new string('=', 90));
             * }
             *
             #endregion test weather block
             *
             #region test currency block
             *
             * Console.WriteLine($"Курс валюты НБРК на {currency.items[0].PubDate.ToString("dd MMMM yyyy", new CultureInfo("ru"))}");
             *
             * var usd = currency.items.Find((item) => item.Title == "USD");
             * var eur = currency.items.Find((item) => item.Title == "EUR");
             *
             * Console.WriteLine($"USD {usd.Description} динамика {usd.Change}");
             * Console.WriteLine($"EUR {eur.Description} динамика {eur.Change}");
             *
             * Console.WriteLine(new string('=', 90));
             *
             #endregion test currency block
             *
             */
            #endregion test without pattern Factory Method

            //=================================================================//

            #region test with patterns - Factory Method  and  MVC model

            ClassBuilder classBuilder = new WeatherDToBuilder("https://xml.meteoservice.ru/export/gismeteo/point/1.xml");
            WeatherDTO   weatherDTO   = (WeatherDTO)classBuilder.Create();

            Console.WriteLine($"\nПрогноз погоды в городе {weatherDTO.City}");
            Console.WriteLine("По данным от " + weatherDTO.currentDate.ToString("F", new CultureInfo("ru")));
            Console.WriteLine(new string('=', 90));

            foreach (var forecast in weatherDTO.forecastsDTO)
            {
                Console.WriteLine(forecast.Date);
                Console.WriteLine(forecast.TimesOfDay);
                Console.WriteLine(forecast.Temperature);
                Console.WriteLine(forecast.Heat);
                Console.WriteLine(forecast.Phenomena.Cloudiness);
                Console.WriteLine(forecast.Phenomena.Precipitation);
                Console.WriteLine(forecast.Phenomena.Rpower);
                Console.WriteLine(forecast.Phenomena.Spower);
                Console.WriteLine(forecast.Wind);
                Console.WriteLine(forecast.Relwet);
                Console.WriteLine(forecast.Pressure);

                Console.WriteLine("\n" + new string('=', 90));
            }

            classBuilder = new CurrencyDToBuilder("https://nationalbank.kz/rss/rates_all.xml?switch=russian");
            CurrencyDTO currencyDTO = (CurrencyDTO)classBuilder.Create();

            Console.WriteLine($"Курс валюты НБРК на {currencyDTO.items[0].PubDate.ToString("dd MMMM yyyy", new CultureInfo("ru"))}");

            var usd = currencyDTO.items.Find((item) => item.Title == "USD");
            var eur = currencyDTO.items.Find((item) => item.Title == "EUR");

            Console.WriteLine($"USD {usd.Description} динамика {usd.Change}");
            Console.WriteLine($"EUR {eur.Description} динамика {eur.Change}");

            Console.WriteLine(new string('=', 90));

            #endregion test with patterns - Factory Method  and  MVC model

            Console.ReadKey();
        }
Example #24
0
 public WeatherRetrievedEventArgs(WeatherDTO weather)
 {
     Weather = weather;
 }
        public static WeatherDTO Convert(this Weather entity)
        {
            var result = new WeatherDTO();

            return(result);
        }
        public static Weather Convert(this WeatherDTO dto)
        {
            var result = new Weather();

            return(result);
        }
Example #27
0
 public bool AddWeatherNotification(WeatherDTO weatherNotificaition)
 {
     _dBContext.Weathers.Add(weatherNotificaition.ToWeather());
     return(_dBContext.SaveChanges() > 0);
 }
Example #28
0
 public void AddWeather(WeatherDTO weather)
 {
     weatherDtos.Add(weather);
 }
Example #29
0
 private void UpdateWeather(WeatherDTO weather)
 {
     Weather = weather;
     PropertyChanged(this, new PropertyChangedEventArgs("Weather"));
 }
 private void LoadLocalSingleDay()
 {
     strLocalLocation = db_helper.GetSavedLocationText();
     localMain        = db_helper.GetSavedMainWeather();
     localWeather     = db_helper.GetSavedWeather();
 }