Пример #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();
        }
Пример #2
0
        private void SetWeatherResult(LiveData data, LiveWeather liveWeather, Forecasts forecasts)
        {
            if (liveWeather != null)
            {
                data.LiveWeather = liveWeather;
            }
            else
            {
                data.LiveWeather = (LiveWeather)SettingHelper.Get(Constants.WEATHER_LIVE_RESULT);
            }

            if (forecasts != null)
            {
                data.Forecasts = forecasts;
            }
            else
            {
                data.Forecasts = (Forecasts)SettingHelper.Get(Constants.WEATHER_FORECAST_RESULT);
            }
        }
Пример #3
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);
            }
        }
Пример #4
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);
                        }
                    }
                }
            }
        }
Пример #5
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;
        }