private async Task GetSampleDataAsyncC() { bool wait = false; lock (dataLock) { if (!isDataLocked) { isDataLocked = true; } else { wait = true; } } if (wait) { while (isDataLocked) { await Task.Delay(100); } return; } if (_results.Count != 0 || _players.Count != 0 || _JYLYresults.Count != 0) { lock (dataLock) { isDataLocked = false; } return; } Uri localUri = new Uri(JSON_FILEPATH_LOCAL_FOLDER + JSON_FILENAME); Uri installationUri = new Uri(JSON_FILEPATH_INSTALLATION_FOLDER + JSON_FILENAME); StorageFile file = null; var localSettings = Windows.Storage.ApplicationData.Current.LocalSettings; if (!localSettings.Values.ContainsKey("FileCreated") ) { Debug.WriteLine("File does not exist, return preloaded data"); Windows.Storage.StorageFolder installedLocation = Windows.ApplicationModel.Package.Current.InstalledLocation; file = await installedLocation.GetFileAsync("data.txt"); } else { Debug.WriteLine("File exists, return local data"); StorageFolder localFolder = ApplicationData.Current.LocalFolder; IReadOnlyList<StorageFile> fileList = await localFolder.GetFilesAsync(); foreach(var Sfile in fileList) { if (Sfile.Name.Contains("data") || Sfile.Name.Contains("Data")) { try { file = await localFolder.GetFileAsync(Sfile.Name); Debug.WriteLine("File read successfully."); break; } catch (System.IO.FileNotFoundException) { Debug.WriteLine("File not found exception. Return preloaded data."); StorageFolder installedLocation = Windows.ApplicationModel.Package.Current.InstalledLocation; file = await installedLocation.GetFileAsync("data.txt"); } } } } string jsonText = ""; try { if (file != null) { jsonText = await FileIO.ReadTextAsync(file); } } catch (FileNotFoundException) { // Handle file not found Debug.WriteLine("json FileNotFound Exception"); } catch (KeyNotFoundException) { Debug.WriteLine("json KeyNotFound Exception"); } catch (System.Exception) { Debug.WriteLine("System.Exception"); } JsonObject jsonObject; if (jsonText != null && jsonText != "") { jsonObject = JsonObject.Parse(jsonText); } else { Debug.WriteLine("jsonText was null, return"); return; } JsonArray jsonArray_results = jsonObject["ResultGroups"].GetArray(); foreach (JsonValue groupValue in jsonArray_results) { JsonObject groupObject = groupValue.GetObject(); GameResultsGroup resultGroup = new GameResultsGroup(groupObject["GameResultsGroupId"].GetString()); foreach (JsonValue resultValue in groupObject["Results"].GetArray()) { JsonObject resultObject = resultValue.GetObject(); resultGroup.Results.Add(new Result(resultObject["ResultId"].GetString(), resultObject["ResultPlayerName"].GetString(), resultObject["ResultGameModeId"].GetString(), resultObject["Score"].GetNumber(), resultObject["ResultDateTime"].GetString())); } this.Results.Add(resultGroup); } if (!localSettings.Values.ContainsKey(UPDATE_ABO_DONE) || this.Results.Count == 2 ) { GameResultsGroup resultGroup = new GameResultsGroup("2"); this.Results.Add(resultGroup); localSettings.Values[UPDATE_ABO_DONE] = true; localSettings.Values["SaveAboGroup"] = true; } if (!localSettings.Values.ContainsKey(UPDATE_JYLY_DONE) || this.Results.Count == 3) { GameResultsGroup resultGroup = new GameResultsGroup("3"); this.Results.Add(resultGroup); localSettings.Values[UPDATE_JYLY_DONE] = true; localSettings.Values["SaveJYLYGroup"] = true; } JsonArray jsonArray_players = jsonObject["PlayerGroups"].GetArray(); foreach (JsonValue playerGroupValue in jsonArray_players) { JsonObject playerGroupObject = playerGroupValue.GetObject(); PlayerGroup playerGroup = new PlayerGroup(playerGroupObject["PlayerGroupId"].GetString()); foreach (JsonValue resultValue in playerGroupObject["Players"].GetArray()) { JsonObject resultObject = resultValue.GetObject(); if (localSettings.Values.ContainsKey(UPDATE_DONE)) { Debug.WriteLine("GetPlayerWithRating"); playerGroup.Players.Add(new Player(resultObject["PlayerId"].GetString(), resultObject["PlayerName"].GetString(), (int)resultObject["GamesPlayed"].GetNumber(), (int)resultObject["PuttRating"].GetNumber())); } else { Debug.WriteLine("get players Without Rating"); playerGroup.Players.Add(new Player(resultObject["PlayerId"].GetString(), resultObject["PlayerName"].GetString(), (int)resultObject["GamesPlayed"].GetNumber())); } } this.Players.Add(playerGroup); } // get JYLY results Debug.WriteLine("Get jylyresults"); JsonArray jsonArray_JYLYresults = null; if (jsonObject.ContainsKey("JYLYResults")) { jsonArray_JYLYresults = jsonObject["JYLYResults"].GetArray(); foreach (JsonValue JYLYResultValue in jsonArray_JYLYresults) { JsonObject JYLYResultObject = JYLYResultValue.GetObject(); JYLYResult jyly_result = new JYLYResult(JYLYResultObject["Serie"].GetString(), JYLYResultObject["PlayerName"].GetString(), JYLYResultObject["Score"].GetNumber(), JYLYResultObject["DateTime"].GetString()); this.JYLYResults.Add(jyly_result); } } Debug.WriteLine("GetData Done"); lock (dataLock) { isDataLocked = false; } }
/* DEBUG ONLY private async void LoadInAppPurchaseProxyFileAsync(string filename) { StorageFile proxyFile = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///DataModel/" + filename)); await CurrentAppSimulator.ReloadSimulatorAsync(proxyFile); }*/ /// <summary> /// Populates the page with content passed during navigation. Any saved state is also /// provided when recreating a page from a prior session. /// </summary> /// <param name="sender"> /// The source of the event; typically <see cref="NavigationHelper"/>. /// </param> /// <param name="e">Event data that provides both the navigation parameter passed to /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested and /// a dictionary of state preserved by this page during an earlier /// session. The state will be null the first time a page is visited.</param> private async void NavigationHelper_LoadState(object sender, LoadStateEventArgs e) { //DEBUG #region debug /* string xml_filename = XML_NOK; if (localSettings.Values.ContainsKey("XML")) { xml_filename = (string)localSettings.Values["XML"]; } Debug.WriteLine("xml_filename: " + xml_filename); LoadInAppPurchaseProxyFileAsync(xml_filename); Debug.WriteLine("xml loaded"); //debug only if (xml_filename == XML_OK) { Debug.WriteLine("xml_OK"); buyProPackText.Visibility = Windows.UI.Xaml.Visibility.Collapsed; }*/ #endregion // If a hardware Back button is present, hide the "soft" Back button // in the command bar, and register a handler for presses of the hardware if (Windows.Foundation.Metadata.ApiInformation.IsTypePresent("Windows.Phone.UI.Input.HardwareButtons")) { HardwareButtons.BackPressed += HardwareButtons_BackPressed; } IEnumerable<GameResultsGroup> resultGroups = null; int counter = 0; while (resultGroups == null && counter < RETRY_COUNT) { resultGroups = await SampleDataSource.GetResultsAsync(); counter++; } this.DefaultViewModel[FirstGroupName] = resultGroups.ElementAt(0); this.DefaultViewModel[SecondGroupName] = resultGroups.ElementAt(1); this.DefaultViewModel[ThirdGroupName] = resultGroups.ElementAt(2); this.DefaultViewModel[FourthGroupName] = resultGroups.ElementAt(3); PlayerGroup playerDatGroup = null; counter = 0; while (playerDatGroup == null && counter < RETRY_COUNT) { playerDatGroup = await SampleDataSource.GetPlayerGroupOne(); counter++; } this.DefaultViewModel[PlayerGroupName] = playerDatGroup; bool saveData = false; #region newResults var localSettings = Windows.Storage.ApplicationData.Current.LocalSettings; if (localSettings.Values.ContainsKey("NewResults")) { // parse new results into Json JsonArray jsonArray = JsonArray.Parse(localSettings.Values["NewResults"].ToString()); // result group where to add new results GameResultsGroup group = null; // every new result is handled foreach (JsonValue jsonVal in jsonArray) { JsonObject jsonObject = jsonVal.GetObject(); Result newResult = new Result(jsonObject["ResultId"].GetString(), jsonObject["ResultPlayerName"].GetString(), jsonObject["ResultGameModeId"].GetString(), jsonObject["Score"].GetNumber(), jsonObject["ResultDateTime"].GetString()); // variable 'group' is set to the result group where the new results are going to be added if (jsonObject["ResultGameModeId"].GetString() == "0") { group = (GameResultsGroup)DefaultViewModel[FirstGroupName]; } else if (jsonObject["ResultGameModeId"].GetString() == "1") { group = (GameResultsGroup)DefaultViewModel[SecondGroupName]; } else if (jsonObject["ResultGameModeId"].GetString() == "2") { group = (GameResultsGroup)DefaultViewModel[ThirdGroupName]; } else if (jsonObject["ResultGameModeId"].GetString() == "3") { group = (GameResultsGroup)DefaultViewModel[FourthGroupName]; } else { // if a new result does not contain gamemode information, it is omitted and the next one is processed continue; } // check if placeholder results are to be removed // if this is the first time results are added to this group, clear it first if (!localSettings.Values.ContainsKey("ResultsAddedForGroup" + jsonObject["ResultGameModeId"].GetString())) { group.Results.Clear(); // set flag that results have been added to this group localSettings.Values["ResultsAddedForGroup" + jsonObject["ResultGameModeId"].GetString()] = true; } // add new result to the gameResultsGroup group.Results.Add(newResult); // if there is at least two results, try to sort if (group.Results.Count > 1) { // sort by moving the item upwards as long as necessary for (int i = 0; i < group.Results.Count; ++i) { // move one upwards, if if (group.Results.Count > i - 1 && group.Results.ElementAt(group.Results.Count - 2 - i).Score < newResult.Score) { group.Results.Move(group.Results.Count - 1 - i, group.Results.Count - 2 - i); if (group.Results.Count - 2 - i == 0) { break; } } else { break; } } } // modify the player's gamesplayed data string resultPlayerName = jsonObject["ResultPlayerName"].GetString(); int counter2 = 0; PlayerGroup playerDataGroup = null; while (playerDataGroup == null && counter2 < RETRY_COUNT) { playerDataGroup = await SampleDataSource.GetPlayerGroupOne(); counter2++; } //get player from the defaultviewmodel's player group Player player = null; foreach (Player p in playerDataGroup.Players) { if (p.PlayerName == resultPlayerName) { player = p; break; } } if (player != null) { player.PuttRating = await ratingCalculator.PlayerRating(player.PlayerName); Debug.WriteLine("player: " + player.PlayerName + " rating: " + player.PuttRating); player.GamesPlayed += 1; } } // new results read from memory, remove them and set up save flag localSettings.Values.Remove("NewResults"); saveData = true; } // new JYLYresults if (localSettings.Values.ContainsKey("NewJYLYResults")) { IEnumerable<JYLYResult> IJYLYResultGroup = null; int counter3 = 0; while (IJYLYResultGroup == null && counter3 < RETRY_COUNT) { IJYLYResultGroup = await SampleDataSource.GetJYLYResultsAsync(); counter3++; } ObservableCollection<JYLYResult> JYLYResultGroup = (ObservableCollection<JYLYResult>)IJYLYResultGroup; // parse new results into Json JsonArray jsonArray = JsonArray.Parse(localSettings.Values["NewJYLYResults"].ToString()); // result group where to add new results // every new result is handled foreach (JsonValue jsonVal in jsonArray) { JsonObject jsonObject = jsonVal.GetObject(); JYLYResult newJYLYResult = new JYLYResult(jsonObject["Serie"].GetString(), jsonObject["PlayerName"].GetString(), jsonObject["Score"].GetNumber(), jsonObject["DateTime"].GetString()); JYLYResultGroup.Add(newJYLYResult); } // new JYLYresults read from memory, remove them and set up save flag localSettings.Values.Remove("NewJYLYResults"); saveData = true; } #endregion Debug.WriteLine("DII: resultGroups.count: " + resultGroups.Count<GameResultsGroup>()); // check if this is the first boot or is the app udated to Abo or JYLY versions to save all data if (saveData || !localSettings.Values.ContainsKey("FirstBootDone") || !localSettings.Values.ContainsKey("update1.2.0.0_done") || localSettings.Values.ContainsKey("SaveAboGroup") || localSettings.Values.ContainsKey("SaveJYLYGroup")) { dataSaver.SaveAllDataToJson(); localSettings.Values["FileCreated"] = true; localSettings.Values["FirstBootDone"] = true; if (localSettings.Values.ContainsKey("SaveAboGroup")) { localSettings.Values.Remove("SaveAboGroup"); } if (localSettings.Values.ContainsKey("SaveJYLYGroup")) { localSettings.Values.Remove("SaveJYLYGroup"); } } if (localSettings.Values.ContainsKey(PIVOT_INDEX)) { this.pivot.SelectedIndex = (int)localSettings.Values[PIVOT_INDEX]; localSettings.Values.Remove(PIVOT_INDEX); } Debug.WriteLine("MainPage LoadState done"); }