public void Start() { Console.WriteLine("\tADD CATEGORY\n"); string categoryName; string description; NLogger logging = new NLogger(); Console.WriteLine("Please enter the new Category name. (Required)"); categoryName = StringValidation(Console.ReadLine()); Console.WriteLine("What is the description of the new category?"); description = StringValidation(Console.ReadLine()); Category category = new Category { CategoryName = categoryName, Description = description }; if (ConfirmSelections(category) == true) { NorthwindContext db = new NorthwindContext(); db.AddCategory(category); } else { logging.Log("INFO", "Operation Cancelled."); } }
public static void Main(string[] args) { logger.Info("Program started"); try { string choice; do { Console.WriteLine("Category Database Options:"); Console.WriteLine("--------------------------"); Console.WriteLine("1) Display Categories"); Console.WriteLine("2) Display one Category and its related products"); Console.WriteLine("3) Display all Categories and their related products"); Console.WriteLine("4) Add Category"); Console.WriteLine("5) Edit a Category"); Console.WriteLine(""); Console.WriteLine("Product Database Options:"); Console.WriteLine("-------------------------"); Console.WriteLine("6) Display Products"); Console.WriteLine("7) Display Specific Product Info"); Console.WriteLine("8) Add Product"); Console.WriteLine("9) Edit Product Info"); Console.WriteLine(""); Console.WriteLine("\"q\" to quit"); Console.Write("==>"); choice = Console.ReadLine(); Console.WriteLine(""); Console.Clear(); logger.Info($"Option {choice} selected"); if (choice == "1") { //display all categories var db = new NorthwindContext(); DisplayCategories(db); } else if (choice == "2") { //display one category and all of its active related products var db = new NorthwindContext(); var query = db.Categories.Include("Products").OrderBy(p => p.CategoryId); Console.WriteLine("Select the category whose products you want to display:"); DisplayCategories(db); Console.Write("==>"); int id = int.Parse(Console.ReadLine()); Console.WriteLine(""); Console.Clear(); logger.Info($"CategoryId {id} selected"); Console.WriteLine(""); Category category = db.Categories.FirstOrDefault(c => c.CategoryId == id); Console.WriteLine($"{category.CategoryName} - {category.Description}"); foreach (Product p in category.Products.Where(ap => ap.Discontinued == false)) { Console.WriteLine(p.ProductName); } Console.WriteLine(""); } else if (choice == "3") { //display all categories and all of their active related products var db = new NorthwindContext(); var query = db.Categories.Include("Products").OrderBy(p => p.CategoryId); foreach (var item in query) { Console.WriteLine($"{item.CategoryName}"); foreach (Product p in item.Products.Where(ap => ap.Discontinued == false)) { Console.WriteLine($"\t{p.ProductName}"); } } Console.WriteLine(""); } else if (choice == "4") { //add category Category category = new Category(); Console.Write("Enter Category Name: "); category.CategoryName = Console.ReadLine(); Console.Write("Enter the Category Description: "); category.Description = Console.ReadLine(); ValidationContext context = new ValidationContext(category, null, null); List <ValidationResult> results = new List <ValidationResult>(); var isValid = Validator.TryValidateObject(category, context, results, true); if (isValid) { var db = new NorthwindContext(); // check for unique name if (db.Categories.Any(c => c.CategoryName == category.CategoryName)) { // generate validation error isValid = false; results.Add(new ValidationResult("Name exists", new string[] { "CategoryName" })); Console.WriteLine(""); } else { logger.Info("Validation passed"); //save category to db db.AddCategory(category); logger.Info("Category added - {name}", category.CategoryName); Console.WriteLine(""); } } if (!isValid) { foreach (var result in results) { logger.Error($"{result.MemberNames.First()} : {result.ErrorMessage}"); Console.WriteLine(""); } } } else if (choice == "5") { //edit an existing category var db = new NorthwindContext(); Console.WriteLine("Choose the category you wish to edit:"); var category = GetCategory(db); Category UpdatedCategory = InputCategory(db); if (UpdatedCategory != null) { UpdatedCategory.CategoryId = category.CategoryId; db.EditCategory(UpdatedCategory); logger.Info("Category (id: {categoryid}) updated", category.CategoryId); Console.WriteLine(""); } } else if (choice == "6") { //display products depending on user choice string displayChoice; do { Console.WriteLine("Which products would you like displayed?"); Console.WriteLine("1) All Products"); Console.WriteLine("2) Active Products"); Console.WriteLine("3) Discontinued Products"); Console.WriteLine("4) Return to main menu"); Console.Write("==>"); displayChoice = Console.ReadLine(); Console.WriteLine(""); Console.Clear(); logger.Info($"Option {displayChoice} selected"); Console.WriteLine(""); if (displayChoice == "1") { //display all products var db = new NorthwindContext(); var query = db.Products.OrderBy(p => p.ProductName); Console.WriteLine($"{query.Count()} product records returned"); Console.WriteLine(""); foreach (var item in query) { Console.WriteLine($"{item.ProductID}) {item.ProductName}"); } Console.WriteLine(""); } else if (displayChoice == "2") { //display all ative products var db = new NorthwindContext(); var query = db.Products.Where(p => p.Discontinued == false).OrderBy(p => p.ProductName); Console.WriteLine($"{query.Count()} active product records returned"); Console.WriteLine(""); foreach (var item in query) { Console.WriteLine($"{item.ProductID} - {item.ProductName}"); } Console.WriteLine(""); } else if (displayChoice == "3") { //display all discontinued products var db = new NorthwindContext(); var query = db.Products.Where(p => p.Discontinued == true).OrderBy(p => p.ProductName); Console.WriteLine($"{query.Count()} discontinued product records returned"); Console.WriteLine(""); foreach (var item in query) { Console.WriteLine($"{item.ProductID} - {item.ProductName}"); } Console.WriteLine(""); } }while (displayChoice != "4"); } else if (choice == "7") { //display all info for a specific product var db = new NorthwindContext(); var query = db.Products.OrderBy(p => p.ProductID); Console.WriteLine("Select the product for which you want to see more info:"); foreach (var item in query) { Console.WriteLine($"{item.ProductID}) {item.ProductName}"); } Console.Write("==>"); int id = int.Parse(Console.ReadLine()); Console.Clear(); logger.Info($"ProductId {id} selected"); Console.WriteLine(""); Product product = db.Products.FirstOrDefault(p => p.ProductID == id); Console.WriteLine($"Product Name: {product.ProductName}"); Console.WriteLine($"Supplier ID: {product.SupplierId}"); Console.WriteLine($"Category ID: {product.CategoryId}"); Console.WriteLine($"Quantity Per Unit: {product.QuantityPerUnit}"); Console.WriteLine($"Unit Price: {product.UnitPrice}"); Console.WriteLine($"Units in Stock: {product.UnitsInStock}"); Console.WriteLine($"Units on Order: {product.UnitsOnOrder}"); Console.WriteLine($"Reorder Level: {product.ReorderLevel}"); Console.WriteLine($"Discontinued: {product.Discontinued}"); Console.WriteLine(""); } else if (choice == "8") { //add new product var db = new NorthwindContext(); Product product = new Product(); Console.Write("Enter Product Name: "); product.ProductName = Console.ReadLine(); Console.WriteLine("Enter the Supplier ID from the list below:"); DisplaySuppliers(db); Console.Write("==>"); product.SupplierId = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("Enter the Cateogry ID from the list below:"); DisplayCategories(db); Console.Write("==>"); product.CategoryId = Convert.ToInt32(Console.ReadLine()); Console.Write("Enter Quantity Per Unit: "); product.QuantityPerUnit = Console.ReadLine(); Console.Write("Enter Unit Price: "); product.UnitPrice = Convert.ToDecimal(Console.ReadLine()); Console.Write("Enter Units in Stock: "); product.UnitsInStock = Convert.ToInt16(Console.ReadLine()); Console.Write("Enter Units on Order: "); product.UnitsOnOrder = Convert.ToInt16(Console.ReadLine()); Console.Write("Enter Reorder Level: "); product.ReorderLevel = Convert.ToInt16(Console.ReadLine()); product.Discontinued = false; ValidationContext context = new ValidationContext(product, null, null); List <ValidationResult> results = new List <ValidationResult>(); var isValid = Validator.TryValidateObject(product, context, results, true); if (isValid) { // check for unique name if (db.Products.Any(p => p.ProductName == product.ProductName)) { // generate validation error isValid = false; results.Add(new ValidationResult("Name exists", new string[] { "ProductName" })); Console.WriteLine("Product was not added to the database"); Console.WriteLine(""); } else { logger.Info("Validation passed"); //save category to db db.AddProduct(product); logger.Info("Product added - {name}", product.ProductName); Console.WriteLine(""); } } if (!isValid) { foreach (var result in results) { logger.Error($"{result.MemberNames.First()} : {result.ErrorMessage}"); } Console.WriteLine(""); } } else if (choice == "9") { //edit an existing product var db = new NorthwindContext(); Console.WriteLine("Choose the product you wish to edit:"); var product = GetProduct(db); Product UpdatedProduct = InputProduct(db); if (UpdatedProduct != null) { UpdatedProduct.ProductID = product.ProductID; db.EditProduct(UpdatedProduct); logger.Info("Product (id: {productid}) updated", product.ProductID); Console.WriteLine(""); } } Console.WriteLine(); } while (choice.ToLower() != "q"); } catch (Exception ex) { logger.Error(ex.Message); } logger.Info("Program ended"); }
public static void Main(string[] args) { logger.Info("Program started"); try { string choice; do { Console.WriteLine(); Console.WriteLine(" 1) Display Product"); Console.WriteLine(" 2) Add Product"); Console.WriteLine(" 3) Edit Product"); Console.WriteLine(" 4) Delete Product"); Console.WriteLine(" 5) Display Category"); Console.WriteLine(" 6) Add Category"); Console.WriteLine(" 7) Edit Category"); Console.WriteLine(" 8) Delete Category"); Console.WriteLine(" \"q\" to quit"); choice = Console.ReadLine(); Console.Clear(); logger.Info($"Option {choice} selected"); Console.WriteLine(); if (choice == "1") // Display Product { string displayChoice = ""; // display choices to user Console.WriteLine(" 1) Display Active Products " + "\n 2) Display Discontinued Products " + "\n 3) Display All Products " + "\n 4) Display Product Detail"); Console.WriteLine(" Enter to quit"); // input selection displayChoice = Console.ReadLine().ToUpper(); Console.Clear(); logger.Info($"Display choice: {displayChoice} selected"); Console.WriteLine(); var db = new NorthwindContext(); if (displayChoice == "1") // Display Active Products { var query = db.Products.OrderBy(p => p.ProductName).Where(b => !b.Discontinued); foreach (var item in query) { Console.WriteLine(" " + item.ProductName); } Console.WriteLine($"\n{query.Count()} active records returned"); logger.Info($"{query.Count()} active records returned"); } else if (displayChoice == "2") // Display Discontinued Products { var query = db.Products.OrderBy(p => p.ProductName).Where(b => b.Discontinued); foreach (var item in query) { Console.WriteLine(" " + item.ProductName); } Console.WriteLine($"\n{query.Count()} discontinued records returned"); logger.Info($"{query.Count()} discontinued records returned"); } else if (displayChoice == "3") // Display All Products { var query = db.Products.OrderBy(p => p.ProductName); foreach (var item in query) { Console.WriteLine(" " + item.ProductName); } Console.WriteLine($"\n{query.Count()} total records returned"); logger.Info($"{query.Count()} total records returned"); } else if (displayChoice == "4") // Display Product Detail { var product = GetProduct(db, "Select the Product ID to Display", false); if (product != null) { Console.WriteLine("\n Product ID: {0,-20}", product.ProductId); Console.WriteLine(" Product Name: {0,-20}", product.ProductName); Console.WriteLine(" Category ID: {0,-40}", product.CategoryId); Console.WriteLine(" Supplier ID: {0,-20}", product.SupplierId); Console.WriteLine($" Quantity per Unit: {product.QuantityPerUnit} "); Console.WriteLine(" Unit Price: {0,-20:C}", product.UnitPrice); Console.WriteLine($" Units In Stock: {product.UnitsInStock} "); Console.WriteLine($" Units On Order: {product.UnitsOnOrder} "); Console.WriteLine($" Reorder Level: {product.ReorderLevel} "); Console.WriteLine($" Discontinued: {product.Discontinued} \n"); logger.Info("Product (id: {productid}) displayed", product.ProductId); } } } else if (choice == "2") // Add Product { Product product = new Product(); NorthwindContext db = new NorthwindContext(); Console.WriteLine(" Enter Product Name:"); product.ProductName = Console.ReadLine(); ValidationContext context = new ValidationContext(product, null, null); List <ValidationResult> results = new List <ValidationResult>(); var isValid = Validator.TryValidateObject(product, context, results, true); if (product.ProductName != "") { // check for unique product name if (db.Products.Any(p => p.ProductName == product.ProductName)) { Console.WriteLine("Product is already in the database"); } else { // allow user to select the category for the product Category category = new Category(); var query = db.Categories.OrderBy(p => p.CategoryName); Console.WriteLine(); if (query.Count() == 0) { Console.WriteLine($" <No Categories>"); } else { foreach (var item in query) { Console.WriteLine($" {item.CategoryId}) {item.CategoryName} - {item.Description}"); } } Console.WriteLine("\n Enter the Category ID for the Product"); if (int.TryParse(Console.ReadLine(), out int intProdCat)) { var valCategory = db.Categories.FirstOrDefault(c => c.CategoryId == intProdCat); if (valCategory != null) { logger.Info($"CategoryId {intProdCat} {valCategory.CategoryName} selected"); Console.WriteLine(" Enter the Quantity per Unit:"); product.QuantityPerUnit = Console.ReadLine(); Console.WriteLine(" Enter the Unit Price:"); if (decimal.TryParse(Console.ReadLine(), out decimal UnitPrice)) { product.UnitPrice = UnitPrice; Console.WriteLine(" Enter the Units in Stock:"); if (short.TryParse(Console.ReadLine(), out short UnitsInStock)) { product.UnitsInStock = UnitsInStock; Console.WriteLine(" Enter the Units on Order:"); if (short.TryParse(Console.ReadLine(), out short UnitsOnOrder)) { product.UnitsOnOrder = UnitsOnOrder; Console.WriteLine(" Enter the Reorder Level:"); if (short.TryParse(Console.ReadLine(), out short Reorder)) { product.ReorderLevel = Reorder; Console.WriteLine(" Has this product been discontinued?"); var YorN = Console.ReadLine(); if (YorN.ToUpper() == "N") { product.Discontinued = false; } else { product.Discontinued = true; } logger.Info("Validation passed"); var productDb = new Product { ProductName = product.ProductName, CategoryId = intProdCat, QuantityPerUnit = product.QuantityPerUnit, UnitPrice = product.UnitPrice, UnitsOnOrder = product.UnitsOnOrder, UnitsInStock = product.UnitsInStock, ReorderLevel = product.ReorderLevel, Discontinued = product.Discontinued }; db.AddProduct(productDb); logger.Info("Product added - {name}", product.ProductName); } else { logger.Info("Invalid Reorder Level"); } } else { logger.Info("Invalid Units On Order"); } } else { logger.Info("Invalid Units In Stock"); } } else { logger.Info("Invalid Price"); } } else { logger.Info("Category Not Found"); } } else { logger.Info("Invalid Category"); } } } else { logger.Info("Product Name is Required"); } } else if (choice == "3") // Edit Product { var db = new NorthwindContext(); var product = GetProduct(db, "Select the Product ID to Update", true); if (product != null) { Product saveProduct = product; // input product Product UpdatedProduct = InputProduct(db, saveProduct); if (UpdatedProduct != null) { UpdatedProduct.ProductId = product.ProductId; db.EditProduct(UpdatedProduct); logger.Info("Product (id: {productid}) updated", UpdatedProduct.ProductId); } } } else if (choice == "4") // Delete Product { var db = new NorthwindContext(); var product = GetProduct(db, "Select the Product ID to Delete", true); if (product != null) { Console.WriteLine("Are you sure you want to delete " + product.ProductName + "?(y/n)"); String answer = Console.ReadLine(); if (answer.ToUpper() == "Y") { db.DeleteProduct(product); logger.Info("Product (id: {productid}) deleted", product.ProductId); } else { Console.WriteLine(product.ProductName + " was not deleted."); } } } else if (choice == "5") { string displayChoice = ""; // display choices to user Console.WriteLine(" 1) Display Categories " + "\n 2) Display Category and Related Products" + "\n 3) Display All Categories and Their Related Products"); // input selection displayChoice = Console.ReadLine().ToUpper(); Console.Clear(); logger.Info($"Display choice: {displayChoice} selected"); Console.WriteLine(); var db = new NorthwindContext(); if (displayChoice == "1") // Display Categories { var query = db.Categories.OrderBy(p => p.CategoryName); foreach (var item in query) { Console.WriteLine($" {item.CategoryName} - {item.Description}"); } Console.WriteLine($"\n{query.Count()} records returned"); logger.Info($"{query.Count()} records returned"); } else if (displayChoice == "2") // Display Category and Related Products { var query = db.Categories.OrderBy(p => p.CategoryId); foreach (var item in query) { Console.WriteLine($" {item.CategoryId}) {item.CategoryName}"); } Console.WriteLine("\nSelect the category whose products you want to display:"); int id = int.Parse(Console.ReadLine()); var valCategory = (db.Categories.FirstOrDefault(c => c.CategoryId == id)); while (valCategory == null) { logger.Error($"CategoryId {id} selected"); Console.WriteLine(" Choose a Category ID from above"); id = int.Parse(Console.ReadLine()); valCategory = (db.Categories.FirstOrDefault(c => c.CategoryId == id)); } Console.Clear(); logger.Info($"CategoryId {id} selected"); Category category = db.Categories.FirstOrDefault(c => c.CategoryId == id); Console.WriteLine($" {category.CategoryName} - {category.Description}"); if (category.Products.Where(c => !c.Discontinued).Count() == 0) { if (category.CategoryId == archive) // Archive category only contains discontinued items { int count = 0; foreach (Product p in category.Products.Where(c => c.Discontinued).OrderBy(c => c.ProductName)) { Console.WriteLine("\t" + p.ProductName); count++; } logger.Info($"{count} products returned"); } else { Console.WriteLine($" <No Active Products>"); } } else { int count = 0; foreach (Product p in category.Products.Where(c => !c.Discontinued).OrderBy(c => c.ProductName)) { Console.WriteLine("\t" + p.ProductName); count++; } logger.Info($"{count} products returned"); } } else if (displayChoice == "3") // Display All Categories and Their Related Products { int ttlCount = 0; var query = db.Categories.Include("Products").OrderBy(p => p.CategoryId); foreach (var item in query) { int count = 0; Console.WriteLine($" {item.CategoryName}"); if (item.Products.Count() == 0) { Console.WriteLine($" <No Products>"); } else { if (item.CategoryId == archive) // Archive category only contains discontinued items { foreach (Product p in item.Products.Where(c => c.Discontinued).OrderBy(c => c.ProductName)) { Console.WriteLine($"\t{p.ProductName}"); count++; ttlCount++; } } else { foreach (Product p in item.Products.Where(c => !c.Discontinued).OrderBy(c => c.ProductName)) { Console.WriteLine($"\t{ p.ProductName}"); count++; ttlCount++; } } } } logger.Info($"{ttlCount} total products returned"); } } else if (choice == "6") // Add Category { Category category = new Category(); Console.WriteLine(" Enter Category Name:"); category.CategoryName = Console.ReadLine(); Console.WriteLine(" Enter the Category Description:"); category.Description = Console.ReadLine(); ValidationContext context = new ValidationContext(category, null, null); List <ValidationResult> results = new List <ValidationResult>(); var isValid = Validator.TryValidateObject(category, context, results, true); if (isValid) { var db = new NorthwindContext(); // check for unique name if (db.Categories.Any(c => c.CategoryName == category.CategoryName)) { // generate validation error isValid = false; results.Add(new ValidationResult("Name exists", new string[] { "CategoryName" })); } else { logger.Info("Validation passed"); var categoryDb = new Category { CategoryName = category.CategoryName, Description = category.Description }; db.AddCategory(categoryDb); logger.Info("Category added - {name}", category.CategoryName); } } if (!isValid) { foreach (var result in results) { logger.Error($"{result.MemberNames.First()} : {result.ErrorMessage}"); } } } else if (choice == "7") // Edit Category { var db = new NorthwindContext(); var query = db.Categories.OrderBy(p => p.CategoryId); foreach (var item in query) { Console.WriteLine($" {item.CategoryId}) {item.CategoryName}"); } Console.WriteLine("\nSelect The Category You Want to Update:"); if (int.TryParse(Console.ReadLine(), out int id)) { Category category = db.Categories.FirstOrDefault(c => c.CategoryId == id); if (category != null) { logger.Info($"CategoryId {id} selected"); Category saveCategory = category; // input category Category UpdatedCategory = InputCategory(db, saveCategory); if (UpdatedCategory != null) { UpdatedCategory.CategoryId = category.CategoryId; db.EditCategory(UpdatedCategory); logger.Info("Category (id: {categoryid}) updated", UpdatedCategory.CategoryId); } Console.WriteLine($"{category.CategoryName} - {category.Description}"); } else { logger.Info("Category not Found"); } } else { logger.Info("Invalid Category ID"); } } else if (choice == "8") // Delete Category and inactivate and move Products to Archive Category { var db = new NorthwindContext(); var query = db.Categories.OrderBy(p => p.CategoryId); foreach (var item in query) { Console.WriteLine($" {item.CategoryId}) {item.CategoryName} - {item.Description}"); } if (int.TryParse(Console.ReadLine(), out int id)) { Category category = db.Categories.FirstOrDefault(c => c.CategoryId == id); if (category != null) { var valCategory = (db.Categories.FirstOrDefault(c => c.CategoryId == id)); logger.Info($"CategoryId {id} {valCategory.CategoryName} selected"); if (id == archive) // Archive Category { Console.WriteLine("Archive Category Cannot Be Deleted"); } else { // Confirm Delete Category delCategory = db.Categories.FirstOrDefault(p => p.CategoryId == id); Console.WriteLine("Are you sure you want to delete " + category.CategoryName + "? (y/n)"); String answer = Console.ReadLine(); if (answer.ToUpper() == "Y") { db.Database.ExecuteSqlCommand("UPDATE Products SET Discontinued = 'true', " + "CategoryId = 22 WHERE CategoryID = " + id); db.Database.ExecuteSqlCommand("DELETE FROM Categories WHERE CategoryId = " + id); logger.Info("Category (id: {categoryid}) deleted", id); } else { Console.WriteLine("Category ID " + id + " was not deleted."); } } } else { logger.Info("Category not Found"); } } else { logger.Info("Invalid Category ID"); } } if (choice != "1" && choice != "2" && choice != "3" && choice != "4" && choice != "5" && choice != "6" && choice != "7" && choice != "8" && choice != "9" && choice.ToLower() != "q") { Console.WriteLine(" Choose a Valid Menu Option"); logger.Info($"Invalid choice made: {choice}"); } } while (choice.ToLower() != "q"); } catch (Exception ex) { logger.Error(ex.Message); } logger.Info("Program ended"); }
public static void Main(string[] args) { logger.Info("Program started"); NorthwindContext NWContext = new NorthwindContext(); try { string choice; do { Console.WriteLine("1) Display Categories"); Console.WriteLine("2) Add Category"); Console.WriteLine("3) Display Category and related products"); Console.WriteLine("4) Display all Categories and their related products"); Console.WriteLine("5) Add Records"); Console.WriteLine("6) Edit Category"); Console.WriteLine("7) Delete Category"); Console.WriteLine("8) Edit Product"); Console.WriteLine("9) Delete Product"); Console.WriteLine("10) Display Products"); Console.WriteLine("\"q\" to quit"); choice = Console.ReadLine(); Console.Clear(); logger.Info($"Option {choice} selected"); switch (choice) { case "1": Console.Clear(); NWContext.DisplayCategories(); break; case "2": Console.Clear(); NWContext.AddCategory(); break; case "3": Console.Clear(); NWContext.DisplayCategoriesAndProducts(); break; case "4": Console.Clear(); NWContext.DisplayAll(); break; case "5": Console.Clear(); NWContext.AddRecord(); break; case "6": Console.Clear(); NWContext.EditCategory(); break; case "7": Console.Clear(); NWContext.DeleteCategory(); break; case "8": Console.Clear(); NWContext.EditProduct(); break; case "9": Console.Clear(); NWContext.DeleteProduct(); break; case "10": Console.Clear(); NWContext.DisplayProducts(); break; default: //Console.Clear(); //NWContext.ListSuppliers(); break; } } while (choice.ToLower() != "q"); } catch (Exception ex) { logger.Error(ex.Message); } logger.Info("Program ended"); }
public static void Main(string[] args) { logger.Info("Program started"); try { Format f = new Format(); int choice; do { f.MainMenu(); choice = f.validateInt(Console.ReadLine()); Console.Clear(); logger.Info($"Option {choice} selected"); //Add Category if (choice == 1) { Category category = new Category(); Console.Clear(); f.AddCategoryHeader(); Console.Write(" Enter Category Name: "); category.CategoryName = Console.ReadLine(); Console.Clear(); f.AddCategoryHeader(); Console.Write(" Enter the Category Description: "); category.Description = Console.ReadLine(); ValidationContext context = new ValidationContext(category, null, null); List<ValidationResult> results = new List<ValidationResult>(); var isValid = Validator.TryValidateObject(category, context, results, true); if (isValid) { var db = new NorthwindContext(); // check for unique name if (db.Categories.Any(c => c.CategoryName == category.CategoryName)) { // generate validation error isValid = false; results.Add(new ValidationResult("Name exists", new string[] { "CategoryName" })); } else { logger.Info("Validation passed"); Console.Clear(); db.AddCategory(category); f.AddCategoryHeader(); Console.Write("\n Category Added Successfully! Press any key to return to the Main Menu: "); Console.ReadKey(); Console.Clear(); } } if (!isValid) { foreach (var result in results) { logger.Error($"{result.MemberNames.First()} : {result.ErrorMessage}"); } } } //Edit Category else if (choice == 2) { var db = new NorthwindContext(); var query = db.Categories.OrderBy(b => b.CategoryId); Console.Clear(); f.EditCategoryHeader(); var category = ShowCategory(db); if (category != null) { Category UpdatedCategory = InputCategroy(db); if (UpdatedCategory != null) { UpdatedCategory.CategoryId = category.CategoryId; db.EditCategory(UpdatedCategory); Console.WriteLine(" Category Successfully Updated!"); // logger.Info("Post (id: {postid}) updated", UpdatedPost.PostId); } } Console.Write("\n Press any key to continue: "); Console.ReadKey(); Console.Clear(); } //View Category else if (choice == 3) { var db = new NorthwindContext(); Console.Clear(); f.ViewCategoryHeader(); Console.ResetColor(); Console.WriteLine("\n 1) View All Categories"); Console.WriteLine(" 2) View Categories and their related Products"); Console.WriteLine(" 3) View a specific Category and its related Products"); Console.Write(" "); int all = f.validateInt(Console.ReadLine()); do { if (all > 3) { Console.Write(" Please choose from 1 or 3 "); all = f.validateInt(Console.ReadLine()); } } while (all > 3); if (all == 1) { var categories = db.Categories.OrderBy(b => b.CategoryId); Console.Clear(); f.ViewAllCategoryHeader(); foreach (Category p in categories) { Console.WriteLine(f.ViewCategoriesFormat(), p.CategoryId, p.CategoryName, p.Description); } Console.ResetColor(); Console.Write("\n Press any key to continue: "); Console.ReadKey(); Console.Clear(); } else if (all == 2) { { var query = from p in db.Products.OrderBy(b => b.CategoryId) join c in db.Categories on p.CategoryId equals c.CategoryId where p.Discontinued == false select new { prodid = p.ProductID, prodname = p.ProductName, catid = c.CategoryId, catname = c.CategoryName, catdesc = c.Description }; Console.Clear(); f.ViewCatProdHeader(); foreach (var p in query.OrderBy(b => b.catid)) { Console.WriteLine(f.ViewCatProdFormat(), p.catid, p.catname, p.catdesc, p.prodid, p.prodname); } Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine(f.ViewCatProdFormat(), "------", "--------------------", "------------------------------------", "------", "--------------------"); Console.ResetColor(); } Console.ResetColor(); Console.Write("\n Press any key to continue: "); Console.ReadKey(); Console.Clear(); } else if (all == 3) { var categories = db.Categories.OrderBy(b => b.CategoryId); Console.Clear(); f.ViewAllCategoryHeader(); foreach (Category p in categories) { Console.WriteLine(f.ViewCategoriesFormat(), p.CategoryId, p.CategoryName, p.Description); } Console.ResetColor(); Console.Write("\n Select the Category ID to view its related Products: "); int cid = f.validateInt(Console.ReadLine()); { var query = from p in db.Products.OrderBy(b => b.CategoryId) join c in db.Categories on p.CategoryId equals c.CategoryId where p.Discontinued == false // && p.CategoryId == cid select new { prodid = p.ProductID, prodname = p.ProductName, catid = c.CategoryId, catname = c.CategoryName, catdesc = c.Description }; Console.Clear(); f.ViewCatProdHeader(); foreach (var p in query.OrderBy(b => b.catid)) { if(p.catid == cid) { Console.WriteLine(f.ViewCatProdFormat(), p.catid, p.catname, p.catdesc, p.prodid, p.prodname); } } Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine(f.ViewCatProdFormat(), "------", "--------------------", "------------------------------------", "------", "--------------------"); Console.ResetColor(); } Console.ResetColor(); Console.Write("\n Press any key to continue: "); Console.ReadKey(); Console.Clear(); } } //Add Product else if (choice == 4) { var db = new NorthwindContext(); Product product = new Product(); ValidationContext context = new ValidationContext(product, null, null); List<ValidationResult> results = new List<ValidationResult>(); Console.Clear(); f.AddProductHeader(); Console.Write(" Enter Product Name: "); product.ProductName = Console.ReadLine(); Console.Clear(); f.AddProductHeader(); Console.Write(" Enter Product Quantity per unit: "); product.QuantityPerUnit = Console.ReadLine(); Console.Clear(); f.AddProductHeader(); Console.WriteLine(" Enter the Category ID. Choose from the available Categories:\n"); Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine(f.ViewCategoryFormat(), "Category ID", "Category"); Console.WriteLine(f.ViewCategoryFormat(), "------", "------------------------------------"); var categories = db.Categories.OrderBy(b => b.CategoryId); foreach (Category p in categories) { Console.WriteLine(f.ViewCategoryFormat(), p.CategoryId, p.CategoryName); } Console.WriteLine(f.ViewCategoryFormat(), "------", "------------------------------------"); Console.ResetColor(); Console.Write(" "); product.CategoryId = f.validateInt(Console.ReadLine()); Console.Clear(); f.AddProductHeader(); Console.WriteLine(" Enter the Product Supplier ID. Choose from the available Suppliers: \n"); f.ViewSuppliersHeaderShort(); Console.ForegroundColor = ConsoleColor.Yellow; var suppliers = db.Suppliers.OrderBy(b => b.SupplierId); foreach (Supplier p in suppliers) { Console.WriteLine(f.ViewSupplierFormat(), p.SupplierId, p.CompanyName, p.City, p.Country); } Console.WriteLine(f.ViewSupplierFormat(), "------", "------------------------------------", "-------------------", "-------------------"); Console.Write(" "); Console.ResetColor(); product.SupplierId = f.validateInt(Console.ReadLine()); Console.Clear(); f.AddProductHeader(); Console.Write(" Enter Product Price: "); product.UnitPrice = f.validateInt(Console.ReadLine()); Console.Clear(); f.AddProductHeader(); Console.Write(" Enter Number of units to add to inventory: "); product.UnitsInStock = Int16.Parse(Console.ReadLine()); Console.Clear(); f.AddProductHeader(); Console.Write(" What level of inventory should we re-order this product: "); product.ReorderLevel = Int16.Parse(Console.ReadLine()); product.UnitsOnOrder = 0; product.Discontinued = false; var isValid = Validator.TryValidateObject(product, context, results, true); if (isValid) { // check for unique name if (db.Products.Any(p => p.ProductName == product.ProductName)) { // generate validation error isValid = false; results.Add(new ValidationResult("Name exists", new string[] { "ProductName" })); } else { //logger.Info("Validation passed"); // TODO: save category to db db.AddProduct(product); Console.Clear(); f.AddProductHeader(); Console.Write("\n Product Added Successfully! Press any key to return to the Main Menu: "); Console.ReadKey(); Console.Clear(); } } if (!isValid) { foreach (var result in results) { logger.Error($"{result.MemberNames.First()} : {result.ErrorMessage}"); } } } //Edit Product else if (choice == 5) { var db = new NorthwindContext(); var query = db.Products.OrderBy(b => b.ProductID); Console.Clear(); f.EditPProductHeader(); var product = ShowProduct(db); if (product != null) { Product UpdatedProduct = InputProduct(db); if (UpdatedProduct != null) { UpdatedProduct.ProductID = product.ProductID; db.EditProduct(UpdatedProduct); Console.WriteLine("\n Product Successfully Updated!"); // logger.Info("Post (id: {postid}) updated", UpdatedPost.PostId); } } Console.Write("\n Press any key to continue: "); Console.ReadKey(); Console.Clear(); } //View Product else if (choice == 6) { var db = new NorthwindContext(); Console.Clear(); f.ViewAllProductsHeader(); string all; do { Console.Write("\n View All Products? Y/N: "); all = Console.ReadLine().ToUpper(); } while ((all != "Y") && (all != "N")); if (all == "Y") { Console.Clear(); f.ViewAllProductsHeader(); string disc; do { Console.Write("\n Include Discontinued Products? Y/N: "); disc = Console.ReadLine().ToUpper(); } while ((disc != "Y") && (disc != "N")); if (disc == "N") { Console.Clear(); f.ViewAllProductsHeader(); var products = db.Products.OrderBy(b => b.ProductID); Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine(f.ViewProdFormat(), "Product Name", "Status"); Console.WriteLine(f.ViewProdFormat(), "------------------------------------", "-------------------"); Console.ResetColor(); foreach (Product p in products) { if (p.Discontinued == false) { Console.WriteLine(" " + p.ProductName); } } } else { Console.Clear(); f.ViewAllProductsHeader(); var products = db.Products.OrderBy(b => b.ProductID); Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine(f.ViewProdFormat(), "Product Name", "Status"); Console.WriteLine(f.ViewProdFormat(), "------------------------------------", "-------------------"); Console.ResetColor(); string status; foreach (Product p in products) { if (p.Discontinued == false) { status = " "; } else { status = "Discontinued"; } Console.WriteLine(f.ViewProdFormat(), p.ProductName, status); } } Console.ResetColor(); Console.Write("\n Press any key to continue: "); Console.ReadKey(); Console.Clear(); } else { Console.Clear(); f.ViewAllProductsHeader(); var products = db.Products.OrderBy(b => b.ProductID); Console.WriteLine(f.ViewProductsFormat(), "Product ID", "Product Name"); Console.WriteLine(f.ViewProductsFormat(), "------", "------------------------------------"); foreach (Product p in products) { Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine(f.ViewProductsFormat(), p.ProductID, p.ProductName); } Console.ResetColor(); Console.Write("\n Select the Product ID to view details: "); int prodid = f.validateInt(Console.ReadLine()); do { if (db.Products.Any(a => a.ProductID == prodid)) { var query = from p in db.Products join c in db.Categories on p.CategoryId equals c.CategoryId join s in db.Suppliers on p.SupplierId equals s.SupplierId select new { prodid = p.ProductID, prodname = p.ProductName, catid = c.CategoryId, catname = c.CategoryName, catdesc = c.Description, qpa = p.QuantityPerUnit, price = p.UnitPrice, instock = p.UnitsInStock, onorder = p.UnitsOnOrder, reorder = p.ReorderLevel, supplier = s.CompanyName }; Console.Clear(); Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine("\n ---------------------------------------------------------------------------------------------\n" + " View Product Details \n" + " ---------------------------------------------------------------------------------------------\n"); Console.ResetColor(); foreach (var p in query) { if (p.prodid == prodid) { Console.ForegroundColor = ConsoleColor.Yellow; Console.Write(" Product ID: "); Console.ResetColor(); Console.Write(p.prodid); Console.ForegroundColor = ConsoleColor.Yellow; Console.Write("\n Product Name: "); Console.ResetColor(); Console.Write(p.prodname); Console.ForegroundColor = ConsoleColor.Yellow; Console.Write("\n Category: "); Console.ResetColor(); Console.Write(p.catname); Console.ForegroundColor = ConsoleColor.Yellow; Console.Write("\n Category Description: "); Console.ResetColor(); Console.Write(p.catname); Console.ForegroundColor = ConsoleColor.Yellow; Console.Write("\n Supplier: "); Console.ResetColor(); Console.Write(p.supplier); Console.ForegroundColor = ConsoleColor.Yellow; Console.Write("\n QPA: "); Console.ResetColor(); Console.Write(p.qpa); Console.ForegroundColor = ConsoleColor.Yellow; Console.Write("\n Unit Price: "); Console.ResetColor(); Console.Write(String.Format("{0:C0}", Convert.ToInt32(p.price))); Console.ForegroundColor = ConsoleColor.Yellow; Console.Write("\n Units in Stock: "); Console.ResetColor(); Console.Write(p.instock); Console.ForegroundColor = ConsoleColor.Yellow; Console.Write("\n Units on Order: "); Console.ResetColor(); Console.Write(p.onorder); Console.ForegroundColor = ConsoleColor.Yellow; Console.Write("\n Reorder Level: "); Console.ResetColor(); Console.Write(p.reorder); prodid = 0; } } } else if (db.Products.Any(a => a.ProductID != prodid)) { Console.WriteLine(" Please choose a valid Product ID, or enter 0 to cancel: \n"); prodid = f.validateIntZero(Console.ReadLine()); } } while ((prodid != 0) && (db.Products.Any(b => b.ProductID != prodid))); Console.Write("\n\n Press any key to continue: "); Console.ReadKey(); Console.Clear(); } } // Display Category and related products else if (choice == 7) { var db = new NorthwindContext(); var query = db.Categories.OrderBy(p => p.CategoryId); Console.WriteLine("Select the category whose products you want to display:"); foreach (var item in query) { Console.WriteLine($"{item.CategoryId}) {item.CategoryName}"); } int id = int.Parse(Console.ReadLine()); Console.Clear(); logger.Info($"CategoryId {id} selected"); Category category = db.Categories.FirstOrDefault(c => c.CategoryId == id); Console.WriteLine($"{category.CategoryName} - {category.Description}"); foreach(Product p in category.Products) { Console.WriteLine(p.ProductName); } } // Display all Categories and their related products else if (choice == 8) { var db = new NorthwindContext(); var query = db.Categories.Include("Products").OrderBy(p => p.CategoryId); foreach(var item in query) { Console.WriteLine($"{item.CategoryName}"); foreach(Product p in item.Products) { Console.WriteLine($"\t{p.ProductName}"); } } } Console.WriteLine(); } while (choice != 0); } catch (Exception ex) { logger.Error(ex.Message); } logger.Info("Program ended"); }
static void Main(string[] args) { logger.Info("Program started"); var db = new NorthwindContext(); string choice; do { //show all options Console.WriteLine("1) Add Product"); Console.WriteLine("2) Edit Product"); Console.WriteLine("3) Display All Products"); Console.WriteLine("4) Display Specific Product"); Console.WriteLine("5) Add Category"); Console.WriteLine("6) Edit Category"); Console.WriteLine("7) Display All Categorys"); Console.WriteLine("8) Display All Categorys and their Active Products"); Console.WriteLine("9) Display Specific Category"); Console.WriteLine("\"q\" to quit"); choice = Console.ReadLine(); logger.Info($"Option {choice} selected"); var categorys = db.Categories.OrderBy(c => c.CategoryId); var products = db.Products.OrderBy(p => p.ProductID); var suppliers = db.Suppliers.OrderBy(s => s.SupplierId); int count = 0; int number = 0; var isValid = false; var stringOrNumber = false; switch (choice) { //add a product case "1": Product product = new Product(); //check if that product already exists isValid = false; String productNameValidation = ""; while (isValid == false) { isValid = true; Console.WriteLine("Enter Product Name:"); productNameValidation = Console.ReadLine(); foreach (var prod in products) { if (productNameValidation == prod.ProductName) { isValid = false; Console.WriteLine("Product already exists"); } } } product.ProductName = productNameValidation; Console.WriteLine("Enter Quantity Per Unit:"); product.QuantityPerUnit = Console.ReadLine(); Console.WriteLine("Enter Unit Price:"); product.UnitPrice = Decimal.Parse(Console.ReadLine()); Console.WriteLine("Enter Units In Stock:"); product.UnitsInStock = Int16.Parse(Console.ReadLine()); Console.WriteLine("Enter Units On Order:"); product.UnitsOnOrder = Int16.Parse(Console.ReadLine()); Console.WriteLine("Enter Reorder Level:"); product.ReorderLevel = Int16.Parse(Console.ReadLine()); String categoryName = ""; count = 0; foreach (var cat in categorys) { count++; } //check that category exists var realCategory = false; while (!realCategory) { count = 0; foreach (var cat in categorys) { Console.WriteLine(++count + ")" + cat.CategoryName); } Console.WriteLine("Enter a Category"); categoryName = Console.ReadLine(); //check if string or number number = 0; count = 0; stringOrNumber = Int32.TryParse(categoryName, out number); foreach (var cat in categorys) { count++; if (number == count || categoryName.ToLower() == cat.CategoryName.ToLower()) { product.CategoryId = cat.CategoryId; realCategory = true; } } } product.Discontinued = false; String supplierName = ""; count = 0; foreach (var sup in suppliers) { count++; } //check that supplier exists var realSupplier = false; while (!realSupplier) { count = 0; foreach (var sup in suppliers) { Console.WriteLine(++count + ") " + sup.CompanyName); } Console.WriteLine("Enter a Supplier name or number"); supplierName = Console.ReadLine(); //check if string or number number = 0; count = 0; stringOrNumber = Int32.TryParse(supplierName, out number); foreach (var sup in suppliers) { count++; if (number == count || supplierName.ToLower() == sup.CompanyName.ToLower()) { product.SupplierId = sup.SupplierId; realSupplier = true; } } } db.AddProduct(product); logger.Info("Product added - {name}", productNameValidation); break; //edit product case "2": // display all products count = 0; foreach (var prod in products) { count++; Console.WriteLine(count + ")" + prod.ProductName); } if (count == 0) { Console.WriteLine("No Products"); } else { var valid = false; Product productToEdit = new Product(); do { Console.WriteLine(count + " Products returned"); Console.WriteLine("Enter name or number"); choice = Console.ReadLine(); //check if string or number number = 0; stringOrNumber = Int32.TryParse(choice, out number); count = 0; foreach (var prod in products) { count++; if (count == number || choice.ToLower() == prod.ProductName.ToLower()) { valid = true; productToEdit.ProductID = prod.ProductID; productToEdit.ProductName = prod.ProductName; productToEdit.QuantityPerUnit = prod.QuantityPerUnit; productToEdit.UnitPrice = prod.UnitPrice; productToEdit.UnitsInStock = prod.UnitsInStock; productToEdit.UnitsOnOrder = prod.UnitsOnOrder; productToEdit.ReorderLevel = prod.ReorderLevel; productToEdit.Discontinued = prod.Discontinued; productToEdit.CategoryId = prod.CategoryId; productToEdit.SupplierId = prod.SupplierId; } } if (!valid) { Console.WriteLine("Enter a valid product name or number"); } } while (!valid); choice = ""; while (!(choice.ToLower() == "q")) { Console.WriteLine("Editing " + productToEdit.ProductName + "\n"); Console.WriteLine("1) Edit Product Name"); Console.WriteLine("2) Edit Product QuantityPerUnit"); Console.WriteLine("3) Edit Product UnitPrice"); Console.WriteLine("4) Edit Product UnitsInStock"); Console.WriteLine("5) Edit Product UnitsOnOrder"); Console.WriteLine("6) Edit Product ReorderLevel"); Console.WriteLine("7) Edit if Product is Discontinued"); Console.WriteLine("8) Edit Product Category Id"); Console.WriteLine("9) Edit Product Supplier Id"); Console.WriteLine("10) Edit All"); Console.WriteLine("11) Delete Product"); Console.WriteLine("\"q\" to quit"); choice = Console.ReadLine(); logger.Info($"Option {choice} selected"); switch (choice) { case "1": //check if that product already exists isValid = false; String newProductName = ""; while (isValid == false) { isValid = true; Console.WriteLine("Enter Product Name: "); newProductName = Console.ReadLine(); foreach (var prod in products) { if (newProductName == prod.ProductName) { isValid = false; Console.WriteLine("Product already exists"); } } } productToEdit.ProductName = newProductName; db.EditProduct(productToEdit); logger.Info("Product edited - {name}", productToEdit.ProductName); break; case "2": //Edit Product QuantityPerUnit Console.WriteLine("Enter Quantity Per Unit:"); productToEdit.QuantityPerUnit = Console.ReadLine(); db.EditProduct(productToEdit); logger.Info("Product edited - {name}", productToEdit.ProductName); break; case "3": //Edit Product UnitPrice Console.WriteLine("Enter Unit Price:"); productToEdit.UnitPrice = Decimal.Parse(Console.ReadLine()); db.EditProduct(productToEdit); logger.Info("Product edited - {name}", productToEdit.ProductName); break; case "4": //Edit Product UnitsInStock Console.WriteLine("Enter Units In Stock:"); productToEdit.UnitsInStock = Int16.Parse(Console.ReadLine()); db.EditProduct(productToEdit); logger.Info("Product edited - {name}", productToEdit.ProductName); break; case "5": //Edit Product UnitsOnOrder Console.WriteLine("Enter Units On Order:"); productToEdit.UnitsOnOrder = Int16.Parse(Console.ReadLine()); db.EditProduct(productToEdit); logger.Info("Product edited - {name}", productToEdit.ProductName); break; case "6": //Edit Product ReorderLevel Console.WriteLine("Enter Reorder Level:"); productToEdit.ReorderLevel = Int16.Parse(Console.ReadLine()); db.EditProduct(productToEdit); logger.Info("Product edited - {name}", productToEdit.ProductName); break; case "7": //Edit if Product is Discontinued Console.WriteLine("Product is Discontinued ('true' or 'false'):"); productToEdit.Discontinued = Boolean.Parse(Console.ReadLine()); db.EditProduct(productToEdit); logger.Info("Product edited - {name}", productToEdit.ProductName); break; case "8": //check that category exists var validCategory = false; while (!validCategory) { count = 0; foreach (var cat in categorys) { Console.WriteLine(++count + ")" + cat.CategoryName); } Console.WriteLine("Enter a New Category"); categoryName = Console.ReadLine(); //check if string or number number = 0; stringOrNumber = Int32.TryParse(categoryName, out number); foreach (var cat in categorys) { if (number == cat.CategoryId || categoryName.ToLower() == cat.CategoryName.ToLower()) { productToEdit.CategoryId = cat.CategoryId; realCategory = true; } } } logger.Info("Product edited - {name}", productToEdit.ProductName); db.EditProduct(productToEdit); break; case "9": //edit supplier id //check that supplier exists realSupplier = false; while (!realSupplier) { count = 0; foreach (var sup in suppliers) { Console.WriteLine(++count + ") " + sup.CompanyName); } Console.WriteLine("Enter a Supplier name or number"); supplierName = Console.ReadLine(); //check if string or number number = 0; count = 0; stringOrNumber = Int32.TryParse(supplierName, out number); foreach (var sup in suppliers) { count++; if (number == count || supplierName.ToLower() == sup.CompanyName.ToLower()) { productToEdit.SupplierId = sup.SupplierId; realSupplier = true; } } } logger.Info("Product edited - {name}", productToEdit.ProductName); db.EditProduct(productToEdit); break; case "10": //edit all //check if that product already exists isValid = false; newProductName = ""; while (isValid == false) { isValid = true; Console.WriteLine("Enter Product Name: "); newProductName = Console.ReadLine(); foreach (var prod in products) { if (newProductName == prod.ProductName) { isValid = false; Console.WriteLine("Product already exists"); } } } productToEdit.ProductName = newProductName; Console.WriteLine("Enter Quantity Per Unit:"); productToEdit.QuantityPerUnit = Console.ReadLine(); Console.WriteLine("Enter Unit Price:"); productToEdit.UnitPrice = Decimal.Parse(Console.ReadLine()); Console.WriteLine("Enter Units In Stock:"); productToEdit.UnitsInStock = Int16.Parse(Console.ReadLine()); Console.WriteLine("Enter Units On Order:"); productToEdit.UnitsOnOrder = Int16.Parse(Console.ReadLine()); Console.WriteLine("Enter Reorder Level:"); productToEdit.ReorderLevel = Int16.Parse(Console.ReadLine()); Console.WriteLine("Product is Discontinued ('true' or 'false'):"); productToEdit.Discontinued = Boolean.Parse(Console.ReadLine()); //check that category exists validCategory = false; while (!validCategory) { count = 0; foreach (var cat in categorys) { Console.WriteLine(++count + ")" + cat.CategoryName); } Console.WriteLine("Enter a New Category"); categoryName = Console.ReadLine(); //check if string or number number = 0; stringOrNumber = Int32.TryParse(categoryName, out number); if (number > 0) { foreach (var cat in categorys) { if (number == cat.CategoryId) { productToEdit.CategoryId = cat.CategoryId; realCategory = true; } } } else { foreach (var cat in categorys) { if (categoryName.ToLower() == cat.CategoryName.ToLower()) { productToEdit.CategoryId = cat.CategoryId; realCategory = true; } } } } //check that supplier exists realSupplier = false; while (!realSupplier) { count = 0; foreach (var sup in suppliers) { Console.WriteLine(++count + ") " + sup.CompanyName); } Console.WriteLine("Enter a Supplier name or number"); supplierName = Console.ReadLine(); //check if string or number number = 0; count = 0; stringOrNumber = Int32.TryParse(supplierName, out number); foreach (var sup in suppliers) { count++; if (number == count || supplierName.ToLower() == sup.CompanyName.ToLower()) { productToEdit.SupplierId = sup.SupplierId; realSupplier = true; } } } logger.Info("Product edited - {name}", productToEdit.ProductName); db.EditProduct(productToEdit); break; case "11": db.DeleteProduct(productToEdit); logger.Info("Product deleted - {name}", productToEdit.ProductName); choice = "q"; break; } } } break; case "3": while (!(choice.ToLower() == "q")) { //user decides if they want to see all, active, or discontinued products Console.WriteLine("1) Display All Products"); Console.WriteLine("2) Display Active Products"); Console.WriteLine("3) Display Discontinued Products"); Console.WriteLine("\"q\" to quit"); choice = Console.ReadLine(); logger.Info($"Option {choice} selected"); var query = db.Products.Where(p => p.ProductID > 0); switch (choice) { case "1": // Display All Products query = db.Products.Where(p => p.ProductID > 0); break; case "2": // Display Active Products query = db.Products.Where(p => p.Discontinued == false); break; case "3": // Display Discontinued Products query = db.Products.Where(p => p.Discontinued == true); break; } count = 0; foreach (var prod in query) { count++; Console.Write(count + ")" + prod.ProductName + " - "); if (prod.Discontinued) { Console.WriteLine("Discontinued"); } else { Console.WriteLine("Active"); } } if (count == 0) { Console.WriteLine("No Products"); } else { Console.WriteLine(count + " Products returned\n"); } } choice = " "; break; case "4": //Display Specific Product count = 0; foreach (var prod in products) { count++; Console.WriteLine(count + ") " + prod.ProductName); } if (count == 0) { Console.WriteLine("No Products"); } else { Console.WriteLine(count + " Products returned"); var valid = false; Product productToView = new Product(); do { Console.WriteLine("Enter name or number to view product"); choice = Console.ReadLine(); //check if string or number number = 0; stringOrNumber = Int32.TryParse(choice, out number); count = 0; foreach (var prod in products) { count++; if (count == number || choice.ToLower() == prod.ProductName.ToLower()) { valid = true; Console.WriteLine("Product ID: " + prod.ProductID + "\n" + "Product Name: " + prod.ProductName + "\n" + "Product Quantity Per Unit: " + prod.QuantityPerUnit + "\n" + "Product Unit Price: " + prod.UnitPrice + "\n" + "Product Units In Stock: " + prod.UnitsInStock + "\n" + "Product Units On Order: " + prod.UnitsOnOrder + "\n" + "Product Reorder Level: " + prod.ReorderLevel + "\n" + "Product Discontinued: " + prod.Discontinued + "\n" + "Product Category ID: " + prod.CategoryId + "\n" + "Product Supplier ID: " + prod.SupplierId); } } if (!valid) { Console.WriteLine("Enter a valid product name or number"); } } while (!valid); } break; case "5": //add category Category category = new Category(); //check if that category already exists isValid = false; String categoryNameValidation = ""; while (isValid == false) { isValid = true; Console.WriteLine("Enter Category Name:"); categoryNameValidation = Console.ReadLine(); foreach (var cat in categorys) { if (categoryNameValidation == cat.CategoryName) { isValid = false; Console.WriteLine("Category already exists"); } } } category.CategoryName = categoryNameValidation; Console.WriteLine("Enter Category Description:"); category.Description = Console.ReadLine(); db.AddCategory(category); logger.Info("Category added - {name}", categoryNameValidation); break; case "6": //edit a category count = 0; foreach (var Cat in categorys) { Console.WriteLine(++count + ") " + Cat.CategoryName); } if (count == 0) { Console.WriteLine("No Categorys"); } else { Console.WriteLine(count + " Categorys returned"); Category categoryToEdit = new Category(); var valid = false; while (!valid) { Console.WriteLine("Enter name or number"); choice = Console.ReadLine(); //check if string or number number = 0; stringOrNumber = Int32.TryParse(choice, out number); count = 0; foreach (var cat in categorys) { count++; if (count == number || choice.ToLower() == cat.CategoryName.ToLower()) { valid = true; categoryToEdit.CategoryId = cat.CategoryId; categoryToEdit.CategoryName = cat.CategoryName; categoryToEdit.Description = cat.Description; } } } choice = ""; while (!(choice.ToLower() == "q")) { Console.WriteLine("Editing " + categoryToEdit.CategoryName + "\n"); Console.WriteLine("1) Edit Category Name"); Console.WriteLine("2) Edit Category Description"); Console.WriteLine("3) Edit Both"); Console.WriteLine("4) Delete Product"); Console.WriteLine("\"q\" to quit"); choice = Console.ReadLine(); logger.Info($"Option {choice} selected"); switch (choice) { case "1": //check if that category already exists isValid = false; categoryNameValidation = ""; while (isValid == false) { isValid = true; Console.WriteLine("Enter Category Name:"); categoryNameValidation = Console.ReadLine(); foreach (var cat in categorys) { if (categoryNameValidation == cat.CategoryName) { isValid = false; Console.WriteLine("Category already exists"); } } } categoryToEdit.CategoryName = categoryNameValidation; db.EditCategory(categoryToEdit); logger.Info("Category edited - {name}", categoryToEdit.CategoryName); break; case "2": Console.WriteLine("Enter New Category Description:"); categoryToEdit.Description = Console.ReadLine(); db.EditCategory(categoryToEdit); logger.Info("Category edited - {name}", categoryToEdit.CategoryName); break; case "3": //check if that category already exists isValid = false; categoryNameValidation = ""; while (isValid == false) { isValid = true; Console.WriteLine("Enter Category Name:"); categoryNameValidation = Console.ReadLine(); foreach (var cat in categorys) { if (categoryNameValidation == cat.CategoryName) { isValid = false; Console.WriteLine("Category already exists"); } } } categoryToEdit.CategoryName = categoryNameValidation; Console.WriteLine("Enter New Category Description:"); categoryToEdit.Description = Console.ReadLine(); db.EditCategory(categoryToEdit); logger.Info("Category edited - {name}", categoryToEdit.CategoryName); break; case "4": //delete category and all related products var productsToDelete = db.Products.Where(p => p.CategoryId == categoryToEdit.CategoryId); count = 0; foreach (var prod in productsToDelete) { Console.WriteLine(++count + ") " + prod.ProductName); } Console.WriteLine("Deleting the " + categoryToEdit.CategoryName + " means that you will also be deleting these products. Are you sure (Y/N)"); string areYouSure = Console.ReadLine(); if (areYouSure.ToLower() == "y" || areYouSure.ToLower() == "yes") { foreach (var prod in productsToDelete) { db.DeleteProduct(prod); logger.Info("Product deleted - {name}", prod.ProductName); } db.DeleteCategory(categoryToEdit); logger.Info("Category deleted - {name}", categoryToEdit.CategoryName); choice = "q"; } break; } } } break; case "7": count = 0; foreach (var cat in categorys) { Console.WriteLine(++count + " Name: " + cat.CategoryName + "\nDescription: " + cat.Description + "\n"); } break; case "8": count = 0; foreach (var cat in categorys) { count++; } var catID = 0; for (var i = 0; i < count; i++) { count = 0; foreach (var cat in categorys) { if (i == count) { catID = cat.CategoryId; Console.WriteLine(i + 1 + ") " + cat.CategoryName); } count++; } var productsInCategory = products.Where(p => p.CategoryId == (catID) && p.Discontinued == false); var hasProducts = false; foreach (var prod in productsInCategory) { hasProducts = true; Console.WriteLine("\t" + prod.ProductName); } if (!hasProducts) { Console.WriteLine("\t0 products"); } Console.WriteLine(); } break; case "9": isValid = false; catID = 0; while (!isValid) { foreach (var cat in categorys) { Console.WriteLine(++count + ") " + cat.CategoryName); } Console.WriteLine("Enter a category to display(name or number)"); choice = Console.ReadLine(); //check if string or number number = 0; stringOrNumber = Int32.TryParse(choice, out number); count = 0; foreach (var cat in categorys) { count++; if (count == number || choice.ToLower() == cat.CategoryName.ToLower()) { isValid = true; catID = cat.CategoryId; } } } count = 0; var catPosition = 0; foreach (var cat in categorys) { if (cat.CategoryId == catID) { catPosition = count; } count++; } count = 0; foreach (var cat in categorys) { if (count == catPosition) { catID = cat.CategoryId; Console.WriteLine(count + 1 + ") " + cat.CategoryName); } count++; } var productsInCategory2 = products.Where(p => p.CategoryId == (catID) && p.Discontinued == false); var hasProducts2 = false; foreach (var prod in productsInCategory2) { hasProducts2 = true; Console.WriteLine("\t" + prod.ProductName); } if (!hasProducts2) { Console.WriteLine("\t0 products"); } Console.WriteLine(); break; } } while (!(choice.ToLower() == "q")); }
public static void Main(string[] args) { logger.Info("Program started"); try { string choice; do { Console.WriteLine("1) Add a Product"); Console.WriteLine("2) Edit a Product"); Console.WriteLine("3) Display Products"); Console.WriteLine("4) Display a specific Products"); Console.WriteLine("5) Display Categories"); Console.WriteLine("6) Add Category"); Console.WriteLine("7) Edit Category"); Console.WriteLine("8) Display Category and related products"); Console.WriteLine("9) Display all Categories and their related products"); Console.WriteLine("\"q\" to quit"); choice = Console.ReadLine(); Console.Clear(); logger.Info($"Option {choice} selected"); if (choice == "1") { Product product = new Product(); Console.WriteLine("Enter the Product Name"); product.ProductName = Console.ReadLine(); ValidationContext context = new ValidationContext(product, null, null); List <ValidationResult> results = new List <ValidationResult>(); var isValid = Validator.TryValidateObject(product, context, results, true); if (isValid) { var db = new NorthwindContext(); if (db.Products.Any(p => p.ProductName == product.ProductName)) { isValid = false; results.Add(new ValidationResult("Name exists", new string[] { "ProductName" })); } else { logger.Info("Validation passed"); db.AddProduct(product); } } if (!isValid) { foreach (var result in results) { logger.Error($"{result.MemberNames.First()} : {result.ErrorMessage}"); } } } else if (choice == "2") { var db = new NorthwindContext(); var p = GetProducts(db); if (p != null) { Product UpdatedProduct = InputProduct(db); if (UpdatedProduct != null) { UpdatedProduct.ProductID = p.ProductID; db.EditProduct(UpdatedProduct); logger.Info("Product (id: {productid}) updated", UpdatedProduct.ProductID); } } p.ProductName = Console.ReadLine(); } else if (choice == "3") { Console.WriteLine("Would you like to see all? (1) Active? (2) Or Disconinued? (3)"); choice = Console.ReadLine(); var db = new NorthwindContext(); if (choice == "2") { var list = db.Products.OrderBy(p => p.ProductName); foreach (Product p in list) { if (p.Discontinued == false) { Console.WriteLine($"Name: {p.ProductName} Discontinued: {p.Discontinued}"); } } } else if (choice == "3") { var list = db.Products.OrderBy(p => p.ProductName); foreach (Product p in list) { if (p.Discontinued == true) { Console.WriteLine($"Name: {p.ProductName} Discontinued: {p.Discontinued}"); } } } else { var list = db.Products.OrderBy(p => p.ProductName); Console.WriteLine($"{list.Count()} records returned"); foreach (var item in list) { Console.WriteLine($"Name: {item.ProductName} Discontinued: {item.Discontinued}"); } } } else if (choice == "4") { var db = new NorthwindContext(); var p = GetProducts(db); if (p != null) { Console.WriteLine($"Product name: {p.ProductName} ID: {p.ProductID} UnitPrice: {p.UnitPrice} UnitsInStock: {p.UnitsInStock}"); } } //End of C part of Project else if (choice == "5") { var db = new NorthwindContext(); var query = db.Categories.OrderBy(p => p.CategoryName); Console.WriteLine($"{query.Count()} records returned"); foreach (var item in query) { Console.WriteLine($"{item.CategoryName} - {item.Description}"); } } else if (choice == "6") { Category category = new Category(); Console.WriteLine("Enter Category Name:"); category.CategoryName = Console.ReadLine(); Console.WriteLine("Enter the Category Description:"); category.Description = Console.ReadLine(); ValidationContext context = new ValidationContext(category, null, null); List <ValidationResult> results = new List <ValidationResult>(); var isValid = Validator.TryValidateObject(category, context, results, true); if (isValid) { var db = new NorthwindContext(); if (db.Categories.Any(c => c.CategoryName == category.CategoryName)) { isValid = false; results.Add(new ValidationResult("Name exists", new string[] { "ProductName" })); } else { logger.Info("Validation passed"); db.AddCategory(category); } } if (!isValid) { foreach (var result in results) { logger.Error($"{result.MemberNames.First()} : {result.ErrorMessage}"); } } } else if (choice == "7") { var db = new NorthwindContext(); var p = GetCategories(db); if (p != null) { Category UpdatedCategory = InputCategory(db); if (UpdatedCategory != null) { UpdatedCategory.CategoryId = p.CategoryId; db.EditCategory(UpdatedCategory); logger.Info("Product (id: {Category id}) updated", UpdatedCategory.CategoryId); } } p.CategoryName = Console.ReadLine(); } else if (choice == "8") { var db = new NorthwindContext(); var query = db.Categories.Include("Products").OrderBy(p => p.CategoryId); Console.WriteLine("Select the category whose products you want to display:"); foreach (var item in query) { Console.WriteLine($"{item.CategoryId}) {item.CategoryName}"); } int id = int.Parse(Console.ReadLine()); Console.Clear(); logger.Info($"CategoryId {id} selected"); Category category = db.Categories.FirstOrDefault(c => c.CategoryId == id); Console.WriteLine($"{category.CategoryName} - {category.Description}"); foreach (Product p in category.Products) { if (p.Discontinued == false) { Console.WriteLine(p.ProductName); } } } else if (choice == "9") { var db = new NorthwindContext(); var query = db.Categories.Include("Products").OrderBy(p => p.CategoryId); foreach (var item in query) { Console.WriteLine($"{item.CategoryName}"); foreach (Product p in item.Products) { if (p.Discontinued == false) { Console.WriteLine($"\t{p.ProductName}"); } } } } Console.WriteLine(); } while (choice.ToLower() != "q"); } catch (Exception ex) { logger.Error(ex.Message); } logger.Info("Program ended"); }
public static void Main(string[] args) { logger.Info("Program started"); try { string choice; do { Console.WriteLine("11) Add Product"); Console.WriteLine("12) Display All Products Field"); Console.WriteLine("13) Edit a specified record from the Products table"); Console.WriteLine("14) Display the Product Name for discontinued Product"); Console.WriteLine("21) Add Category"); Console.WriteLine("22) Edit a specified record from the Category table"); Console.WriteLine("23) Display Categories"); Console.WriteLine("24) Display Category and related products"); Console.WriteLine("25) Display all Categories and their related products"); Console.WriteLine("\"q\" to quit"); choice = Console.ReadLine(); Console.Clear(); logger.Info($"Option {choice} selected"); if (choice == "11") { Product product = new Product(); Console.WriteLine("Enter Product Name:"); product.ProductName = Console.ReadLine(); Console.WriteLine("Enter the Product QuantityPerunit:"); product.QuantityPerUnit = Console.ReadLine(); //try code product.UnitPrice = 100; product.UnitsInStock = 50; product.UnitsOnOrder = 10; product.ReorderLevel = 20; product.Discontinued = true; product.CategoryId = 1; product.SupplierId = 3; ValidationContext context = new ValidationContext(product, null, null); List <ValidationResult> results = new List <ValidationResult>(); var isValid = Validator.TryValidateObject(product, context, results, true); if (isValid) { var db = new NorthwindContext(); // check for unique name if (db.Products.Any(c => c.ProductName == product.ProductName)) { // generate validation error isValid = false; results.Add(new ValidationResult("Name exists", new string[] { "ProductName" })); } else { logger.Info("Validation passed"); db.AddProduct(product); logger.Info("Product added - {ProductName}", product.ProductName); } } if (!isValid) { foreach (var result in results) { logger.Error($"{result.MemberNames.First()} : {result.ErrorMessage}"); } } } else if (choice == "12") { var db = new NorthwindContext(); var query = db.Products.OrderBy(p => p.ProductName); Console.WriteLine($"{query.Count()} records returned"); foreach (var item in query) { Console.WriteLine($"{item.ProductName} - {item.QuantityPerUnit} - {item.UnitPrice} - {item.UnitsInStock} - {item.UnitsOnOrder} - {item.ReorderLevel} - {item.Discontinued}"); } } else if (choice == "13") { // Edit product Console.WriteLine("Choose the product to edit:"); var db = new NorthwindContext(); var product = GetProduct(db); if (product != null) { // input category Product UpdatedProduct = InputProduct(db); if (UpdatedProduct != null) { UpdatedProduct.ProductID = product.ProductID; db.EditProduct(UpdatedProduct); logger.Info("Product (id: {productid}) updated", UpdatedProduct.ProductID); } } } else if (choice == "14") { var db = new NorthwindContext(); var query = db.Products.Where(p => p.Discontinued == true).OrderBy(p => p.ProductName); Console.WriteLine($"{query.Count()} records returned"); foreach (var item in query) { Console.WriteLine($"{item.ProductName}"); //- {item.QuantityPerUnit} - {item.UnitPrice} - {item.UnitsInStock} - {item.UnitsOnOrder} - {item.ReorderLevel} - {item.Discontinued}"); } } else if (choice == "21") { //Add Category Category category = new Category(); Console.WriteLine("Enter Category Name:"); category.CategoryName = Console.ReadLine(); Console.WriteLine("Enter the Category Description:"); category.Description = Console.ReadLine(); ValidationContext context = new ValidationContext(category, null, null); List <ValidationResult> results = new List <ValidationResult>(); var isValid = Validator.TryValidateObject(category, context, results, true); if (isValid) { var db = new NorthwindContext(); // check for unique name if (db.Categories.Any(c => c.CategoryName == category.CategoryName)) { // generate validation error isValid = false; results.Add(new ValidationResult("Name exists", new string[] { "CategoryName" })); } else { logger.Info("Validation passed"); // TODO: save category to db db.AddCategory(category); logger.Info("Category added - {CategoryName}", category.CategoryName); } } if (!isValid) { foreach (var result in results) { logger.Error($"{result.MemberNames.First()} : {result.ErrorMessage}"); } } } else if (choice == "22") { // Edit Category Console.WriteLine("Choose the category to edit:"); var db = new NorthwindContext(); var category = GetCategory(db); if (category != null) { // input categoy Category UpdatedCategory = InputCategory(db); if (UpdatedCategory != null) { UpdatedCategory.CategoryId = category.CategoryId; db.EditCategory(UpdatedCategory); logger.Info("Category (id: {categoryid}) updated", UpdatedCategory.CategoryId); } } } else if (choice == "23") { //Display Category var db = new NorthwindContext(); var query = db.Categories.OrderBy(p => p.CategoryName); Console.WriteLine($"{query.Count()} records returned"); foreach (var item in query) { Console.WriteLine($"{item.CategoryName} - {item.Description}"); } } else if (choice == "24") { var db = new NorthwindContext(); var query = db.Categories.OrderBy(p => p.CategoryId); Console.WriteLine("Select the category whose products you want to display:"); foreach (var item in query) { Console.WriteLine($"{item.CategoryId}) {item.CategoryName}"); } int id = int.Parse(Console.ReadLine()); Console.Clear(); logger.Info($"CategoryId {id} selected"); Category category = db.Categories.FirstOrDefault(c => c.CategoryId == id); Console.WriteLine($"{category.CategoryName} - {category.Description}"); foreach (Product p in category.Products.Where(p => p.Discontinued == false)) { Console.WriteLine(p.ProductName); } } else if (choice == "25") { var db = new NorthwindContext(); var query = db.Categories.Include("Products").OrderBy(p => p.CategoryId); foreach (var item in query) { Console.WriteLine($"{item.CategoryName}"); foreach (Product p in item.Products) { Console.WriteLine($"\t{p.ProductName}"); } } } Console.WriteLine(); } while (choice.ToLower() != "q"); } catch (Exception ex) { logger.Error(ex.Message); } logger.Info("Program ended"); }
public static void Main(string[] args) { logger.Info("Program started"); try { string choice; do { Console.WriteLine("1) Display Categories"); Console.WriteLine("2) Add Category"); Console.WriteLine("3) Display Category and related products"); Console.WriteLine("4) Display all Categories and their related products"); Console.WriteLine("\"q\" to quit"); choice = Console.ReadLine(); Console.Clear(); logger.Info($"Option {choice} selected"); if (choice == "1") { var db = new NorthwindContext(); var query = db.Categories.OrderBy(p => p.CategoryName); Console.WriteLine($"{query.Count()} records returned"); foreach (var item in query) { Console.WriteLine($"{item.CategoryName} - {item.Description}"); } } else if (choice == "2") { Category category = new Category(); Console.WriteLine("Enter Category Name:"); category.CategoryName = Console.ReadLine(); Console.WriteLine("Enter the Category Description:"); category.Description = Console.ReadLine(); // save category to db var db = new NorthwindContext(); try { db.AddCategory(category); logger.Info($"Category Added: {category.CategoryName}"); } catch (Exception) { foreach (var validationResult in db.GetValidationErrors()) { foreach (var error in validationResult.ValidationErrors) { logger.Error( "Entity Property: {0}, Error {1}", error.PropertyName, error.ErrorMessage); } } } } else if (choice == "3") { var db = new NorthwindContext(); var query = db.Categories.OrderBy(p => p.CategoryId); List <int> categoryIdCheck = new List <int>(); Console.WriteLine("Select the category whose products you want to display:"); foreach (var item in query) { Console.WriteLine($"{item.CategoryId}) {item.CategoryName}"); categoryIdCheck.Add(item.CategoryId); } int id = int.Parse(Console.ReadLine()); Console.Clear(); logger.Info($"CategoryId {id} selected"); try { Category category = db.Categories.FirstOrDefault(c => c.CategoryId == id); Console.WriteLine($"{category.CategoryName} - {category.Description}"); foreach (Product p in category.Products) { Console.WriteLine(p.ProductName); } } catch (NullReferenceException) { logger.Error($"CategoryID invalid."); } } else if (choice == "4") { var db = new NorthwindContext(); var query = db.Categories.Include("Products").OrderBy(p => p.CategoryId); var productList = db.Products.OrderBy(p => p.CategoryId).ToList(); List <int?> productCategoryId = new List <int?>(); foreach (var productItem in productList) { productCategoryId.Add(productItem.CategoryId); } foreach (var item in query) { Console.WriteLine($"{item.CategoryName}"); if (!productCategoryId.Contains(item.CategoryId)) { Console.WriteLine("\tNo products found."); } else { foreach (Product p in item.Products) { Console.WriteLine($"\t{p.ProductName}"); } } } } Console.WriteLine(); } while (choice.ToLower() != "q"); } catch (Exception ex) { logger.Error(ex.Message); } logger.Info("Program ended"); }
static void Main(string[] args) { logger.Info("Program Started"); String option; Menu menu = new Menu(); do { menu.MainMenu(); option = Console.ReadLine(); switch (option) { case "1": { menu.ProductsMenu(); String option1 = Console.ReadLine(); switch (option1) { case "1": { var db = new NorthwindContext(); db.DisplayProducts(); } break; case "2": { var db = new NorthwindContext(); bool isValidProId = false; var prodChoice = ""; do { menu.ExistingProducts(); prodChoice = Console.ReadLine(); switch (prodChoice) { case "1": var products = db.Products; var proId = ""; do { db.DisplayProducts(); Console.WriteLine("\nWhich Product do you want to view?\n" + "-------------------------------\n"); proId = Console.ReadLine(); int ID = int.Parse(proId); if (isValidProId == false) { foreach (var id in products) { if (id.ProductId == ID) { isValidProId = true; } } } if (isValidProId == true) { var product = db.Products.Where(p => p.ProductId == ID); foreach (var p in product) { Console.WriteLine ( ("Product Id: {0}\n" + "Product name: {1}\n" + "Quantity per unit: {2}\n" + "Reorder Level: {3}\n" + "Supplier Id: {4}\n" + "Unit Price: {5}\n" + "Units in stock: {6}\n" + "Units in order: {7}\n" + "Discontinued: {8}\n"), p.ProductId, p.ProductName, p.QuantityPerUnit, p.ReorderLevel, p.SupplierID, p.UnitPrice, p.UnitsInStock, p.UnitsOnOrder, p.Discontinued ); } } if (isValidProId == false) { isValidProId = false; logger.Warn("Invalid selection... pick again.."); } } while (isValidProId == false); break; case "2": var disProducts = db.Products.Where(p => p.Discontinued == true); foreach (var dp in disProducts) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("{0}\n", dp.ProductName + " * * Discontinued * *"); Console.ForegroundColor = ConsoleColor.Gray; } break; case "3": var actProducts = db.Products.Where(p => p.Discontinued == false); foreach (var ap in actProducts) { Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("{0}\n", ap.ProductName + " * * Active * *"); Console.ForegroundColor = ConsoleColor.Gray; } break; } } while (!prodChoice.Equals("4")); } break; case "3": { var db = new NorthwindContext(); Console.WriteLine("Enter the name of the product\n"); var name = Console.ReadLine(); Console.WriteLine("What kind of Product is {0}?", name); Console.WriteLine("-------------------------------"); var categories = db.Categories; var catId = ""; bool isValidID = false; do { foreach (var category in categories) { Console.WriteLine("{0}) {1}", category.CategoryId, category.CategoryName); } catId = Console.ReadLine(); if (isValidID == false) { foreach (var id in categories) { if (id.CategoryId == int.Parse(catId)) { isValidID = true; } } } if (isValidID == false) { isValidID = false; logger.Warn("Invalid selection... pick again.."); } } while (isValidID == false); Console.WriteLine("Who is the Supplier for that product?"); Console.WriteLine("-------------------------------"); var suppliers = db.Suppliers; var supId = ""; isValidID = false; do { foreach (var supplier in suppliers) { Console.WriteLine("{0}) {1}", supplier.SupplierId, supplier.CompanyName); } supId = Console.ReadLine(); if (isValidID == false) { foreach (var id in suppliers) { if (id.SupplierId == int.Parse(supId)) { isValidID = true; } } } if (isValidID == false) { isValidID = false; logger.Warn("Invalid selection... pick again.."); } } while (isValidID == false); var newProduct = new Product { ProductName = name, CategoryID = int.Parse(catId), SupplierID = 3 }; db.AddProduct(newProduct); logger.Info("{0} added to Products..", newProduct.ProductName); } break; case "4": var editdb = new NorthwindContext(); var editQuery = editdb.Products; var editId = ""; bool isValidEdit = false; do { editdb.DisplayProducts(); Console.WriteLine("\nWhich Product do you want to edit?"); editId = Console.ReadLine(); if (isValidEdit == false) { foreach (var id in editQuery) { if (id.ProductId == int.Parse(editId)) { isValidEdit = true; } } } var ID = int.Parse(editId); if (isValidEdit == true) { var edit = editdb.Products.Where(e => e.ProductId == ID); bool isValidDetail = false; do { menu.ProductDetails(); var editChoice = Console.ReadLine(); switch (editChoice) { case "1": Console.WriteLine("Enter new Product name\n" + "-------------------------------\n"); var newName = Console.ReadLine(); try { foreach (var ed in edit) { ed.ProductName = newName; logger.Info("Product name changed to \"{0}\"", newName); } ; editdb.SaveChanges(); } catch (Exception e) { logger.Warn("Unable to change product name, try again..."); logger.Warn(e.Message); } break; case "2": Console.WriteLine("Enter new Quantity per Unit\n" + "-------------------------------\n"); var newQPU = Console.ReadLine(); try { foreach (var ed in edit) { ed.QuantityPerUnit = newQPU; logger.Info("Quantity per Unit changed to \"{0}\"", newQPU); } ; editdb.SaveChanges(); } catch (Exception e) { logger.Warn("Unable to change Quantity per Unit, try again..."); logger.Warn(e.Message); } break; case "3": Console.WriteLine("Enter new Unit Price\n" + "-------------------------------\n"); var newUP = Console.ReadLine(); try { foreach (var ed in edit) { ed.UnitPrice = decimal.Parse(newUP); logger.Info("Unit Price changed to \"${0}\"", decimal.Parse(newUP)); } ; editdb.SaveChanges(); } catch (Exception e) { logger.Warn("Unable to change Units in Stock, try again..."); logger.Warn(e.Message); } break; case "4": Console.WriteLine("Enter new Units in Stock\n" + "-------------------------------\n"); var newUS = Console.ReadLine(); try { foreach (var ed in edit) { ed.UnitsInStock = short.Parse(newUS); logger.Info("Units in Stock changed to \"{0}\"", short.Parse(newUS)); } ; editdb.SaveChanges(); } catch (Exception e) { logger.Warn("Unable to change Units in Stock, try again..."); logger.Warn(e.Message); } break; case "5": Console.WriteLine("Enter new Units on Order\n" + "-------------------------------\n"); var newUO = Console.ReadLine(); try { foreach (var ed in edit) { ed.UnitsOnOrder = short.Parse(newUO); logger.Info("Units on Order changed to \"{0}\"", short.Parse(newUO)); } ; editdb.SaveChanges(); } catch (Exception e) { logger.Warn("Unable to change Units on Order, try again..."); logger.Warn(e.Message); } break; case "6": Console.WriteLine("Enter new Reorder level\n" + "-------------------------------\n"); var newRL = Console.ReadLine(); try { foreach (var ed in edit) { ed.ReorderLevel = short.Parse(newRL); logger.Info("Reorder level changed to \"{0}\"", short.Parse(newRL)); } ; editdb.SaveChanges(); } catch (Exception e) { logger.Warn("Unable to change Reorder level, try again..."); logger.Warn(e.Message); } break; case "7": Console.WriteLine("Is this item Discontinued Y/N?\n" + "-------------------------------\n"); var newD = Console.ReadLine(); if (newD.ToUpper().Equals("Y")) { try { foreach (var ed in edit) { ed.Discontinued = true; logger.Info(ed.ProductName + " is now Discontinued"); } ; editdb.SaveChanges(); } catch (Exception e) { logger.Warn("Unable to change Discontinued, try again..."); logger.Warn(e.Message); } } else if (newD.ToUpper().Equals("N")) { try { foreach (var ed in edit) { ed.Discontinued = false; logger.Info(ed.ProductName + " is now Active"); } ; editdb.SaveChanges(); } catch (Exception e) { logger.Warn("Unable to change Discontinued, try again..."); logger.Warn(e.Message); } } else { logger.Warn("Not valid response"); } break; case "8": isValidDetail = true; break; } } while (isValidDetail == false); } } while (isValidEdit == false); break; case "5": //delete product i think var deleteDb = new NorthwindContext(); var deleteQuery = deleteDb.Products; Boolean isValidProductID = false; deleteDb.DisplayProducts(); Console.WriteLine("\nChoose a Product you would like to delete"); var input = Console.ReadLine(); int proID = int.Parse(input); if (isValidProductID == false) { foreach (var item in deleteQuery) { if (item.ProductId == proID) { isValidProductID = true; } } if (isValidProductID == true) { var deleteProduct = deleteDb.Products.SingleOrDefault(p => p.ProductId == proID); Console.WriteLine("\nAre you sure you want to delete " + deleteProduct.ProductName + "? Y/N"); if (Console.ReadLine().ToUpper().Equals("Y")) { deleteDb.DeleteProduct(deleteProduct); logger.Info("Product \"{0}\" removed from Products", deleteProduct.ProductName); } } else { logger.Info("Not a valid Product ID"); } } else { logger.Info("Not a valid Integer"); } break; } } break; case "2": var catDB = new NorthwindContext(); var catResp = ""; do { menu.ExistingCategories(); catResp = Console.ReadLine(); switch (catResp) { case "1": var categories = catDB.Categories; menu.CategoryHeader(); foreach (var category in categories) { Console.WriteLine("{0}) {1} - {2}", category.CategoryId, category.CategoryName, category.Description); } break; case "2": var proByCat = catDB.Categories.Include("Products").OrderBy(p => p.CategoryId); menu.CategoryHeader(); foreach (var category in proByCat) { Console.WriteLine("\n{0}) {1} - {2}\n", category.CategoryId, category.CategoryName, category.Description); foreach (Product product in category.Products) { Console.WriteLine("- {0}", product.ProductName); } } break; case "3": var c = catDB.Categories; var catId = ""; bool isValidID = false; do { menu.CategoryHeader(); foreach (var category in c) { Console.WriteLine("{0}) {1}", category.CategoryId, category.CategoryName); } catId = Console.ReadLine(); if (isValidID == false) { foreach (var id in c) { if (id.CategoryId == int.Parse(catId)) { isValidID = true; } } } var pID = int.Parse(catId); if (isValidID == true) { var catPro = catDB.Categories.Where(p => p.CategoryId == pID); var sp = catDB.Products.Where(s => s.CategoryID == pID); foreach (var p in catPro) { Console.WriteLine("\n{0} - {1}", p.CategoryName, p.Description); Console.WriteLine("-------------------------------\n"); } foreach (var item in sp) { Console.WriteLine("{0}", item.ProductName); } } if (isValidID == false) { isValidID = false; logger.Warn("Invalid selection... pick again.."); } } while (isValidID == false); break; case "4": // add new cat var nc = catDB.Categories.OrderBy(n => n.CategoryId); var catName = ""; bool isValidCat = true; do { Console.WriteLine("Enter name of new Category\n"); catName = Console.ReadLine(); foreach (var n in nc) { if (n.CategoryName.ToUpper().Equals(catName)) { isValidCat = false; } } if (isValidCat == false) { logger.Warn("Category name {0} already exists - enter a different name", catName); } if (isValidCat == true) { var newCat = new Category { CategoryName = catName }; catDB.AddCategory(newCat); logger.Info("Category added - {0}", catName); } } while (isValidCat == false); break; case "5": // edit cat var editCat = new NorthwindContext(); var ec = editCat.Categories; bool isVcatId = false; do { menu.CategoryHeader(); foreach (var category in ec) { Console.WriteLine("{0}) {1}", category.CategoryId, category.CategoryName); } Console.WriteLine("\nChoose a Category to edit\n" + "-------------------------------\n"); var catInput = Console.ReadLine(); int ID = int.Parse(catInput); if (isVcatId == false) { foreach (var id in ec) { if (id.CategoryId == ID) { isVcatId = true; } } } if (isVcatId == true) { var catEdit = editCat.Categories.Where(e => e.CategoryId == ID); var catChoice = ""; do { Console.WriteLine("1) Edit Category Name"); Console.WriteLine("2) Edit Category Description"); Console.WriteLine("3) Exit"); catChoice = Console.ReadLine(); switch (catChoice) { case "1": Console.WriteLine("Enter new Category name\n" + "-------------------------------\n"); var newCatName = Console.ReadLine(); try { foreach (var ed in catEdit) { ed.CategoryName = newCatName; logger.Info("Category name changed to \"{0}\"", newCatName); } ; editCat.SaveChanges(); } catch (Exception e) { logger.Warn("Unable to change category name, try again..."); logger.Warn(e.Message); } break; case "2": Console.WriteLine("Enter new Category description\n" + "-------------------------------\n"); var newCatDesc = Console.ReadLine(); try { foreach (var ed in catEdit) { ed.Description = newCatDesc; logger.Info("Category description changed to \"{0}\"", newCatDesc); } ; editCat.SaveChanges(); } catch (Exception e) { logger.Warn("Unable to change category description, try again..."); logger.Warn(e.Message); } break; } } while (!catChoice.Equals("3")); } } while (isVcatId == false); break; case "6": // delete cat var deleteCat = new NorthwindContext(); var deleteQuery = deleteCat.Categories; bool isValidCategoryID = false; do { menu.CategoryHeader(); foreach (var category in deleteQuery) { Console.WriteLine("{0}) {1}", category.CategoryId, category.CategoryName); } Console.WriteLine("\nChoose a Category you wish to delete"); var delInput = Console.ReadLine(); int catID = int.Parse(delInput); foreach (var item in deleteQuery) { if (item.CategoryId == catID) { isValidCategoryID = true; } } if (isValidCategoryID == true) { var deleteCategory = deleteCat.Categories.SingleOrDefault(p => p.CategoryId == catID); Console.WriteLine("Are you sure you want to delete " + deleteCategory.CategoryName + "? Y/N"); if (Console.ReadLine().ToUpper().Equals("Y")) { Console.WriteLine("\nIf you delete " + deleteCategory.CategoryName + " you will delete all Products in this category"); Console.WriteLine("Would you like to:"); Console.WriteLine("1) Delete all Products within " + deleteCategory.CategoryName + "?"); Console.WriteLine("2) Change the Category of all Products within " + deleteCategory.CategoryName + "?"); var deleteChoice = Console.ReadLine(); switch (deleteChoice) { case "1": { var deleteProducts = deleteCat.Products.Where(p => p.CategoryID == catID); List <Product> productArray = new List <Product>(); foreach (var p in deleteProducts) { productArray.Add(p); } foreach (var p in productArray) { deleteCat.DeleteProduct(p); } deleteCat.DeleteCategory(deleteCategory); logger.Info("{0} successfully removed from Categories", deleteCategory.CategoryName); break; } case "2": { bool isValid = false; do { menu.CategoryHeader(); foreach (var category in deleteQuery) { Console.WriteLine("{0}) {1}", category.CategoryId, category.CategoryName); } Console.WriteLine("\nChoose wish category you wish to replace " + deleteCategory.CategoryName + " with"); String catIDchoice = Console.ReadLine(); int newCatID = int.Parse(catIDchoice); if (isValid == false) { foreach (var item in deleteQuery) { if (item.CategoryId == newCatID && newCatID != catID) { isValid = true; } } } if (isValid == true) { var changeProducts = deleteCat.Products.Where(p => p.CategoryID == catID); foreach (var p in changeProducts) { p.CategoryID = newCatID; } deleteCat.DeleteCategory(deleteCategory); logger.Info("{0} successfully removed from Categories", deleteCategory.CategoryName); } else { logger.Info("Not a valid CategoryID"); } } while (isValid == false); break; } } } } } while (isValidCategoryID == false); break; } } while (!catResp.Equals("7")); break; } } while (!option.Equals("3")); }
static void Main(string[] args) { logger.Info("Program Started"); try { string choice; var db = new NorthwindContext(); do { Console.WriteLine("Select:"); Console.WriteLine("1) Add Product"); Console.WriteLine("2) Edit Product"); Console.WriteLine("3) Display Product(s)"); Console.WriteLine("4) Add Category"); Console.WriteLine("5) Edit Category"); Console.WriteLine("6) Display Categories"); Console.WriteLine("7) Delete Product"); Console.WriteLine("8) Delete Category"); Console.WriteLine("Anything Else to Quit"); choice = Console.ReadLine(); Console.Clear(); logger.Info("User Choice: " + choice); if (choice == "1") { Product product = new Product(); Console.WriteLine("Product Name: "); product.ProductName = Console.ReadLine(); Console.WriteLine("Supplier ID: "); product.SupplierID = int.Parse(Console.ReadLine()); Console.WriteLine("Category ID: "); product.CategoryID = int.Parse(Console.ReadLine()); Console.WriteLine("Quantity Per Unit: "); product.QuantityPerUnit = Console.ReadLine(); Console.WriteLine("Unit Price: $"); product.UnitPrice = decimal.Parse(Console.ReadLine()); Console.WriteLine("Units In Stock: "); product.UnitsInStock = Int16.Parse(Console.ReadLine()); Console.WriteLine("Units On Order: "); product.UnitsOnOrder = Int16.Parse(Console.ReadLine()); Console.WriteLine("Reorder Level: "); product.ReorderLevel = Int16.Parse(Console.ReadLine()); Console.WriteLine("Discontinued(y/n): "); string dis = Console.ReadLine(); if ((dis[0] + "").ToLower() == "y") { product.Discontinued = true; } else { product.Discontinued = false; } db.AddProduct(product); } else if (choice == "2") { Product product = new Product(); var query = db.Products.OrderBy(p => p.ProductID); foreach (Product p in query) { Console.WriteLine(p.ProductID + " - " + p.ProductName); } try { Console.WriteLine("Product ID: "); product.ProductID = int.Parse(Console.ReadLine()); Console.WriteLine("New Product Name: "); product.ProductName = Console.ReadLine(); Console.WriteLine("New Supplier ID: "); string user = Console.ReadLine(); product.SupplierID = (user.Length > 0 ? int.Parse(user) : -1); Console.WriteLine("New Category ID: "); user = Console.ReadLine(); product.CategoryID = (user.Length > 0 ? int.Parse(user) : -1); Console.WriteLine("New Quantity Per Unit: "); product.QuantityPerUnit = Console.ReadLine(); Console.WriteLine("New Unit Price: $"); user = Console.ReadLine(); product.UnitPrice = (user.Length > 0 ? decimal.Parse(user) : -1); Console.WriteLine("Units In Stock: "); user = Console.ReadLine(); product.UnitsInStock = (user.Length > 0 ? Int16.Parse(user) : Int16.Parse("-1")); Console.WriteLine("New Units On Order: "); user = Console.ReadLine(); product.UnitsOnOrder = (user.Length > 0 ? Int16.Parse(user) : Int16.Parse("-1")); Console.WriteLine("New Reorder Level: "); user = Console.ReadLine(); product.ReorderLevel = (user.Length > 0 ? Int16.Parse(user) : Int16.Parse("-1")); Console.WriteLine("Discontinued(y/n): "); string dis = Console.ReadLine(); if ((dis[0] + "").ToLower() == "y") { product.Discontinued = true; } else { product.Discontinued = false; } db.UpdateProduct(product); logger.Info($"Updated Product {product.ProductName} - ID: {product.ProductID}"); } catch { logger.Error("That was not a valid input"); } } else if (choice == "3") { string productDisplay = "0"; Console.WriteLine("Select:"); Console.WriteLine("1) Display All Products"); Console.WriteLine("2) Display Products Based On Criteria"); Console.WriteLine("Anything Else to Cancel"); productDisplay = Console.ReadLine(); Console.Clear(); logger.Info("User Entered " + productDisplay); var query = db.Products.OrderBy(p => p.ProductName); if (productDisplay == "2") { Console.WriteLine("Select Criteria:"); Console.WriteLine("1) ProductID"); Console.WriteLine("2) ProductName"); Console.WriteLine("3) SupplierID"); Console.WriteLine("4) CategoryID"); Console.WriteLine("5) UnitPrice"); Console.WriteLine("6) Discontinued"); Console.WriteLine("Anything Else to Cancel"); productDisplay = Console.ReadLine(); Console.Clear(); logger.Info("User Entered " + productDisplay); if (productDisplay == "1") { Console.WriteLine("One Product ID to Display:"); List <int> ids = new List <int>(); string next = ""; do { Console.WriteLine("Enter s to Stop Entering IDs"); next = Console.ReadLine(); logger.Info("User Entered: " + next); try { int id = int.Parse(next); if (id > 0 && id <= db.Products.Max(p => p.ProductID)) { ids.Add(id); Console.WriteLine("Another ID:"); } else { next = "s"; } } catch { next = "s"; } } while (next != "s"); if (ids.Count > 0) { query = db.Products.Where(p => p.ProductID == 0).OrderBy(p => p.ProductID); foreach (int id in ids) { query = query.Union(db.Products.Where(p => p.ProductID == id).OrderBy(p => p.ProductID)).OrderBy(p => p.ProductID); } } else { productDisplay = ""; } } else if (productDisplay == "2") { Console.WriteLine("One Product Name to Display:"); List <string> names = new List <string>(); string next = ""; do { Console.WriteLine("Enter s to Stop Entering Names"); next = Console.ReadLine(); logger.Info("User Entered: " + next); if (next != "s") { names.Add(next); } } while (next != "s"); if (names.Count > 0) { query = db.Products.Where(p => p.ProductName == "").OrderBy(p => p.ProductName); foreach (string name in names) { query = query.Union(db.Products.Where(p => p.ProductName == name).OrderBy(p => p.ProductName)).OrderBy(p => p.ProductName); } } else { productDisplay = ""; } } else if (productDisplay == "3") { Console.WriteLine("One Product from a Supplier ID to Display:"); List <int> ids = new List <int>(); string next = ""; do { Console.WriteLine("Enter s to Stop Entering IDs"); next = Console.ReadLine(); logger.Info("User Entered: " + next); try { int id = int.Parse(next); if (id > 0 && id <= db.Products.Max(p => p.ProductID)) { ids.Add(id); Console.WriteLine("Another ID:"); } else { next = "s"; } } catch { next = "s"; } } while (next != "s"); if (ids.Count > 0) { query = db.Products.Where(p => p.SupplierID == 0).OrderBy(p => p.SupplierID); foreach (int id in ids) { query = query.Union(db.Products.Where(p => p.SupplierID == id).OrderBy(p => p.SupplierID)).OrderBy(p => p.SupplierID); } } else { productDisplay = ""; } } else if (productDisplay == "4") { Console.WriteLine("One Product from a Category ID to Display:"); List <int> ids = new List <int>(); string next = ""; do { Console.WriteLine("Enter s to Stop Entering IDs"); next = Console.ReadLine(); logger.Info("User Entered: " + next); try { int id = int.Parse(next); if (id > 0 && id <= db.Products.Max(p => p.ProductID)) { ids.Add(id); Console.WriteLine("Another ID:"); } else { next = "s"; } } catch { next = "s"; } } while (next != "s"); if (ids.Count > 0) { query = db.Products.Where(p => p.CategoryID == 0).OrderBy(p => p.CategoryID); foreach (int id in ids) { query = query.Union(db.Products.Where(p => p.CategoryID == id).OrderBy(p => p.CategoryID)).OrderBy(p => p.CategoryID); } } else { productDisplay = ""; } } else if (productDisplay == "5") { decimal min = 0; decimal max = 0; try { Console.WriteLine("Minimum Unit Price: $"); min = decimal.Parse(Console.ReadLine()); try { Console.WriteLine("Maximum Unit Price: $"); max = decimal.Parse(Console.ReadLine()); query = db.Products.Where(p => p.UnitPrice >= min && p.UnitPrice <= max).OrderBy(p => p.UnitPrice); } catch { logger.Error("That is not a valid Maximum Unit Price"); productDisplay = ""; } } catch { logger.Error("That is not a valid Minimum Unit Price"); productDisplay = ""; } } else if (productDisplay == "6") { Console.WriteLine("Discontinued(y) or Not(n)"); Console.WriteLine("Anything else to cancel"); string dis = Console.ReadLine(); if ((dis[0] + "").ToLower() == "y") { query = db.Products.Where(p => p.Discontinued).OrderBy(p => p.ProductID); } else if ((dis[0] + "").ToLower() == "n") { query = db.Products.Where(p => !p.Discontinued).OrderBy(p => p.ProductID); } else { productDisplay = ""; } } else { productDisplay = ""; } } if (productDisplay.Length > 0) { Console.WriteLine($"{query.Count()} Products Returned"); foreach (var item in query) { if (!item.Discontinued) { Console.ForegroundColor = ConsoleColor.Green; } else { Console.ForegroundColor = ConsoleColor.Red; } Console.WriteLine(item.ProductName); } Console.ResetColor(); } else { logger.Info("Product Display Canceled"); } } else if (choice == "4") { Category category = new Category(); Console.WriteLine("Category Name: "); category.CategoryName = Console.ReadLine(); Console.WriteLine("Category Description: "); category.Description = Console.ReadLine(); db.AddCategory(category); } else if (choice == "5") { Category category = new Category(); var query = db.Categories.OrderBy(c => c.CategoryID); foreach (Category c in query) { Console.WriteLine(c.CategoryID + " - " + c.CategoryName); } try { Console.WriteLine("Category ID: "); category.CategoryID = int.Parse(Console.ReadLine()); Console.WriteLine("Category Name: "); category.CategoryName = Console.ReadLine(); Console.WriteLine("Category Description: "); category.Description = Console.ReadLine(); db.UpdateCategory(category); logger.Info($"Updated Category {category.CategoryName} - ID: {category.CategoryID}"); } catch { logger.Error("That is not a valid input"); } } else if (choice == "6") { string categoryDisplay = "0"; Console.WriteLine("1) Display All Categories"); Console.WriteLine("2) Display All Categories and Their Valid Products"); Console.WriteLine("3) Display Categories Based on Criteria"); Console.WriteLine("4) Display Categories Based on Criteria and Their Valid Products"); Console.WriteLine("Anything Else to Cancel"); categoryDisplay = Console.ReadLine(); Console.Clear(); logger.Info("User Entered " + categoryDisplay); var query = db.Categories.OrderBy(c => c.CategoryName); if (categoryDisplay == "1") { Console.WriteLine($"{query.Count()} Categories Returned"); foreach (Category c in query) { Console.WriteLine(c.CategoryName); Console.WriteLine(" " + c.Description); } } else if (categoryDisplay == "2") { Console.WriteLine($"{query.Count()} Categories Returned"); var newDB = new NorthwindContext(); var pQuery = newDB.Products.OrderBy(p => p.ProductName); foreach (Category c in query) { Console.WriteLine(c.CategoryName); pQuery = newDB.Products.Where(p => p.CategoryID == c.CategoryID).OrderBy(p => p.ProductName); Console.WriteLine($"{pQuery.Count()} Products Returned"); foreach (Product p in pQuery) { Console.WriteLine(" " + p.ProductName); } } } else if (categoryDisplay == "3") { Console.WriteLine("Select Which Criteria To Use:"); Console.WriteLine("1) Category ID"); Console.WriteLine("2) Category Name"); Console.WriteLine("Anything Else To Cancel"); categoryDisplay = Console.ReadLine(); Console.Clear(); logger.Info("User Entered " + categoryDisplay); if (categoryDisplay == "1") { Console.WriteLine("One Category ID to Display:"); List <int> ids = new List <int>(); string next = ""; do { Console.WriteLine("Enter s to Stop Entering IDs"); next = Console.ReadLine(); logger.Info("User Entered: " + next); try { int id = int.Parse(next); if (id > 0 && id <= db.Categories.Max(c => c.CategoryID)) { ids.Add(id); Console.WriteLine("Another ID:"); } else { next = "s"; } } catch { next = "s"; } } while (next != "s"); if (ids.Count > 0) { query = db.Categories.Where(c => c.CategoryID == 0).OrderBy(c => c.CategoryID); foreach (int id in ids) { query = query.Union(db.Categories.Where(c => c.CategoryID == id).OrderBy(c => c.CategoryID)).OrderBy(c => c.CategoryID); } } else { categoryDisplay = ""; } } else if (categoryDisplay == "2") { Console.WriteLine("One Category Name to Display:"); List <string> names = new List <string>(); string next = ""; do { Console.WriteLine("Enter s to Stop Entering IDs"); next = Console.ReadLine(); logger.Info("User Entered: " + next); names.Add(next); } while (next != "s"); if (names.Count > 0) { query = db.Categories.Where(c => c.CategoryName == "").OrderBy(c => c.CategoryName); foreach (string name in names) { query = query.Union(db.Categories.Where(c => c.CategoryName == name).OrderBy(c => c.CategoryName)).OrderBy(c => c.CategoryName); } } else { categoryDisplay = ""; } } Console.WriteLine($"{query.Count()} Categories Returned"); foreach (Category c in query) { Console.WriteLine(c.CategoryName); Console.WriteLine(" " + c.Description); } } else if (categoryDisplay == "4") { Console.WriteLine("Select Which Criteria To Use:"); Console.WriteLine("1) Category ID"); Console.WriteLine("2) Category Name"); Console.WriteLine("Anything Else To Cancel"); categoryDisplay = Console.ReadLine(); Console.Clear(); logger.Info("User Entered " + categoryDisplay); if (categoryDisplay == "1") { Console.WriteLine("One Category ID to Display:"); List <int> ids = new List <int>(); string next = ""; do { Console.WriteLine("Enter s to Stop Entering IDs"); next = Console.ReadLine(); logger.Info("User Entered: " + next); try { int id = int.Parse(next); if (id > 0 && id <= db.Categories.Max(c => c.CategoryID)) { ids.Add(id); Console.WriteLine("Another ID:"); } else { next = "s"; } } catch { next = "s"; } } while (next != "s"); if (ids.Count > 0) { query = db.Categories.Where(c => c.CategoryID == 0).OrderBy(c => c.CategoryID); foreach (int id in ids) { query = query.Union(db.Categories.Where(c => c.CategoryID == id).OrderBy(c => c.CategoryID)).OrderBy(c => c.CategoryID); } } else { categoryDisplay = ""; } } else if (categoryDisplay == "2") { Console.WriteLine("One Category Name to Display:"); List <string> names = new List <string>(); string next = ""; do { Console.WriteLine("Enter s to Stop Entering IDs"); next = Console.ReadLine(); logger.Info("User Entered: " + next); names.Add(next); } while (next != "s"); if (names.Count > 0) { query = db.Categories.Where(c => c.CategoryName == "").OrderBy(c => c.CategoryName); foreach (string name in names) { query = query.Union(db.Categories.Where(c => c.CategoryName == name).OrderBy(c => c.CategoryName)).OrderBy(c => c.CategoryName); } } else { categoryDisplay = ""; } } if (categoryDisplay.Length > 0) { Console.WriteLine($"{query.Count()} Categories Returned"); var newDB = new NorthwindContext(); var pQuery = newDB.Products.OrderBy(p => p.ProductName); foreach (Category c in query) { Console.WriteLine(c.CategoryName); pQuery = newDB.Products.Where(p => p.CategoryID == c.CategoryID).OrderBy(p => p.ProductName); Console.WriteLine($"{pQuery.Count()} Products Returned"); foreach (Product p in pQuery) { if (!p.Discontinued) { Console.ForegroundColor = ConsoleColor.Green; } else { Console.ForegroundColor = ConsoleColor.Red; } Console.WriteLine(" " + p.ProductName); } Console.ResetColor(); } } else { logger.Info("Category Display Cancelled"); } } } else if (choice == "7") { var products = db.Products.OrderBy(p => p.ProductID); Console.WriteLine("Select Which Product To Delete"); foreach (var p in products) { Console.WriteLine(p.ProductID + " - " + p.ProductName); } Console.WriteLine("C to Cancel"); string delete = Console.ReadLine(); Console.Clear(); logger.Info("User Entered " + delete); try { int id = int.Parse(delete); if (id > 0 && id <= products.Max(p => p.ProductID)) { Product product = db.Products.Find(id); if (product != null) { Console.WriteLine($"Are You Sure You Want To Delete The Product ID: {id} Named {product.ProductName}?\nThis Will Delete It Forever, And Delete All Orders Associated With It(Y/N)."); string answer = Console.ReadLine(); Console.Clear(); logger.Info("User Entered " + answer); if (answer.ToLower()[0] + "" == "y") { db.RemoveProduct(id); logger.Info($"Deleted Product ID: {id} Named {product.ProductName}"); } else { logger.Info("Delete Cancelled"); } } else { logger.Error($"Product ID {id} Does Not Exist"); } } else { logger.Error($"Product ID {id} Does Not Exist"); } } catch { logger.Error($"{delete} Is not a valid Input"); } } else if (choice == "8") { var categories = db.Categories.OrderBy(c => c.CategoryID); Console.WriteLine("Select Which Category To Delete"); foreach (var c in categories) { Console.WriteLine(c.CategoryID + " - " + c.CategoryName); } Console.WriteLine("C to Cancel"); string delete = Console.ReadLine(); Console.Clear(); logger.Info("User Entered " + delete); try { int id = int.Parse(delete); if (id > 0 && id <= categories.Max(c => c.CategoryID)) { Category category = db.Categories.Find(id); if (category != null) { Console.WriteLine($"Are You Sure You Want To Delete The Category ID: {id} Named {category.CategoryName}?\nThis Will Delete It Forever, And Delete All Products Associated With It, As Well as Any Orders Associated With The Products Deleted(Y/N)."); string answer = Console.ReadLine(); Console.Clear(); logger.Info("User Entered " + answer); if (answer.ToLower()[0] + "" == "y") { db.RemoveProduct(id); logger.Info($"Deleted Category ID: {id} Named {category.CategoryName}"); } else { logger.Info("Delete Cancelled"); } } else { logger.Error($"Category ID {id} Does Not Exist"); } } else { logger.Error($"Category ID {id} Does Not Exist"); } } catch { logger.Error($"{delete} Is not a valid Input"); } } } while (choice == "1" || choice == "2" || choice == "3" || choice == "4" || choice == "5" || choice == "6" || choice == "7" || choice == "8"); } catch (Exception ex) { logger.Error(ex.Message + " " + ex.InnerException); } logger.Info("Program Ended"); }
static void Main(string[] args) { var db = new NorthwindContext(); logger.Info("Started"); try { string choice; do { Console.WriteLine("1) Add Products records"); Console.WriteLine("2) Edit a Products record"); Console.WriteLine("3) Display Products records"); Console.WriteLine("4) Add Categories records"); Console.WriteLine("5) Edit a Categories record"); Console.WriteLine("6) Display Categories records"); Console.WriteLine("7) Delete a Products record"); Console.WriteLine("8) Delete a Categories record"); Console.WriteLine("9) Display a random product"); Console.WriteLine("0) Display a random category and its products"); choice = Console.ReadLine(); Console.Clear(); logger.Info($"Option {choice} selected"); // add products record if (choice == "1") { Product product = new Product(); Console.WriteLine("Enter Product Name:"); product.ProductName = Console.ReadLine(); Console.WriteLine("Enter the quantity per unit (string): "); product.QuantityPerUnit = Console.ReadLine(); Console.WriteLine("Enter the unit price (decimal): "); product.UnitPrice = Convert.ToDecimal(Console.ReadLine()); Console.WriteLine("Enter units in stock (int): "); product.UnitsInStock = Convert.ToInt16(Console.ReadLine()); Console.WriteLine("Enter units on order (int): "); product.UnitsOnOrder = Convert.ToInt16(Console.ReadLine()); Console.WriteLine("Enter reorder level (int): "); product.ReorderLevel = Convert.ToInt16(Console.ReadLine()); Console.WriteLine("Enter discontinued (bool): "); product.Discontinued = Convert.ToBoolean(Console.ReadLine()); Console.WriteLine("Enter category ID (int): "); product.CategoryId = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("Enter supplier ID (int): "); product.SupplierId = Convert.ToInt32(Console.ReadLine()); ValidationContext context = new ValidationContext(product, null, null); List <ValidationResult> results = new List <ValidationResult>(); var isValid = Validator.TryValidateObject(product, context, results, true); if (isValid) { // check for unique name if (db.Products.Any(p => p.ProductName == product.ProductName)) { // generate validation error isValid = false; results.Add(new ValidationResult("Name exists", new string[] { "CategoryName" })); } // add to db else { logger.Info("Validation passed"); db.AddProduct(product); logger.Info("Product added - {name}", product.ProductName); } } } // edit a products record else if (choice == "2") { var query = db.Products.OrderBy(b => b.ProductID); var counter = 1; foreach (var item in query) { Console.WriteLine(counter + ") " + item.ProductName); counter++; } Console.WriteLine("Select the product number to edit: "); var productSelection = Convert.ToInt32(Console.ReadLine()); var selectedProduct = db.Products.Find(productSelection); Product newProduct = new Product(); Console.WriteLine("Enter new Product Name:"); newProduct.ProductName = Console.ReadLine(); Console.WriteLine("Enter the new quantity per unit (string): "); newProduct.QuantityPerUnit = Console.ReadLine(); Console.WriteLine("Enter the new unit price (decimal): "); newProduct.UnitPrice = Convert.ToDecimal(Console.ReadLine()); Console.WriteLine("Enter new units in stock (int): "); newProduct.UnitsInStock = Convert.ToInt16(Console.ReadLine()); Console.WriteLine("Enter new units on order (int): "); newProduct.UnitsOnOrder = Convert.ToInt16(Console.ReadLine()); Console.WriteLine("Enter new reorder level (int): "); newProduct.ReorderLevel = Convert.ToInt16(Console.ReadLine()); Console.WriteLine("Enter new discontinued (bool): "); newProduct.Discontinued = Convert.ToBoolean(Console.ReadLine()); Console.WriteLine("Enter new category ID (int): "); newProduct.CategoryId = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("Enter new supplier ID (int): "); newProduct.SupplierId = Convert.ToInt32(Console.ReadLine()); db.EditProduct(selectedProduct, newProduct); } // display products records else if (choice == "3") { string productsDisplayChoice; Console.WriteLine("1) See all products"); Console.WriteLine("2) See discontinued products"); Console.WriteLine("3) See active products"); Console.WriteLine("4) Display a specific product"); productsDisplayChoice = Console.ReadLine(); Console.Clear(); logger.Info($"Option {productsDisplayChoice} selected"); // all products if (productsDisplayChoice == "1") { var query = db.Products.OrderBy(p => p.ProductID); Console.WriteLine($"{query.Count()} records returned"); foreach (var item in query) { Console.WriteLine($"{item.ProductName} - (Discontinued = {item.Discontinued})"); } logger.Info("Product(s) displayed."); } // discontinued products else if (productsDisplayChoice == "2") { var query = db.Products.OrderBy(p => p.ProductID); foreach (var item in query) { if (item.Discontinued == true) { Console.WriteLine($"{item.ProductName} - (Discontinued = {item.Discontinued})"); } } logger.Info("Product(s) displayed."); } // active products else if (productsDisplayChoice == "3") { var query = db.Products.OrderBy(p => p.ProductID); foreach (var item in query) { if (item.Discontinued == false) { Console.WriteLine($"{item.ProductName} - (Discontinued = {item.Discontinued})"); } } logger.Info("Product(s) displayed."); } // specific product else if (productsDisplayChoice == "4") { var query = db.Products.OrderBy(p => p.ProductID); var counter = 1; foreach (var item in query) { Console.WriteLine(counter + ") " + item.ProductName); counter++; } Console.WriteLine("Select the product number to view: "); var productSelection = Convert.ToInt32(Console.ReadLine()); var selectedProduct = db.Products.Find(productSelection); Console.WriteLine($"{selectedProduct.ProductName}"); Console.WriteLine($"Product ID: {selectedProduct.ProductID}"); Console.WriteLine($"Quantity per Unit: {selectedProduct.QuantityPerUnit}"); Console.WriteLine($"Unit Price: {selectedProduct.UnitPrice}"); Console.WriteLine($"Units in Stock: {selectedProduct.UnitsInStock}"); Console.WriteLine($"Units on Order: {selectedProduct.UnitsOnOrder}"); Console.WriteLine($"Reorder Level: {selectedProduct.ReorderLevel}"); Console.WriteLine($"Discontinued: {selectedProduct.Discontinued}"); logger.Info("Product(s) displayed."); } } // add categories record else if (choice == "4") { Category category = new Category(); Console.WriteLine("Enter Category Name:"); category.CategoryName = Console.ReadLine(); Console.WriteLine("Enter the Category Description:"); category.Description = Console.ReadLine(); ValidationContext context = new ValidationContext(category, null, null); List <ValidationResult> results = new List <ValidationResult>(); var isValid = Validator.TryValidateObject(category, context, results, true); if (isValid) { // check for unique name if (db.Categories.Any(c => c.CategoryName == category.CategoryName)) { // generate validation error isValid = false; results.Add(new ValidationResult("Name exists", new string[] { "CategoryName" })); } // add to db else { logger.Info("Validation passed"); db.AddCategory(category); logger.Info("Category added - {name}", category.CategoryName); } } } // edit categories record else if (choice == "5") { var query = db.Categories.OrderBy(c => c.CategoryId); var counter = 1; foreach (var item in query) { Console.WriteLine(counter + ". " + item.CategoryName); counter++; } Console.WriteLine("Select the category number to edit: "); var categorySelection = Convert.ToInt32(Console.ReadLine()); var selectedCategory = db.Categories.Find(categorySelection); Category newCategory = new Category(); Console.WriteLine("Enter new Category Name:"); newCategory.CategoryName = Console.ReadLine(); Console.WriteLine("Enter the new Category Description:"); newCategory.Description = Console.ReadLine(); db.EditCategory(selectedCategory, newCategory); } // display categories records else if (choice == "6") { string categoryDisplayChoice; Console.WriteLine("1) See all categories"); Console.WriteLine("2) See all categories and related active products"); Console.WriteLine("3) See specific category and related active products"); categoryDisplayChoice = Console.ReadLine(); Console.Clear(); logger.Info($"Option {categoryDisplayChoice} selected"); // all categories if (categoryDisplayChoice == "1") { var query = db.Categories.OrderBy(c => c.CategoryId); Console.WriteLine($"{query.Count()} records returned"); foreach (var item in query) { Console.WriteLine($"{item.CategoryName} - {item.Description}"); } } // all categories and products else if (categoryDisplayChoice == "2") { var query = db.Categories.OrderBy(c => c.CategoryId); var products = db.Products.OrderBy(p => p.CategoryId); foreach (var item in query) { Console.WriteLine("------------"); Console.WriteLine(item.CategoryName); Console.WriteLine("------------"); var selectedCategory = item; db.productsInCategory(selectedCategory); } } // specific category else if (categoryDisplayChoice == "3") { var query = db.Categories.OrderBy(c => c.CategoryId); var products = db.Products.OrderBy(p => p.ProductName); var counter = 1; foreach (var item in query) { Console.WriteLine(counter + ") " + item.CategoryName); counter++; } Console.WriteLine("Select the category number to view: "); var categorySelection = Convert.ToInt32(Console.ReadLine()); var selectedCategory = db.Categories.Find(categorySelection); Console.WriteLine($"{selectedCategory.CategoryName}"); foreach (var item in products) { if (selectedCategory.CategoryId == item.CategoryId && item.Discontinued == false) { Console.WriteLine($"{item.ProductName}"); } } logger.Info("Product(s) displayed."); } } // delete products record else if (choice == "7") { var query = db.Products.OrderBy(p => p.ProductName); var counter = 1; foreach (var item in query) { Console.WriteLine(counter + ") " + item.ProductName); counter++; } Console.WriteLine("Select the product number to delete: "); var productSelection = Convert.ToInt32(Console.ReadLine()); var selectedProduct = db.Products.Find(productSelection); db.DeleteProduct(selectedProduct); logger.Info("Product deleted"); } // delete categories record else if (choice == "8") { var query = db.Categories.OrderBy(c => c.CategoryId); var counter = 1; foreach (var item in query) { Console.WriteLine(counter + ") " + item.CategoryName); counter++; } Console.WriteLine("Select the category number to delete: "); var categorySelection = Convert.ToInt32(Console.ReadLine()); var selectedCategory = db.Categories.Find(categorySelection); db.DeleteCategory(selectedCategory); logger.Info("Category deleted"); } // view random product else if (choice == "9") { var query = db.Products.OrderBy(p => p.ProductName); int lowestProductId = 1; int highestProductId = 0; foreach (var item in query) { highestProductId = item.ProductID; } var rand = new Random(); int generatedProduct = rand.Next(lowestProductId, highestProductId); var selectedProduct = db.Products.Find(generatedProduct); Console.WriteLine($"{selectedProduct.ProductName}"); Console.WriteLine($"Product ID: {selectedProduct.ProductID}"); Console.WriteLine($"Quantity per Unit: {selectedProduct.QuantityPerUnit}"); Console.WriteLine($"Unit Price: {selectedProduct.UnitPrice}"); Console.WriteLine($"Units in Stock: {selectedProduct.UnitsInStock}"); Console.WriteLine($"Units on Order: {selectedProduct.UnitsOnOrder}"); Console.WriteLine($"Reorder Level: {selectedProduct.ReorderLevel}"); Console.WriteLine($"Discontinued: {selectedProduct.Discontinued}"); } // view random category else if (choice == "0") { var query = db.Categories.OrderBy(c => c.CategoryId); var products = db.Products.OrderBy(p => p.ProductName); int lowestCategoryId = 1; int highestCategoryId = 0; foreach (var item in query) { highestCategoryId = item.CategoryId; } var rand = new Random(); int generatedCategory = rand.Next(lowestCategoryId, highestCategoryId); var selectedCategory = db.Categories.Find(generatedCategory); Console.WriteLine("------------"); Console.WriteLine(selectedCategory.CategoryName); Console.WriteLine("------------"); foreach (var item in products) { if (selectedCategory.CategoryId == item.CategoryId) { Console.WriteLine($"{item.ProductName}"); } } } // invalid option else { Console.WriteLine("Invalid choice."); } } while (choice.ToLower() != "q"); } catch (Exception ex) { logger.Error(ex.Message); } logger.Info("Ended"); }
public static void Main(string[] args) { var db = new NorthwindContext(); logger.Info("Program started"); try { string choice; do { Console.WriteLine("1) Display Categories"); Console.WriteLine("2) Add Category"); Console.WriteLine("3) Display Category and related products"); Console.WriteLine("4) Display all Categories and their related products"); Console.WriteLine("\"q\" to quit"); choice = Console.ReadLine(); Console.Clear(); logger.Info($"Option {choice} selected"); if (choice == "1") { var query = db.Categories.OrderBy(p => p.CategoryName); Console.WriteLine($"{query.Count()} records returned"); foreach (var item in query) { Console.WriteLine($"{item.CategoryName} - {item.Description}"); } } else if (choice == "2") { Category category = new Category(); Console.WriteLine("Enter Category Name:"); category.CategoryName = Console.ReadLine(); Console.WriteLine("Enter the Category Description:"); category.Description = Console.ReadLine(); ValidationContext context = new ValidationContext(category, null, null); List <ValidationResult> results = new List <ValidationResult>(); var isValid = Validator.TryValidateObject(category, context, results, true); if (isValid) { // check for unique name if (db.Categories.Any(c => c.CategoryName == category.CategoryName)) { // generate validation error isValid = false; results.Add(new ValidationResult("Name exists", new string[] { "CategoryName" })); } else { logger.Info("Validation passed"); // TODO: save category to db db.AddCategory(category); logger.Info("Category added - {name}", category.CategoryName); } } if (!isValid) { foreach (var result in results) { logger.Error($"{result.MemberNames.First()} : {result.ErrorMessage}"); } } } else if (choice == "3") { var query = db.Categories.OrderBy(p => p.CategoryId); Console.WriteLine("Select the category whose products you want to display:"); foreach (var item in query) { Console.WriteLine($"{item.CategoryId}) {item.CategoryName}"); } int id = int.Parse(Console.ReadLine()); Console.Clear(); logger.Info($"CategoryId {id} selected"); Category category = db.Categories.FirstOrDefault(c => c.CategoryId == id); Console.WriteLine($"{category.CategoryName} - {category.Description}"); foreach (Product p in category.Products) { Console.WriteLine(p.ProductName); } } else if (choice == "4") { var query = db.Categories.Include("Products").OrderBy(p => p.CategoryId); foreach (var item in query) { Console.WriteLine($"{item.CategoryName}"); foreach (Product p in item.Products) { Console.WriteLine($"\t{p.ProductName}"); } } } Console.WriteLine(); } while (choice.ToLower() != "q"); } catch (Exception ex) { logger.Error(ex.Message); } logger.Info("Program ended"); }
public static void Main(string[] args) { logger.Info("Program started"); try { string choice; do { Console.WriteLine("1) Display Categories"); Console.WriteLine("2) Add Category"); Console.WriteLine("3) Edit Category"); Console.WriteLine("4) Display a specific category and related active products"); Console.WriteLine("5) Display all categories and related products"); Console.WriteLine("6) Add a new product"); Console.WriteLine("7) Edit a product"); Console.WriteLine("8) Display products"); Console.WriteLine("9) Display a single product"); Console.WriteLine("10) Delete a category"); Console.WriteLine("11) Delete a product"); Console.WriteLine("\"q\" to quit"); choice = Console.ReadLine(); Console.Clear(); logger.Info($"Option {choice} selected"); if (choice == "1") { //Category.ListCategoriesWithDescription(); var table = new ConsoleTable(); var db = new NorthwindContext(); table.SetHeaders("Name", "Descripion"); foreach (var item in db.Categories) { table.AddRow(item.CategoryName, item.Description); } Console.WriteLine(table.ToString()); } else if (choice == "2") { Category category = new Category(); Console.WriteLine("Enter Category Name:"); category.CategoryName = Console.ReadLine(); ValidationContext context = new ValidationContext(category, null, null); List <ValidationResult> results = new List <ValidationResult>(); var isValid = Validator.TryValidateObject(category, context, results, true); if (isValid) { var db = new NorthwindContext(); // check for unique name if (db.Categories.Any(c => c.CategoryName == category.CategoryName)) { // generate validation error isValid = false; results.Add(new ValidationResult("Name exists", new string[] { "CategoryName" })); } else { Console.WriteLine("Enter the Category Description:"); category.Description = Console.ReadLine(); logger.Info("Validation passed"); db.AddCategory(category); logger.Info("Category added - {title}", category.CategoryName); } } if (!isValid) { foreach (var result in results) { logger.Error($"{result.MemberNames.First()} : {result.ErrorMessage}"); } } } else if (choice == "3") { Category.EditCategory(); } else if (choice == "4") { var db = new NorthwindContext(); var query = db.Categories.OrderBy(p => p.CategoryId); foreach (var item in query) { Console.WriteLine($"{item.CategoryId}) {item.CategoryName}"); } Console.WriteLine("Select the category whose products you want to display:"); int id = int.Parse(Console.ReadLine()); Console.Clear(); logger.Info($"CategoryId {id} selected"); Category category = db.Categories.FirstOrDefault(c => c.CategoryId == id); Console.WriteLine($"{category.CategoryName} - {category.Description}"); foreach (Product p in category.Products.Where(p => p.Discontinued != true)) { Console.WriteLine(p.ProductName); } } else if (choice == "5") { //Display all Categories and their related active (not discontinued) product data (CategoryName, ProductName) var db = new NorthwindContext(); var query = db.Categories.Include("Products").OrderBy(p => p.CategoryId); foreach (var item in query) { Console.WriteLine($"{item.CategoryName}"); foreach (Product p in item.Products) { if (p.Discontinued == false) { Console.WriteLine($"\t{p.ProductName}"); } } } } else if (choice == "6") { var db = new NorthwindContext(); var categoryQuery = db.Categories.OrderBy(p => p.CategoryId); var supplierQuery = db.Suppliers.OrderBy(p => p.SupplierId); Console.WriteLine("Select a product Category"); foreach (var item in categoryQuery) { Console.WriteLine($"{item.CategoryId}) {item.CategoryName}"); } //check for valid category if (int.TryParse(Console.ReadLine(), out int CategoryId)) { if (db.Categories.Any(c => c.CategoryId == CategoryId)) { Console.Clear(); Console.WriteLine("Enter a product Supplier or \"add\" to enter a new supplier."); foreach (var item in supplierQuery) { Console.WriteLine($"{item.SupplierId}) {item.CompanyName}"); } var supplier = Console.ReadLine(); //check for valid supplier if (supplier.ToLower() == "add") { Supplier.NewSupplier(); } else if (int.TryParse(supplier, out int supplierId)) { if (db.Suppliers.Any(s => s.SupplierId == supplierId)) { Product product = InputProduct(db); product.CategoryId = CategoryId; if (product != null) { product.SupplierId = supplierId; db.AddProduct(product); logger.Info("Product added - {title}", product.ProductName); } } else { logger.Error("There are no Suppliers with that Id"); } } else { logger.Error("Invalid Supplier Id"); } } else { logger.Error("There are no Categories with that Id"); } } else { logger.Error("Invalid Category Id"); } } else if (choice == "7") { var db = new NorthwindContext(); var query = db.Categories.Include("Products").OrderBy(p => p.CategoryId); Console.WriteLine("Select the product category:"); foreach (var item in query) { Console.WriteLine($"{item.CategoryId}) {item.CategoryName}"); } //check for valid category if (int.TryParse(Console.ReadLine(), out int CategoryId)) { if (db.Categories.Any(c => c.CategoryId == CategoryId)) { logger.Info($"CategoryId {CategoryId} selected"); Console.Clear(); Console.WriteLine("Select the product number you wish to edit:"); logger.Info($"CategoryId {CategoryId} selected"); var productList = db.Products.Where(pl => pl.CategoryId == CategoryId).OrderBy(pl => pl.ProductId); foreach (var item in productList) { Console.WriteLine($"{item.ProductId}) {item.ProductName}"); } //check for valid product id if (int.TryParse(Console.ReadLine(), out int ProductId)) { if (db.Products.Any(p => p.ProductId == ProductId)) { Product product = db.Products.FirstOrDefault(p => p.ProductId == ProductId); Product.EditProduct(product, db); } } } } } else if (choice == "8") { string displayChoice; var db = new NorthwindContext(); Console.Clear(); Console.WriteLine("1) Display ALL products"); Console.WriteLine("2) Display only DISCONTINUED products"); Console.WriteLine("3) Display only ACTIVE products"); displayChoice = Console.ReadLine(); logger.Info($"Option {choice} selected"); if (displayChoice == "1") { logger.Info("{0} records returned", db.Products.Count()); Console.WriteLine("ALL Products (Discontinued products in Red)"); foreach (var item in db.Products) { Console.BackgroundColor = item.Discontinued ? ConsoleColor.Red : ConsoleColor.Black; Console.WriteLine(item.ProductName); } Console.ResetColor(); } if (displayChoice == "2") { var query = db.Products.Where(p => p.Discontinued == true); logger.Info("{0} records returned", query.Count()); Console.WriteLine("ALL Discontinued Products"); foreach (var item in query) { Console.WriteLine(item.ProductName); } } if (displayChoice == "3") { var query = db.Products.Where(p => p.Discontinued == false); logger.Info("{0} records returned", query.Count()); Console.WriteLine("ALL Active Products"); foreach (var item in query) { Console.WriteLine(item.ProductName); } } } else if (choice == "9") { string searchTerm; string displayChoice; var db = new NorthwindContext(); Console.Clear(); Console.WriteLine("Chose how you wish to select a product:"); Console.WriteLine("1) Enter Product Id"); Console.WriteLine("2) Search for product name"); displayChoice = Console.ReadLine(); if (displayChoice == "1") { Console.WriteLine("Enter the Id number of the product you wish to display"); if (int.TryParse(Console.ReadLine(), out int productId)) { if (db.Products.Any(p => p.ProductId == productId)) { Console.Clear(); Product.DisplayProduct(db.Products.FirstOrDefault(p => p.ProductId == productId)); } else { logger.Error("There are no Products with that Id"); } } else { logger.Error("Invalid product Id"); } } if (displayChoice == "2") { Console.WriteLine("Enter all or part of the product name"); searchTerm = Console.ReadLine(); var query = db.Products.Where(p => p.ProductName.Contains(searchTerm)).OrderBy(p => p.ProductName); Console.WriteLine($"{query.Count()} records returned"); if (query.Count() == 1) { Console.Clear(); Product.DisplayProduct(query.FirstOrDefault()); } if (query.Count() > 1) { Console.WriteLine("{0,-8} {1,-50}", "ID", "ProductName"); foreach (var item in query) { Console.WriteLine("{0,-8} {1,-50}", item.ProductId, item.ProductName); } Console.WriteLine("\nEnter the Id number of the product you wish to display"); if (int.TryParse(Console.ReadLine(), out int productId)) { if (db.Products.Any(p => p.ProductId == productId)) { Console.Clear(); Product.DisplayProduct(db.Products.FirstOrDefault(p => p.ProductId == productId)); } else { logger.Error("There are no Products with that Id"); } } else { logger.Error("Invalid product Id"); } } } } else if (choice == "10") { var db = new NorthwindContext(); Category.ListCategories(); Console.WriteLine("Enter the Category Id that you wish to delete"); int id = int.Parse(Console.ReadLine()); Console.Clear(); logger.Info($"CategoryId {id} selected"); Category category = db.Categories.FirstOrDefault(c => c.CategoryId == id); if (db.DeleteCategory(category)) { logger.Info("Category {0} successfully deleted", category.CategoryName); } else { logger.Error("Unable to delete a category with associated products."); Console.WriteLine("You may not delete a category with associated products. In order to delete a category, all the associated products must first be placed in another category or deleted."); } } else if (choice == "11") { //Select and display product string searchTerm; string displayChoice; var db = new NorthwindContext(); Console.Clear(); Console.WriteLine("Chose how you wish to select a product:"); Console.WriteLine("1) Enter Product Id"); Console.WriteLine("2) Search for product name"); displayChoice = Console.ReadLine(); if (displayChoice == "1") { Console.WriteLine("Enter the Id number of the product you wish to delete"); if (int.TryParse(Console.ReadLine(), out int productId)) { if (db.Products.Any(p => p.ProductId == productId)) { Console.Clear(); //Product.DisplayProduct(db.Products.FirstOrDefault(p => p.ProductId == productId)); db.DeleteProduct(db.Products.FirstOrDefault(p => p.ProductId == productId)); logger.Info("Product Id {0} successfully deleted.", productId); } else { logger.Error("There are no Products with that Id"); } } else { logger.Error("Invalid product Id"); } } if (displayChoice == "2") { Console.WriteLine("Enter all or part of the product name"); searchTerm = Console.ReadLine(); var query = db.Products.Where(p => p.ProductName.Contains(searchTerm)).OrderBy(p => p.ProductName); Console.WriteLine($"{query.Count()} records returned"); if (query.Count() == 1) { Console.Clear(); Product.DisplayProduct(query.FirstOrDefault()); db.DeleteProduct(query.FirstOrDefault()); logger.Info("Product id {0} successfully deleted", query.FirstOrDefault().ProductId); } if (query.Count() > 1) { Console.WriteLine("{0,-8} {1,-50}", "ID", "ProductName"); foreach (var item in query) { Console.WriteLine("{0,-8} {1,-50}", item.ProductId, item.ProductName); } Console.WriteLine("\nEnter the Id number of the product you wish to delete"); if (int.TryParse(Console.ReadLine(), out int productId)) { if (db.Products.Any(p => p.ProductId == productId)) { Console.Clear(); Product.DisplayProduct(db.Products.FirstOrDefault(p => p.ProductId == productId)); } else { logger.Error("There are no Products with that Id"); } } else { logger.Error("Invalid product Id"); } } } } Console.WriteLine(); } while (choice.ToLower() != "q"); } catch (Exception ex) { logger.Error(ex.Message); } logger.Info("Program ended"); }