Exemple #1
0
        public void SaveNullShouldNotTryAddToDatabase()
        {
            //Arrange
            WeatherMain expecWeatherMain = new WeatherMain()
            {
                Humidity       = 0,
                Pressure       = 0,
                Temperature    = 0,
                TemperatureMin = 0,
                TemperatureMax = 0,
            };
            Wind expectedWind = new Wind()
            {
                Direction = 0,
                Speed     = 0
            };
            PredictionDate expectedPredictionDate = new PredictionDate()
            {
                Time = DateTime.Now,
            };
            Clouds expectedClouds = new Clouds()
            {
                All = 0
            };
            Forecast expectedForecast = new Forecast()
            {
                Clouds      = expectedClouds,
                WeatherMain = expecWeatherMain,
                Wind        = expectedWind,
                Time        = expectedPredictionDate,
                CityId      = 0
            };
            ForecastEntity expectedEntity = new ForecastEntity()
            {
                WeatherMain    = expecWeatherMain,
                Wind           = expectedWind,
                PredictionDate = expectedPredictionDate,
                Clouds         = expectedClouds,
                CityServiceId  = 0,
                Forecast       = expectedForecast
            };

            var weatherContextMock = new Mock <WeatherDataContext>();

            weatherContextMock.Setup(x => x.Forecast.Add(It.IsAny <Forecast>())).Returns((Forecast f) => f);
            weatherContextMock.Setup(x => x.City.Add(It.IsAny <City>())).Returns((City f) => f);
            weatherContextMock.Setup(x => x.Clouds.Add(It.IsAny <Clouds>())).Returns((Clouds f) => f);
            weatherContextMock.Setup(x => x.PredictionDate.Add(It.IsAny <PredictionDate>())).Returns((PredictionDate f) => f);
            weatherContextMock.Setup(x => x.WeatherMain.Add(It.IsAny <WeatherMain>())).Returns((WeatherMain f) => f);
            weatherContextMock.Setup(x => x.Wind.Add(It.IsAny <Wind>())).Returns((Wind f) => f);
            WeatherManager weather = new WeatherManager(weatherContextMock.Object);

            //Act

            var savedEntities = weather.SaveForecastEntity(expectedEntity).Result;

            //Assert
            Assert.Equal(1, savedEntities);
            weatherContextMock.Verify(x => x.SaveChangesAsync(), Times.Never);
        }
        public ForecastEntity ConvertEntity(Forecast forecast)
        {
            Clouds         clouds         = forecast.Clouds;
            PredictionDate predictionDate = forecast.Time;
            WeatherMain    weatherMain    = forecast.WeatherMain;
            Wind           wind           = forecast.Wind;
            ForecastEntity forecastEntity = new ForecastEntity
            {
                Clouds         = clouds,
                PredictionDate = predictionDate,
                WeatherMain    = weatherMain,
                Wind           = wind
            };

            return(forecastEntity);
        }
 public Task <IResult> Create(WeatherMain Model)
 {
     this._result.Success = false;
     try
     {
         this._result.Message = "正在執行 insert WeatherMain ";
         this._repository.Create(Model);
         this._unitOfWork.SaveChange();
         this._result.Success = true;
         this._result.Message = "insert WeatherMain OK!";
     }
     catch (Exception e)
     {
         this._result.Exception = e;
     }
     return(Task.FromResult(this._result));
 }
        public ForecastEntity GetForecastEntity(City city, DateTime date)
        {
            DateTime       preciseTime    = GetCLosestForecastTime(date);
            var            forecast       = dataContext.Forecast.Where(f => f.Time.Time == preciseTime).Where(c => c.City.ServiceId == city.ServiceId).First();
            Clouds         clouds         = forecast.Clouds;
            PredictionDate predictionDate = forecast.Time;
            WeatherMain    weatherMain    = forecast.WeatherMain;
            Wind           wind           = forecast.Wind;
            ForecastEntity forecastEntity = new ForecastEntity
            {
                Clouds         = clouds,
                PredictionDate = predictionDate,
                WeatherMain    = weatherMain,
                Wind           = wind
            };

            return(forecastEntity);
        }
        private List <ForecastEntity> ConvertEntities(IQueryable <Forecast> forecast)
        {
            List <ForecastEntity> forecasts = new List <ForecastEntity>();

            foreach (var item in forecast)
            {
                Clouds         clouds         = item.Clouds;
                PredictionDate predictionDate = item.Time;
                WeatherMain    weatherMain    = item.WeatherMain;
                Wind           wind           = item.Wind;
                ForecastEntity forecastEntity = new ForecastEntity
                {
                    Clouds         = clouds,
                    PredictionDate = predictionDate,
                    WeatherMain    = weatherMain,
                    Wind           = wind
                };
                forecasts.Add(forecastEntity);
            }

            return(forecasts);
        }
Exemple #6
0
        public virtual IActionResult SaveWeather(string data)
        {
            try
            {
                WeatherMain weather_response = JsonConvert.DeserializeObject <WeatherMain>(data);

                WeatherMain new_weather = new WeatherMain()
                {
                    Name        = weather_response.Name,
                    DateTime    = weather_response.DateTime,
                    Main        = weather_response.Main,
                    Description = weather_response.Description,
                    Temp        = weather_response.Temp,
                    TempMax     = weather_response.TempMax,
                    TempMin     = weather_response.TempMin,
                    FeelsLike   = weather_response.FeelsLike,
                    Pressure    = weather_response.Pressure,
                    Humidity    = weather_response.Humidity,
                    WindSpeed   = weather_response.WindSpeed,
                    WindDeg     = weather_response.WindDeg,
                    Clouds      = weather_response.Clouds,
                    Rain1h      = weather_response.Rain1h,
                    Rain3h      = weather_response.Rain3h,
                    Snow1h      = weather_response.Snow1h,
                    Snow3h      = weather_response.Snow3h
                };

                _db.WeatherMain.Add(new_weather);
                _db.SaveChanges();

                return(Ok());
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error", ex);
                return(BadRequest(ex.Message));
            }
        }
Exemple #7
0
        private async Task <IResult> SaveData(string strLocationID, DateTime dtTime)
        {
            this._IResult.Success = false;
            var CheckData = await this._IWeatherMainRepository.GetQuery(dtTime, strLocationID);

            if (CheckData == null)
            {
                string strUrl         = this._Configuration.GetSection("WeatherAPI").Value;
                var    csCodeArea     = this._ICodeAreaRepository.GetAll();
                var    csCodeLocation = this._ICodeLocationRepository.GetAll();
                string strHiours      = DateTime.Now.Hour >= 12 ? "12" : "06";
                var    Result         = await this._IApiManagers.Get <Weather>(string.Format(strUrl, strLocationID, dtTime.ToString("yyyy-MM-dd"), strHiours));

                if (Result != null)
                {
                    WeatherMain csWeatherMain = new WeatherMain();
                    csWeatherMain.ApiId = strLocationID;
                    var Locations = Result.records.locations;

                    #region 資料整理
                    foreach (var item in Locations)
                    {
                        #region 未建立CODELocation表資料
                        if (!(await csCodeLocation).Any(x => x.Id == item.dataid))
                        {
                            CodeLocation CodeLocation = new CodeLocation()
                            {
                                Id   = item.dataid,
                                Name = item.locationsName
                            };
                            var LocationResult = await this._ICodeLocationRepository.Create(CodeLocation);

                            if (!LocationResult.Success)
                            {
                                this._IResult.Success = false;
                                this._IResult.Message = LocationResult.Message + LocationResult.Exception.Message + LocationResult.Exception.StackTrace;
                                break;
                            }
                        }
                        #endregion

                        foreach (var Location in item.location)
                        {
                            #region 未建立CODEArea表資料
                            if (!(await csCodeArea).Any(x => x.Id == Location.geocode))
                            {
                                CodeArea CodeArea = new CodeArea()
                                {
                                    Id           = Location.geocode,
                                    CodeLocation = item.dataid,
                                    Name         = Location.locationName
                                };
                                var AreaResult = await this._ICodeAreaRepository.Create(CodeArea);

                                if (!AreaResult.Success)
                                {
                                    this._IResult.Success = false;
                                    this._IResult.Message = AreaResult.Message + AreaResult.Exception.Message + AreaResult.Exception.StackTrace;
                                    break;
                                }
                            }
                            #endregion

                            csWeatherMain.LocationId = item.dataid;
                            csWeatherMain.Date       = dtTime;
                            csWeatherMain.Ctime      = DateTime.Now;
                            WeatherDetail csWeatherDetail = new WeatherDetail();
                            foreach (var Weather in Location.weatherElement)
                            {
                                csWeatherDetail.AreaId = Location.geocode;
                                var ElementName = (WEATHER)Enum.Parse(typeof(WEATHER), Weather.elementName, true);
                                var ValueModel  = Weather.time.FirstOrDefault();

                                #region 天氣各節點資料
                                switch (ElementName)
                                {
                                case WEATHER.PoP12h:
                                    csWeatherDetail.StartTime = "0600";
                                    csWeatherDetail.EndTime   = "1200";
                                    if (ValueModel != null)
                                    {
                                        DateTime dtStartTime = Convert.ToDateTime(ValueModel.startTime);
                                        csWeatherDetail.RainRatio = Convert.ToDecimal(ValueModel.elementValue.FirstOrDefault().value);
                                    }
                                    else
                                    {
                                        csWeatherDetail.RainRatio = 0;
                                    }
                                    break;

                                case WEATHER.Wx:
                                    if (ValueModel != null)
                                    {
                                        csWeatherDetail.States = ValueModel.elementValue.FirstOrDefault().value;
                                    }
                                    else
                                    {
                                        csWeatherDetail.States = "N/A";
                                    }
                                    break;

                                case WEATHER.AT:
                                    if (ValueModel != null)
                                    {
                                        csWeatherDetail.BodyTemperature = Convert.ToDecimal(ValueModel.elementValue.FirstOrDefault().value);
                                    }
                                    else
                                    {
                                        csWeatherDetail.BodyTemperature = 0;
                                    }
                                    break;

                                case WEATHER.T:
                                    if (ValueModel != null)
                                    {
                                        csWeatherDetail.Temperature = Convert.ToDecimal(ValueModel.elementValue.FirstOrDefault().value);
                                    }
                                    else
                                    {
                                        csWeatherDetail.Temperature = 0;
                                    }
                                    break;

                                case WEATHER.RH:
                                    if (ValueModel != null)
                                    {
                                        csWeatherDetail.Humidity = Convert.ToDecimal(ValueModel.elementValue.FirstOrDefault().value);
                                    }
                                    else
                                    {
                                        csWeatherDetail.Humidity = 0;
                                    }
                                    break;

                                case WEATHER.CI:
                                    if (ValueModel != null)
                                    {
                                        csWeatherDetail.ComfortIndex = Convert.ToDecimal(ValueModel.elementValue[0].value);
                                        csWeatherDetail.Comfort      = ValueModel.elementValue[1].value;
                                    }
                                    else
                                    {
                                        csWeatherDetail.ComfortIndex = 0;
                                        csWeatherDetail.Comfort      = "N/A";
                                    }
                                    break;

                                case WEATHER.WeatherDescription:
                                    if (ValueModel != null)
                                    {
                                        csWeatherDetail.Detail = ValueModel.elementValue.FirstOrDefault().value;
                                    }
                                    else
                                    {
                                        csWeatherDetail.Detail = "N/A";
                                    }
                                    break;

                                case WEATHER.WS:
                                    if (ValueModel != null)
                                    {
                                        csWeatherDetail.WindSpeed = Convert.ToDecimal(ValueModel.elementValue.FirstOrDefault().value);
                                    }
                                    else
                                    {
                                        csWeatherDetail.WindSpeed = 0;
                                    }
                                    break;

                                case WEATHER.WD:
                                    if (ValueModel != null)
                                    {
                                        csWeatherDetail.WindDirection = ValueModel.elementValue.FirstOrDefault().value;
                                    }
                                    else
                                    {
                                        csWeatherDetail.WindDirection = "N/A";
                                    }
                                    break;

                                case WEATHER.Td:
                                    if (ValueModel != null)
                                    {
                                        csWeatherDetail.DewPoint = Convert.ToDecimal(ValueModel.elementValue.FirstOrDefault().value);
                                    }
                                    else
                                    {
                                        csWeatherDetail.DewPoint = 0;
                                    }
                                    break;
                                }
                                #endregion
                            }
                            csWeatherMain.WeatherDetails.Add(csWeatherDetail);
                        }
                    }
                    #endregion

                    var DBResult = await this._IWeatherMainRepository.Create(csWeatherMain);

                    this._IResult.Success   = DBResult.Success;
                    this._IResult.Exception = DBResult.Exception;
                    this._IResult.Message   = DBResult.Message;
                }
            }
            else
            {
                this._IResult.Success = false;
                this._IResult.Message = "已有該天資料";
            }
            return(this._IResult);
        }
Exemple #8
0
        /// <summary>
        /// Получение данных о погоде,и запись в бд
        /// </summary>
        /// <param name="state"></param>
        public void GetWeathers(object state)
        {
            try
            {
                using (var scope = _scopeFactory.CreateScope())
                    using (var db = scope.ServiceProvider.GetRequiredService <WeatherContext>())
                    {
                        _logger.LogInformation("Отправка запроса на полученние данных...");

                        HttpWebRequest  httpWebRequest  = (HttpWebRequest)WebRequest.Create(url);
                        HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();

                        string weather_json;
                        using (StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream()))
                            weather_json = streamReader.ReadToEnd();

                        Root     weather_response = JsonConvert.DeserializeObject <Root>(weather_json);
                        DateTime datatime         = DateTimeExtension.LongToDateTime(weather_response.dt)
                                                    .AddHours(4);

                        if (db.WeatherMain.Where(p => p.DateTime == datatime).FirstOrDefault() == null)
                        {
                            WeatherMain weather = new WeatherMain
                            {
                                Name         = weather_response.name,
                                DateTime     = datatime,
                                Main         = weather_response.weather.FirstOrDefault().main,
                                Description  = weather_response.weather.FirstOrDefault().description,
                                Temp         = weather_response.main.temp,
                                TempMax      = weather_response.main.temp_max,
                                TempMin      = weather_response.main.temp_min,
                                FeelsLike    = weather_response.main.feels_like,
                                Pressure     = weather_response.main.pressure,
                                Humidity     = weather_response.main.humidity,
                                WindSpeed    = weather_response.wind.speed,
                                WindDeg      = weather_response.wind.deg,
                                Clouds       = weather_response.clouds.all,
                                OriginalJson = weather_json
                            };

                            if (weather_response.rain != null)
                            {
                                weather.Rain1h = weather_response.rain.H1;
                                weather.Rain3h = weather_response.rain.H3;
                            }
                            if (weather_response.snow != null)
                            {
                                weather.Snow1h = weather_response.snow.H1;
                                weather.Snow3h = weather_response.snow.H3;
                            }

                            db.WeatherMain.Add(weather);
                            db.SaveChanges();

                            _logger.LogInformation("Данные успешно сохранены");
                        }
                    }
            }
            catch (Exception ex)
            {
                _logger.LogInformation($"Ошибка получение данных: {ex.Message}");
                Console.WriteLine($"Ошибка получение данных: {ex.Message}");
            }
        }
Exemple #9
0
        public async Task getWeather(string city, char degrees = ' ')
        {
            string degreesFormat = "units=metric";
            string url           = $"http://api.openweathermap.org/data/2.5/weather?q={city}&{degreesFormat}&appid={Settings.WeatherApiKey}";

            if (degrees != ' ')
            {
                switch (degrees)
                {
                default:
                case 'c':
                case 'C':
                {
                    degreesFormat = "units=metric";
                    url           = $"http://api.openweathermap.org/data/2.5/weather?q={city}&{degreesFormat}&appid={Settings.WeatherApiKey}";
                    break;
                }

                case 'F':
                case 'f':
                {
                    degreesFormat = "units=imperial";
                    url           = $"http://api.openweathermap.org/data/2.5/weather?q={city}&{degreesFormat}&appid={Settings.WeatherApiKey}";
                    break;
                }

                case 'K':
                case 'k':
                {
                    url = $"http://api.openweathermap.org/data/2.5/weather?q={city}&appid={Settings.WeatherApiKey}";
                    break;
                }
                }
            }
            try
            {
                WebRequest         request  = WebRequest.Create(url);
                Task <WebResponse> response = request.GetResponseAsync();
                using (StreamReader sr = new StreamReader(response.Result.GetResponseStream()))
                {
                    string json = await sr.ReadToEndAsync();

                    WeatherMain  weather  = JsonConvert.DeserializeObject <WeatherMain>(json);
                    JObject      weather2 = JObject.Parse(json);
                    EmbedBuilder eb       = new EmbedBuilder();
                    eb.AddField($"Weather in {weather.Name}, {weather.Sys.Country}", $"**State: {weather2.SelectToken("weather[0].description")}**");
                    if (degrees == ' ')
                    {
                        degrees = 'C';
                    }
                    eb.AddField("Temperature", $"**{weather.Main.Temp}°{degrees.ToString().ToUpper()}**", true);
                    eb.AddField("Humidity", $"**{weather.Main.Humidity}%**", true);
                    eb.AddField("Pressure", $"**{weather.Main.Pressure} hPa**", true);
                    eb.AddField("Wind speed", $"**{weather.Wind.Speed} m/s**", true);
                    eb.WithFooter($"Last update: {UnixTimeStampToDateTime(weather.Dt)} UTC");
                    eb.WithThumbnailUrl($"http://openweathermap.org/img/w/{(string)weather2.SelectToken("weather[0].icon")}.png");
                    eb.WithColor(40, 200, 150);
                    await Context.Channel.SendMessageAsync("", false, eb.Build());
                }
            }
            catch (JsonReaderException)
            {
                await Context.Channel.SendMessageAsync(":x: **Data of this city is unaviable. Please try again later.**");

                return;
            }
            catch (AggregateException)
            {
                await Context.Channel.SendMessageAsync(":x: **City name is incorrect! Please use a right one.**");

                return;
            }
        }