コード例 #1
0
ファイル: Program.cs プロジェクト: pjbrahm1/Northwind-Console
        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");
        }
コード例 #2
0
        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");
        }
コード例 #3
0
        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");
        }
コード例 #4
0
        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");
        }
コード例 #5
0
        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");
        }
コード例 #6
0
        public static void Main(string[] args)
        {
            logger.Info("Program started");
            try
            {
                string choice;
                do
                {
                    //Sorry Mark, I prefer the switch over an if/else statement, hope you don't mind I changed it up.
                    Console.Clear();
                    //For a "C" Grade
                    Console.WriteLine("1) Add a Product");
                    Console.WriteLine("2) Display all Products");
                    Console.WriteLine("3) Edit a Product");
                    Console.WriteLine("4) Display Active Products");
                    Console.WriteLine("5) Display Discontinued Products");
                    Console.WriteLine("6) Search Products");
                    //For a "B" Grade
                    Console.WriteLine("7) Add a Category");
                    Console.WriteLine("8) Edit a Category");
                    Console.WriteLine("9) Display all Categories");
                    Console.WriteLine("10) Display all non-discontinued items by a Category");
                    Console.WriteLine("11) Display all non-discontinued items by a specific Category");
                    //For an "A" Grade
                    Console.WriteLine("12) Delete a Category");
                    Console.WriteLine("13) Delete a Product");
                    Console.WriteLine("\"q\" to quit");
                    choice = Console.ReadLine();

                    switch (choice)
                    {
                    //add product
                    case "1":
                    {
                        Product.addProducts(logger);
                        break;
                    }

                    //display products
                    case "2":
                    {
                        Product.displayAllProducts(logger);
                        break;
                    }

                    //edit product
                    case "3":
                    {
                        var db = new NorthwindContext();
                        Console.WriteLine("Choose Product ID to edit: ");
                        var product = Product.getProduct(db, logger);

                        if (product != null)
                        {
                            Product UpdatedProduct = Product.EditProduct(db, logger);

                            if (UpdatedProduct != null)
                            {
                                UpdatedProduct.ProductID = product.ProductID;
                                db.EditProducts(UpdatedProduct);
                                logger.Info($"Product ID: {UpdatedProduct.ProductID}, {UpdatedProduct.ProductName} updated");
                            }
                        }
                        Console.WriteLine();
                        Console.WriteLine("Press any key to return to the Menu", Color.Red);
                        Console.ReadLine();
                        break;
                    }

                    //display active products
                    case "4":
                    {
                        Product.displayActiveProducts(logger);
                        break;
                    }

                    //display discountinued products
                    case "5":
                    {
                        Product.displayDiscontinuedProducts(logger);
                        break;
                    }

                    //search products
                    case "6":
                    {
                        Product.searchProducts(logger);
                        break;
                    }

                    //add category
                    case "7":
                    {
                        Category.addCategories(logger);
                        break;
                    }

                    //edit category
                    case "8":
                    {
                        var db = new NorthwindContext();
                        Console.WriteLine("Choose category ID to edit: ");
                        var category = Category.GetCategory(db, logger);

                        if (category != null)
                        {
                            Category UpdatedCategory = Category.InputCategory(db, logger);

                            if (UpdatedCategory != null)
                            {
                                UpdatedCategory.CategoryId = category.CategoryId;
                                db.EditCategory(UpdatedCategory);
                                logger.Info($"Category Id: {UpdatedCategory.CategoryId} updated");
                            }
                        }
                        Console.WriteLine();
                        Console.WriteLine("Press any key to return to the Menu", Color.Red);
                        Console.ReadLine();
                        break;
                    }

                    //display all categories
                    case "9":
                    {
                        Category.displayAllCategories(logger);
                        break;
                    }

                    //display all non-discontinued items by Category
                    case "10":
                    {
                        Category.displayAllCategoriesProductsNotDiscontinued(logger);
                        break;
                    }

                    //display all non-discontinued items by specific Category
                    case "11":
                    {
                        Category.displaySpecificCategoryProducts(logger);
                        break;
                    }

                    //delete a category
                    case "12":
                    {
                        var db = new NorthwindContext();
                        Console.WriteLine("Select category ID to delete:");
                        var categoryToDelete = Category.GetCategory(db, logger);
                        try
                        {
                            db.deleteCategory(categoryToDelete);
                            logger.Info($"{categoryToDelete.CategoryName} deleted");
                        }
                        catch (Exception)
                        {
                            logger.Error("Cannot Delete a record that affects other tables");
                        }
                        Console.WriteLine();
                        Console.WriteLine("Press any key to return to the Menu", Color.Red);
                        Console.ReadLine();
                        break;
                    }

                    //delete a product
                    case "13":
                    {
                        var db = new NorthwindContext();
                        Console.WriteLine("Select product ID to delete:");
                        var productToDelete = Product.getProduct(db, logger);
                        try
                        {
                            db.deleteProduct(productToDelete);
                            logger.Info($"{productToDelete.ProductName} deleted");
                        }
                        catch (Exception)
                        {
                            logger.Error("Cannot Delete a record that will affect other tables");
                        }
                        Console.WriteLine();
                        Console.WriteLine("Press any key to return to the Menu", Color.Red);
                        Console.ReadLine();
                        break;
                    }
                    }
                } while (choice.ToLower() != "q");
            }
            catch (Exception ex)
            {
                logger.Error(ex.Message);
            }
            logger.Info("Program ended");
        }
コード例 #7
0
        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"));
        }
コード例 #8
0
        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");
        }
コード例 #9
0
ファイル: Program.cs プロジェクト: ikevin1/Console
        private static string ProductIDD;// i had this for choice 7 to work

        public static void Main(string[] args)
        {
            logger.Info("Program started");
            TextInfo Ti = new CultureInfo("en-US", false).TextInfo;

            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 Products");
                    Console.WriteLine("6) Edit Specific Products");
                    Console.WriteLine("7) Display all Products(see all products, discontinued products, or active products)");
                    Console.WriteLine("8) Edit Category");
                    Console.WriteLine("9) Display Categories(see a specific category & its prodcuts, display a specific category");
                    Console.WriteLine("10) Delete Category");
                    Console.WriteLine("11) Delete Specific 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(c => c.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();
                        string                  categoryChoice = "";
                        ValidationContext       context        = new ValidationContext(category, null, null);
                        List <ValidationResult> results        = new List <ValidationResult>();
                        var db      = new NorthwindContext();
                        var isValid = Validator.TryValidateObject(category, context, results, true);

                        do
                        {
                            Console.WriteLine("Enter Category Name:");
                            category.CategoryName = Console.ReadLine();
                            category.CategoryName = Ti.ToTitleCase(category.CategoryName);


                            if (db.Categories.Any(c => c.CategoryName == category.CategoryName))
                            {
                                // generate validation error
                                isValid = false;
                                results.Add(new ValidationResult("Name exists", new string[] { "CategoryName" }));
                                if (!isValid)
                                {
                                    foreach (var result in results)
                                    {
                                        logger.Error($"{result.MemberNames.First()} : {result.ErrorMessage}");
                                    }
                                }
                            }
                            else if (category.CategoryName == "")
                            {
                                // generate validation error
                                isValid = false;
                                results.Add(new ValidationResult("Opps!!!...No Blank category", new string[] { "CategoryName" }));
                                if (!isValid)
                                {
                                    foreach (var result in results)
                                    {
                                        logger.Error($"{result.MemberNames.First()} : {result.ErrorMessage}");
                                    }
                                }
                            }
                            else
                            {
                                Console.WriteLine("Enter the Category Description:");
                                category.Description = Console.ReadLine();
                                //ToDO add new category to database
                                db.Categories.Add(category);
                                db.SaveChanges();
                                logger.Info("Category added");
                            }
                            Console.WriteLine("Do you want to enter another category name or enter q to quit");
                            categoryChoice = Console.ReadLine();
                        } while (categoryChoice.ToLower() != "q");
                    }
                    else if (choice == "3")
                    {
                        var db    = new NorthwindContext();
                        var query = db.Categories.OrderBy(c => c.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 db    = new NorthwindContext();
                        var query = db.Categories.Include("Products").OrderBy(c => c.CategoryId);
                        foreach (var item in query)
                        {
                            Console.WriteLine($"{item.CategoryName}");
                            foreach (Product p in item.Products)
                            {
                                Console.WriteLine($"\t{p.ProductName}");
                            }
                        }
                    }
                    else if (choice == "5")
                    {
                        Product                 product = new Product();
                        Boolean                 isValid;
                        ValidationContext       context = new ValidationContext(product, null, null);
                        List <ValidationResult> results = new List <ValidationResult>();
                        var    db            = new NorthwindContext();
                        string productChoice = "";

                        do
                        {
                            Console.WriteLine("Enter Product Name:");
                            product.ProductName = Console.ReadLine();
                            product.ProductName = Ti.ToTitleCase(product.ProductName);
                            // check for unique name
                            if (db.Products.Any(p => p.ProductName == product.ProductName))
                            {
                                // generate validation error
                                isValid = false;
                                results.Add(new ValidationResult("Data already exists", new string[] { "ProductName" }));
                            }

                            else
                            {
                                Console.WriteLine("Enter Product Quantity:");
                                product.QuantityPerUnit = Console.ReadLine();
                                Console.WriteLine("Enter Product UnitPrice:");
                                string  price = Console.ReadLine();
                                decimal unitPrice;
                                if (decimal.TryParse(price, out unitPrice))
                                {
                                    product.UnitPrice = unitPrice;
                                    Console.WriteLine("Enter the Products Units In Stock:");
                                    string stock = Console.ReadLine();
                                    Int16  UnitsInStock;
                                    if (Int16.TryParse(stock, out UnitsInStock))
                                    {
                                        product.UnitsInStock = UnitsInStock;
                                        //logger.Info("Validation passed");
                                        Console.WriteLine("");
                                        Console.WriteLine("Enter the Products Units On Order:");
                                        string Order = Console.ReadLine();
                                        Int16  UnitsOnOrder;
                                        if (Int16.TryParse(Order, out UnitsOnOrder))
                                        {
                                            product.UnitsOnOrder = UnitsOnOrder;
                                            //logger.Info("Validation passed");
                                            Console.WriteLine("Enter the Products ReorderLevel:");
                                            string Level = Console.ReadLine();
                                            Int16  ReorderLevel;

                                            if (Int16.TryParse(Level, out ReorderLevel))
                                            {
                                                product.ReorderLevel = ReorderLevel;
                                                // logger.Info("Validation passed");
                                            }

                                            Console.WriteLine("Discontinued? " + "Enter the active status of the product(false if active and true if discontinued)");
                                            string Disc = Console.ReadLine();
                                            bool   Discontinued;
                                            if (bool.TryParse(Disc, out Discontinued))
                                            {
                                                product.Discontinued = Discontinued;
                                                logger.Info("Validation passed");
                                            }
                                            //save to file
                                            db.Products.Add(product);
                                            db.SaveChanges();
                                            logger.Info("Product (id: {productId}) added", product.ProductID);
                                        }
                                    }
                                    else
                                    {
                                        Console.WriteLine("Invalid Stock entered");
                                    }
                                }
                                else
                                {
                                    Console.WriteLine("Invalid price entered");
                                }
                            }

                            Console.WriteLine("Do you want to enter another Product or enter q to quit");
                            productChoice = Console.ReadLine();
                        } while (productChoice.ToLower() != "q");
                    }
                    else if (choice == "6")
                    {
                        // edit product

                        Console.WriteLine("Choose the product to edit:");
                        var product = Console.ReadLine();

                        var db = new NorthwindContext();

                        if (product != null)
                        {
                            // input product
                            Product UpdatedProduct = db.Products.FirstOrDefault(p => p.ProductName == product);
                            if (UpdatedProduct != null)
                            {
                                string editChoice = "";
                                do
                                {
                                    //show the product details entered here
                                    Console.WriteLine("1) Edit Product Name");
                                    Console.WriteLine("2) Edit Quantity Per Unit");
                                    Console.WriteLine("3) Edit Unit Price of product");
                                    Console.WriteLine("4) Edit Units In Stock");
                                    Console.WriteLine("5) Edit Units On Order");
                                    Console.WriteLine("6) Edit Reorder Level");
                                    Console.WriteLine("7) Edit Discontinued status(false/true entre only)");
                                    editChoice = Console.ReadLine();
                                    Console.Clear();
                                    logger.Info($"Option {editChoice} selected");
                                    //1) edit product name


                                    if (editChoice == "1")
                                    {
                                        Console.WriteLine("Enter new Product Name:");
                                        UpdatedProduct.ProductName = Console.ReadLine();
                                        UpdatedProduct.ProductName = Ti.ToTitleCase(UpdatedProduct.ProductName);
                                        db.EditProduct(UpdatedProduct);
                                        logger.Info("Product (id: {productId}) updated", UpdatedProduct.ProductID);
                                    }
                                    else if (editChoice == "2")
                                    {
                                        Console.WriteLine("Enter new Product Quantity:");
                                        UpdatedProduct.QuantityPerUnit = Console.ReadLine();
                                        db.EditProduct(UpdatedProduct);
                                        logger.Info("Product (id: {productId}) updated", UpdatedProduct.ProductID);
                                    }
                                    else if (editChoice == "3")
                                    {
                                        Console.WriteLine("Enter new Product UnitPrice:");
                                        string  price = Console.ReadLine();
                                        decimal unitPrice;
                                        if (decimal.TryParse(price, out unitPrice))
                                        {
                                            UpdatedProduct.UnitPrice = unitPrice;
                                            logger.Info("Validation passed");
                                        }
                                        db.EditProduct(UpdatedProduct);
                                        logger.Info("Product (id: {productId}) updated", UpdatedProduct.ProductID);
                                    }
                                    else if (editChoice == "4")
                                    {
                                        Console.WriteLine("Enter the Products Units In Stock:");
                                        string stock = Console.ReadLine();
                                        Int16  UnitsInStock;
                                        if (Int16.TryParse(stock, out UnitsInStock))
                                        {
                                            UpdatedProduct.UnitsInStock = UnitsInStock;

                                            logger.Info("Validation passed");
                                        }
                                        db.EditProduct(UpdatedProduct);
                                        logger.Info("Product (id: {productId}) updated", UpdatedProduct.ProductID);
                                    }
                                    else if (editChoice == "5")
                                    {
                                        Console.WriteLine("Enter the Products Units In Order:");
                                        string Order = Console.ReadLine();
                                        Int16  UnitsOnOrder;
                                        if (Int16.TryParse(Order, out UnitsOnOrder))
                                        {
                                            UpdatedProduct.UnitsOnOrder = UnitsOnOrder;

                                            logger.Info("Validation passed");
                                        }
                                        db.EditProduct(UpdatedProduct);
                                        logger.Info("Product (id: {productId}) updated", UpdatedProduct.ProductID);
                                    }
                                    else if (editChoice == "6")
                                    {
                                        Console.WriteLine("Enter the Products reorder level:");
                                        string level = Console.ReadLine();
                                        Int16  ReorderLevel;
                                        if (Int16.TryParse(level, out ReorderLevel))
                                        {
                                            UpdatedProduct.ReorderLevel = ReorderLevel;

                                            logger.Info("Validation passed");
                                        }
                                        db.EditProduct(UpdatedProduct);
                                        logger.Info("Product (id: {productId}) updated", UpdatedProduct.ProductID);
                                    }
                                    else if (editChoice == "7")
                                    {
                                        Console.WriteLine("Enter the Products Active(Discontuned) status(True/False):");
                                        string disc = Console.ReadLine();
                                        bool   Discontinued;
                                        if (bool.TryParse(disc, out Discontinued))
                                        {
                                            UpdatedProduct.Discontinued = Discontinued;

                                            logger.Info("Validation passed");
                                        }
                                        db.EditProduct(UpdatedProduct);
                                        logger.Info("Product (id: {productId}) updated", UpdatedProduct.ProductID);
                                    }


                                    Console.WriteLine("Do you want to enter to edit another Product or enter q to quit");
                                    editChoice = Console.ReadLine();
                                } while (editChoice.ToLower() != "q");
                            }
                        }
                    }
                    else if (choice == "7")// Display Products(all or sub)
                    {
                        do
                        {
                            var db    = new NorthwindContext();
                            var query = db.Products.OrderBy(b => b.ProductID);
                            foreach (var item in query)
                            {
                                Console.WriteLine($"{item.ProductID}) Products from {item.ProductName}");
                            }
                            Console.WriteLine("");
                            Console.WriteLine("Select the product to display:");
                            Console.WriteLine("0) All Products ");
                            Console.WriteLine("1) See a specific Products ");
                            Console.WriteLine("2) Discontinued Products ");
                            Console.WriteLine("3) Active Products ");


                            if (int.TryParse(Console.ReadLine(), out int ProductID))
                            {
                                IEnumerable <Product> Products;
                                if (ProductID != 0 && db.Products.Count(p => p.ProductID == ProductID) == 0)
                                {
                                    logger.Error("No Product was saved with that Id");
                                }
                                else
                                {
                                    // display products from all category
                                    Products = db.Products.OrderBy(p => p.ProductName);

                                    if (ProductID == 0)
                                    {
                                        // display all products from all category
                                        Products = db.Products.OrderBy(p => p.ProductName);
                                    }
                                    else if (ProductID == 2)
                                    {
                                        //display discontinued
                                        Products = db.Products.OrderBy(p => p.ProductName).Where(p => p.Discontinued == true);
                                    }
                                    else if (ProductID == 3)
                                    {
                                        //display discontinued
                                        Products = db.Products.OrderBy(p => p.ProductName).Where(p => p.Discontinued == false);
                                    }
                                    else if (ProductID == 1)
                                    {
                                        // display product from selected category
                                        Console.WriteLine("Choose the product to display:");
                                        var product = Console.ReadLine();
                                        Products = db.Products.Where(p => p.ProductName == product);
                                    }
                                    Console.WriteLine($"{Products.Count()} product(s) returned");
                                    foreach (var item in Products)
                                    {
                                        Console.WriteLine($"Product: {item.ProductName}\nQuantity: {item.QuantityPerUnit}\nPrice: {item.UnitPrice}\nUnits on Stock: {item.UnitsInStock}" +
                                                          $"\nUnit on Order: {item.UnitsOnOrder}\nReorder Level: {item.ReorderLevel}\nDiscontinued: {item.Discontinued}\n");
                                    }
                                }
                            }

                            Console.WriteLine("Do you want to enter another Product or enter q to quit");
                            ProductIDD = Console.ReadLine(); //converts int to string to work well
                        } while (ProductIDD != "q");         //this is the only problem check it later
                    }

                    else if (choice == "8")
                    {
                        // edit category

                        Console.WriteLine("Choose the category to edit:");
                        var category = Console.ReadLine();

                        var db = new NorthwindContext();

                        if (category != null)
                        {
                            // input category
                            Category UpdatedCategory = db.Categories.FirstOrDefault(c => c.CategoryName == category);
                            if (UpdatedCategory != null)
                            {
                                string editChoiceCaty = "";
                                do
                                {
                                    //show the category details entered here
                                    var query = db.Categories.OrderBy(c => c.CategoryId);
                                    Console.WriteLine("1) Edit category Name");
                                    Console.WriteLine("2) Edit description");
                                    editChoiceCaty = Console.ReadLine();
                                    Console.Clear();
                                    logger.Info($"Option {editChoiceCaty} selected");

                                    if (editChoiceCaty == "1")
                                    {
                                        Console.WriteLine("Enter new category Name:");
                                        UpdatedCategory.CategoryName = Console.ReadLine();
                                        UpdatedCategory.CategoryName = Ti.ToTitleCase(UpdatedCategory.CategoryName);
                                        db.EditCategory(UpdatedCategory);
                                        logger.Info("Category (id: {CategoryId}) updated", UpdatedCategory.CategoryId);
                                    }
                                    else if (editChoiceCaty == "2")
                                    {
                                        Console.WriteLine("Enter new category description:");
                                        UpdatedCategory.Description = Console.ReadLine();
                                        db.EditCategory(UpdatedCategory);
                                        logger.Info("Category (id: {CategoryId}) updated", UpdatedCategory.CategoryId);
                                    }



                                    Console.WriteLine("Do you want to enter to edit another Category or enter q to quit");
                                    editChoiceCaty = Console.ReadLine();
                                } while (editChoiceCaty.ToLower() != "q");
                            }
                        }
                    }
                    else if (choice == "9")// Display Categories
                    {
                        string CategoryIdd;
                        do
                        {
                            var db    = new NorthwindContext();
                            var query = db.Categories.OrderBy(c => c.CategoryId);

                            foreach (var item in query)
                            {
                                Console.WriteLine($"{item.CategoryId}) {item.CategoryName}");
                            }
                            Console.WriteLine("");
                            Console.WriteLine("Select the product to display:");
                            Console.WriteLine("0) All Category ");
                            Console.WriteLine("1) Display a specific Category ");
                            Console.WriteLine("2) Display a specific Category and its active products ");



                            if (int.TryParse(Console.ReadLine(), out int CategoryId))
                            {
                                IEnumerable <Category> Categories;
                                if (CategoryId != 0 && db.Categories.Count(p => p.CategoryId == CategoryId) == 0)
                                {
                                    logger.Error("No category was saved with that Id");
                                }


                                if (CategoryId == 0)
                                {
                                    // display all  category
                                    db    = new NorthwindContext();
                                    query = db.Categories.OrderBy(c => c.CategoryName);

                                    Console.WriteLine($"{query.Count()} records returned");
                                    foreach (var item in query)
                                    {
                                        Console.WriteLine($"{item.CategoryId}) {item.CategoryName}");
                                    }
                                }

                                else if (CategoryId == 1)
                                {
                                    //display a specific category
                                    {
                                        Console.WriteLine("Choose the category to display:");
                                        var category = Console.ReadLine();
                                        Categories = db.Categories.Where(c => c.CategoryName == category);
                                    }
                                    Console.WriteLine($"{Categories.Count()} category returned");
                                }

                                else if (CategoryId == 2)
                                {
                                    // display a specific category and its active products

                                    Console.WriteLine("Choose the category to display:");
                                    var category = Console.ReadLine();
                                    Categories = db.Categories.Where(c => c.CategoryName == category);

                                    Console.WriteLine($"{Categories.Count()} category(ies) returned");
                                    Console.WriteLine(" ");
                                    foreach (var item in Categories)
                                    {
                                        Console.WriteLine($"{item.CategoryName}");
                                    }
                                    foreach (Product p in db.Products)
                                    {
                                        Console.WriteLine($"Product: {p.ProductName}\nQuantity: {p.QuantityPerUnit}\nPrice: {p.UnitPrice}\nUnits on Stock: {p.UnitsInStock}" +
                                                          $"\nUnit on Order: {p.UnitsOnOrder}\nReorder Level: {p.ReorderLevel}\nDiscontinued: {p.Discontinued}\n");
                                    }
                                }
                            }

                            Console.WriteLine("Do you want to enter another Product or enter q to quit");
                            CategoryIdd = Console.ReadLine();
                        } while (CategoryIdd != "q");
                    }
                    else if (choice == "10")// delete category.....
                    {
                        Console.WriteLine("Choose the category to delete:");
                        var category = Console.ReadLine();

                        var db = new NorthwindContext();

                        if (category != null)
                        {
                            // input category
                            Category RemoveCategory = db.Categories.FirstOrDefault(c => c.CategoryName == category);
                            if (RemoveCategory != null)
                            {
                                db.DeleteCategory(RemoveCategory);
                                logger.Info("Category (id: {categoryId}) deleted", RemoveCategory);
                            }
                            else
                            {
                                logger.Info("Not found");
                            }
                        }
                    }
                    else if (choice == "11")
                    {
                        Console.WriteLine("Choose the product to delete:");
                        var product = Console.ReadLine();

                        var db = new NorthwindContext();

                        if (product != null)
                        {
                            // input product
                            Product RemoveProduct = db.Products.FirstOrDefault(p => p.ProductName == product);
                            if (RemoveProduct != null)
                            {
                                db.DeleteProduct(RemoveProduct);
                                logger.Info("Product (id: {productid}) deleted", RemoveProduct);
                            }
                            else
                            {
                                logger.Info("Not found");
                            }
                        }
                    }
                    Console.WriteLine();
                } while (choice.ToLower() != "q");
            }
            catch (Exception ex)
            {
                logger.Error(ex.Message);
            }
            logger.Info("Program ended");
        }
コード例 #10
0
        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");
        }
コード例 #11
0
        public static void Main(string[] args)
        {
            logger.Info("Program started");
            try
            {
                string choice;
                do
                {
                    Console.Clear();
                    Console.WriteLine("1) Add Product");
                    Console.WriteLine("2) Display all Products");
                    Console.WriteLine("3) Display Active Products");
                    Console.WriteLine("4) Display Discontinued Products");
                    Console.WriteLine("5) Search Products");
                    Console.WriteLine("6) Add Category");
                    Console.WriteLine("7) Edit Category");
                    Console.WriteLine("8) Display all Categories");
                    Console.WriteLine("9) Display all non-discontinued items by Category");
                    Console.WriteLine("10) Display all non-discontinued items by speciic Category");
                    Console.WriteLine("11) Delete Category");
                    Console.WriteLine("12) Delete Product");
                    Console.WriteLine("\"q\" to quit");
                    choice = Console.ReadLine();

                    switch (choice)
                    {
                    case "1":
                        Product.addProducts(logger);
                        break;

                    case "2":
                        Product.displayAllProducts(logger);
                        break;

                    case "3":
                        Product.displayActiveProducts(logger);
                        break;

                    case "4":
                        Product.displayDiscontinuedProducts(logger);
                        break;

                    case "5":
                        Product.searchProducts(logger);
                        break;

                    case "6":
                        Category.addCategories(logger);
                        break;

                    case "7":

                        var db = new NorthwindContext();

                        Console.WriteLine("Choose category ID to edit: ");

                        var category = Category.GetCategory(db, logger);


                        if (category != null)
                        {
                            Category UpdatedCategory = Category.InputCategory(db, logger);

                            if (UpdatedCategory != null)
                            {
                                UpdatedCategory.CategoryId = category.CategoryId;
                                db.EditCategory(UpdatedCategory);
                                logger.Info($"Category Id: {UpdatedCategory.CategoryId} updated");
                            }
                        }

                        Console.WriteLine();
                        Console.WriteLine("Press any key to return to menu");
                        Console.ReadLine();
                        break;

                    case "8":
                        Category.displayAllCategories(logger);
                        break;

                    case "9":
                        Category.displayAllCategoriesAndProductsNotDiscontinued(logger);
                        break;

                    case "10":
                        Category.displaySpecificCategoryAndProducts(logger);
                        break;

                    case "11":
                        db = new NorthwindContext();
                        Console.WriteLine("Select category ID to delete:");
                        var categoryToDelete = Category.GetCategory(db, logger);
                        try
                        {
                            db.deleteCategory(categoryToDelete);
                            logger.Info($"{categoryToDelete.CategoryName} deleted");
                        }
                        catch (Exception)
                        {
                            logger.Error("Cannot Delete a record that affects other tables");
                        }



                        Console.WriteLine();
                        Console.WriteLine("Press any key to return to menu");
                        Console.ReadLine();

                        break;

                    case "12":
                        db = new NorthwindContext();
                        Console.WriteLine("Select product ID to delete:");
                        var productToDelete = Product.GetProduct(db, logger);
                        try
                        {
                            db.deleteProduct(productToDelete);
                            logger.Info($"{productToDelete.ProductName} deleted");
                        }
                        catch (Exception)
                        {
                            logger.Error("Cannot Delete a record that affects other tables");
                        }



                        Console.WriteLine();
                        Console.WriteLine("Press any key to return to menu");
                        Console.ReadLine();

                        break;

                    default:
                        logger.Info("No option chosen");
                        break;
                    }
                } while (choice.ToLower() != "q");
            }
            catch (Exception ex)
            {
                logger.Error(ex.Message);
            }
            logger.Info("Program ended");
        }