Exemplo n.º 1
0
        void weatherBug_LiveWeatherCompleted(object sender, LiveWeather liveWeather, Forecasts forecasts)
        {
            //도시검색을 통해서 들어온 경우라면 폰상태 정보의 도시정보를 설정에 저장하고 삭제
            if (PhoneApplicationService.Current.State.ContainsKey(Constants.WEATHER_MAIN_CITY))
            {
                SettingHelper.Set(Constants.WEATHER_MAIN_CITY, PhoneApplicationService.Current.State[Constants.WEATHER_MAIN_CITY], true);
                PhoneApplicationService.Current.State.Remove(Constants.WEATHER_MAIN_CITY);
            }

            if (liveWeather == null || !(liveWeather is LiveWeather) || forecasts == null || !(forecasts is Forecasts))
            {
                WeatherCity city = SettingHelper.Get(Constants.WEATHER_MAIN_CITY) as WeatherCity;

                PIWeather.Header            = city.IsGpsLocation ? AppResources.Refresh : city.CityName;
                GridLiveWeather.Visibility  = System.Windows.Visibility.Collapsed;
                ListBoxForecasts.Visibility = System.Windows.Visibility.Collapsed;
                TxtWeatherNoCity.Visibility = System.Windows.Visibility.Visible;
                TxtWeatherNoCity.Text       = AppResources.MsgNotSupportWeatherLocation;
                return;
            }
            //검색된 결과값 저장
            SettingHelper.Set(Constants.WEATHER_LIVE_RESULT, liveWeather, true);
            //화면에 검색된 결과를 표시
            RenderLiveWeather(liveWeather);
            //조회된 주간예보 정보를 저장
            SettingHelper.Set(Constants.WEATHER_FORECAST_RESULT, forecasts, true);
            //조회된 주간예보 정보를 화면에 표시
            RenderForecast(forecasts);
            //날씨 라이브타일 다시 로드
            CreateWeatherLivetileImage();

            //로딩 레이어 제거
            HideLoadingPanel();
        }
Exemplo n.º 2
0
 private static void ActualizationWeather()
 {
     if (CurrentDateTime == null)
     {
         CurrentDateTime = DateTime.Now;
         PreviosDateTime = CurrentDateTime;
         Weather         = new WeatherCity();
         Weather.Set(WeatherCity.CreateWeatherCity("54.735950", "55.982370"));
     }
     else if (DateTime.Now > ((DateTime)PreviosDateTime).AddMinutes(30))
     {
         CurrentDateTime = DateTime.Now;
         PreviosDateTime = DateTime.Now;
         Weather         = new WeatherCity();
         Weather.Set(WeatherCity.CreateWeatherCity("54.735950", "55.982370"));
     }
     else
     {
         CurrentDateTime = DateTime.Now;
         if (Weather == null)
         {
             Weather = new WeatherCity();
             Weather.Set(WeatherCity.CreateWeatherCity("54.735950", "55.982370"));
         }
     }
 }
Exemplo n.º 3
0
 /// <summary>
 /// 新增一个天气服务城市信息
 /// </summary>
 /// <param name="weatherCity">天气服务城市信息</param>
 public void AddWeatherCity(WeatherCity weatherCity)
 {
     using (var db = new InterfaceCoreDB())
     {
         db.WeatherCity.Add(weatherCity);
         db.SaveChanges();
     }
 }
Exemplo n.º 4
0
        public JsonResult GetWeather(string city)
        {
            var result = new WeatherCity().GetTodayWeather(city);

            return(new JsonResult(result, new JsonSerializerSettings()
            {
                DateFormatHandling = DateFormatHandling.MicrosoftDateFormat,
                DateTimeZoneHandling = DateTimeZoneHandling.Utc
            }));
        }
        internal static void addWeatherForACity(WeatherCity weathercityModel)
        {
            string Command = "INSERT OR REPLACE INTO Weather(City, Date, MinTemp, MaxTemp)" +
                             " VALUES('" + weathercityModel.City + "', date('" + weathercityModel.Date.ToString("yyy-MM-dd") + "')," + weathercityModel.MinTemp + "," +
                             weathercityModel.MaxTemp + ");";

            WeatherTableCreator.ReadData(Command);

            return;
        }
Exemplo n.º 6
0
 /// <summary>
 /// Executes the plug in.
 /// </summary>
 /// <param name="SESSION">The SESSION.</param>
 /// <param name="InPacket">The in packet.</param>
 /// <param name="OutPacket">The out packet.</param>
 /// <param name="Key">The key.</param>
 protected override void ExecutePlugIn(eTerm.AsyncSDK.Core.eTerm363Session SESSION, eTerm.AsyncSDK.Core.eTerm363Packet InPacket, eTerm.AsyncSDK.Core.eTerm363Packet OutPacket, eTerm.AsyncSDK.AsyncLicenceKey Key)
 {
     try {
         List<WeatherCity> collection = new List<WeatherCity>();
         WeatherCity RootCity = new WeatherCity() { CityId = string.Empty, CityName = string.Empty };
         ReadCity(RootCity,collection);
         new WeaterCityVersion() { VersionDate=DateTime.Now, WebCityList=collection }.XmlSerialize(TEACrypter.GetDefaultKey, new FileInfo(@"Weather.BIN").FullName);
         SESSION.SendPacket(__eTerm443Packet.BuildSessionPacket(SESSION.SID, SESSION.RID, "城市更新成功"));
     }
     catch(Exception ex) {
         SESSION.SendPacket(__eTerm443Packet.BuildSessionPacket(SESSION.SID, SESSION.RID, ex.Message));
     }
 }
        protected void LoadCurrentWeather(WeatherCity city)
        {
            if (!WEATHER_CITY_TO_ID.ContainsKey(city))
            {
                Debug.LogError("Can't find this city's ID in the dictionary; returning.");
                return;
            }
            //gets the string that the OpenWeatherMap API uses to identify the city.
            string cityID = WEATHER_CITY_TO_ID [city];

            //Call the weather data provider to do the actual loading.
            this.weatherDataProvider.LoadCurrentWeather(cityID, OnCurrentWeatherLoaded);
        }
 /// <summary>
 /// After a city button is selected we make it so all buttons are reset to the inactive color except for the one selected, which is set to the active color.
 /// Lastly, we fire our CityButtonSelectedAction action.
 /// </summary>
 /// <param name="city">City.</param>
 /// <param name="button">Button.</param>
 protected void OnCityButtonSelected(WeatherCity city, Button button)
 {
     //TODO: Fill.
     for (int i = 0; i < cityButtons.Length; i++)
     {
         if (cityButtons[i].city == city)
         {
             cityButtons[i].button.SetNormalColor(activeButtonColor);
         }
         else
         {
             cityButtons[i].button.SetNormalColor(inactiveButtonColor);
         }
     }
     CityButtonSelectedAction(city);
 }
        public List <WeatherCity> GetAllCity()
        {
            List <WeatherCity> models = new List <WeatherCity>();

            using (DbDataReader dr = this.SqlHelper.ExecuteReader("select * from [WeatherCity] ", null))
            {
                while (dr.Read())
                {
                    WeatherCity model = new WeatherCity();
                    model.CityCode = dr["CityCode"].ToString();
                    model.CityName = dr["CityName"].ToString();
                    models.Add(model);
                }
            }
            return(models);
        }
Exemplo n.º 10
0
 /// <summary>
 /// Reads the city.
 /// </summary>
 /// <param name="ParentCity">The parent city.</param>
 private void ReadCity(WeatherCity ParentCity, List<WeatherCity> collection)
 {
     HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create(string.Format(@"http://www.weather.com.cn/data/list3/city{0}.xml", ParentCity.CityId));
     using (HttpWebResponse myRes = (HttpWebResponse)myReq.GetResponse()) {
         using (Stream stream = myRes.GetResponseStream()) {
             StreamReader sr = new StreamReader(stream, Encoding.UTF8);
             //250401|衡阳,250402|衡山,250403|衡东,250404|祁东,250405|衡阳县,250406|常宁,250407|衡南,250408|耒阳,250409|南岳
             foreach (Match m in Regex.Matches(sr.ReadToEnd(), @"([0-9]+)\|([\u4E00-\u9FA5 0-9]+)", RegexOptions.IgnoreCase)) {
                 WeatherCity subCity = new WeatherCity() { ParentId=ParentCity.CityId, CityId = m.Groups[1].Value, CityName = m.Groups[2].Value, CityPinYin = Cn2PyUtil.FullConvert(m.Groups[2].Value) };
                 if (!Regex.IsMatch(subCity.CityName, @"^[0-9]+$")) {
                     ReadCity(subCity, collection);
                 }
                 collection.Add(subCity);
             }
             sr.Dispose();
         }
     }
 }
        async void OutputByAsync(int CityID)
        {
            string     uri     = $"http://api.openweathermap.org/data/2.5/weather?id={CityID}&units=metric&APPID=861ee4fb7dc955580611e95897e7387f";
            HttpClient client  = new HttpClient();
            string     content = await client.GetStringAsync(uri);

            WeatherCity m = JsonConvert.DeserializeObject <WeatherCity>(content);

            // блок кода для подключения картинки
            BitmapImage img1 = new BitmapImage();

            img1.BeginInit();
            img1.UriSource = new Uri($"http://openweathermap.org/img/w/{m.weather[0].icon}.png");
            img1.EndInit();
            imgTxbl.Source     = img1;
            imgTxbl.Visibility = Visibility.Visible;

            DataCity.Text = $"City:{m.name}\nState:{m.sys.country}\nTemprature:{m.main.temp}C°\nWindSpeed:{m.wind.speed}\nHumidity:{m.main.humidity}";
        }
Exemplo n.º 12
0
        private void RetrieveWeather()
        {
            WeatherCity city = SettingHelper.Get(Constants.WEATHER_MAIN_CITY) as WeatherCity;

            if (SettingHelper.ContainsKey(Constants.WEATHER_LIVE_RESULT))
            {
                LiveWeather liveWeather = SettingHelper.Get(Constants.WEATHER_LIVE_RESULT) as LiveWeather;

                System.DateTime updDttm = GetDateTime(liveWeather.ObDate);
                //System.DateTime updDttm = liveWeather.UpdatedDateTime;

                //업데이트 후 1시간이 지나지 않았다면
                if (DateTime.Now.Subtract(updDttm).TotalMinutes < 60)
                {
                    //도시 설정
                    weatherBug.DefaultWeatherCity = city;
                    //화면 표시
                    RenderLiveWeather(liveWeather);

                    //업데이트 불필요 기존 데이터를 다시 로드하여 보여줌
                    if (SettingHelper.ContainsKey(Constants.WEATHER_FORECAST_RESULT))
                    {
                        Forecasts forecasts = SettingHelper.Get(Constants.WEATHER_FORECAST_RESULT) as Forecasts;

                        //주간 예보 표시
                        RenderForecast(forecasts);
                        return;
                    }
                }
            }

            if (city != null)
            {
                RetrieveWeather(city);
            }
        }
Exemplo n.º 13
0
        private void LLSLocation_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (sender == null)
            {
                return;
            }

            Location location = (sender as LongListSelector).SelectedItem as Location;

            WeatherCity city = new WeatherCity();

            city.CityName = location.CityName;
            //city.IsGpsLocation = false;
            city.isZipCode     = location.IsUsa;
            city.Code          = location.IsUsa ? location.ZipCode : location.CityCode;
            city.IsGpsLocation = true;
            city.Latitude      = location.Lat;
            city.Longitude     = location.Lon;
            city.StateName     = location.CityName != location.StateName ? location.StateName : string.Empty;
            city.CountryName   = location.CountryName;

            PhoneApplicationService.Current.State[Constants.WEATHER_MAIN_CITY] = city;
            NavigationService.GoBack();
        }
        public static List <WeatherCity> ReadData(string CommandText)
        {
            List <WeatherCity> result = new List <WeatherCity>();

            SQLiteDataReader sqlite_datareader;
            SQLiteCommand    sqlite_cmd;

            sqlite_cmd             = ConnectorDatabase.sqliteConnection.CreateCommand();
            sqlite_cmd.CommandText = CommandText;

            sqlite_datareader = sqlite_cmd.ExecuteReader();
            while (sqlite_datareader.Read())
            {
                var row = new WeatherCity();
                row.City    = sqlite_datareader.GetString(0);
                row.Date    = sqlite_datareader.GetDateTime(1);
                row.MinTemp = sqlite_datareader.GetInt32(2);
                row.MaxTemp = sqlite_datareader.GetInt32(3);

                result.Add(row);
            }

            return(result);
        }
        ////////////////////////////////////////
        //
        // Weather Event Functions

        protected void OnWeatherCityButtonSelected(WeatherCity weatherCity)
        {
            LoadCurrentWeather(weatherCity);
        }
Exemplo n.º 16
0
        private async void FindLocation()
        {
            if (!SettingHelper.ContainsKey(Constants.WEATHER_LOCATION_CONSENT))
            {
                MessageBoxResult result =
                    MessageBox.Show(AppResources.MsgConfirmUseLocation,
                                    AppResources.AgreeUseLocation,
                                    MessageBoxButton.OKCancel);

                SettingHelper.Set(Constants.WEATHER_LOCATION_CONSENT, (result == MessageBoxResult.OK), false);
            }

            if (!SettingHelper.ContainsKey(Constants.WEATHER_LOCATION_CONSENT))
            {
                // The user has opted out of Location.
                return;
            }

            Geolocator geolocator = new Geolocator();

            geolocator.DesiredAccuracyInMeters = 50;

            try
            {
                Geoposition geoposition = await geolocator.GetGeopositionAsync(
                    maximumAge : TimeSpan.FromMinutes(5),
                    timeout : TimeSpan.FromSeconds(10)
                    );

                DisplayUnit unitType = (DisplayUnit)SettingHelper.Get(Constants.WEATHER_UNIT_TYPE);

                //날씨 조회 모드 설정 변경
                WeatherCity city = new WeatherCity();
                city.IsGpsLocation = true;
                city.Latitude      = geoposition.Coordinate.Latitude.ToString();
                city.Longitude     = geoposition.Coordinate.Longitude.ToString();
                //검색조건 저장
                SettingHelper.Set(Constants.WEATHER_MAIN_CITY, city, false);

                //좌표로 날씨 조회
                RetrieveWeather(city);
            }
            catch (Exception ex)
            {
                if ((uint)ex.HResult == 0x80004004)
                {
                    //로딩 패널 제거
                    HideLoadingPanel();

                    // the application does not have the right capability or the location master switch is off
                    //StatusTextBlock.Text = "location  is disabled in phone settings.";
                    if (MessageBox.Show(AppResources.MsgFailLocationService, AppResources.Confirm, MessageBoxButton.OKCancel) == MessageBoxResult.OK)
                    {
                        var navigate = Windows.System.Launcher.LaunchUriAsync(new Uri("ms-settings-location:"));
                    }
                }
                //else
                {
                    // something else happened acquring the location
                }
            }
        }
 /// <summary>
 /// After a city button is selected we make it so all buttons are reset to the inactive color except for the one selected, which is set to the active color.
 /// Lastly, we fire our CityButtonSelectedAction action.
 /// </summary>
 /// <param name="city">City.</param>
 /// <param name="button">Button.</param>
 protected void OnCityButtonSelected(WeatherCity city, Button button)
 {
     //TODO: Fill.
 }
Exemplo n.º 18
0
        /// <summary>
        /// 예약된 작업을 실행하는 에이전트입니다.
        /// </summary>
        /// <param name="task">
        /// 호출한 작업입니다.
        /// </param>
        /// <remarks>
        /// 이 메서드는 정기적 작업 또는 리소스를 많이 사용하는 작업이 호출될 때 호출됩니다.
        /// </remarks>
        protected override void OnInvoke(ScheduledTask task)
        {
            bool isLiveTileTurn = true;

            scheduleSettings = MutexedIsoStorageFile.Read <ScheduleSettings>("ScheduleSettings", Constants.MUTEX_DATA);

            //스케쥴러는 30분마다 들어온다.
            //이번이 누구 차례인가를 생성해야 한다.
            //라이브타일과 락스크린은 각각의 인터벌이 있고, 그 인터벌은 어느 순간 중복될 수 있다.
            //중복되면 라이브타일에 우선권을 부여하여 실행하며, 락스크린은 그 이후 스케줄로 밀린다.
            //판별에 사용될 변수는 1.인터벌, 2.실행대상, 3.실행대상의 최종 실행시간
#if !DEBUG_AGENT
            {
                DateTime LastRunForLivetile, LastRunForLockscreen;
                IsolatedStorageSettings.ApplicationSettings.TryGetValue <DateTime>(Constants.LAST_RUN_LIVETILE, out LastRunForLivetile);
                IsolatedStorageSettings.ApplicationSettings.TryGetValue <DateTime>(Constants.LAST_RUN_LOCKSCREEN, out LastRunForLockscreen);
                bool useLockscreenRotator;
                IsolatedStorageSettings.ApplicationSettings.TryGetValue <bool>(Constants.LOCKSCREEN_USE_ROTATOR, out useLockscreenRotator);

                double lockscreenTerm = DateTime.Now.Subtract(LastRunForLockscreen).TotalMinutes - scheduleSettings.LockscreenUpdateInterval;
                //한번도 락스크린 스케쥴러를 실행한적이 없고 락스크린이 스케쥴에서 사용되지 않는 경우는 -1로 설정하여 락스크린으로 분기되지 않도록 처리
                if (LastRunForLockscreen.Year == 1 && LastRunForLockscreen.Month == 1 && LastRunForLockscreen.Day == 1 && !useLockscreenRotator)
                {
                    lockscreenTerm = -1;
                }

                if (DateTime.Now.Subtract(LastRunForLivetile).TotalMinutes < scheduleSettings.LivetileUpdateInterval &&
                    lockscreenTerm < 0)
                {
                    System.Diagnostics.Debug.WriteLine("Too soon, stopping.");
                    NotifyComplete();
                    return;
                }
                else if (lockscreenTerm >= 0)
                {
                    isLiveTileTurn = false;
                }
            }
#else
            isLiveTileTurn = false;
#endif
            if (isLiveTileTurn)
            {
                Deployment.Current.Dispatcher.BeginInvoke(() =>
                {
                    System.Diagnostics.Debug.WriteLine("1 =>" + Microsoft.Phone.Info.DeviceStatus.ApplicationCurrentMemoryUsage);
                    LivetileData data = new LivetileData()
                    {
                        DayList = VsCalendar.GetCalendarOfMonth(DateTime.Now, DateTime.Now, true, true),
                    };

                    try
                    {
                        System.Diagnostics.Debug.WriteLine("타일 전 =>" + Microsoft.Phone.Info.DeviceStatus.ApplicationCurrentMemoryUsage);

                        bool hasWeather  = ShellTile.ActiveTiles.Any(x => x.NavigationUri.ToString().Contains("weather"));
                        bool hasCalendar = ShellTile.ActiveTiles.Any(x => x.NavigationUri.ToString().Contains("calendar"));

                        if (hasWeather)
                        {
                            //1. 날씨 타일이 핀되어 있다.
                            WeatherCity city   = SettingHelper.Get(Constants.WEATHER_MAIN_CITY) as WeatherCity;
                            DisplayUnit unit   = (DisplayUnit)SettingHelper.Get(Constants.WEATHER_UNIT_TYPE);
                            WeatherBug weather = new WeatherBug();
                            weather.LiveWeatherCompletedLoad += (s, r, f) =>
                            {
                                //조회된 데이터를 셋팅(없으면 저장된 날씨를 사용함)
                                SetWeatherResult(data, r, f);
                                //달력 적용 또는 직접 렌더링
                                DelegateUpdateProcess(task, data, hasCalendar);
                            };
                            weather.RequestFailed += (s, r) =>
                            {
                                //데이터를 얻는데 실패 한 경우 네트워크가 연결되지 않았다면, 이전 저장된 데이터를 사용
                                if (!DeviceNetworkInformation.IsNetworkAvailable)
                                {
                                    data.LiveWeather = (LiveWeather)SettingHelper.Get(Constants.WEATHER_LIVE_RESULT);
                                    data.Forecasts   = (Forecasts)SettingHelper.Get(Constants.WEATHER_FORECAST_RESULT);
                                }

                                //달력 적용 또는 직접 렌더링
                                DelegateUpdateProcess(task, data, hasCalendar);
                            };

                            if (city != null)
                            {
                                weather.LiveWeather(city, unit);
                            }
                            else
                            {
                                //달력 적용 또는 직접 렌더링
                                DelegateUpdateProcess(task, data, hasCalendar);
                            }
                        }
                        else
                        {
                            //달력 적용 또는 직접 렌더링
                            DelegateUpdateProcess(task, data, hasCalendar);
                        }
                    }
                    catch (Exception e)
                    {
                        System.Diagnostics.Debug.WriteLine(e.Message);
                    }
                });
            }
            else
            {
                if (!LockScreenManager.IsProvidedByCurrentApplication)
                {
                    System.Diagnostics.Debug.WriteLine("잠금화면 제공앱이 아니므로 변경할수 없음.");
                    NotifyComplete();
                    return;
                }

                if (!IsolatedStorageSettings.ApplicationSettings.Contains(Constants.LOCKSCREEN_USE_ROTATOR) ||
                    !(bool)IsolatedStorageSettings.ApplicationSettings[Constants.LOCKSCREEN_USE_ROTATOR])
                {
                    System.Diagnostics.Debug.WriteLine("로테이터 사용안함.");
                    NotifyComplete();
                    return;
                }

                Deployment.Current.Dispatcher.BeginInvoke(() =>
                {
                    System.Diagnostics.Debug.WriteLine("1 =>" + Microsoft.Phone.Info.DeviceStatus.ApplicationCurrentMemoryUsage);
                    LockscreenData data = new LockscreenData(true)
                    {
                        DayList = VsCalendar.GetCalendarOfMonth(DateTime.Now, DateTime.Now, true, true),
                    };

                    bool hasWeather  = false;
                    bool hasCalendar = false;

                    LockscreenItemInfo[] items = data.Items;

                    for (int i = 0; i < items.Length; i++)
                    {
                        switch (items[i].LockscreenItem)
                        {
                        case LiveItems.Weather:
                        case LiveItems.NoForecast:
                            hasWeather = true;
                            break;

                        case LiveItems.Calendar:
                            hasCalendar = true;
                            break;
                        }
                    }

                    if (hasWeather)
                    {
                        WeatherBug weather = new WeatherBug();
                        WeatherCity city   = SettingHelper.Get(Constants.WEATHER_MAIN_CITY) as WeatherCity;
                        DisplayUnit unit   = (DisplayUnit)SettingHelper.Get(Constants.WEATHER_UNIT_TYPE);

                        weather.LiveWeatherCompletedLoad += (s, r, f) =>
                        {
                            //조회된 데이터를 셋팅(없으면 저장된 날씨를 사용함)
                            SetWeatherResult(data, r, f);
                            //달력 적용 또는 직접 렌더링
                            DelegateUpdateProcess(task, data, hasCalendar);
                        };

                        weather.RequestFailed += (s, r) =>
                        {
                            if (!DeviceNetworkInformation.IsNetworkAvailable)
                            {
                                data.LiveWeather = (LiveWeather)SettingHelper.Get(Constants.WEATHER_LIVE_RESULT);
                                data.Forecasts   = (Forecasts)SettingHelper.Get(Constants.WEATHER_FORECAST_RESULT);
                            }
                            //달력 적용 또는 직접 렌더링
                            DelegateUpdateProcess(task, data, hasCalendar);
                        };

                        if (city != null)
                        {
                            weather.LiveWeather(city, unit);
                        }
                        else
                        {
                            //달력 적용 또는 직접 렌더링
                            DelegateUpdateProcess(task, data, hasCalendar);
                        }
                    }
                    else
                    {
                        //달력 적용 또는 직접 렌더링
                        DelegateUpdateProcess(task, data, hasCalendar);
                    }
                });
            }
        }
Exemplo n.º 19
0
        public async void LiveWeather(WeatherCity city, DisplayUnit unitType)
        {
            if (LiveWeatherBeforeLoad != null)
            {
                LiveWeatherBeforeLoad(this, null);
            }

            DefaultWeatherCity = city;
            DefaultUnitType    = unitType;

            StringBuilder urlBuilder = new StringBuilder(API_REST_XML_BASE_URL);

            urlBuilder.AppendFormat(API_COMBINING_MULTIPLE_DATA,
                                    new object[] { unitType == DisplayUnit.Fahrenheit ? "0" : "1", country, language, REST_XML_API_KEY });

            if (city.IsGpsLocation)
            {
                urlBuilder.AppendFormat("&{0}={1}&{2}={3}", new object[] { "la", city.Latitude, "lo", city.Longitude });
            }
            else if (city.isZipCode)
            {
                urlBuilder.AppendFormat("&{0}={1}", new object[] { "zip", city.Code });
            }
            else
            {
                urlBuilder.AppendFormat("&{0}={1}", new object[] { "city", city.Code });
            }

            using (HttpClient httpClient = new HttpClient())
            {
                LiveWeather liveWeather = null;
                Forecasts   forecasts   = null;

                var response = await httpClient.GetAsync(urlBuilder.ToString(), HttpCompletionOption.ResponseContentRead);

                {
                    if (response.IsSuccessStatusCode)
                    {
                        String jsonString = await response.Content.ReadAsStringAsync();

                        if (!string.IsNullOrEmpty(jsonString))
                        {
                            var parsedJson = JObject.Parse(jsonString);

                            JToken weather = parsedJson["weather"]["ObsData"];
                            if ((bool)(weather["hasData"] as JValue).Value)
                            {
                                if (liveWeather == null)
                                {
                                    liveWeather         = new LiveWeather();
                                    liveWeather.Station = new Station();
                                }

                                long ldt = (weather["dateTime"] as JValue).Value <long>();

                                DateTime dt = new DateTime(1970, 1, 1, 0, 0, 0, 0);
                                dt = dt.AddSeconds(ldt / 1000);

                                liveWeather.ObDate = new WeatherDateTime()
                                {
                                    Year  = dt.Year.ToString(),
                                    Month = new ValueInfo()
                                    {
                                        Number = dt.Month.ToString()
                                    },
                                    Day = new ValueInfo()
                                    {
                                        Number = dt.Day.ToString()
                                    },
                                    Hour24 = dt.Hour.ToString(),
                                    Minute = dt.Minute.ToString(),
                                    Second = dt.Second.ToString()
                                };
                                liveWeather.Station.City = (weather["stationName"] as JValue).Value <string>();
                                //liveWeather.Station.Id = (string)(item["stationId"] as JValue).Value;
                                //liveWeather.Station.Name = (string)(item["stationName"] as JValue).Value;
                                liveWeather.CurrentCondition     = (string)(weather["desc"] as JValue).Value;
                                liveWeather.CurrentConditionIcon = (string)(weather["icon"] as JValue).Value;
                                liveWeather.FeelsLike            = new ValueUnits()
                                {
                                    Value = (weather["feelsLike"] as JValue).Value <string>(),
                                    Units = (weather["temperatureUnits"] as JValue).Value <string>()
                                };
                                liveWeather.FeelsLikeLabel = (weather["feelsLikeLabel"] as JValue).Value <string>();
                                liveWeather.Humidity       = new WeatherUnit()
                                {
                                    Value = new ValueUnits()
                                    {
                                        Value = (weather["humidity"] as JValue).Value <string>(),
                                        Units = (weather["humidityUnits"] as JValue).Value <string>()
                                    }
                                };
                                liveWeather.Temp = new WeatherUnit()
                                {
                                    Value = new ValueUnits()
                                    {
                                        Value = (weather["temperature"] as JValue).Value <string>(),
                                        Units = (weather["temperatureUnits"] as JValue).Value <string>()
                                    },
                                    High = new ValueUnits()
                                    {
                                        Value = (weather["temperatureHigh"] as JValue).Value <string>(),
                                        Units = (weather["temperatureUnits"] as JValue).Value <string>()
                                    },
                                    Low = new ValueUnits()
                                    {
                                        Value = (weather["temperatureLow"] as JValue).Value <string>(),
                                        Units = (weather["temperatureUnits"] as JValue).Value <string>()
                                    }
                                };
                                liveWeather.WindSpeed = new ValueUnits()
                                {
                                    Value = (weather["windSpeed"] as JValue).Value <string>(),
                                    Units = (weather["windUnits"] as JValue).Value <string>()
                                };
                                liveWeather.WindDirection = (weather["windDirection"] as JValue).Value <string>();
                            }

                            if (liveWeather != null)
                            {
                                weather = parsedJson["weather"]["LocationData"]["location"];
                                if (weather.Any())
                                {
                                    liveWeather.Station.City  = (weather["city"] as JValue).Value <string>();
                                    liveWeather.Station.State = (weather["state"] as JValue).Value <string>();
                                    //liveWeather.Station.ZipCode = (weather["zipCode"] as JValue).Value<string>();
                                    //liveWeather.Station.CityCode = (weather["cityCode"] as JValue).Value<string>();
                                    liveWeather.Station.Country = (weather["country"] as JValue).Value <string>();
                                    //liveWeather.Station.Latitude = Value<string>()(weather["lat"] as JValue).Value<string>();
                                    //liveWeather.Station.Longitude = Value<string>()(weather["lon"] as JValue).Value<string>();

                                    if (string.IsNullOrEmpty(liveWeather.Station.City))
                                    {
                                        liveWeather.Station.City = city.CityName;
                                    }
                                }
                                else
                                {
                                    liveWeather.Station.City    = city.CityName;
                                    liveWeather.Station.State   = city.StateName;
                                    liveWeather.Station.Country = city.CountryName;
                                }

                                string   title = null;
                                string[] days  = DateTimeFormatInfo.CurrentInfo.DayNames;
                                weather = parsedJson["weather"]["ForecastData"]["forecastList"];

                                foreach (var item in weather)
                                {
                                    if (forecasts == null)
                                    {
                                        forecasts = new Forecasts();
                                    }

                                    long     ldt = (item["dateTime"] as JValue).Value <long>();
                                    DateTime dt  = new DateTime(1970, 1, 1, 0, 0, 0, 0).AddSeconds(ldt / 1000);
                                    title = (item["dayTitle"] as JValue).Value <string>();
                                    for (int j = 0; j < days.Length; j++)
                                    {
                                        if (days[j].ToLower() == title.ToLower())
                                        {
                                            if (forecasts.Items == null && days[j] == DateTime.Today.ToString("dddd"))
                                            {
                                                title = ChameleonLib.Resources.AppResources.WeatherToday;
                                            }
                                            else
                                            {
                                                title = DateTimeFormatInfo.CurrentInfo.AbbreviatedDayNames[j];
                                            }
                                            break;
                                        }
                                    }

                                    Forecast forecast = new Forecast()
                                    {
                                        DateTime  = dt,
                                        AltTitle  = title,
                                        ImageIcon = (item["dayIcon"] as JValue).Value <string>(),
                                        LowHigh   = new ValueUnits[2]
                                        {
                                            new ValueUnits()
                                            {
                                                Value = (item["low"] as JValue).Value <string>(),
                                                Units = liveWeather.Temp.Value.Units
                                            },
                                            new ValueUnits()
                                            {
                                                Value = (item["high"] as JValue).Value <string>(),
                                                Units = liveWeather.Temp.Value.Units
                                            }
                                        },
                                        Prediction         = (item["dayPred"] as JValue).Value <string>(),
                                        AltTitleForNight   = (item["nightTitle"] as JValue).Value <string>(),
                                        ImageIconForNight  = (item["nightIcon"] as JValue).Value <string>(),
                                        PredictionForNight = (item["nightPred"] as JValue).Value <string>(),
                                    };

                                    if (string.IsNullOrEmpty(forecast.ImageIcon))
                                    {
                                        forecast.ImageIcon = "cond999";
                                    }

                                    if (string.IsNullOrEmpty(forecast.ImageIconForNight))
                                    {
                                        forecast.ImageIconForNight = "cond999";
                                    }

                                    if (forecasts.Items == null)
                                    {
                                        forecasts.Items = new List <Forecast>();
                                    }

                                    forecasts.Items.Add(forecast);
                                }

                                if (forecasts != null && forecasts.Items.Count > 0)
                                {
                                    forecasts.Today = forecasts.Items[0];

                                    if (forecasts.Items.Count == 7)
                                    {
                                        forecasts.Items.RemoveAt(0);
                                    }
                                }
                            }
                        }

                        if (LiveWeatherCompletedLoad != null)
                        {
                            LiveWeatherCompletedLoad(this, liveWeather, forecasts);
                        }
                    }
                    else
                    {
                        if (RequestFailed != null)
                        {
                            RequestFailed(this, response.StatusCode);
                        }
                    }
                }
            }
        }
Exemplo n.º 20
0
        public HttpResponseMessage Post([FromBody] WeatherCity weathercityModel)
        {
            DatabaseQueryWeather.addWeatherForACity(weathercityModel);

            return(Request.CreateResponse(HttpStatusCode.OK));
        }
Exemplo n.º 21
0
        private void RetrieveWeather(WeatherCity city)
        {
            DisplayUnit unitType = (DisplayUnit)SettingHelper.Get(Constants.WEATHER_UNIT_TYPE);

            weatherBug.LiveWeather(city, unitType);
        }
        public void OpenCSV(string filePath)//从csv读取数据返回table
        {
            //filePath = @"F:\ManagersiGitHub\WeatherForecast\DataBase\china-city-list\view-source_https___cdn.heweather.com_china-city-list.csv";

            System.Text.Encoding encoding = GetType(filePath); //Encoding.ASCII;//
            //DataTable dt = new DataTable();
            System.IO.FileStream fs = new System.IO.FileStream(filePath, System.IO.FileMode.Open,
                                                               System.IO.FileAccess.Read);

            System.IO.StreamReader sr = new System.IO.StreamReader(fs, encoding);

            //记录每次读取的一行记录
            string strLine = "";

            //记录每行记录中的各字段内容
            string[] aryLine   = null;
            string[] tableHead = null;
            //标示列数
            int columnCount = 0;
            //标示是否是读取的第一行
            bool IsFirst = true;

            //逐行读取CSV中的数据
            while ((strLine = sr.ReadLine()) != null)
            {
                if (IsFirst == true)
                {
                    tableHead   = strLine.Split('\t');
                    IsFirst     = false;
                    columnCount = tableHead.Length;
                    //创建列
                    for (int i = 0; i < columnCount; i++)
                    {
                        Console.WriteLine(tableHead[i]);
                        //DataColumn dc = new DataColumn(tableHead[i]); //赋值给datatable
                        //dt.Columns.Add(dc);
                    }
                }
                else
                {
                    aryLine = strLine.Split('\t');
                    //DataRow dr = dt.NewRow();    //赋值给datarow
                    //for(int j = 0;j < columnCount;j++) {
                    //  dr[j] = aryLine[j];
                    //}
                    //dt.Rows.Add(dr);
                    if (AllCityDict.ContainsKey(aryLine[0].Trim()))
                    {
                        //数据库已存在 -- 赋值给类
                        var city = AllCityDict[aryLine[0].Trim()];
                        city.CityCode    = aryLine[0].Trim();
                        city.NameEN      = aryLine[1].Trim();
                        city.Name_CN     = aryLine[2].Trim();
                        city.CountryCode = aryLine[3].Trim();
                        city.CountryEN   = aryLine[4].Trim();
                        city.CountryCN   = aryLine[5].Trim();
                        city.ProvinceEN  = aryLine[6].Trim();
                        city.ProvinceCN  = aryLine[7].Trim();
                        city.ParentEN    = aryLine[8].Trim();
                        city.ParentCN    = aryLine[9].Trim();
                        if (KeyCityDict.ContainsKey(city.ParentCN))
                        {
                            city.ParentID = KeyCityDict[city.ParentCN];
                        }
                        else if (KeyCityDict.ContainsKey(city.ProvinceCN))
                        {
                            city.ParentID = KeyCityDict[city.ProvinceCN];
                        }
                        city.Latitude  = aryLine[10].Trim();
                        city.Longitude = aryLine[11].Trim();
                        city.State     = "1";
                        //添加到数据库
                        bl.Update(city);
                        if (!KeyCityDict.ContainsKey(city.Name_CN))
                        {
                            KeyCityDict.Add(city.Name_CN, city.ID);
                        }
                    }
                    else
                    {
                        //赋值给类
                        var city = new WeatherCity();
                        city.CityCode    = aryLine[0].Trim();
                        city.NameEN      = aryLine[1].Trim();
                        city.Name_CN     = aryLine[2].Trim();
                        city.CountryCode = aryLine[3].Trim();
                        city.CountryEN   = aryLine[4].Trim();
                        city.CountryCN   = aryLine[5].Trim();
                        city.ProvinceEN  = aryLine[6].Trim();
                        city.ProvinceCN  = aryLine[7].Trim();
                        city.ParentEN    = aryLine[8].Trim();
                        city.ParentCN    = aryLine[9].Trim();
                        if (KeyCityDict.ContainsKey(city.ParentCN))
                        {
                            city.ParentID = KeyCityDict[city.ParentCN];
                        }
                        else if (KeyCityDict.ContainsKey(city.ProvinceCN))
                        {
                            city.ParentID = KeyCityDict[city.ProvinceCN];
                        }
                        city.Latitude  = aryLine[10].Trim();
                        city.Longitude = aryLine[11].Trim();

                        city.State = "1";
                        //添加到数据库
                        bl.Insert(city);
                        if (!KeyCityDict.ContainsKey(city.Name_CN))
                        {
                            KeyCityDict.Add(city.Name_CN, city.ID);
                        }
                    }
                }
            }
            //if(aryLine != null && aryLine.Length > 0) {
            //  dt.DefaultView.Sort = tableHead[0] + " " + "asc";
            //}
            sr.Close();
            fs.Close();
            //return dt;
        }
Exemplo n.º 23
0
 /// <summary>
 /// 新增一个天气服务城市信息
 /// </summary>
 /// <param name="weatherCity">天气服务城市信息</param>
 public void AddWeatherCity(WeatherCity weatherCity)
 {
     db.WeatherCity.Add(weatherCity);
     db.SaveChanges();
 }
Exemplo n.º 24
0
        private void RenderLiveWeather(LiveWeather result)
        {
            WeatherCity city = SettingHelper.Get(Constants.WEATHER_MAIN_CITY) as WeatherCity;

            TxtWeatherNoCity.Visibility = System.Windows.Visibility.Collapsed;
            GridLiveWeather.Visibility  = System.Windows.Visibility.Visible;

            SystemTray.SetIsVisible(this, false);
            if (SystemTray.ProgressIndicator != null)
            {
                SystemTray.ProgressIndicator.IsVisible = false;
            }

            BitmapImage imageSource = new BitmapImage();

            imageSource.UriSource = new WeatherImageIconConverter().Convert(result.CurrentConditionIcon, null, "205x172", null) as Uri;
            //업데이트 시간
            System.DateTime dateTime = GetDateTime(result.ObDate);
            //지역
            string[] langs = CultureInfo.CurrentCulture.Name.Split('-');
            if (langs[0] == "ko" || langs[0] == "ja" || langs[1] == "zh")
            {
                PIWeather.Header = (string.IsNullOrEmpty(result.Station.State) ? string.Empty : result.Station.State + " ") + result.Station.City;
            }
            else
            {
                PIWeather.Header = result.Station.City + (string.IsNullOrEmpty(result.Station.State) ? string.Empty : " ," + result.Station.State);
            }

            //업데이트 시간
            TxtLiveWeatherDtUpdated.Text = dateTime.ToString(CultureInfo.CurrentUICulture.DateTimeFormat.LongDatePattern);
            TxtLiveWeatherTmUpdated.Text = string.Format(AppResources.WeatherUpdatedTime, dateTime.ToString(CultureInfo.CurrentUICulture.DateTimeFormat.ShortTimePattern));
            //날씨 이미지
            ImgLiveWeatherIcon.Source = imageSource;
            //날씨 텍스트
            TxtLiveWeatherCondition.Text = result.CurrentCondition;
            //기온
            string[] temp = result.Temp.Value.Value.Split('.');
            TxtLiveWeatherTemp.Text = temp[0];
            //TxtLiveWeatherTemp.Text = "-50";

            double orgFontSize = TxtLiveWeatherTemp.FontSize;

            //온도 표시 문자열의 길이에 따라 폰트 사이즈 변경
            while (TxtLiveWeatherTemp.Width < TxtLiveWeatherTemp.ActualWidth)
            {
                TxtLiveWeatherTemp.FontSize--;
            }

            if (temp.Length > 1)
            {
                TxtLiveWeatherTempFloat.Text = "." + temp[1];
            }
            TxtLiveWeatherTempUnits.Text = (WeatherUnitsConverter.ConvertOnlyUnit(result.Temp.Value) as ValueUnits).Units;
            //체감온도
            string feelsLikeLabel = string.IsNullOrEmpty(result.FeelsLikeLabel) ? AppResources.WeatherLiveFeelsLike : result.FeelsLikeLabel + " {0}";

            TxtLiveWeatherFeelTemp.Text = string.Format(feelsLikeLabel, WeatherUnitsConverter.Convert(result.FeelsLike));
            //습도
            TxtLiveWeatherHumidity.Text = string.Format(AppResources.WeatherLiveHumidity, result.Humidity.Value.Value, result.Humidity.Value.Units);
            //바람
            TxtLiveWeatherWind.Text = string.Format(AppResources.WeatherLiveWind, result.WindDirection, result.WindSpeed.Value, result.WindSpeed.Units);
            //최고/최저 기온
            TxtLiveWeatherTempRange.Text = WeatherRangeConverter.RangeText(
                new ValueUnits[2]
            {
                result.Temp.Low,
                result.Temp.High
            }, true);

            double dTemp = 0;
            double dFeel = 0;

            try
            {
                dTemp = Double.Parse(result.Temp.Value.Value);
                dFeel = Double.Parse(result.FeelsLike.Value);
            }
            catch (Exception e)
            {
                System.Diagnostics.Debug.WriteLine("온도 파싱 에러" + e.Message);
            }

            if (string.IsNullOrEmpty(result.FeelsLike.Value) ||
                string.Format("{0:F1}", dTemp) == string.Format("{0:F1}", dFeel))
            {
                BrdLiveWeatherFeelTemp.Visibility = System.Windows.Visibility.Collapsed;
            }

            //현재 기온의 텍스트 크기가 변경이 되었다면... 단위와 소수점 크기도 변경
            double    rt     = TxtLiveWeatherTemp.FontSize / orgFontSize;
            Thickness margin = GrdTempSub.Margin;

            margin.Top        *= rt;
            GrdTempSub.Margin  = margin;
            GrdTempSub.Height *= rt;
            TxtLiveWeatherTempUnits.FontSize *= rt;
            TxtLiveWeatherTempFloat.FontSize *= rt;
        }
Exemplo n.º 25
0
        // ViewModel 항목에 대한 데이터를 로드합니다.
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            string from;

            NavigationContext.QueryString.TryGetValue("from", out from);
            if (from == "flashlight")
            {
                NavigationService.RemoveBackEntry();
            }

            //네비게이션 모드
            bool isChangedSettings = e.NavigationMode == NavigationMode.Back && PhoneApplicationService.Current.State.ContainsKey(Constants.CHANGED_SETTINGS);

            //스케쥴 데이터 로드
            scheduleSettings = MutexedIsoStorageFile.Read <ScheduleSettings>("ScheduleSettings", Constants.MUTEX_DATA);

            if (e.NavigationMode == NavigationMode.New)
            {
                //달력 환경 설정 로딩
                LoadConfigCalendar();
                //라이브타일 로드
                LoadLivetile();
                //락스크린 리스트 로드
                LoadLockscreenList();
                //날씨 로드(비동기 처리로..)
                LoadLiveWeather();
                //달력 로드
                LoadCalendar(DateTime.Now);
            }
            else
            {
                if (PanoramaMainView != null && PanoramaMainView.SelectedItem != null)
                {
                    string panoramaName = (PanoramaMainView.SelectedItem as PanoramaItem).Name;

                    if (panoramaName == PILockscreen.Name)
                    {
                        //락스크린 리스트 로드
                        LoadLockscreenList();
                    }
                    else if (panoramaName == PIWeather.Name)
                    {
                        //if (!PhoneApplicationService.Current.State.ContainsKey(Constants.WEATHER_MAIN_CITY))
                        //{
                        //    PhoneApplicationService.Current.State[Constants.WEATHER_UNIT_TYPE] = true;
                        //}
                        //날씨 조회 지역을 찾아서 선택하고 들어온 경우는 날씨를 업데이트 해주고 락스크린을 갱신
                        if (PhoneApplicationService.Current.State.ContainsKey(Constants.WEATHER_MAIN_CITY))
                        {
                            WeatherCity city = PhoneApplicationService.Current.State[Constants.WEATHER_MAIN_CITY] as WeatherCity;
                            //위의 설정값은 RetriveWeather에서도 사용되며, 콜백 메소드에서 사용되므로 해당 콜백 메소드에서 지워야 함.
                            RetrieveWeather(city);
                        }
                    }
                    else if (panoramaName == PICalendar.Name)
                    {
                        //달력 환경 설정 로딩
                        LoadConfigCalendar();
                        //등록후 재검색..
                        LoadCalendar(CurrentCalendar);
                        //락스크린 갱신되도록 설정
                        PhoneApplicationService.Current.State[Constants.LIVETILE_CALENDAR_BACKGROUND_COLOR] = true;
                    }
                }
            }

            string lockscreenKey = "WallpaperSettings";
            string piName        = string.Empty;

            if (NavigationContext.QueryString.TryGetValue(lockscreenKey, out piName))
            {
                //잠금화면 설정에서 진입했는가를 체크
                piName = PILockscreen.Name;
            }
            else
            {
                //라이브 타일을 눌러서 진입했는가를 체크
                NavigationContext.QueryString.TryGetValue("pi", out piName);
                NavigationContext.QueryString.Remove("pi");
            }

            if (!string.IsNullOrEmpty(piName))
            {
                //해당 메뉴로 이동 시킴
                foreach (PanoramaItem pi in PanoramaMainView.Items)
                {
                    if (pi.Name == piName)
                    {
                        PanoramaMainView.DefaultItem = pi;

                        if (piName == PILivetile.Name)
                        {
                            ApplicationBar           = IAppBarLivetile;
                            ApplicationBar.IsVisible = true;
                        }
                        else if (piName == PILockscreen.Name)
                        {
                            ApplicationBar           = IAppBarLockscreen;
                            ApplicationBar.IsVisible = true;
                        }
                        else if (piName == PIWeather.Name)
                        {
                            ApplicationBar           = iAppBarWeather;
                            ApplicationBar.IsVisible = true;
                            PhoneApplicationService.Current.State[Constants.WEATHER_UNIT_TYPE] = true;
                        }
                        else if (piName == PICalendar.Name)
                        {
                            ApplicationBar           = IAppBarCalendar;
                            ApplicationBar.IsVisible = true;
                        }

                        break;
                    }
                }
            }

            bool isLoadedBatteryTile  = false;
            bool isLoadedWeatherTile  = false;
            bool isLoadedCalendarTile = false;

            if (ExistStatus(Constants.LIVETILE_RANDOM_BACKGROUND_COLOR))
            {
                //라이브타일 전체 다시 로드
                CreateCalendarLivetileImage();
                CreateWeatherLivetileImage();
                CreateBatteryLivetileImage();
                //타일 로딩 여부
                isLoadedCalendarTile = true;
                isLoadedBatteryTile  = true;
            }
            else
            {
                if (ExistStatus(Constants.LIVETILE_CALENDAR_BACKGROUND_COLOR))
                {
                    //달력 라이브타일 다시 로드
                    CreateCalendarLivetileImage();
                    isLoadedCalendarTile = true;
                }
                if (ExistStatus(Constants.LIVETILE_WEATHER_BACKGROUND_COLOR))
                {
                    //날씨 라이브타일 다시 로드
                    CreateWeatherLivetileImage();
                    isLoadedWeatherTile = true;
                }
                if (ExistStatus(Constants.LIVETILE_BATTERY_BACKGROUND_COLOR))
                {
                    //배터리 라이브타일 다시 로드
                    CreateBatteryLivetileImage();
                    isLoadedBatteryTile = true;
                }
            }

            if (ExistStatus(Constants.LIVETILE_FONT_WEIGHT))
            {
                if (!isLoadedWeatherTile)
                {
                    //날씨 라이브타일 다시 로드
                    CreateWeatherLivetileImage();
                }
                if (!isLoadedCalendarTile)
                {
                    //달력 라이브타일 다시 로드
                    CreateCalendarLivetileImage();
                }
            }

            if (ExistStatus(Constants.LIVETILE_WEATHER_FONT_SIZE) && !isLoadedWeatherTile)
            {
                //날씨 라이브타일 다시 로드
                CreateWeatherLivetileImage();
            }

            if (ExistStatus(Constants.LIVETILE_BATTERY_FULL_INDICATION) && !isLoadedBatteryTile)
            {
                //배터리 라이브타일 다시 로드
                CreateBatteryLivetileImage();
            }

            if (ExistStatus(Constants.WEATHER_UNIT_TYPE) || ExistStatus(Constants.WEATHER_ICON_TYPE))
            {
                //날시 아이콘 다시 로딩
                if (ExistStatus(Constants.WEATHER_ICON_TYPE))
                {
                    WeatherIconMap.Instance.Load((WeatherIconType)SettingHelper.Get(Constants.WEATHER_ICON_TYPE));
                }
                //날씨 갱신 (무조건)
                RefreshLiveWeather();
            }

            if (ExistStatus(Constants.CHAMELEON_USE_PROTECTIVE_COLOR))
            {
                if (!(bool)SettingHelper.Get(Constants.CHAMELEON_USE_PROTECTIVE_COLOR))
                {
                    //바탕화면 색상 갱신
                    Color color = (SettingHelper.Get(Constants.CHAMELEON_SKIN_BACKGROUND_COLOR) as ColorItem).Color;
                    ChangeBackgroundColor(color);
                    SetAppbarColor(ApplicationBar, color);
                }
            }
            if (ExistStatus(Constants.CALENDAR_FIRST_DAY_OF_WEEK) || ExistStatus(Constants.CALENDAR_SHOW_APPOINTMENT))
            {
                LoadConfigCalendar();
                LoadCalendar(CurrentCalendar);
                //달력 타일 로드
                if (!isLoadedCalendarTile)
                {
                    CreateCalendarLivetileImage();
                }
            }

            PhoneApplicationService.Current.State.Remove(Constants.CHANGED_SETTINGS);
            PhoneApplicationService.Current.State.Remove(Constants.CHAMELEON_USE_PROTECTIVE_COLOR);
            PhoneApplicationService.Current.State.Remove(Constants.LIVETILE_CALENDAR_BACKGROUND_COLOR);
            PhoneApplicationService.Current.State.Remove(Constants.LIVETILE_WEATHER_BACKGROUND_COLOR);
            PhoneApplicationService.Current.State.Remove(Constants.LIVETILE_BATTERY_BACKGROUND_COLOR);
            PhoneApplicationService.Current.State.Remove(Constants.LIVETILE_WEATHER_FONT_SIZE);
            PhoneApplicationService.Current.State.Remove(Constants.LIVETILE_BATTERY_FULL_INDICATION);
            PhoneApplicationService.Current.State.Remove(Constants.WEATHER_UNIT_TYPE);
            PhoneApplicationService.Current.State.Remove(Constants.WEATHER_ICON_TYPE);
            PhoneApplicationService.Current.State.Remove(Constants.CALENDAR_FIRST_DAY_OF_WEEK);
            PhoneApplicationService.Current.State.Remove(Constants.CALENDAR_SHOW_APPOINTMENT);
        }
        /// <summary>
        /// 执行定时任务,保存日志到库
        /// </summary>
        /// <param name="richTextLog">winform日志显示</param>
        public override void ExecMethod(RichTextConsole console)
        {
            console.Debug($"{TimerName}定时任务,开始执行...", false);
            List <AreaCodeName> areaCodeNameList = areaProvider.SearchAreaCode(AreaLevel.Province);
            List <WeatherCity>  weatherCities    = new List <WeatherCity>();

            areaCodeNameList.ForEach(areaCodeName =>
            {
                WeatherCity weatherCity = new WeatherCity()
                {
                    Id             = areaCodeName.Code,
                    Name           = areaCodeName.Name,
                    ParentId       = "null",
                    WCityLevel     = WCityLevel.PROVINCE,
                    WCityLevelName = WCityLevel.GetName(WCityLevel.PROVINCE),
                    CreateTime     = DateTime.Now
                };
                weatherCities.Add(weatherCity);
            });
            weatherCityManage.SaveWeatherCity(WinFormConfig.CoreDBConnectString, weatherCities);
            console.Info($"{TimerName}定时任务,成功保存省份集合信息。", isWriteLog: false);
            weatherCities.Clear();//清空省份数据,开始保存城市数据
            areaCodeNameList.ForEach(areaCodeName =>
            {
                List <AreaCodeName> cityAreaCodeNameList = areaProvider.SearchAreaCode(AreaLevel.City, areaCodeName.Code);
                for (int i = 0; i < cityAreaCodeNameList.Count; i++)
                {
                    var cityAreaCodeName    = cityAreaCodeNameList[i];
                    WeatherCity weatherCity = new WeatherCity()
                    {
                        Id             = cityAreaCodeName.Code,
                        Name           = cityAreaCodeName.Name,
                        ParentId       = areaCodeName.Code,
                        WCityLevel     = WCityLevel.CITY,
                        WCityLevelName = WCityLevel.GetName(WCityLevel.CITY),
                        CreateTime     = DateTime.Now
                    };
                    weatherCities.Add(weatherCity);
                }
                weatherCityManage.SaveWeatherCity(WinFormConfig.CoreDBConnectString, weatherCities);
                console.Info($"{TimerName}定时任务,成功保存{areaCodeName.Name}省份的城市集合信息。", isWriteLog: false);
                weatherCities.Clear();//清空城市数据,开始保存城市的区域数据
                cityAreaCodeNameList.ForEach(cityCodeName =>
                {
                    List <AreaCodeName> regionCodeNameList = areaProvider.SearchAreaCode(AreaLevel.Region, cityCodeName.Code);
                    foreach (var regionCodeName in regionCodeNameList)
                    {
                        WeatherCity weatherCity = new WeatherCity()
                        {
                            Id             = regionCodeName.Code,
                            Name           = regionCodeName.Name,
                            ParentId       = cityCodeName.Code,
                            WCityLevel     = WCityLevel.REGION,
                            WCityLevelName = WCityLevel.GetName(WCityLevel.REGION),
                            CreateTime     = DateTime.Now
                        };
                        weatherCities.Add(weatherCity);
                    }
                    weatherCityManage.SaveWeatherCity(WinFormConfig.CoreDBConnectString, weatherCities);
                    console.Info($"{TimerName}定时任务,成功保存{cityCodeName.Name}城市的区域集合信息。", isWriteLog: false);
                    weatherCities.Clear(); //清空区域数据,开始保存下一个城市的区域数据
                });
                weatherCities.Clear();     //清空城市数据,开始保存下一个省份的城市数据
            });
            console.Info($"{TimerName}定时任务,已执行完成。", isWriteLog: false);
        }