static void Main(string[] args) { // Make new instances of other classes UserInterface ui = new UserInterface(); BeverageCollection bc = new BeverageCollection(); // Prompt user for input int choice = ui.GetUserInput(); // Variables used in the switch statements int load = 0; int arraySpace = 3943; // Switch statement for the user's choice while (choice != 5) { switch (choice) { // Case for loading the csv file case 1: if (load == 0) { bc.CSVLoad(); ui.LoadChosen(load); load = 1; } else { ui.LoadChosen(load); } break; // Case for displaying the array case 2: bc.PrintString(); break; // Case for searching the array case 3: bc.Search(); break; // Case for adding to the array case 4: bc.Add(arraySpace); arraySpace++; break; // Case for exiting the console case 5: break; } // re-prompt user for input choice = ui.GetUserInput(); } }
/* |---------------------------------------------------------------------- | Public Methods |---------------------------------------------------------------------- */ // Public method to Import the CSV public bool ImportCSV(BeverageCollection beverages, string pathToCSVFile) { // Declare the streamreader StreamReader streamReader = null; // If it has already been imported if (hasBeenImported) { return(false); } // Has not been imported yet, so do the import. try { // Declare a string for the line string line; // Instantiate a new StreamReader class instance streamReader = new StreamReader(pathToCSVFile); // While still reading a line from the file while ((line = streamReader.ReadLine()) != null) { // Process the line this.processLine(line, beverages); } // Set hasBeenImported to true now that it is imported hasBeenImported = true; // Return true to represent success return(true); } catch (Exception e) { // Output the Error that occured. // This is the only output that is NOT // being done in the UI class Console.WriteLine(e.ToString()); Console.WriteLine(); Console.WriteLine(e.StackTrace); // Return false to signify that it failed return(false); } finally { // If the stream reader was instanciated, // make sure it is closed before exiting. if (streamReader != null) { streamReader.Close(); } } }
/**********************************************/ /* Program Main */ /**********************************************/ static void Main(string[] args) { UserInterface ui = new UserInterface(); CsvProcessor file = new CsvProcessor("../../../datafiles/beverage_list.csv"); BeverageCollection beverages = new BeverageCollection(4000, 100); string userInput = ""; do { switch (ui.GetUserInput(MenuOption.ShowMenu).Last()) { case "0": if (!file.DataLoaded) { if (file.Import(beverages) == null) { ui.Display("File loaded succesfully"); } else { ui.Display("Unable to load file. File may not be in correct directory."); } } else { ui.Display("Data file is already loaded"); } break; case "1": if (beverages.LastBeverage >= 0) { ui.Display(beverages.GetPrintString()); } else { ui.Display("No item's are in the inventory. Add items or load them from a CSV file."); } break; case "2": var values = ui.GetUserInput(MenuOption.AddItem); beverages.AddBeverage(values[0], values[1], values[2], decimal.Parse(values[3]), bool.Parse(values[4])); break; case "3": break; default: break; } } while (userInput != "exit"); }
public static void ProcessLine(string line, BeverageCollection collection) { var fields = line.Split(','); string id = fields[0].Trim(); string name = fields[1].Trim(); string pack = fields[2].Trim(); decimal price = Decimal.Parse(fields[3].Trim()); bool active = Convert.ToBoolean(fields[4].Trim()); collection.AddBeverage(id, name, pack, price, active); }
/* |---------------------------------------------------------------------- | Private Methods |---------------------------------------------------------------------- */ private void processLine(string line, BeverageCollection beverageCollection) { // Declare array of parts that will contain the // results of splitting the read in string. string[] parts = line.Split(','); // Assign each part to a variable string id = parts[0]; string name = parts[1]; string pack = parts[2]; decimal price = decimal.Parse(parts[3]); bool active = (parts[4] == "True"); // Add a new beverage into the collection with the properties // of what was read in. beverageCollection.AddNewItem(id, name, pack, price, active); }
/// <summary> /// Processes one line of the CSV file. Splits the line by delimiters (',') and stores each part /// as a member of a string array. Automatically parses price to decimal and active/inactive to bool. /// Lastly, calls the collection's AddABeverage() method and adds the beverage to the collection. /// </summary> /// <param name="line"></param> /// <param name="sodaStand"></param> /// <param name="index"></param> private void processCSVLine(string line, BeverageCollection sodaStand, int index) { // declare an array of parts that will contain the results of // splitting the string string[] parts = line.Split(','); // assign each part to a variable string id = parts[0]; string desc = parts[1]; string pack = parts[2]; //string price = parts[3]; decimal price = decimal.Parse(parts[3]); bool active = bool.Parse(parts[4]); // populate the list with one item sodaStand.AddABeverage(id, desc, pack, price, active); }
/// <summary> /// Method to search the beverage list by ID. Returns an error string if the beverage item was not found. Returns the /// beverage item as a string if the item was found. /// </summary> /// <param name="collection"></param> /// <returns>string</returns> public string SearchBeverageList(BeverageCollection collection) { string foundBeverage = ""; Console.Write("\n\t\t\t\tEnter the ID of the beverage you wish to search for: "); string id = Console.ReadLine().ToUpper(); if (collection.FindBeverageById(id) != null) { Console.ForegroundColor = ConsoleColor.Yellow; foundBeverage = "\n\t\t\t\tItem found:" + collection.FindBeverageById(id); } else { Console.ForegroundColor = ConsoleColor.Red; foundBeverage = "\n\t\t\t\tNo matching beverage item found."; } return(foundBeverage); }
/// <summary> /// Public method to import the CSV. Checks to see if the list is NOT loaded; if it isn't, it /// sends the CSV one line at a time to the ImportCSV() method. If the CSV is already loaded /// this method returns false. /// </summary> /// <param name="pathToCSV"></param> /// <param name="sodaStand"></param> /// <returns>bool</returns> public bool ImportCSV(string pathToCSV, BeverageCollection sodaStand) { StreamReader streamReader = null; if (!listIsLoaded) { try { string csvLine; streamReader = new StreamReader(pathToCSV); int counter = 0; while ((csvLine = streamReader.ReadLine()) != null) { this.processCSVLine(csvLine, sodaStand, counter++); } listIsLoaded = true; return(true); } catch (Exception e) { // output the exception Console.WriteLine(e.ToString()); Console.WriteLine(); Console.WriteLine(e.StackTrace); // return false if things went wrong return(false); } finally { if (streamReader != null) { streamReader.Close(); } } } else { return(false); } }
//Methods /*********************************************/ public Exception Import(BeverageCollection beverageCollection) { try { stream = new StreamReader(path); string line; while ((line = stream.ReadLine()) != null) { CsvProcessor.ProcessLine(line, beverageCollection); } dataLoaded = true; } catch (Exception e) { return(e); } finally { stream.Close(); } return(null); }
static void Main(string[] args) { // Set Console Window Size Console.BufferHeight = Int16.MaxValue - 1; Console.WindowHeight = 40; Console.WindowWidth = 120; // Set a constant for the size of the collection const int beverageCollectionSize = 4000; // Set a constant for the path to the CSV File const string pathToCSVFile = "../../../datafiles/beverage_list.csv"; // Create an instance of the UserInterface class UserInterface userInterface = new UserInterface(); // Create an instance of the BeverageCollection class BeverageCollection beverageCollection = new BeverageCollection(beverageCollectionSize); // Create an instance of the CSVProcessor class CSVProcessor csvProcessor = new CSVProcessor(); // Display the Welcome Message to the user userInterface.DisplayWelcomeGreeting(); // Display the Menu and get the response. Store the response in the choice integer // This is the 'primer' run of displaying and getting. int choice = userInterface.DisplayMenuAndGetResponse(); // While the choice is not exit program while (choice != 5) { switch (choice) { case 1: // Load the CSV File bool success = csvProcessor.ImportCSV(beverageCollection, pathToCSVFile); if (success) { // Display Success Message userInterface.DisplayImportSuccess(); } else { // Display Fail Message userInterface.DisplayImportError(); } break; case 2: // Print Entire List Of Items string allItemsString = beverageCollection.ToString(); if (!String.IsNullOrWhiteSpace(allItemsString)) { // Display all of the items userInterface.DisplayAllItems(allItemsString); } else { // Display error message for all items userInterface.DisplayAllItemsError(); } break; case 3: // Search For An Item string searchQuery = userInterface.GetSearchQuery(); string itemInformation = beverageCollection.FindById(searchQuery); if (itemInformation != null) { userInterface.DisplayItemFound(itemInformation); } else { userInterface.DisplayItemFoundError(); } break; case 4: // Add A New Item To The List string[] newItemInformation = userInterface.GetNewItemInformation(); if (beverageCollection.FindById(newItemInformation[0]) == null) { beverageCollection.AddNewItem( newItemInformation[0], newItemInformation[1], newItemInformation[2], decimal.Parse(newItemInformation[3]), (newItemInformation[4] == "True") ); userInterface.DisplayAddWineItemSuccess(); } else { userInterface.DisplayItemAlreadyExistsError(); } break; } // Get the new choice of what to do from the user choice = userInterface.DisplayMenuAndGetResponse(); } }
static void Main(string[] args) { // Making a new instance of UI class UserInterface ui = new UserInterface(); // Making a new instance of the Beverage class Beverage beverageList = new Beverage("39171", "1221 Cabernet Cuvee", "6 / 750 ml", 70.1m, "TRUE"); // Makes an array to hold instances in Beverage class Beverage[] beverages = new Beverage[3942]; // Making a new instance of the BeverageCollection class BeverageCollection bevCollection = new BeverageCollection(); // Make instance of CSVProcessor CSVProcessor csvProcessor = new CSVProcessor(); // Makes an array to hold instances in BeverageCollection class BeverageCollection[] beveragesCollection = new BeverageCollection[3942]; // Get input from the user int choice = ui.UserInput(); // While the choice they selected is not 5, continue to do work while (choice != 5) { // Load the list if (choice == 1) { // Make a string for the path to the csv file string pathToCsv = "../../../datafiles/beverage_list.csv"; // starts at bin debug. Each .. goes back one folder // Call the ImportCSV method sending over the path and the array to store the read in records to. csvProcessor.ImportCsv(pathToCsv, beverages); } // Print out list if (choice == 2) { // Create a string that can be concated t string outputString = ""; //// Print out the beverages in an array foreach (Beverage beverage in beverages) { // Check to ensure there is a beverage object to be able to access properties on if (beverage != null) { outputString += beverage.ToString() + Environment.NewLine; } } // Call UI method to output list ui.OptionTwo(outputString); Console.WriteLine(); // Empty space } // Search for beverage if (choice == 3) { // Call the ImportCSV method sending over the array to search csvProcessor.Search(beverages); Console.WriteLine(); // Empty space } // Add a new beverage if (choice == 4) { Console.WriteLine(); // Empty space } // Re-display for input choice = ui.UserInput(); } }
/// <summary> /// Main program entry point. /// </summary> /// <param name="args"></param> static void Main(string[] args) { const int sodaStandSize = 4000; string pathToCSV = "../../../datafiles/beverage_list.csv"; string menuChoice = null; UserInterface aMenu = new UserInterface(); BeverageCollection sodaStand = new BeverageCollection(sodaStandSize); CSVProcessor csvProcessor = new CSVProcessor(); DisplayMenu(); /// Displays the menu and calls HandleInput to deal with the user's response stored in the variable menuChoice. void DisplayMenu() { Console.Clear(); Console.Write(aMenu.DisplayMenu()); Console.Write("\n\n\t\t\t\t"); menuChoice = Console.ReadLine(); HandleInput(menuChoice); } /// Handles the user's input via a switch. Each menu function is encapsulated within each case. /// The work done on the user's choice is done in other classes; the output is handled by the /// UserInterface class. /// void HandleInput(string userSelection) { userSelection = userSelection.ToUpper(); switch (userSelection) { // Loads the beverage list. Note that this is the only location we call ImportCSV() from. case "L": Console.WriteLine(aMenu.LoadListMessage()); bool loadedSuccessfully = csvProcessor.ImportCSV(pathToCSV, sodaStand); if (loadedSuccessfully) { Console.Write(aMenu.LoadSuccess()); aMenu.Pause(); } else { // We don't want to try to reload the list again so we use the public boolean variable // that is set from within the class. We use this in any situation where we don't want // the user to do a thing until the list is loaded (add, search...). if (csvProcessor.listIsLoaded) { Console.Write(aMenu.AlreadyLoaded()); aMenu.Pause(); } else { Console.Write(aMenu.LoadFailure()); } aMenu.Pause(); } DisplayMenu(); break; case "P": // Print the list. Burp if the list isn't loaded yet. aMenu.PrintListMessage(); if (!csvProcessor.listIsLoaded) { Console.Write(aMenu.NothingToPrint()); aMenu.Pause(); } else { string[] allBeverages = sodaStand.PrintTheBeveragesInventory(); aMenu.PrintBeverageList(allBeverages); } aMenu.Pause(); DisplayMenu(); break; case "S": // Search the list. Burp if the list isn't loaded yet. aMenu.SearchListMessage(); if (!csvProcessor.listIsLoaded) { Console.Write(aMenu.NothingToSearch()); aMenu.Pause(); } else { Console.Write(aMenu.SearchBeverageList(sodaStand)); } aMenu.Pause(); DisplayMenu(); break; case "A": // Add to the list. Burp if the list isn't loaded yet. if (!csvProcessor.listIsLoaded) { Console.Write(aMenu.CannotAddUntilLoaded()); aMenu.Pause(); } else { string[] beverageToAdd = aMenu.AddABeverage(); if (sodaStand.FindBeverageById(beverageToAdd[0]) == null) { sodaStand.AddABeverage(beverageToAdd[0], beverageToAdd[1], beverageToAdd[2], decimal.Parse(beverageToAdd[3]), bool.Parse(beverageToAdd[4])); Console.Write(aMenu.BeverageAdded()); aMenu.Pause(); } else { Console.Write(aMenu.BeverageExists()); aMenu.Pause(); } } aMenu.Pause(); DisplayMenu(); break; // Quit the program. Quits regardless of whether the list is loaded. Never burps. case "Q": Console.WriteLine(aMenu.QuitProgramMessage()); aMenu.Pause(); Environment.Exit(0); break; // The default option is invoked for any choices not on the menu. This may be an invalid // entry or a blank entry. In either case, error is shown in red and the menu is simply redrawn. default: aMenu.InvalidOptionMessage(); aMenu.Pause(); DisplayMenu(); break; } } }