public new void BeforeSave() { // If we're in a Vanilla-compatible area, copy from _Safe (new) to _Unsafe (legacy). if (LastArea_Safe.GetLevelSet() == "Celeste") { LastArea_Unsafe = LastArea_Safe; } if (CurrentSession_Safe != null && CurrentSession_Safe.Area.GetLevelSet() == "Celeste") { CurrentSession_Unsafe = CurrentSession_Safe; } // Make sure that subchapter references to parent chapters aren't stored. // They'll be reverted afterwards with AfterInitialize. // Fill each LevelSetStats with its areas. foreach (LevelSetStats set in LevelSets) { if (set.Name == "Celeste") { continue; } int countRoots = AreaData.Areas.Count(other => other.GetLevelSet() == set.Name && string.IsNullOrEmpty(other?.GetMeta()?.Parent)); List <AreaStats> areas = set.Areas; while (areas.Count > countRoots) { areas.RemoveAt(areas.Count - 1); } } orig_BeforeSave(); UserIO.Save <ModSaveData>(GetFilename(FileSlot) + "-modsavedata", UserIO.Serialize(new ModSaveData(this))); foreach (EverestModule mod in Everest._Modules) { mod.SaveSaveData(FileSlot); mod.SaveSession(FileSlot); } }
public Product GetProductByIndex(int productindex, List <Product> Products) { bool realProduct = false; int userchoice = productindex - 1; while (!realProduct) { Console.WriteLine("Enter the number of the product you wish to select"); if (userchoice < Products.Count() && userchoice >= 0) { Product myproduct = Products[userchoice]; return(myproduct); } else { Console.WriteLine("Invalid selection"); userchoice = UserIO.GetIntegerFromUser() - 1; } } return(null); }
public void Execute() { OrderManager manager = OrderManagerFactory.Create(); DateTime date = UserIO.GetDateFromUser("Enter the date the order was placed (example \"MM-DD-YYYY\"):"); DisplayOrderResponse response = manager.OrderLookup(date); if (response.Success) { ConsoleIO.DisplayOrderDetails(response.Order, response.Date); } else { Console.WriteLine(response.Message); } Console.WriteLine("Press any key to continue..."); Console.ReadKey(); Console.Clear(); }
public override void Update() { orig_Update(); // Slightly dirty place to perform this, but oh well... if (CoreModule.Settings.QuickRestart != null) { int slot = CoreModule.Settings.QuickRestart.Value; CoreModule.Settings.QuickRestart = null; CoreModule.Instance.SaveSettings(); SaveData save = UserIO.Load <SaveData>(SaveData.GetFilename(slot)); if (save != null) { SaveData.Start(save, slot); if (slot == 4) { save.DebugMode = true; } if (save.CurrentSession?.InArea ?? false) { Engine.Scene = new LevelLoader(save.CurrentSession); } else { Overworld.Goto <OuiChapterSelect>(); } } } if (!updateChecked && Everest.Updater.HasUpdate && alpha >= 1f) { updateChecked = true; Tween tween = Tween.Create(Tween.TweenMode.Oneshot, Ease.CubeInOut, 0.3f, true); tween.OnUpdate = t => { updateAlpha = t.Percent; }; Add(tween); } }
private IEnumerator Routine() { Session oldSession = SaveData.Instance.CurrentSession_Safe; Session newSession = null; if (targetSID != null) { newSession = new Session(AreaData.Get(targetSID).ToKey()); newSession.FirstLevel = false; newSession.StartedFromBeginning = false; newSession.Level = targetRoom ?? newSession.MapData.StartLevel().Name; newSession.RespawnPoint = targetRoom == null ? (Vector2?)null : targetSpawnPoint; SaveData.Instance.CurrentSession_Safe = newSession; } UserIO.SaveHandler(file: true, settings: true); while (UserIO.Saving) { yield return(null); } while (SaveLoadIcon.OnScreen) { yield return(null); } SaveData.Instance.CurrentSession_Safe = oldSession; if (targetSID == null) { // failsafe: if there is no lobby to return to, return to map instead. Engine.Scene = new OverworldLoader( exitMode == LevelExit.Mode.Completed ? Overworld.StartMode.AreaComplete : Overworld.StartMode.AreaQuit); } else { new DynData <Session>(newSession)["pauseTimerUntilAction"] = true; LevelEnter.Go(newSession, false); } }
private static void CmdGiveHearts(int amount = -1, string levelSet = null) { SaveData saveData = SaveData.Instance; if (saveData == null) { saveData = UserIO.Load <SaveData>(SaveData.GetFilename(-1)) ?? new SaveData(); SaveData.Start(saveData, -1); } if (amount == -1) { amount = saveData.LevelSetStats.MaxHeartGems; } if (levelSet.IsNullOrEmpty()) { levelSet = saveData.GetLevelSet(); } int num = 0; foreach (AreaStats areaStats in saveData.Areas_Safe.Where(stats => stats.LevelSet == levelSet)) { foreach (AreaModeStats areaStatsMode in areaStats.Modes) { if (num < amount) { areaStatsMode.HeartGem = true; num++; } else { areaStatsMode.HeartGem = false; } } } }
private IEnumerator QuickFullRestartRoutine() { SaveData save = global::Celeste.SaveData.Instance; if (save != null) { Settings.QuickRestart = save.FileSlot; save.BeforeSave(); UserIO.Save <SaveData>(global::Celeste.SaveData.GetFilename(save.FileSlot), UserIO.Serialize(save)); SaveSettings(); } Everest.Events.Celeste.OnShutdown += () => { AudioExt.System?.release(); Thread offspring = new Thread(() => { System.Diagnostics.Process game = new System.Diagnostics.Process(); // If the game was installed via Steam, it should restart in a Steam context on its own. if (Environment.OSVersion.Platform == PlatformID.Unix || Environment.OSVersion.Platform == PlatformID.MacOSX) { // The Linux and macOS versions come with a wrapping bash script. game.StartInfo.FileName = "bash"; game.StartInfo.Arguments = "\"" + Path.Combine(Everest.PathGame, "Celeste") + "\""; } else { game.StartInfo.FileName = Path.Combine(Everest.PathGame, "Celeste.exe"); } game.StartInfo.WorkingDirectory = Everest.PathGame; game.Start(); }); offspring.Start(); }; Engine.Instance.Exit(); yield break; }
public State GetStateByIndex(List <State> States) { bool realState = false; while (!realState) { Console.WriteLine("Enter the number of the sales zone you wish to select"); int userchoice = UserIO.GetIntegerFromUser() - 1; if (userchoice < States.Count && userchoice >= 0) { State myState = States[userchoice]; realState = true; return(myState); } else { Console.WriteLine("Please select a valid zone"); realState = false; } } return(null); }
private static IEnumerator _SlowFullRestart(bool fromOverworld, BlackScreen scene) { SaveData save = SaveData.Instance; if (save != null && save.FileSlot == patch_SaveData.LoadedModSaveDataIndex) { if (!fromOverworld) { CoreModule.Settings.QuickRestart = save.FileSlot; } save.BeforeSave(); UserIO.Save <SaveData>(SaveData.GetFilename(save.FileSlot), UserIO.Serialize(save)); patch_UserIO.ForceSerializeModSave(); if (CoreModule.Settings.SaveDataFlush ?? false) { CoreModule.Instance.ForceSaveDataFlush++; } CoreModule.Instance.SaveSettings(); } Events.Celeste.OnShutdown += BOOT.StartCelesteProcess; scene.RunAfterRender = () => Engine.Instance.Exit(); yield break; }
// Used where BeforeSave was previously used to enforce mod saving. internal static void ForceSerializeModSave() { UserIO.Save <ModSaveData>(SaveData.GetFilename(SaveData.Instance.FileSlot) + "-modsavedata", UserIO.Serialize(new ModSaveData((patch_SaveData)SaveData.Instance))); foreach (EverestModule mod in Everest._Modules) { if (CoreModule.Settings.SaveDataFlush ?? false) { mod.ForceSaveDataFlush += 2; } if (mod.SaveDataAsync) { mod.WriteSaveData(SaveData.Instance.FileSlot, mod.SerializeSaveData(SaveData.Instance.FileSlot)); mod.WriteSession(SaveData.Instance.FileSlot, mod.SerializeSession(SaveData.Instance.FileSlot)); } else { #pragma warning disable CS0618 // Synchronous save / load IO is obsolete but some mods still override / use it. mod.SaveSaveData(SaveData.Instance.FileSlot); mod.SaveSession(SaveData.Instance.FileSlot); #pragma warning restore CS0618 } } }
public void Execute() { Console.Clear(); Console.WriteLine("Edit Orders"); Console.WriteLine(UserIO.Separator); order.dateTime = io.RemoveEditGetDate(); List <Orders> orders = orderManager.DisplayOrder(order.dateTime).Orders; order = io.EditGettingOrderNumber(orders); if (order != null) { order = io.EditOrder(order); if (order != null) { EditResponse response = orderManager.EditOrder(order); if (response.Success) { Console.Clear(); UserIO.DisplayForCustomer(response.Order); Console.ReadKey(); } } } }
public void Execute() { Console.Clear(); Console.WriteLine("Adding Orders"); Console.WriteLine("Please fill out the Information"); Console.WriteLine(UserIO.Separator); order.dateTime = io.AddGetDate(); order.CustomerName = io.GettingName(); tax = io.GettingState(); product = io.GettingProduct(); order.Area = io.GettingArea(); io.AddAssigningValue(order); UserIO.DisplayForCustomer(order); order = io.AddingOrders(order); if (order != null) { AddResponse response = orderManager.AddOrder(order.dateTime, order); if (response.Success) { Console.WriteLine("Order have been process"); Console.ReadKey(); } } }
private static void LoadCommand(string command, string[] args) { try { if (SaveData.Instance == null || (!Manager.allowUnsafeInput && SaveData.Instance.FileSlot != -1)) { int slot = SaveData.Instance == null ? -1 : SaveData.Instance.FileSlot; SaveData data = UserIO.Load <SaveData>(SaveData.GetFilename(slot)); SaveData.Start(data, -1); // Complete Prologue if incomplete LevelSetStats stats = SaveData.Instance.GetLevelSetStatsFor("Celeste"); if (stats.UnlockedAreas == 0) { stats.UnlockedAreas = 1; stats.AreasIncludingCeleste[0].Modes[0].Completed = true; } } AreaMode mode = AreaMode.Normal; if (command == "hard") { mode = AreaMode.BSide; } else if (command == "rmx2") { mode = AreaMode.CSide; } int levelID = GetLevelID(args[0]); if (args.Length > 1) { if (!int.TryParse(args[1], out int x)) { string screen = args[1]; if (screen.StartsWith("lvl_")) { screen = screen.Substring(4); } if (args.Length > 2) { int checkpoint = int.Parse(args[2]); Load(mode, levelID, screen, checkpoint); } else { Load(mode, levelID, screen); } } else if (args.Length > 2) { int y = int.Parse(args[2]); Load(mode, levelID, new Vector2(x, y)); } } else { Load(mode, levelID); } } catch { } }
private static void ListAllPokemon(PokemonRepository repo) { UserIO.PrintPokemon(repo.ListAll()); }
/// <summary> /// Initializes mod save data backups if required (if Everest was just updated past 2104). /// </summary> private static void checkModSaveDataBackups() { Version previousVersion; try { previousVersion = new Version(CoreModule.Settings.CurrentVersion); } catch { // oops, version is null or can't be parsed for any reason. previousVersion = new Version(0, 0, 0); } if (previousVersion < new Version(1, 2109, 0)) { // user just upgraded: create mod save data backups. // (this is very similar to OverworldLoader.CheckVariantsPostcardAtLaunch) Logger.Log("core", $"User just upgraded from version {previousVersion}: creating mod save data backups."); for (int i = 0; i < 3; i++) // only the first 3 saves really matter. { if (!UserIO.Exists(SaveData.GetFilename(i))) { continue; } SaveData saveData = UserIO.Load <SaveData>(SaveData.GetFilename(i), backup: false); if (saveData != null) { saveData.AfterInitialize(); UserIO.Save <ModSaveData>(SaveData.GetFilename(saveData.FileSlot) + "-modsavedata", UserIO.Serialize(new ModSaveData(saveData as patch_SaveData))); } } UserIO.Close(); SaveData.Instance = null; } }
public void Execute() { OrderManager manager = OrderManagerFactory.Create(); DateTime date = UserIO.GetDateFromUser("Enter the date the order was placed (example \"MM-DD-YYYY\"):"); DisplayOrderResponse response = manager.OrderLookup(date); Console.Clear(); if (response.Success) { Order order = null; while (order == null) { ConsoleIO.DisplayOrderDetails(response.Order, response.Date); order = UserIO.GetOrderFromUser("Which order would you like to edit? (Use Order ID) :", response.Order); if (order == null) { Console.WriteLine("The input did not match an order ID"); } else { break; } } while (true) { string customerName = UserIO.GetStringFromUserCanBeNull($"Please enter a new name for the customer. The current customer name is {order.CustomerName}. If you do no wish to change this field hit enter without entering any data. :"); if (customerName.Trim() == string.Empty) { break; } bool result = order.CustomerName.All(c => Char.IsLetterOrDigit(c) || c == '.' || c == ',' || c == ' '); if (result == false) { Console.WriteLine("The customer name you entered contained an invalid value"); Console.ReadLine(); } else { order.CustomerName = customerName; break; } } Console.Clear(); TaxesRepository taxRepo = new TaxesRepository(); ConsoleIO.DisplayTaxRepo(taxRepo.List()); Taxes tax = null; while (tax == null) { string state = UserIO.GetStringFromUserCanBeNull($"Please enter the new state Abbreviation for the customer. The current state is {order.State}.If you do no wish to change this field hit enter without entering any data. :").ToUpper(); if (state != string.Empty) { tax = taxRepo.List().FirstOrDefault(t => t.StateAbbreviation.ToUpper() == state); if (tax != null) { order.State = tax.StateAbbreviation; order.TaxRate = tax.TaxRate; break; } else { Console.WriteLine("We do not do business in that state"); Console.WriteLine("Press any key to try again..."); Console.ReadLine(); } } else { break; } } Console.Clear(); ProductRepository productRepo = new ProductRepository(); ConsoleIO.DisplayProductRepo(productRepo.List()); Product product = null; while (product == null) { string productType = UserIO.GetStringFromUserCanBeNull($"Please enter the new product type information for the customer. The current product type is {order.ProductType} (Carpet, Laminate, Tile, Wood). If you do no wish to change this field hit enter without entering any data. :").ToUpper(); if (productType != string.Empty) { product = productRepo.List().FirstOrDefault(p => p.ProductType.ToUpper() == productType); if (product != null) { order.CostPerSquareFoot = product.CostPerSquareFoot; order.LaborCostPerSquareFoot = product.LaborCostPerSquareFoot; order.ProductType = product.ProductType; break; } if (product == null) { Console.WriteLine("We do not offer that flooring type."); Console.WriteLine("Press any key to try again..."); Console.ReadKey(); } } else { break; } } Console.Clear(); while (true) { decimal area = UserIO.GetAreaFromUserCanBe0($"Please enter the new area information for this order. The current area is {order.Area}. If you do no wish to change this field hit enter without entering any data. :"); if (area == 0) { break; } else { order.Area = area; break; } } order.MaterialCost = order.Area * order.CostPerSquareFoot; order.LaborCost = order.Area * order.LaborCostPerSquareFoot; order.Total = order.MaterialCost + order.LaborCost + order.Tax; order.Tax = (order.MaterialCost + order.LaborCost) * (order.TaxRate / 100); order.OrderDate = response.Date; order.MaterialCost.ToString(); order.LaborCost.ToString(); order.Tax.ToString(); order.Total.ToString(); string line = "{0, 5} {1, 10} {2, 12} {3,8} {4, 15} {5, 15} {6, 12} {7, 9} {8, 9}"; Console.WriteLine(line, "Order ID", "Order Date", "Cust Name", "State", "Prod Type", "Material Cost", "Labor Cost", "Tax", "Total"); Console.WriteLine("_______________________________________________________________________________________"); string line2 = "{0, 5} {1, 12} {2, 9} {3, 10} {4, 14} {5, 12} {6, 16} {7, 11} {8, 11}"; Console.WriteLine(line2, order.OrderNumber, order.OrderDate.ToString("MM/dd/yyyy"), order.CustomerName, order.State, order.ProductType, String.Format("{0:0.00}", order.MaterialCost), String.Format("{0:0.00}", order.LaborCost), String.Format("{0:0.00}", order.Tax), String.Format("{0:0.00}", order.Total)); string input = UserIO.GetYesOrNoFromUser($"Do you want to save these changes for {order.CustomerName}?"); if (input == "Y") { EditOrderResponse editResponse = manager.OrderEdit(order); if (editResponse.Success == true) { Console.WriteLine("The order has been added."); Console.WriteLine("Press any key to continue..."); Console.ReadLine(); } else { Console.WriteLine(editResponse.Message); Console.WriteLine("The request has been cancelled. Press any key to return to the main menu"); Console.ReadKey(); } } else { Console.WriteLine("You have chosen not to save the changes to the order. Press any key to return to the main menu."); Console.ReadKey(); } } else { Console.WriteLine("There are no orders from that date."); Console.WriteLine("Press any key to continue..."); Console.ReadKey(); } }
public override void Update() { orig_Update(); // Slightly dirty place to perform this, but oh well... if (CoreModule.Settings.QuickRestart != null) { int slot = CoreModule.Settings.QuickRestart.Value; CoreModule.Settings.QuickRestart = null; CoreModule.Instance.SaveSettings(); SaveData save = UserIO.Load <SaveData>(SaveData.GetFilename(slot)); if (save != null) { SaveData.Start(save, slot); if (slot == -1) { save.DebugMode = true; } if (save.CurrentSession?.InArea ?? false) { LevelEnter.Go(save.CurrentSession, true); } else { Overworld.Goto <OuiChapterSelect>(); } } } if (!updateChecked && Everest.Updater.HasUpdate && Everest.Updater.Newest != null && alpha >= 1f) { updateChecked = true; updateTex = Everest.Updater.Newest.Branch == "stable" ? GFX.Gui["areas/new"] : GFX.Gui["areas/new-yellow"]; Tween tween = Tween.Create(Tween.TweenMode.Oneshot, Ease.CubeInOut, 0.3f, true); tween.OnUpdate = t => { updateAlpha = t.Percent; }; Add(tween); } if (alpha >= 1f && Selected && Input.MenuRight && arrowToVanilla != null && warningMessageMenu == null) { switchingToVanillaBack = Math.Max(0f, switchingToVanillaBack - Engine.DeltaTime * 8f); switchingToVanilla += Engine.DeltaTime; if (switchingToVanilla >= switchingToVanillaDuration && !Everest.RestartVanilla) { if (CoreModule.Settings.RestartIntoVanillaWarningShown) { restartIntoVanilla(); } else { warningMessageMenu = new TextMenu(); Action onCancel = () => { // remove the menu Scene.Remove(warningMessageMenu); warningMessageMenu.Visible = false; warningMessageMenu = null; hideConfirmButton = false; // revert the "switch to vanilla" animation switchingToVanilla = 0f; switchingToVanillaBack = 0f; // fade the vanilla title screen back in alpha = 0f; Tween tween = Tween.Create(Tween.TweenMode.Oneshot, Ease.CubeInOut, 0.6f, start: true); tween.OnUpdate = t => { alpha = t.Percent; textY = MathHelper.Lerp(1200f, 1000f, t.Eased); }; Add(tween); }; warningMessageMenu.OnESC = warningMessageMenu.OnCancel = () => { Audio.Play(SFX.ui_main_button_back); onCancel(); }; warningMessageMenu.Add(new TextMenu.Button(Dialog.Clean("MENU_TITLESCREEN_OK")).Pressed(() => { if (!CoreModule.Settings.RestartIntoVanillaWarningShown) { CoreModule.Settings.RestartIntoVanillaWarningShown = true; CoreModule.Instance.SaveSettings(); } warningMessageMenu.Focused = false; restartIntoVanilla(); })); warningMessageMenu.Add(new TextMenu.Button(Dialog.Clean("MENU_TITLESCREEN_CANCEL")).Pressed(onCancel)); Scene.Add(warningMessageMenu); hideConfirmButton = true; } } } else if (switchingToVanilla < switchingToVanillaDuration) { if (switchingToVanilla > 0f) { switchingToVanillaBack = Math.Max(switchingToVanilla, switchingToVanillaBack); } switchingToVanillaBack = Math.Max(0f, switchingToVanillaBack - Engine.DeltaTime * 4f); switchingToVanilla = 0f; } warningEase = Calc.Approach(warningEase, warningMessageMenu != null ? 1f : 0f, Engine.DeltaTime); }
//------------------------------------------------------------------------------------------------------------------------------------- public void RemoveOrder() { string date = PseudoDateSelect(); string filename = "Orders_" + date + ".txt"; string path = @"C:\repos\chris-williams-individual-work\FlooringMasteryV5\Data\Orders\" + filename; List <Order> CurrentOrders = new List <Order>(); if (!File.Exists(path)) { Console.WriteLine("Invalid date"); Console.WriteLine("Press any key to continue"); Console.ReadKey(); return; } try { LoadOrders current = new LoadOrders(); CurrentOrders = current.ParseFileData(filename); } catch { Console.WriteLine("Could not open specified file"); return; } Console.Clear(); Console.WriteLine($"Orders on {date}"); Console.WriteLine("Order#, Customer name, State, product type, area, total cost"); foreach (Order order in CurrentOrders) { Console.WriteLine($"{order.OrderNumber}, {order.CustomerName}, {order.State}, {order.Product}, {order.Area}, {order.Total:C}"); } bool GoodOrder = false; int todelete = 0; int maxOrderNumber = CurrentOrders[CurrentOrders.Count - 1].OrderNumber; while (!GoodOrder) { Console.WriteLine("Please enter the order number of the order you wish to delete"); int selection = UserIO.GetIntegerFromUser(); if (selection > maxOrderNumber || selection < 1) { GoodOrder = false; Console.WriteLine("Please enter a valid order number"); } else { GoodOrder = true; todelete = selection; break; } } foreach (Order order in CurrentOrders) { if (order.OrderNumber == todelete) { CurrentOrders.Remove(order); break; } } if (CurrentOrders.Count < 1) { File.Delete(path); Console.WriteLine("Date file deleted"); } else { try { using (StreamWriter sw = new StreamWriter(path)) { sw.WriteLine("OrderNumber,CustomerName,State,TaxRate,ProductType,Area,CostPerSquareFoot,LaborCostPerSquareFoot,MaterialCost,LaborCost,Tax,Total"); foreach (Order MyOrder in CurrentOrders) { sw.WriteLine($"{MyOrder.OrderNumber},\"{MyOrder.CustomerName}\",{MyOrder.State},{MyOrder.TaxRate},{MyOrder.Product},{MyOrder.Area},{MyOrder.CostPerSquareFoot},{MyOrder.LaborCostPerSquareFoot},{MyOrder.MaterialCost},{MyOrder.LaborCost},{MyOrder.Tax},{MyOrder.Total}"); } } } catch { Console.WriteLine("Could not write updated order to file"); return; } } Console.WriteLine("Order deleted"); Console.ReadLine(); }
public new void AfterInitialize() { // Vanilla / new saves don't have the LevelSets list. if (LevelSets == null) { LevelSets = new List <LevelSetStats>(); } if (LevelSetRecycleBin == null) { LevelSetRecycleBin = new List <LevelSetStats>(); } if (LevelSets.Count <= 1 && LevelSetRecycleBin.Count == 0 && !HasModdedSaveData) { // the save file doesn't have any mod save data (just created, overwritten by vanilla, or Everest just updated). // we want to carry mod save data that was backed up in the mod save file, if any. ModSaveData modSaveData = UserIO.Load <ModSaveData>(GetFilename(FileSlot) + "-modsavedata"); if (modSaveData != null) { modSaveData.CopyToCelesteSaveData(this); Logger.Log(LogLevel.Warn, "SaveData", $"{LevelSets.Count} level set(s) were restored from mod backup for save slot {FileSlot}"); } } HasModdedSaveData = true; if (Areas_Unsafe == null) { Areas_Unsafe = new List <AreaStats>(); } // Add missing LevelSetStats. foreach (AreaData area in AreaData.Areas) { string set = area.GetLevelSet(); if (!LevelSets.Exists(other => other.Name == set)) { LevelSetStats recycleBinLevelSet = LevelSetRecycleBin.FirstOrDefault(other => other.Name == set); if (recycleBinLevelSet != null) { // the level set is actually in the recycle bin - restore it. LevelSets.Add(recycleBinLevelSet); LevelSetRecycleBin.Remove(recycleBinLevelSet); } else { // create a new LevelSetStats entry. LevelSets.Add(new LevelSetStats { Name = set, UnlockedAreas = set == "Celeste" ? UnlockedAreas_Unsafe : 0 }); } } } // Fill each LevelSetStats with its areas. for (int lsi = 0; lsi < LevelSets.Count; lsi++) { LevelSetStats set = LevelSets[lsi]; set.SaveData = this; List <AreaStats> areas = set.Areas; if (set.Name == "Celeste") { areas = Areas_Unsafe; } int offset = set.AreaOffset; if (offset == -1) { // LevelSet gone - let's move it to the recycle bin. LevelSetStats levelSetAlreadyInRecycleBin = LevelSetRecycleBin.FirstOrDefault(other => other.Name == set.Name); if (levelSetAlreadyInRecycleBin != null) { // a level set with the same name already exists in the recycle bin - replace it. LevelSetRecycleBin.Remove(levelSetAlreadyInRecycleBin); } LevelSetRecycleBin.Add(set); // now, remove it to prevent any unwanted access. LevelSets.RemoveAt(lsi); lsi--; continue; } // Refresh all stat IDs based on their SIDs, sort, fill and remove leftovers. // Temporarily use ID_Unsafe; later ID_Safe to ID_Unsafe to resync the SIDs. // This keeps the stats bound to their SIDs, not their indices, while removing non-existent areas. int countRoots = AreaData.Areas.Count(other => other.GetLevelSet() == set.Name && string.IsNullOrEmpty(other?.GetMeta()?.Parent)); int countAll = AreaData.Areas.Count(other => other.GetLevelSet() == set.Name); // Fix IDs for (int i = 0; i < areas.Count; i++) { AreaData area = AreaDataExt.Get(areas[i]); if (!string.IsNullOrEmpty(area?.GetMeta()?.Parent)) { area = null; } ((patch_AreaStats)areas[i]).ID_Unsafe = area?.ID ?? int.MaxValue; } // Sort areas.Sort((a, b) => ((patch_AreaStats)a).ID_Unsafe - ((patch_AreaStats)b).ID_Unsafe); // Remove leftovers while (areas.Count > 0 && ((patch_AreaStats)areas[areas.Count - 1]).ID_Unsafe == int.MaxValue) { areas.RemoveAt(areas.Count - 1); } // Fill gaps for (int i = 0; i < countRoots; i++) { if (i >= areas.Count || ((patch_AreaStats)areas[i]).ID_Unsafe != offset + i) { areas.Insert(i, new AreaStats(offset + i)); } } // Duplicate parent stat refs into their respective children slots. for (int i = countRoots; i < countAll; i++) { if (i >= areas.Count) { areas.Insert(i, areas[AreaDataExt.Get(AreaData.Get(offset + i).GetMeta().Parent).ID - offset]); } } // Resync SIDs for (int i = 0; i < areas.Count; i++) { ((patch_AreaStats)areas[i]).ID_Safe = ((patch_AreaStats)areas[i]).ID_Unsafe; } int lastCompleted = -1; for (int i = 0; i < countRoots; i++) { if (areas[i].Modes[0].Completed) { lastCompleted = i; } } if (set.Name == "Celeste") { if (UnlockedAreas_Unsafe < lastCompleted + 1 && set.MaxArea >= lastCompleted + 1) { UnlockedAreas_Unsafe = lastCompleted + 1; } if (DebugMode) { UnlockedAreas_Unsafe = set.MaxArea; } } else { if (set.UnlockedAreas < lastCompleted + 1 && set.MaxArea >= lastCompleted + 1) { set.UnlockedAreas = lastCompleted + 1; } if (DebugMode) { set.UnlockedAreas = set.MaxArea; } } foreach (AreaStats area in areas) { area.CleanCheckpoints(); } } // Assign SaveData for the level sets in the recycle bin to prevent crashes. foreach (LevelSetStats set in LevelSetRecycleBin) { set.SaveData = this; } // Order the levelsets to appear just as their areas appear in AreaData.Areas LevelSets.Sort((set1, set2) => set1.AreaOffset.CompareTo(set2.AreaOffset)); // If there is no mod progress, carry over any progress from vanilla saves. if (LastArea_Safe.ID == 0) { LastArea_Safe = LastArea_Unsafe; } if (CurrentSession_Safe == null) { CurrentSession_Safe = CurrentSession_Unsafe; } // Trick unmodded instances of Celeste to thinking that we last selected prologue / played no level. LastArea_Unsafe = AreaKey.Default; CurrentSession_Unsafe = null; // Fix areas with missing SID (f.e. deleted or renamed maps). if (AreaData.Get(LastArea) == null) { LastArea = AreaKey.Default; } // Fix out of bounds areas. if (LastArea.ID < 0 || LastArea.ID >= AreaData.Areas.Count) { LastArea = AreaKey.Default; } if (string.IsNullOrEmpty(TheoSisterName)) { TheoSisterName = Dialog.Clean("THEO_SISTER_NAME", null); if (Name.IndexOf(TheoSisterName, StringComparison.InvariantCultureIgnoreCase) >= 0) { TheoSisterName = Dialog.Clean("THEO_SISTER_ALT_NAME", null); } } AssistModeChecks(); if (Version != null) { Version v = new Version(Version); if (v < new Version(1, 2, 1, 1)) { for (int id = 0; id < Areas_Unsafe.Count; id++) { AreaStats area = Areas_Unsafe[id]; if (area == null) { continue; } for (int modei = 0; modei < area.Modes.Length; modei++) { AreaModeStats mode = area.Modes[modei]; if (mode == null) { continue; } if (mode.BestTime > 0L) { mode.SingleRunCompleted = true; } mode.BestTime = 0L; mode.BestFullClearTime = 0L; } } } } }
private static void LoadCommand(string command, string[] args) { try { if (SaveData.Instance == null || !Manager.AllowUnsafeInput && SaveData.Instance.FileSlot != -1) { SaveData data = SaveData.Instance ?? UserIO.Load <SaveData>(SaveData.GetFilename(-1)) ?? new SaveData(); if (SaveData.Instance?.FileSlot is { } slot&& slot != -1) { SaveData.TryDelete(-1); SaveData.LoadedModSaveDataIndex = -1; foreach (EverestModule module in Everest.Modules) { if (module._Session != null) { module._Session.Index = -1; } if (module._SaveData != null) { module._SaveData.Index = -1; } } SaveData.Instance = data; SaveData.Instance.FileSlot = -1; UserIO.SaveHandler(true, true); } else { SaveData.Start(data, -1); } // Complete Prologue if incomplete and make sure the return to map menu item will be shown LevelSetStats stats = data.GetLevelSetStatsFor("Celeste"); if (!data.Areas[0].Modes[0].Completed) { data.Areas[0].Modes[0].Completed = true; stats.UnlockedAreas++; } } AreaMode mode = AreaMode.Normal; if (command.Equals("hard", StringComparison.InvariantCultureIgnoreCase)) { mode = AreaMode.BSide; } else if (command.Equals("rmx2", StringComparison.InvariantCultureIgnoreCase)) { mode = AreaMode.CSide; } int levelId = GetLevelId(args[0]); if (args.Length > 1) { if (!double.TryParse(args[1], out double x) || args.Length == 2) { string screen = args[1]; if (screen.StartsWith("lvl_")) { screen = screen.Substring(4); } if (args.Length > 2) { int spawnpoint = int.Parse(args[2]); Load(mode, levelId, screen, spawnpoint); } else { Load(mode, levelId, screen); } } else if (args.Length > 2 && double.TryParse(args[2], out double y)) { Vector2 position = new((int)Math.Round(x), (int)Math.Round(y)); Vector2 remainder = new((float)(x - position.X), (float)(y - position.Y)); Vector2 speed = Vector2.Zero; if (args.Length > 3 && float.TryParse(args[3], out float speedX)) { speed.X = speedX; } if (args.Length > 4 && float.TryParse(args[4], out float speedY)) { speed.Y = speedY; } Load(mode, levelId, position, remainder, speed); } } else { Load(mode, levelId); } } catch {
private static void ListAllCharacters(CharacterRepository repo) { UserIO.PrintCharacters(repo.ReadAll()); }
public Game(GameObject chessboard, GameObject messageBox) { Chessboard = chessboard; MessageBox = messageBox; UserIO = new UserIO(this); }
public void setIO(UserIO io) { this.io = io; }
//-------------------------------------------------------------------------------------------------------------------------------------- public void AddOrder() { List <Product> Products = new List <Product>(); try { Products = LoadProducts.LoadAllProducts(); } catch { Console.WriteLine("Could not load product data"); } List <State> States = new List <State>(); try { States = LoadStates.LoadAllStates(); } catch { Console.WriteLine("Could not load sales tax data"); } int ordernumber = FileIO.ReturnHighestOrderNumber() + 1; string date = DateSelect(); string filename = "Orders_" + date + ".txt"; string path = @"C:\repos\chris-williams-individual-work\FlooringMasteryV5\Data\Orders\" + filename; List <Order> CurrentOrders = new List <Order>(); if (File.Exists(path)) { LoadOrders current = new LoadOrders(); CurrentOrders = current.ParseFileData(filename); } if (!File.Exists(path)) { using (StreamWriter sw = new StreamWriter(path, true)) { sw.WriteLine("OrderNumber,CustomerName,State,TaxRate,ProductType,Area,CostPerSquareFoot,LaborCostPerSquareFoot,MaterialCost,LaborCost,Tax,Total"); } } string name = GetName(); Console.Clear(); Console.WriteLine("Please enter the number associated with the customer's sales zone"); UserIO.DisplayStates(); State state = GetStateByIndex(States); Console.Clear(); UserIO.DisplayProducts(); Product myProduct = GetProductByIndex(Products); decimal area = GetArea(); Order MyOrder = new Order(ordernumber, name, state, myProduct, area, date); Console.WriteLine($"The order for {name} in {state.StateName} is {area}ft^2 of {myProduct.ProductName}"); Console.WriteLine($"The cost/ft^2 for material is{MyOrder.CostPerSquareFoot}, and the labor cost/ft^2 is{MyOrder.LaborCostPerSquareFoot}"); Console.WriteLine($"Total material cost: {MyOrder.MaterialCost:C} \nTotal labor cost: {MyOrder.LaborCost:C}\nTaxes: {MyOrder.Tax:C}\nTotal cost: {MyOrder.Total:C}"); Console.WriteLine("Do you wish to submit this order? Enter \"n\" to discard order"); string input = Console.ReadLine().ToUpper(); if (input != "N") { try { using (StreamWriter sw = new StreamWriter(path, true)) { sw.WriteLine($"{MyOrder.OrderNumber},{MyOrder.CustomerName},{MyOrder.State},{MyOrder.TaxRate},{MyOrder.Product},{MyOrder.Area},{MyOrder.CostPerSquareFoot},{MyOrder.LaborCostPerSquareFoot},{MyOrder.MaterialCost},{MyOrder.LaborCost},{MyOrder.Tax},{MyOrder.Total}"); } } catch { Console.WriteLine("System Error: order not submitted"); Console.WriteLine("Press any key to continue"); Console.ReadKey(); return; } } else { Console.WriteLine("Order terminated"); Console.WriteLine("Press any key to continue"); Console.ReadKey(); return; } Console.WriteLine("Order entry complete"); }
public override void Update() { orig_Update(); // Slightly dirty place to perform this, but oh well... if (CoreModule.Settings.QuickRestart != null) { int slot = CoreModule.Settings.QuickRestart.Value; CoreModule.Settings.QuickRestart = null; if (CoreModule.Settings.SaveDataFlush ?? false) { CoreModule.Instance.ForceSaveDataFlush++; } CoreModule.Instance.SaveSettings(); SaveData save = UserIO.Load <SaveData>(SaveData.GetFilename(slot)); if (save != null) { SaveData.Start(save, slot); if (slot == -1) { save.DebugMode = true; } if (save.CurrentSession?.InArea ?? false) { LevelEnter.Go(save.CurrentSession, true); } else { Overworld.Goto <OuiChapterSelect>(); } } } if (!updateChecked && Everest.Updater.HasUpdate && Everest.Updater.Newest != null && alpha >= 1f) { updateChecked = true; updateTex = Everest.Updater.Newest.Branch == "stable" ? GFX.Gui["areas/new"] : GFX.Gui["areas/new-yellow"]; Tween tween = Tween.Create(Tween.TweenMode.Oneshot, Ease.CubeInOut, 0.3f, true); tween.OnUpdate = t => { updateAlpha = t.Percent; }; Add(tween); } if (alpha >= 1f && Selected && Input.MenuRight && arrowToVanilla != null) { switchingToVanillaBack = Math.Max(0f, switchingToVanillaBack - Engine.DeltaTime * 8f); switchingToVanilla += Engine.DeltaTime; if (switchingToVanilla >= switchingToVanillaDuration && !Everest.RestartVanilla) { Everest.RestartVanilla = true; new FadeWipe(Scene, false, () => { Engine.Scene = new Scene(); if (Everest.Flags.IsXNA && Engine.Graphics.IsFullScreen) { Engine.SetWindowed(320 * Settings.Instance.WindowScale, 180 * Settings.Instance.WindowScale); } Engine.Instance.Exit(); }); } } else if (switchingToVanilla < switchingToVanillaDuration) { if (switchingToVanilla > 0f) { switchingToVanillaBack = Math.Max(switchingToVanilla, switchingToVanillaBack); } switchingToVanillaBack = Math.Max(0f, switchingToVanillaBack - Engine.DeltaTime * 4f); switchingToVanilla = 0f; } }
private static void openReturnToLobbyConfirmMenu(Level level, int returnIndex) { level.Paused = true; TextMenu menu = new TextMenu(); menu.AutoScroll = false; menu.Position = new Vector2((float)Engine.Width / 2f, (float)Engine.Height / 2f - 100f); // RETURN TO LOBBY? menu.Add(new TextMenu.Header(Dialog.Clean("collabutils2_returntolobby_confirm_title"))); // Save if (CollabModule.Instance.Session.SaveAndReturnToLobbyAllowed) { // add some explanatory text on the "Save" and "Do Not Save" options menu.Add(new TextMenu.SubHeader(Dialog.Clean("collabutils2_returntolobby_confirm_note1"))); menu.Add(new TextMenuExt.SubHeaderExt(Dialog.Clean("collabutils2_returntolobby_confirm_note2")) { HeightExtra = 0f }); menu.Add(new TextMenu.SubHeader("")); menu.Add(new TextMenu.Button(Dialog.Clean("collabutils2_returntolobby_confirm_save")).Pressed(() => { Engine.TimeRate = 1f; menu.Focused = false; Audio.SetMusic(null); Audio.BusStopAll("bus:/gameplay_sfx", immediate: true); // add a death, like vanilla Save & Quit level.Session.InArea = true; level.Session.Deaths++; level.Session.DeathsInCurrentLevel++; SaveData.Instance.AddDeath(level.Session.Area); level.DoScreenWipe(wipeIn: false, () => { CollabModule.Instance.SaveData.SessionsPerLevel.Add(level.Session.Area.GetSID(), Encoding.UTF8.GetString(UserIO.Serialize(level.Session))); // save all mod sessions of mods that have mod sessions. Dictionary <string, string> modSessions = new Dictionary <string, string>(); foreach (EverestModule mod in Everest.Modules) { if (mod._Session != null && !(mod._Session is EverestModuleBinarySession)) { try { modSessions[mod.Metadata.Name] = YamlHelper.Serializer.Serialize(mod._Session); } catch (Exception e) { // this is the same fallback message as the base EverestModule class if something goes wrong. Logger.Log(LogLevel.Warn, "CollabUtils2/ReturnToLobbyHelper", "Failed to save the session of " + mod.Metadata.Name + "!"); Logger.LogDetailed(e); } } } CollabModule.Instance.SaveData.ModSessionsPerLevel.Add(level.Session.Area.GetSID(), modSessions); Engine.Scene = new LevelExitToLobby(LevelExit.Mode.SaveAndQuit, level.Session); }); foreach (LevelEndingHook component in level.Tracker.GetComponents <LevelEndingHook>()) { component.OnEnd?.Invoke(); } })); } // Do Not Save menu.Add(new TextMenu.Button(Dialog.Clean(CollabModule.Instance.Session.SaveAndReturnToLobbyAllowed ? "collabutils2_returntolobby_confirm_donotsave" : "menu_return_continue")).Pressed(() => { Engine.TimeRate = 1f; menu.Focused = false; Audio.SetMusic(null); Audio.BusStopAll("bus:/gameplay_sfx", immediate: true); level.DoScreenWipe(wipeIn: false, () => { Engine.Scene = new LevelExitToLobby(LevelExit.Mode.GiveUp, level.Session); }); foreach (LevelEndingHook component in level.Tracker.GetComponents <LevelEndingHook>()) { component.OnEnd?.Invoke(); } })); // Cancel menu.Add(new TextMenu.Button(Dialog.Clean(CollabModule.Instance.Session.SaveAndReturnToLobbyAllowed ? "collabutils2_returntolobby_confirm_cancel" : "menu_return_cancel")).Pressed(() => { menu.OnCancel(); })); // handle Pause button menu.OnPause = (menu.OnESC = () => { menu.RemoveSelf(); level.Paused = false; Engine.FreezeTimer = 0.15f; Audio.Play("event:/ui/game/unpause"); }); // handle Cancel button menu.OnCancel = () => { Audio.Play("event:/ui/main/button_back"); menu.RemoveSelf(); level.Pause(returnIndex, minimal: false); }; level.Add(menu); }
static void Main(string[] args) { Robot robot = new Robot(); RobotController rController = new RobotController(); BoardErrorChecker boardChecker = new BoardErrorChecker(); Console.WriteLine("Toy Robot Simulator"); Console.WriteLine("Enter board height: "); int boardHeight = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("Enter board length: "); int boardLength = Convert.ToInt32(Console.ReadLine()); Board board = new Board(boardLength, boardHeight, robot); string userInput = ""; while (userInput != "End") { userInput = Console.ReadLine().ToUpper(); //If the robot has not been placed yet we only expect one kind of command if (!boardChecker.isRobotPresentOnBoard(board) && !rController.isRobotOnABoard(robot)) { // If there is a valid command to place the robot if (UserIO.validPlaceCommand(userInput)) { string stringWithoutPlace = userInput.Substring(6); string[] commandValues = stringWithoutPlace.Split(','); rController.placeRobotOnBoard(robot, commandValues[0], commandValues[1], commandValues[2]); if (!boardChecker.checkRobot(board)) { rController.removeRobotFromBoard(robot); } else { rController.setPreviousLocationAsNewLocation(robot); boardChecker.placeRobotOnBoard(board); } } else { UserIO.showMessage("Robot has not been placed yet. Try 'PLACE 0,0,NORTH'"); } } //Validate if what the user entered is correct at all. If not return an error else if (UserIO.validCommand(userInput) && boardChecker.isRobotPresentOnBoard(board) && rController.isRobotOnABoard(robot)) { //Move the robot rController.assignMove(robot, userInput); //If the robot is not in a valid position move it back. If it is in a valid position update the previous position. if (!boardChecker.checkRobot(board)) { rController.reverseMove(robot); } else { rController.setPreviousLocationAsNewLocation(robot); } } else { UserIO.showMessage("Please enter a valid movement."); } } }
public void Execute() { OrderManager manager = OrderManagerFactory.Create(); DateTime date = UserIO.GetDateFromUser("Enter the date the order was placed (example \"MM-DD-YYYY\"):"); DisplayOrderResponse response = manager.OrderLookup(date); if (response.Success) { ConsoleIO.DisplayOrderDetails(response.Order, response.Date); Order order = UserIO.GetOrderFromUser("Which order would you like to remove? (Use Order ID) :", response.Order); Console.Clear(); order.MaterialCost.ToString(); order.LaborCost.ToString(); order.Tax.ToString(); order.Total.ToString(); string line = "{0, 5} {1, 10} {2, 12} {3,8} {4, 15} {5, 15} {6, 12} {7, 9} {8, 9}"; Console.WriteLine(line, "Order ID", "Order Date", "Cust Name", "State", "Prod Type", "Material Cost", "Labor Cost", "Tax", "Total"); Console.WriteLine("_______________________________________________________________________________________"); string line2 = "{0, 5} {1, 12} {2, 9} {3, 10} {4, 14} {5, 12} {6, 16} {7, 11} {8, 11}"; Console.WriteLine(line2, order.OrderNumber, date.ToString("MM/dd/yyyy"), order.CustomerName, order.State, order.ProductType, String.Format("{0:0.00}", order.MaterialCost), String.Format("{0:0.00}", order.LaborCost), String.Format("{0:0.00}", order.Tax), String.Format("{0:0.00}", order.Total)); string input = null; while (input == null) { input = UserIO.GetYesOrNoFromUser("Do you want to remove this order?"); if (string.IsNullOrEmpty(input)) { Console.WriteLine("You must enter either Y or N"); Console.WriteLine("Press any key to try again"); Console.ReadKey(); input = null; } else { if (input != "Y" && input != "N") { Console.WriteLine("You must enter either Y or N"); Console.WriteLine("Press any key to try again"); Console.ReadKey(); input = null; } else if (input == "Y") { RemoveOrderResponse removeResponse = manager.OrderRemove(date, order.OrderNumber, order); if (removeResponse.Success == true) { Console.WriteLine(removeResponse.Message); Console.ReadKey(); } else { Console.WriteLine(removeResponse.Message); Console.ReadKey(); } } else if (input == "N") { Console.WriteLine("You have chosen to cancel the remove order request. It will not be removed. Press any to return to the main menuc"); Console.ReadKey(); } } } } else { Console.WriteLine("There are no orders from that date."); Console.WriteLine("Press any key to continue..."); Console.ReadKey(); } Console.Clear(); }
public static T Load <T>(string path) where T : class => UserIO.Load <T>(path, false);
//-------------------------------------------------------------------------------------------------------------------------------------- public void EditOrder() { List <Product> Products = new List <Product>(); try { Products = LoadProducts.LoadAllProducts(); } catch { Console.WriteLine("Could not load product data"); } List <State> States = new List <State>(); try { States = LoadStates.LoadAllStates(); } catch { Console.WriteLine("Could not load sales tax data"); } string date = PseudoDateSelect(); string filename = "Orders_" + date + ".txt"; //enusre write-ability string path = @"C:\repos\chris-williams-individual-work\FlooringMasteryV5\Data\Orders\" + filename; List <Order> CurrentOrders = new List <Order>(); if (!File.Exists(path)) { Console.WriteLine("Invalid date"); Console.WriteLine("Press any key to continue"); Console.ReadKey(); return; } try { LoadOrders current = new LoadOrders(); CurrentOrders = current.ParseFileData(filename); } catch { Console.WriteLine("Could not open specified file"); return; } Console.Clear(); Console.WriteLine($"Orders on {date}"); Console.WriteLine("Order#, Customer name, State, product type, area, total cost"); foreach (Order order in CurrentOrders) { Console.WriteLine($"{order.OrderNumber}, {order.CustomerName}, {order.State}, {order.Product}, {order.Area}, {order.Total:C}"); } bool GoodOrder = false; Order OrderToEdit = new Order(); while (!GoodOrder) { Console.WriteLine("Please enter the order number of the order you wish to edit"); int selection = UserIO.GetIntegerFromUser(); Order chosen = CurrentOrders.Where(o => o.OrderNumber == selection).FirstOrDefault(); if (chosen != null) { OrderToEdit = chosen; GoodOrder = true; break; } else { Console.WriteLine("Enter a valid order number"); } } Console.WriteLine($"The current Customer name is {OrderToEdit.CustomerName}"); Console.WriteLine("Enter a new name, or leave the field blank to retain the current name"); string namechange = Console.ReadLine(); // will need this to be better, maybe seperate into change name function if (namechange != "") { if (namechange[0].ToString() != " ") { OrderToEdit.CustomerName = namechange; Console.WriteLine($"Customer name changed to {OrderToEdit.CustomerName}"); } else { Console.WriteLine($"Customer name reamins {OrderToEdit.CustomerName}"); } } else { Console.WriteLine($"Customer name remains {OrderToEdit.CustomerName}"); } Console.WriteLine($"The current state is {OrderToEdit.State}"); UserIO.DisplayStates(); Console.WriteLine("Please enter the number associated with the customer's updated state"); string statechange = Console.ReadLine(); State Mystate = null; if (statechange != "") { if (statechange[0].ToString() != " ") { Mystate = EditState(States, statechange); OrderToEdit.State = Mystate.StateCode; OrderToEdit.TaxRate = Mystate.TaxRate; } else { Console.WriteLine($"State remains {OrderToEdit.State}"); Mystate = GetState(OrderToEdit.State, States); } } else { Console.WriteLine($"State remains {OrderToEdit.State}"); Mystate = GetState(OrderToEdit.State, States); } Console.Clear(); UserIO.DisplayProducts(); Console.WriteLine($"The current product selected is {OrderToEdit.Product}"); Console.WriteLine("please enter the new product, or leave the field empty to continue"); Product changedproduct = null; string productchange = Console.ReadLine(); if (productchange != "") { if (productchange[0].ToString() != " ") { bool isFinished = false; int productchangeIndex = 0; while (!isFinished) { bool goodInt = int.TryParse(productchange, out productchangeIndex); if (goodInt) { changedproduct = GetProductByIndex(productchangeIndex, Products); OrderToEdit.Product = changedproduct.ProductName; OrderToEdit.LaborCostPerSquareFoot = changedproduct.LaborCost; OrderToEdit.CostPerSquareFoot = changedproduct.CostperSquare; Console.WriteLine($"The product has been updated to {OrderToEdit.Product} with a material cost of of {OrderToEdit.CostPerSquareFoot:C}/ft^2, \nand a labor cost of {OrderToEdit.LaborCostPerSquareFoot:C}"); isFinished = true; } else { Console.WriteLine($"Please enter a valid index number in the range of 1 to {Products.Count}"); productchange = Console.ReadLine(); } } } else { Console.WriteLine($"Product remains {OrderToEdit.Product}"); changedproduct = GetMyProduct(OrderToEdit.Product, Products); } } else { Console.WriteLine($"Product remains {OrderToEdit.Product}"); changedproduct = GetMyProduct(OrderToEdit.Product, Products); } Console.WriteLine($"The current area is {OrderToEdit.Area}"); Console.WriteLine("please enter the new area, or leave the field empty to continue"); string areachange = Console.ReadLine(); if (areachange != "") { if (areachange[0].ToString() != " ") { OrderToEdit.Area = GetArea(areachange); Console.WriteLine($"The new area is {OrderToEdit.Area}"); } else { Console.WriteLine($"The area remains {OrderToEdit.Area}"); } } else { Console.WriteLine($"The area remains {OrderToEdit.Area}"); } OrderToEdit.ComputOrderValues(changedproduct, Mystate); Console.WriteLine($"The order now stands at:\n{ OrderToEdit.CustomerName}, in {OrderToEdit.State}, for {OrderToEdit.Area}ft^2 {OrderToEdit.Product} for a total of {OrderToEdit.Total:C}"); Console.WriteLine("Do you wish to save these these changes?"); Console.WriteLine("enter \'N\' to discard changes or any other key to keep changes?"); string SaveChoice = Console.ReadLine().ToUpper(); if (SaveChoice == "N") { Console.WriteLine("Changes Discared"); return; } else { try { using (StreamWriter sw = new StreamWriter(path)) { sw.WriteLine("OrderNumber,CustomerName,State,TaxRate,ProductType,Area,CostPerSquareFoot,LaborCostPerSquareFoot,MaterialCost,LaborCost,Tax,Total"); foreach (Order MyOrder in CurrentOrders) { sw.WriteLine($"{MyOrder.OrderNumber},\"{MyOrder.CustomerName}\",{MyOrder.State},{MyOrder.TaxRate},{MyOrder.Product},{MyOrder.Area},{MyOrder.CostPerSquareFoot},{MyOrder.LaborCostPerSquareFoot},{MyOrder.MaterialCost},{MyOrder.LaborCost},{MyOrder.Tax},{MyOrder.Total}"); } } } catch { Console.WriteLine("Could not write updated order to file"); return; } Console.WriteLine("Order edited"); } }