private static void OnUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs args) { var e = args.Exception; string directoryPath = Path.Combine(Environment.CurrentDirectory, "Logs"); string filePath = Path.Combine(directoryPath, $"CrashLog {DateTime.Now.ToString("dd-MM-yyyy HH-mm-ss")}.txt"); if (!Directory.Exists(directoryPath)) { Directory.CreateDirectory(directoryPath); } using (var writer = new StreamWriter(filePath)) { writer.WriteLine($"Exception message: {e.Message}"); writer.WriteLine($"Inner exception: {e.InnerException}"); writer.WriteLine($"Stack trace: {e.StackTrace}"); writer.WriteLine(); writer.WriteLine("User.json file:"); // If exception was thrown before loading User.json (Ingots.Count can't be null after loading) if (User.Instance.Ingots?.Count == 0) { var encryptedUserJson = File.ReadAllBytes(UserDataHelper.UserDataPath); var userJson = EncryptionHelper.DecryptJsonUsingAes(encryptedUserJson); writer.Write(userJson); } else { writer.Write(UserDataHelper.Save()); } } AlertBox.Show("There was an error with the game. A log file has been generated in the Logs folder. To help us fix the issue, you can contribute the log file at X. We apologize for the inconvenience.\nYour data has been saved.", MessageBoxButton.OK); }
protected void Application_Startup(object sender, StartupEventArgs e) { // Set crash logs output to Logs - any unhandled exceptions will be saved to a text file locally. // Release only, because we want to see Exceptions in IDE during development. #if RELEASE Application.Current.DispatcherUnhandledException += OnUnhandledException; #endif // Set default culture for all threads for this application (affects date and string formats, e.g. periods instead of commas) CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; CultureInfo.DefaultThreadCurrentCulture = CultureInfo.InvariantCulture; CultureInfo.DefaultThreadCurrentUICulture = CultureInfo.InvariantCulture; // Load JSONs. GameAssetsHelper.Load(); var gameWindow = new GameWindow(); Current.MainWindow = gameWindow; gameWindow.Show(); UserDataHelper.Load(); (GameAssets.Pages["MainMenu"] as MainMenuPage).UpdateCreateHeroButton(); (GameAssets.Pages["MainMenu"] as MainMenuPage).UpdateSelectOrDeleteHeroButtons(); // Save current time as the application's start time (for achievement tracking). User.SessionStartDate = DateTime.Now; GeneralToolTipHelper.SetGlobalToolTipDelay(); }
public UpdateUserSteps(TestHost testHost, UserDataHelper userDataHelper) { this.testHost = testHost; this.userDataHelper = userDataHelper; this.invalidId = "Invalid_ID"; this.nonExistentId = Guid.NewGuid(); this.updatedUserEmail = "*****@*****.**"; this.championStartDate = DateTime.Now; this.name = "UserName"; this.email = "*****@*****.**"; this.specialistArea = "Security"; /* * Conversion from/to Unix timestamp is necessary here to mimic the * same operation the server does when inserting into the DB, resulting * in a DateTimeOffset to 3 decimal places after the seconds rather than 6 */ this.championStartDate = DateTimeOffset.FromUnixTimeMilliseconds ( DateTimeOffset.Now .Subtract(TimeSpan.FromDays(7)) .ToUniversalTime() .ToUnixTimeMilliseconds() ); }
public GetAchievementSteps( TestHost testHost, AchievementDataHelper achievementDataHelper, MaturityCategoryDataHelper maturityCategoryDataHelper, MaturityLevelDataHelper maturityLevelDataHelper, UserDataHelper userDataHelper ) { this.testHost = testHost; this.achievementDataHelper = achievementDataHelper; this.maturityCategoryDataHelper = maturityCategoryDataHelper; this.maturityLevelDataHelper = maturityLevelDataHelper; this.userDataHelper = userDataHelper; /* * Conversion from/to Unix timestamp is necessary here to mimic the * same operation the server does when inserting into the DB, resulting * in a DateTimeOffset to 3 decimal places after the seconds rather than 6, * so 2020-08-09 16:05:15.7954576+00:00 becomes 2020-08-09 16:05:15.795+00:00 */ this.achievementDate = DateTimeOffset.FromUnixTimeMilliseconds ( DateTimeOffset.Now .Subtract(TimeSpan.FromDays(7)) .ToUniversalTime() .ToUnixTimeMilliseconds() ); this.comment = "I did X, Y and Z to achieve this maturity level."; }
public static async void SetTheme() { if (await ApplicationData.Current.RoamingFolder.TryGetItemAsync("Settings.json") != null) { var settings = await UserDataHelper.GetSettings("Settings.json"); if (Application.Current.Resources.MergedDictionaries.Count > 1) { Application.Current.Resources.MergedDictionaries.RemoveAt(1); } if (settings.Theme != null && settings.Theme != "Colored") { Application.Current.Resources.MergedDictionaries.Add(new ResourceDictionary { Source = new Uri("ms-appx:///Styles/" + settings.Theme + ".xaml") }); } var titleBar = ApplicationView.GetForCurrentView().TitleBar; if (settings.Theme == "Light") { titleBar.ButtonForegroundColor = Windows.UI.Colors.Black; titleBar.ButtonBackgroundColor = Windows.UI.Colors.Transparent; } else { titleBar.ButtonForegroundColor = Windows.UI.Colors.White; titleBar.ButtonBackgroundColor = Windows.UI.Colors.Transparent; } } }
private async void SaveData_Click(object sender, RoutedEventArgs e) { SavedText.Visibility = Visibility.Collapsed; if (ChoosenPlace != null && _Themes != null && _SaveData != null && _UnitsFormat != null && _TimeFormat != null && Languages.SelectedIndex != -1) { UserSettings _Settings = new UserSettings(); var checkLocation = AlwaysDetect.IsChecked == true ? 1 : 0; _Settings = new UserSettings() { Theme = _Themes, Language = (Languages.SelectedItem as Data.ComboBoxItem).Key, CheckLocation = checkLocation, DataFormat = new DataFormat() { UnitsFormat = _UnitsFormat, TimeFormat = _TimeFormat }, SaveData = _SaveData, DefaultLocation = ChoosenPlace }; var WriteToFile = (await UserDataHelper.WriteFile("Settings.json", _Settings)); WeatherPage.IsSettingsChanged = true; SavedText.Visibility = Visibility.Visible; DataError.Visibility = Visibility.Collapsed; } else { SavedText.Visibility = Visibility.Collapsed; DataError.Visibility = Visibility.Visible; } }
private async void CloseSettings_Click(object sender, RoutedEventArgs e) { SettingsPageGrid.Visibility = Visibility.Collapsed; SettingsPage.Content = ""; if (IsFavoritesChanged == true) { IsFavoritesChanged = false; var favorites = (await UserDataHelper.GetFavorites("Favorites.json")); var _CurrentPlace = favorites.Where(x => x.PlaceId == _CityData.PlaceInfo.PlaceId).ToList(); if (_CurrentPlace.Count == 0) { SaveToFavorites.Visibility = Visibility.Visible; RemoveFromFavorites.Visibility = Visibility.Collapsed; } } if (IsSettingsChanged == true) { IsSettingsChanged = false; PlaceInfo _argument = null; var rootFrame = Window.Current.Content as Frame; if (rootFrame == null) { rootFrame = new Frame(); } if (_CityData.PlaceInfo.PlaceId != _Settings.DefaultLocation.PlaceId) { _argument = _CityData.PlaceInfo; } rootFrame.Navigate(typeof(ShellPage), _argument); } }
public DeleteUserSteps(TestHost testHost, UserDataHelper userDataHelper) { this.testHost = testHost; this.userDataHelper = userDataHelper; this.invalidId = "invalid_id"; this.nonExistentId = Guid.NewGuid(); }
private async void DownloadImage_Click(object sender, RoutedEventArgs e) { ShowToolTip("DownloadingImage", 2000); var url = (sender as Button).Tag.ToString(); await UserDataHelper.DownloadAsset(url); ShowToolTip("Downloaded", 2000); }
/// <summary> /// Actualiza los UserFlavors del usuario por los nuevos seleccionados. /// </summary> /// <param name="Flavor1Weight">Peso del primer Fashion Flavor seleccionado.</param> /// <param name="Flavor2Weight">Peso del segudno Fashion Falvor determinado.</param> /// <param name="values">Coleccion de objetos del formulario</param> /// <returns>Actualiza los flavors seleccionados y redirecciona a la Home.</returns> public ActionResult UpdateUserFlavors(string Flavor1Weight, string Flavor2Weight, string submit) { bool previous = (submit != null && submit.ToLower() == "previous"); if (previous) { return(RedirectToAction("Index", "FlavorSelect")); } IList <FashionFlavor> flavors = ClosetState.Flavors; IList <UserFlavor> userFlavors = new List <UserFlavor>(); if (flavors != null) { if (!string.IsNullOrEmpty(Flavor1Weight)) { userFlavors.Add(new UserFlavor(flavors[0], Convert.ToDecimal(Flavor1Weight))); } if (!string.IsNullOrEmpty(Flavor2Weight)) { userFlavors.Add(new UserFlavor(flavors[1], Convert.ToDecimal(Flavor2Weight))); } } RegisteredUser user = registeredUserRepository.Get(this.UserId); List <int> flavorsIds = new List <int>(); List <int> myGarmentsIds = new List <int>(); foreach (FashionFlavor ff in flavors) { flavorsIds.Add(ff.Id); } IList <ClosetGarment> closetGarments = closetRepository.GetGarmentsForUser(user); foreach (ClosetGarment closetGarment in closetGarments) { myGarmentsIds.Add(closetGarment.Garment.Id); } if (!new OutfitEngineServiceClient().HasValidCombinations(myGarmentsIds, flavorsIds)) { return(RedirectToAction("FlavorChangeResult", "FlavorSelect", new { flavorsChanged = false })); } user.SetFlavors(userFlavors); //Update UserFlavors registeredUserRepository.DbContext.BeginTransaction(); registeredUserRepository.SaveOrUpdate(user); registeredUserRepository.DbContext.CommitTransaction(); new OutfitEngineServiceClient().CreateOutfits(user.Closet.Id); UserDataHelper.LoadFromDatabase(); return(RedirectToAction("FlavorChangeResult", "FlavorSelect", new { flavorsChanged = true })); }
protected override void Seed(IPosDbContext context) { if (IposConfig.UseMembership) { UserDataHelper.ConfigureIposMemberShip(context); } UserDataHelper.CreateRoles(context); var adminUser = UserDataHelper.CreateAdminUser(context); //UserDataHelper.CreateTestData(context, adminUser); }
protected async override void OnNavigatedTo(NavigationEventArgs e) { var settings = await UserDataHelper.GetSettings("Settings.json"); DefaultLocation.Text = settings.DefaultLocation.DisplayName; ChoosenPlace = settings.DefaultLocation; var _Languages = new Data.Settings().GetSettings()[4].values; Languages.ItemsSource = _Languages; Languages.SelectedIndex = settings.Language != null?_Languages.IndexOf(_Languages.Where(x => x.Key == settings.Language).ToList()[0]) : 0; if (settings.CheckLocation == 1) { AlwaysDetect.IsChecked = true; } if (settings.Theme == "Colored") { Themes0.IsChecked = true; } else if (settings.Theme == "Light") { Themes1.IsChecked = true; } else { Themes2.IsChecked = true; } if (settings.SaveData == "0") { SaveData0.IsChecked = true; } else { SaveData1.IsChecked = true; } if (settings.DataFormat.UnitsFormat == "metric") { Units0.IsChecked = true; } else { Units1.IsChecked = true; } if (settings.DataFormat.TimeFormat == "24h") { TimeFormat0.IsChecked = true; } else { TimeFormat1.IsChecked = true; } }
private void Login_Click(object sender, EventArgs e) { if (treeWebsite.SelectedNode != null) { string sitename = this.treeWebsite.SelectedNode.Name; LoginEntity entity = new LoginEntity(); entity = UserDataHelper.GetEntityBySiteName(sitename); CommonLogin login = new CommonLogin(); login.Login(entity); } }
private void treeWebsite_AfterSelect(object sender, TreeViewEventArgs e) { string sitename = this.treeWebsite.SelectedNode.Name; LoginEntity entity = new LoginEntity(); entity = UserDataHelper.GetEntityBySiteName(sitename); if (entity != null) { UserName.Text = entity.USERNAME; Password.Text = entity.PASSWORD; } }
private void ModifyItem_Click(object sender, EventArgs e) { if (treeWebsite.SelectedNode.Level != 0) { ScaleMain parent = (ScaleMain)this.Parent.Parent; LoginEntity entity = UserDataHelper.GetEntityBySiteName(treeWebsite.SelectedNode.Name); if (entity != null) { parent.Open("NewSite", entity); this.Close(); } } }
public CreateAchievementSteps( TestHost testHost, AchievementDataHelper achievementDataHelper, UserDataHelper userDataHelper, MaturityCategoryDataHelper maturityCategoryDataHelper, MaturityLevelDataHelper maturityLevelDataHelper ) { this.testHost = testHost; this.achievementDataHelper = achievementDataHelper; this.userDataHelper = userDataHelper; this.maturityCategoryDataHelper = maturityCategoryDataHelper; this.maturityLevelDataHelper = maturityLevelDataHelper; }
public void RemoveItem(string sitename) { bool issuccess = UserDataHelper.RemoveItem(sitename); if (issuccess) { MessageBox.Show("删除成功"); treeWebsite.Nodes[0].Nodes[sitename].Remove(); } else { MessageBox.Show("删除失败"); } }
public GetUserSteps(TestHost testHost, UserDataHelper userDataHelper) { this.testHost = testHost; this.userDataHelper = userDataHelper; this.name = "UserName"; this.email = "*****@*****.**"; this.specialistArea = "Security"; /* * Conversion from/to Unix timestamp is necessary here to mimic the * same operation the server does when inserting into the DB, resulting * in a DateTimeOffset to 3 decimal places after the seconds rather than 6, * so 2020-08-09 16:05:15.7954576+00:00 becomes 2020-08-09 16:05:15.795+00:00 */ this.championStartDate = DateTimeOffset.FromUnixTimeMilliseconds ( DateTimeOffset.Now .Subtract(TimeSpan.FromDays(7)) .ToUniversalTime() .ToUnixTimeMilliseconds() ); }
private async void StartApp_Click(object sender, RoutedEventArgs e) { ErrorText.Visibility = Visibility.Collapsed; if (ChoosenPlace != null && SaveData.SelectedIndex != -1 && Theme.SelectedIndex != -1 && Units.SelectedIndex != -1 && TimeFormat.SelectedIndex != -1 && Languages.SelectedIndex != -1) { var checkLocation = AlwaysDetect.IsChecked == true ? 1 : 0; var theme = (Theme.SelectedItem as Data.ComboBoxItem).Key; var units = (Units.SelectedItem as Data.ComboBoxItem).Key; var time = (TimeFormat.SelectedItem as Data.ComboBoxItem).Key; var savedata = (SaveData.SelectedItem as Data.ComboBoxItem).Key; UserSettings _Settings = new UserSettings(); _Settings = new UserSettings() { Theme = theme, Language = (Languages.SelectedItem as Data.ComboBoxItem).Key, CheckLocation = checkLocation, DataFormat = new DataFormat() { UnitsFormat = units, TimeFormat = time }, SaveData = savedata, DefaultLocation = ChoosenPlace }; var WriteToFile = (await UserDataHelper.WriteFile("Settings.json", _Settings)); if (WriteToFile == true) { Frame.Navigate(typeof(ShellPage)); } } else { ErrorText.Visibility = Visibility.Visible; } }
private void Save_Click(object sender, EventArgs e) { LoginEntity entity = new LoginEntity(); PropertyInfo[] pinfo = entity.GetType().GetProperties(); foreach (PropertyInfo p in pinfo) { Control[] controllist = this.Controls.Find(p.Name, true); if (controllist != null && controllist.Count() > 0) { TextBox t = controllist[0] as TextBox; p.SetValue(entity, t.Text); } } bool issuccess = false; if (UserDataHelper.IsExsitedSiteName(entity.SITENAME)) { issuccess = UserDataHelper.UpdateALine(entity); } else { issuccess = UserDataHelper.WriteALine(entity); } if (issuccess) { MessageBox.Show("保存成功"); ScaleMain parent = (ScaleMain)this.Parent.Parent; parent.Open("Main"); this.Close(); } else { MessageBox.Show("保存失败"); } }
private void ResetProgressButton_Click(object sender, RoutedEventArgs e) { var result = AlertBox.Show("This action will delete all heroes, along with their equipment, as well as all currencies and achievements. Are you sure?"); if (result == MessageBoxResult.Yes) { User.Instance.LastHeroId = 0; User.Instance.Heroes.Clear(); User.Instance.Gold = 0; User.Instance.DungeonKeys.Clear(); UserDataHelper.SeedDungeonKeys(); User.Instance.Ingots.Clear(); UserDataHelper.SeedIngots(); User.Instance.Achievements.TotalTimePlayed = default; User.Instance.Achievements.NumericAchievementCollection = new ObservableDictionary <NumericAchievementType, long>(); CollectionsHelper.InitializeDictionary(User.Instance.Achievements.NumericAchievementCollection); UpdateSelectOrDeleteHeroButtons(); UpdateCreateHeroButton(); } }
private async void RemovePlaceFormFavorites(object sender, RoutedEventArgs e) { var _PlaceId = (sender as Button).Tag.ToString(); var _CityData = new CityData() { PlaceInfo = new PlaceInfo() { PlaceId = _PlaceId } }; bool WriteToFile = (await UserDataHelper.RemoveFromFavorites("Favorites.json", _CityData.PlaceInfo)); if (WriteToFile == true) { WeatherPage.IsFavoritesChanged = true; await UserDataHelper.RemoveFavoriteWeather(_CityData.PlaceInfo.PlaceId); FavoritePlaces = FavoritePlaces.Where(x => x.PlaceInfo.PlaceId != _PlaceId).ToList(); SavedPlacesGridView.ItemsSource = FavoritePlaces; var _Count = FavoritePlaces.Count(); switch (_Count) { case 0: NoPlaces.Visibility = Visibility.Visible; break; case 1: SavedPlacesGridView.MaxWidth = 250; break; case 2: SavedPlacesGridView.MaxWidth = 500; break; case 3: SavedPlacesGridView.MaxWidth = 750; break; case 4: SavedPlacesGridView.MaxWidth = 1000; break; case 5: SavedPlacesGridView.MaxWidth = 1250; break; case 6: SavedPlacesGridView.MaxWidth = 1500; break; case 7: SavedPlacesGridView.MaxWidth = 1750; break; case 8: SavedPlacesGridView.MaxWidth = 2000; break; case 9: SavedPlacesGridView.MaxWidth = 2250; break; case 10: SavedPlacesGridView.MaxWidth = 2500; break; } } }
protected override async void OnNavigatedTo(NavigationEventArgs e) { Frame PageFrame = Window.Current.Content as Frame; if (PageFrame == null) { PageFrame = new Frame(); } var settings = await ApplicationData.Current.RoamingFolder.TryGetItemAsync("Settings.json") == null ? null : await UserDataHelper.GetSettings("Settings.json"); if (settings == null) { ApplicationLanguages.PrimaryLanguageOverride = "en"; DefaultFrame.Navigate(typeof(FirstUse)); LoadingControl.IsLoading = false; return; } string Language = settings.Language ?? "en"; ApplicationLanguages.PrimaryLanguageOverride = Language; bool IsConnected = NetworkInformation.GetInternetConnectionProfile() != null ? true : false; string TimeFormat = settings.DataFormat.TimeFormat == "24h" ? "H:mm" : "h:mmtt"; if (IsConnected == false && e.Parameter == null) { if (await ApplicationData.Current.LocalFolder.TryGetItemAsync("HomeWeather.json") == null) { NoInternetGrid.Visibility = Visibility.Visible; return; } _CityData = await UserDataHelper.GetSavedHomeWeather(); _CityData.IsLocalData = true; var _File = await ApplicationData.Current.LocalFolder.GetFileAsync("HomeWeather.json"); _CityData.LastUpdate = System.IO.File.GetLastWriteTime(_File.Path).ToString(TimeFormat); PageFrame.Navigate(typeof(WeatherPage), _CityData); return; } if (e.Parameter != null) { if (IsConnected == true) { _PlaceInfo = e.Parameter as PlaceInfo; _CityData = (await WeatherData.GetWeather(_PlaceInfo, settings.DataFormat, Language)); if (_CityData.Current.cod == 200) { _CityData.LastUpdate = DateTime.Now.ToLocalTime().ToString(TimeFormat); PageFrame.Navigate(typeof(WeatherPage), _CityData); return; } } NoInternetGrid.Visibility = Visibility.Visible; } else { if (settings.CheckLocation == 1) { var coords = await Geolocation.GetLocationInfo(); if (coords.Latitude == 0 && coords.Longitude == 0) { LoadingControl.IsLoading = false; NotFoundGrid.Visibility = Visibility.Visible; NotFoundText.Text = "Sorry! Can't locate you!"; NotFoudHint.Text = "You can try searching instead"; return; } else { var plid = await PlacesSearch.GetCityNameByCoordinate(coords.Latitude, coords.Longitude); if (plid != null) { _PlaceInfo = new PlaceInfo() { Latitude = plid.Latitude, Longitude = plid.Longitude, DisplayName = plid.DisplayName, PlaceId = plid.PlaceId }; } else { LoadingControl.IsLoading = false; NotFoundGrid.Visibility = Visibility.Visible; NotFoundText.Text = "Sorry! Can't locate you!"; NotFoudHint.Text = "You can try searching instead"; return; } } } else { _PlaceInfo = new PlaceInfo { Latitude = settings.DefaultLocation.Latitude, Longitude = settings.DefaultLocation.Longitude, DisplayName = settings.DefaultLocation.DisplayName, PlaceId = settings.DefaultLocation.PlaceId }; } _CityData = (await WeatherData.GetWeather(_PlaceInfo, settings.DataFormat, Language)); _CityData.LastUpdate = DateTime.Now.ToLocalTime().ToString(TimeFormat); bool _SaveData = await UserDataHelper.SaveHomeWeather(_CityData); PageFrame.Navigate(typeof(WeatherPage), _CityData); } LoadingControl.IsLoading = false; /*try * { * } * catch (Exception) * { * await new MessageDialog("Unexpected exception occurred: 7221252017").ShowAsync(); * }*/ }
protected override void Seed(PhonebookManager.DataAccess.Context.PhonebookManagerContext context) { var result = UserDataHelper.CreateAdminUser(context).Result; }
/// <summary> /// 保存至文件 /// </summary> /// <param name="filePath">文件路径</param> protected virtual void SaveToFile(string filePath) { UserDataHelper.SaveToFile(_dataSource, filePath); }
private async void AvailableActions_ItemClick(object sender, ItemClickEventArgs e) { switch ((e.ClickedItem as StackPanel).Tag.ToString()) { case "SetHome": var settings = await UserDataHelper.GetSettings("Settings.json"); settings.DefaultLocation = _CityData.PlaceInfo; await UserDataHelper.WriteFile("Settings.json", settings); SetAsHome.IsEnabled = false; ShowToolTip("SavedAsHome", 2000); break; case "Favorite": var IsFavorited = (await UserDataHelper.SaveToFavorites("Favorites.json", _CityData.PlaceInfo)); if (IsFavorited == true) { await UserDataHelper.SaveFavoriteWeather(_CityData); SaveToFavorites.Visibility = Visibility.Collapsed; RemoveFromFavorites.Visibility = Visibility.Visible; ShowToolTip("Favorited", 2000); } break; case "UnFavorite": var IsUnfavorited = (await UserDataHelper.RemoveFromFavorites("Favorites.json", _CityData.PlaceInfo)); if (IsUnfavorited == true) { await UserDataHelper.RemoveFavoriteWeather(_CityData.PlaceInfo.PlaceId); SaveToFavorites.Visibility = Visibility.Visible; RemoveFromFavorites.Visibility = Visibility.Collapsed; ShowToolTip("Unfavorited", 2000); } break; case "Pin": ShowToolTip("Pinning", 2000); var IsPined = await LiveTile.UpdateCustomTile(PlaceInfo, CurrentWeatherResult, DailyForecastResult, CoverLink); if (IsPined == true) { PinToStart.Visibility = Visibility.Collapsed; UnPinFromStart.Visibility = Visibility.Visible; ShowToolTip("Pined", 2000); } break; case "UnPin": ShowToolTip("Unpinning", 2000); var IsUnPined = await LiveTile.UnpinCustomTile(_CityData.PlaceInfo.PlaceId); if (IsUnPined == true) { PinToStart.Visibility = Visibility.Visible; UnPinFromStart.Visibility = Visibility.Collapsed; ShowToolTip("Unpined", 2000); } break; case "Download": ShowToolTip("DownloadingImage", 2000); BitmapImage bitMap = Cover.Source as BitmapImage; string uri = bitMap?.UriSource.ToString(); await UserDataHelper.DownloadAsset(uri); ShowToolTip("Downloaded", 2000); break; case "Rate": await Launcher.LaunchUriAsync(new Uri(string.Format("ms-windows-store:REVIEW?PFN={0}", Windows.ApplicationModel.Package.Current.Id.FamilyName))); break; case "Feedback": await Microsoft.Services.Store.Engagement.StoreServicesFeedbackLauncher.GetDefault().LaunchAsync(); break; default: break; } }
/// <summary> /// 从文件中读取 /// </summary> /// <param name="filePath"></param> /// <returns></returns> protected static UserData LoadFromFile(string filePath) { return(UserDataHelper.LoadFromFile(filePath)); }
protected async override void OnNavigatedTo(NavigationEventArgs e) { base.OnNavigatedTo(e); _CityData = e.Parameter as CityData; /*set country flag*/ /*string _CountryCode = _CityData.PlaceInfo.DisplayName; * _CountryCode = _CountryCode.Substring(_CountryCode.LastIndexOf(",") + 2); * StorageFolder _assets = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFolderAsync("Assets"); * StorageFolder _flags = await _assets.GetFolderAsync("CountriesFlag"); * * if (_flags.TryGetItemAsync(_CountryCode + ".png") != null) * { * CurrentPlaceName.Text = _CityData.PlaceInfo.DisplayName.Substring(0, _CityData.PlaceInfo.DisplayName.LastIndexOf(",")); * BitmapImage image = new BitmapImage(new Uri("ms-appx:///Assets/CountriesFlag/" + _CountryCode + ".png")); * CountryFlag.Source = image; * } * else { * CurrentPlaceName.Text = _CityData.PlaceInfo.DisplayName; * }*/ /*set country flag*/ CurrentPlaceName.Text = _CityData.PlaceInfo.DisplayName; this.DataContext = _CityData; DailyForecastResult = _CityData.DailyForecast; CurrentWeatherResult = _CityData.Current; PlaceInfo = _CityData.PlaceInfo; CoverLink = _CityData.CoverImage; /*set back navigation arguments*/ if (_LocationHistory == null) { _LocationHistory = new List <PlaceInfo>(); _LocationHistory.Add(_CityData.PlaceInfo); } if (_LocationHistory[_LocationHistory.Count - 1].PlaceId != _CityData.PlaceInfo.PlaceId) { _LocationHistory.Add(_CityData.PlaceInfo); } if (_LocationHistory.Count > 1) { SystemNavigationManager.GetForCurrentView().AppViewBackButtonVisibility = AppViewBackButtonVisibility.Visible; AppNameGrid.Margin = new Thickness(55, 10, 0, 10); } else { SystemNavigationManager.GetForCurrentView().AppViewBackButtonVisibility = AppViewBackButtonVisibility.Collapsed; AppNameGrid.Margin = new Thickness(20, 10, 0, 10); } /*set back navigation arguments*/ _Settings = await UserDataHelper.GetSettings("Settings.json"); if (_Settings.SaveData == "1" || _CityData.IsLocalData == true) { BottomItemsPivot.Items.Remove(BottomItemsPivot.Items.Single(p => ((PivotItem)p).Name == "NewsPivot")); BottomItemsPivot.Items.Remove(BottomItemsPivot.Items.Single(p => ((PivotItem)p).Name == "GalleryPivot")); _CityData.CoverImage = "ms-appx:///Assets/Weather/11.jpg"; if (_CityData.CoverImage != null) { BitmapImage image = new BitmapImage(new Uri(_CityData.CoverImage)); Cover.Source = image; } } else { int _CheckFileAge = await ApplicationData.Current.LocalFolder.TryGetItemAsync("News.json") != null ? await UserDataHelper.CheckFileAge("News.json", "local") : 1441; string Language = _Settings.Language ?? "en"; if (_CheckFileAge >= 1440) { _NewsResults = await News.GetNewsData(Language); bool _SaveNews = await UserDataHelper.SaveNewsData(_NewsResults); } else { _NewsResults = await UserDataHelper.GetSavedNews(); if (_NewsResults.Language != _Settings.Language) { _NewsResults = await News.GetNewsData(Language); bool _SaveNews = await UserDataHelper.SaveNewsData(_NewsResults); } } NewsData.ItemsSource = _NewsResults.articles; await GetCover(_CityData.PlaceInfo.DisplayName); } CoverLink = _CityData.CoverImage; var favorites = (await UserDataHelper.GetFavorites("Favorites.json")); var _CurrentPlace = favorites.Where(x => x.PlaceId == _CityData.PlaceInfo.PlaceId).ToList(); if (_CurrentPlace.Count > 0) { SaveToFavorites.Visibility = Visibility.Collapsed; RemoveFromFavorites.Visibility = Visibility.Visible; } SetAsHome.IsEnabled = _CityData.PlaceInfo.PlaceId == _Settings.DefaultLocation.PlaceId ? false : true; if (SecondaryTile.Exists(_CityData.PlaceInfo.PlaceId)) { PinToStart.Visibility = Visibility.Collapsed; UnPinFromStart.Visibility = Visibility.Visible; await LiveTile.UpdateCustomTile(PlaceInfo, CurrentWeatherResult, DailyForecastResult, CoverLink); } if (_CityData.PlaceInfo.PlaceId == _Settings.DefaultLocation.PlaceId) { LiveTile.UpdateTile(PlaceInfo, CurrentWeatherResult, DailyForecastResult, CoverLink); } if (favorites.ToList().Where(x => x.PlaceId == _CityData.PlaceInfo.PlaceId).FirstOrDefault() != null) { await UserDataHelper.SaveFavoriteWeather(_CityData); } }
protected async override void OnNavigatedTo(NavigationEventArgs e) { var favorites = (await UserDataHelper.GetFavorites("Favorites.json")); FavoritePlaces = new List <CityData>(); foreach (var item in favorites) { var _data = await UserDataHelper.GetFavoriteWeather(item.PlaceId); if (_data != null) { FavoritePlaces.Add(_data); } else { FavoritePlaces.Add(new CityData() { CoverImage = "ms-appx:///Assets/Weather/11.jpg", PlaceInfo = item }); } } var _Count = FavoritePlaces.Count(); switch (_Count) { case 0: NoPlaces.Visibility = Visibility.Visible; break; case 1: SavedPlacesGridView.MaxWidth = 250; break; case 2: SavedPlacesGridView.MaxWidth = 500; break; case 3: SavedPlacesGridView.MaxWidth = 750; break; case 4: SavedPlacesGridView.MaxWidth = 1000; break; case 5: SavedPlacesGridView.MaxWidth = 1250; break; case 6: SavedPlacesGridView.MaxWidth = 1500; break; case 7: SavedPlacesGridView.MaxWidth = 1750; break; case 8: SavedPlacesGridView.MaxWidth = 2000; break; case 9: SavedPlacesGridView.MaxWidth = 2250; break; case 10: SavedPlacesGridView.MaxWidth = 2500; break; } SavedPlacesGridView.ItemsSource = FavoritePlaces; }