コード例 #1
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");
        }
コード例 #2
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");
        }
コード例 #3
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"));
        }
コード例 #4
0
        static void Main(string[] args)
        {
            logger.Info("Program Started");

            String option;
            Menu   menu = new Menu();

            do
            {
                menu.MainMenu();
                option = Console.ReadLine();
                switch (option)
                {
                case "1":
                {
                    menu.ProductsMenu();
                    String option1 = Console.ReadLine();
                    switch (option1)
                    {
                    case "1":
                    {
                        var db = new NorthwindContext();

                        db.DisplayProducts();
                    }
                    break;

                    case "2":
                    {
                        var db = new NorthwindContext();

                        bool isValidProId = false;
                        var  prodChoice   = "";

                        do
                        {
                            menu.ExistingProducts();
                            prodChoice = Console.ReadLine();
                            switch (prodChoice)
                            {
                            case "1":
                                var products = db.Products;
                                var proId    = "";
                                do
                                {
                                    db.DisplayProducts();
                                    Console.WriteLine("\nWhich Product do you want to view?\n" +
                                                      "-------------------------------\n");
                                    proId = Console.ReadLine();
                                    int ID = int.Parse(proId);
                                    if (isValidProId == false)
                                    {
                                        foreach (var id in products)
                                        {
                                            if (id.ProductId == ID)
                                            {
                                                isValidProId = true;
                                            }
                                        }
                                    }
                                    if (isValidProId == true)
                                    {
                                        var product = db.Products.Where(p => p.ProductId == ID);
                                        foreach (var p in product)
                                        {
                                            Console.WriteLine
                                            (
                                                ("Product Id: {0}\n" +
                                                 "Product name: {1}\n" +
                                                 "Quantity per unit: {2}\n" +
                                                 "Reorder Level: {3}\n" +
                                                 "Supplier Id: {4}\n" +
                                                 "Unit Price: {5}\n" +
                                                 "Units in stock: {6}\n" +
                                                 "Units in order: {7}\n" +
                                                 "Discontinued: {8}\n"), p.ProductId, p.ProductName, p.QuantityPerUnit, p.ReorderLevel, p.SupplierID, p.UnitPrice, p.UnitsInStock, p.UnitsOnOrder, p.Discontinued
                                            );
                                        }
                                    }
                                    if (isValidProId == false)
                                    {
                                        isValidProId = false;
                                        logger.Warn("Invalid selection... pick again..");
                                    }
                                } while (isValidProId == false);
                                break;

                            case "2":
                                var disProducts = db.Products.Where(p => p.Discontinued == true);
                                foreach (var dp in disProducts)
                                {
                                    Console.ForegroundColor = ConsoleColor.Red;
                                    Console.WriteLine("{0}\n", dp.ProductName + " * * Discontinued * *");
                                    Console.ForegroundColor = ConsoleColor.Gray;
                                }
                                break;

                            case "3":
                                var actProducts = db.Products.Where(p => p.Discontinued == false);
                                foreach (var ap in actProducts)
                                {
                                    Console.ForegroundColor = ConsoleColor.Green;
                                    Console.WriteLine("{0}\n", ap.ProductName + " * * Active * *");
                                    Console.ForegroundColor = ConsoleColor.Gray;
                                }
                                break;
                            }
                        } while (!prodChoice.Equals("4"));
                    }
                    break;

                    case "3":
                    {
                        var db = new NorthwindContext();

                        Console.WriteLine("Enter the name of the product\n");
                        var name = Console.ReadLine();

                        Console.WriteLine("What kind of Product is {0}?", name);
                        Console.WriteLine("-------------------------------");
                        var  categories = db.Categories;
                        var  catId      = "";
                        bool isValidID  = false;
                        do
                        {
                            foreach (var category in categories)
                            {
                                Console.WriteLine("{0}) {1}", category.CategoryId, category.CategoryName);
                            }
                            catId = Console.ReadLine();

                            if (isValidID == false)
                            {
                                foreach (var id in categories)
                                {
                                    if (id.CategoryId == int.Parse(catId))
                                    {
                                        isValidID = true;
                                    }
                                }
                            }
                            if (isValidID == false)
                            {
                                isValidID = false;
                                logger.Warn("Invalid selection... pick again..");
                            }
                        } while (isValidID == false);

                        Console.WriteLine("Who is the Supplier for that product?");
                        Console.WriteLine("-------------------------------");
                        var suppliers = db.Suppliers;
                        var supId     = "";
                        isValidID = false;
                        do
                        {
                            foreach (var supplier in suppliers)
                            {
                                Console.WriteLine("{0}) {1}", supplier.SupplierId, supplier.CompanyName);
                            }
                            supId = Console.ReadLine();

                            if (isValidID == false)
                            {
                                foreach (var id in suppliers)
                                {
                                    if (id.SupplierId == int.Parse(supId))
                                    {
                                        isValidID = true;
                                    }
                                }
                            }
                            if (isValidID == false)
                            {
                                isValidID = false;
                                logger.Warn("Invalid selection... pick again..");
                            }
                        } while (isValidID == false);

                        var newProduct = new Product
                        {
                            ProductName = name,
                            CategoryID  = int.Parse(catId),
                            SupplierID  = 3
                        };

                        db.AddProduct(newProduct);
                        logger.Info("{0} added to Products..", newProduct.ProductName);
                    }
                    break;

                    case "4":
                        var  editdb      = new NorthwindContext();
                        var  editQuery   = editdb.Products;
                        var  editId      = "";
                        bool isValidEdit = false;
                        do
                        {
                            editdb.DisplayProducts();
                            Console.WriteLine("\nWhich Product do you want to edit?");
                            editId = Console.ReadLine();
                            if (isValidEdit == false)
                            {
                                foreach (var id in editQuery)
                                {
                                    if (id.ProductId == int.Parse(editId))
                                    {
                                        isValidEdit = true;
                                    }
                                }
                            }
                            var ID = int.Parse(editId);
                            if (isValidEdit == true)
                            {
                                var  edit          = editdb.Products.Where(e => e.ProductId == ID);
                                bool isValidDetail = false;
                                do
                                {
                                    menu.ProductDetails();
                                    var editChoice = Console.ReadLine();
                                    switch (editChoice)
                                    {
                                    case "1":
                                        Console.WriteLine("Enter new Product name\n" +
                                                          "-------------------------------\n");
                                        var newName = Console.ReadLine();
                                        try
                                        {
                                            foreach (var ed in edit)
                                            {
                                                ed.ProductName = newName;
                                                logger.Info("Product name changed to \"{0}\"", newName);
                                            }
                                            ;
                                            editdb.SaveChanges();
                                        } catch (Exception e)
                                        {
                                            logger.Warn("Unable to change product name, try again...");
                                            logger.Warn(e.Message);
                                        }
                                        break;

                                    case "2":
                                        Console.WriteLine("Enter new Quantity per Unit\n" +
                                                          "-------------------------------\n");
                                        var newQPU = Console.ReadLine();
                                        try
                                        {
                                            foreach (var ed in edit)
                                            {
                                                ed.QuantityPerUnit = newQPU;
                                                logger.Info("Quantity per Unit changed to \"{0}\"", newQPU);
                                            }
                                            ;
                                            editdb.SaveChanges();
                                        }
                                        catch (Exception e)
                                        {
                                            logger.Warn("Unable to change Quantity per Unit, try again...");
                                            logger.Warn(e.Message);
                                        }
                                        break;

                                    case "3":
                                        Console.WriteLine("Enter new Unit Price\n" +
                                                          "-------------------------------\n");
                                        var newUP = Console.ReadLine();
                                        try
                                        {
                                            foreach (var ed in edit)
                                            {
                                                ed.UnitPrice = decimal.Parse(newUP);
                                                logger.Info("Unit Price changed to \"${0}\"", decimal.Parse(newUP));
                                            }
                                            ;
                                            editdb.SaveChanges();
                                        }
                                        catch (Exception e)
                                        {
                                            logger.Warn("Unable to change Units in Stock, try again...");
                                            logger.Warn(e.Message);
                                        }
                                        break;

                                    case "4":
                                        Console.WriteLine("Enter new Units in Stock\n" +
                                                          "-------------------------------\n");
                                        var newUS = Console.ReadLine();
                                        try
                                        {
                                            foreach (var ed in edit)
                                            {
                                                ed.UnitsInStock = short.Parse(newUS);
                                                logger.Info("Units in Stock changed to \"{0}\"", short.Parse(newUS));
                                            }
                                            ;
                                            editdb.SaveChanges();
                                        }
                                        catch (Exception e)
                                        {
                                            logger.Warn("Unable to change Units in Stock, try again...");
                                            logger.Warn(e.Message);
                                        }
                                        break;

                                    case "5":
                                        Console.WriteLine("Enter new Units on Order\n" +
                                                          "-------------------------------\n");
                                        var newUO = Console.ReadLine();
                                        try
                                        {
                                            foreach (var ed in edit)
                                            {
                                                ed.UnitsOnOrder = short.Parse(newUO);
                                                logger.Info("Units on Order changed to \"{0}\"", short.Parse(newUO));
                                            }
                                            ;
                                            editdb.SaveChanges();
                                        }
                                        catch (Exception e)
                                        {
                                            logger.Warn("Unable to change Units on Order, try again...");
                                            logger.Warn(e.Message);
                                        }
                                        break;

                                    case "6":
                                        Console.WriteLine("Enter new Reorder level\n" +
                                                          "-------------------------------\n");
                                        var newRL = Console.ReadLine();
                                        try
                                        {
                                            foreach (var ed in edit)
                                            {
                                                ed.ReorderLevel = short.Parse(newRL);
                                                logger.Info("Reorder level changed to \"{0}\"", short.Parse(newRL));
                                            }
                                            ;
                                            editdb.SaveChanges();
                                        }
                                        catch (Exception e)
                                        {
                                            logger.Warn("Unable to change Reorder level, try again...");
                                            logger.Warn(e.Message);
                                        }
                                        break;

                                    case "7":
                                        Console.WriteLine("Is this item Discontinued Y/N?\n" +
                                                          "-------------------------------\n");
                                        var newD = Console.ReadLine();
                                        if (newD.ToUpper().Equals("Y"))
                                        {
                                            try
                                            {
                                                foreach (var ed in edit)
                                                {
                                                    ed.Discontinued = true;
                                                    logger.Info(ed.ProductName + " is now Discontinued");
                                                }
                                                ;
                                                editdb.SaveChanges();
                                            }
                                            catch (Exception e)
                                            {
                                                logger.Warn("Unable to change Discontinued, try again...");
                                                logger.Warn(e.Message);
                                            }
                                        }
                                        else if (newD.ToUpper().Equals("N"))
                                        {
                                            try
                                            {
                                                foreach (var ed in edit)
                                                {
                                                    ed.Discontinued = false;
                                                    logger.Info(ed.ProductName + " is now Active");
                                                }
                                                ;
                                                editdb.SaveChanges();
                                            }
                                            catch (Exception e)
                                            {
                                                logger.Warn("Unable to change Discontinued, try again...");
                                                logger.Warn(e.Message);
                                            }
                                        }
                                        else
                                        {
                                            logger.Warn("Not valid response");
                                        }
                                        break;

                                    case "8":
                                        isValidDetail = true;
                                        break;
                                    }
                                } while (isValidDetail == false);
                            }
                        } while (isValidEdit == false);
                        break;

                    case "5":
                        //delete product i think
                        var     deleteDb         = new NorthwindContext();
                        var     deleteQuery      = deleteDb.Products;
                        Boolean isValidProductID = false;
                        deleteDb.DisplayProducts();
                        Console.WriteLine("\nChoose a Product you would like to delete");
                        var input = Console.ReadLine();
                        int proID = int.Parse(input);

                        if (isValidProductID == false)
                        {
                            foreach (var item in deleteQuery)
                            {
                                if (item.ProductId == proID)
                                {
                                    isValidProductID = true;
                                }
                            }

                            if (isValidProductID == true)
                            {
                                var deleteProduct = deleteDb.Products.SingleOrDefault(p => p.ProductId == proID);
                                Console.WriteLine("\nAre you sure you want to delete " + deleteProduct.ProductName + "? Y/N");

                                if (Console.ReadLine().ToUpper().Equals("Y"))
                                {
                                    deleteDb.DeleteProduct(deleteProduct);
                                    logger.Info("Product \"{0}\" removed from Products", deleteProduct.ProductName);
                                }
                            }
                            else
                            {
                                logger.Info("Not a valid Product ID");
                            }
                        }
                        else
                        {
                            logger.Info("Not a valid Integer");
                        }
                        break;
                    }
                }
                break;

                case "2":
                    var catDB   = new NorthwindContext();
                    var catResp = "";
                    do
                    {
                        menu.ExistingCategories();
                        catResp = Console.ReadLine();
                        switch (catResp)
                        {
                        case "1":
                            var categories = catDB.Categories;
                            menu.CategoryHeader();
                            foreach (var category in categories)
                            {
                                Console.WriteLine("{0}) {1} - {2}", category.CategoryId, category.CategoryName, category.Description);
                            }
                            break;

                        case "2":
                            var proByCat = catDB.Categories.Include("Products").OrderBy(p => p.CategoryId);
                            menu.CategoryHeader();
                            foreach (var category in proByCat)
                            {
                                Console.WriteLine("\n{0}) {1} - {2}\n", category.CategoryId, category.CategoryName, category.Description);
                                foreach (Product product in category.Products)
                                {
                                    Console.WriteLine("- {0}", product.ProductName);
                                }
                            }
                            break;

                        case "3":
                            var  c         = catDB.Categories;
                            var  catId     = "";
                            bool isValidID = false;
                            do
                            {
                                menu.CategoryHeader();
                                foreach (var category in c)
                                {
                                    Console.WriteLine("{0}) {1}", category.CategoryId, category.CategoryName);
                                }
                                catId = Console.ReadLine();

                                if (isValidID == false)
                                {
                                    foreach (var id in c)
                                    {
                                        if (id.CategoryId == int.Parse(catId))
                                        {
                                            isValidID = true;
                                        }
                                    }
                                }
                                var pID = int.Parse(catId);
                                if (isValidID == true)
                                {
                                    var catPro = catDB.Categories.Where(p => p.CategoryId == pID);
                                    var sp     = catDB.Products.Where(s => s.CategoryID == pID);
                                    foreach (var p in catPro)
                                    {
                                        Console.WriteLine("\n{0} - {1}", p.CategoryName, p.Description);
                                        Console.WriteLine("-------------------------------\n");
                                    }
                                    foreach (var item in sp)
                                    {
                                        Console.WriteLine("{0}", item.ProductName);
                                    }
                                }
                                if (isValidID == false)
                                {
                                    isValidID = false;
                                    logger.Warn("Invalid selection... pick again..");
                                }
                            } while (isValidID == false);
                            break;

                        case "4":
                            // add new cat
                            var  nc         = catDB.Categories.OrderBy(n => n.CategoryId);
                            var  catName    = "";
                            bool isValidCat = true;
                            do
                            {
                                Console.WriteLine("Enter name of new Category\n");
                                catName = Console.ReadLine();

                                foreach (var n in nc)
                                {
                                    if (n.CategoryName.ToUpper().Equals(catName))
                                    {
                                        isValidCat = false;
                                    }
                                }
                                if (isValidCat == false)
                                {
                                    logger.Warn("Category name {0} already exists - enter a different name", catName);
                                }
                                if (isValidCat == true)
                                {
                                    var newCat = new Category
                                    {
                                        CategoryName = catName
                                    };
                                    catDB.AddCategory(newCat);
                                    logger.Info("Category added - {0}", catName);
                                }
                            } while (isValidCat == false);
                            break;

                        case "5":
                            // edit cat
                            var  editCat  = new NorthwindContext();
                            var  ec       = editCat.Categories;
                            bool isVcatId = false;
                            do
                            {
                                menu.CategoryHeader();
                                foreach (var category in ec)
                                {
                                    Console.WriteLine("{0}) {1}", category.CategoryId, category.CategoryName);
                                }
                                Console.WriteLine("\nChoose a Category to edit\n" +
                                                  "-------------------------------\n");
                                var catInput = Console.ReadLine();
                                int ID       = int.Parse(catInput);
                                if (isVcatId == false)
                                {
                                    foreach (var id in ec)
                                    {
                                        if (id.CategoryId == ID)
                                        {
                                            isVcatId = true;
                                        }
                                    }
                                }
                                if (isVcatId == true)
                                {
                                    var catEdit   = editCat.Categories.Where(e => e.CategoryId == ID);
                                    var catChoice = "";
                                    do
                                    {
                                        Console.WriteLine("1) Edit Category Name");
                                        Console.WriteLine("2) Edit Category Description");
                                        Console.WriteLine("3) Exit");
                                        catChoice = Console.ReadLine();
                                        switch (catChoice)
                                        {
                                        case "1":
                                            Console.WriteLine("Enter new Category name\n" +
                                                              "-------------------------------\n");
                                            var newCatName = Console.ReadLine();
                                            try
                                            {
                                                foreach (var ed in catEdit)
                                                {
                                                    ed.CategoryName = newCatName;
                                                    logger.Info("Category name changed to \"{0}\"", newCatName);
                                                }
                                                ;
                                                editCat.SaveChanges();
                                            }
                                            catch (Exception e)
                                            {
                                                logger.Warn("Unable to change category name, try again...");
                                                logger.Warn(e.Message);
                                            }
                                            break;

                                        case "2":
                                            Console.WriteLine("Enter new Category description\n" +
                                                              "-------------------------------\n");
                                            var newCatDesc = Console.ReadLine();
                                            try
                                            {
                                                foreach (var ed in catEdit)
                                                {
                                                    ed.Description = newCatDesc;
                                                    logger.Info("Category description changed to \"{0}\"", newCatDesc);
                                                }
                                                ;
                                                editCat.SaveChanges();
                                            }
                                            catch (Exception e)
                                            {
                                                logger.Warn("Unable to change category description, try again...");
                                                logger.Warn(e.Message);
                                            }
                                            break;
                                        }
                                    } while (!catChoice.Equals("3"));
                                }
                            } while (isVcatId == false);
                            break;

                        case "6":
                            // delete cat
                            var  deleteCat         = new NorthwindContext();
                            var  deleteQuery       = deleteCat.Categories;
                            bool isValidCategoryID = false;
                            do
                            {
                                menu.CategoryHeader();
                                foreach (var category in deleteQuery)
                                {
                                    Console.WriteLine("{0}) {1}", category.CategoryId, category.CategoryName);
                                }
                                Console.WriteLine("\nChoose a Category you wish to delete");
                                var delInput = Console.ReadLine();
                                int catID    = int.Parse(delInput);

                                foreach (var item in deleteQuery)
                                {
                                    if (item.CategoryId == catID)
                                    {
                                        isValidCategoryID = true;
                                    }
                                }

                                if (isValidCategoryID == true)
                                {
                                    var deleteCategory = deleteCat.Categories.SingleOrDefault(p => p.CategoryId == catID);
                                    Console.WriteLine("Are you sure you want to delete " + deleteCategory.CategoryName + "? Y/N");

                                    if (Console.ReadLine().ToUpper().Equals("Y"))
                                    {
                                        Console.WriteLine("\nIf you delete " + deleteCategory.CategoryName + " you will delete all Products in this category");
                                        Console.WriteLine("Would you like to:");
                                        Console.WriteLine("1) Delete all Products within " + deleteCategory.CategoryName + "?");
                                        Console.WriteLine("2) Change the Category of all Products within " + deleteCategory.CategoryName + "?");
                                        var deleteChoice = Console.ReadLine();
                                        switch (deleteChoice)
                                        {
                                        case "1":
                                        {
                                            var deleteProducts = deleteCat.Products.Where(p => p.CategoryID == catID);

                                            List <Product> productArray = new List <Product>();

                                            foreach (var p in deleteProducts)
                                            {
                                                productArray.Add(p);
                                            }

                                            foreach (var p in productArray)
                                            {
                                                deleteCat.DeleteProduct(p);
                                            }

                                            deleteCat.DeleteCategory(deleteCategory);
                                            logger.Info("{0} successfully removed from Categories", deleteCategory.CategoryName);
                                            break;
                                        }

                                        case "2":
                                        {
                                            bool isValid = false;
                                            do
                                            {
                                                menu.CategoryHeader();
                                                foreach (var category in deleteQuery)
                                                {
                                                    Console.WriteLine("{0}) {1}", category.CategoryId, category.CategoryName);
                                                }
                                                Console.WriteLine("\nChoose wish category you wish to replace " + deleteCategory.CategoryName + " with");
                                                String catIDchoice = Console.ReadLine();
                                                int    newCatID    = int.Parse(catIDchoice);
                                                if (isValid == false)
                                                {
                                                    foreach (var item in deleteQuery)
                                                    {
                                                        if (item.CategoryId == newCatID && newCatID != catID)
                                                        {
                                                            isValid = true;
                                                        }
                                                    }
                                                }

                                                if (isValid == true)
                                                {
                                                    var changeProducts = deleteCat.Products.Where(p => p.CategoryID == catID);

                                                    foreach (var p in changeProducts)
                                                    {
                                                        p.CategoryID = newCatID;
                                                    }
                                                    deleteCat.DeleteCategory(deleteCategory);
                                                    logger.Info("{0} successfully removed from Categories", deleteCategory.CategoryName);
                                                }
                                                else
                                                {
                                                    logger.Info("Not a valid CategoryID");
                                                }
                                            } while (isValid == false);
                                            break;
                                        }
                                        }
                                    }
                                }
                            } while (isValidCategoryID == false);
                            break;
                        }
                    } while (!catResp.Equals("7"));
                    break;
                }
            } while (!option.Equals("3"));
        }
コード例 #5
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");
        }
コード例 #6
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");
        }
コード例 #7
0
        public static void Main(string[] args)
        {
            logger.Info("Program started");
            try
            {
                string choice;
                do
                {
                    Console.WriteLine("1) Display Categories");
                    Console.WriteLine("2) Add Category");
                    Console.WriteLine("3) Edit Category");
                    Console.WriteLine("4) Display a specific category and related active products");
                    Console.WriteLine("5) Display all categories and related products");
                    Console.WriteLine("6) Add a new product");
                    Console.WriteLine("7) Edit a product");
                    Console.WriteLine("8) Display products");
                    Console.WriteLine("9) Display a single product");
                    Console.WriteLine("10) Delete a category");
                    Console.WriteLine("11) Delete a product");
                    Console.WriteLine("\"q\" to quit");
                    choice = Console.ReadLine();
                    Console.Clear();
                    logger.Info($"Option {choice} selected");
                    if (choice == "1")
                    {
                        //Category.ListCategoriesWithDescription();

                        var table = new ConsoleTable();
                        var db    = new NorthwindContext();

                        table.SetHeaders("Name", "Descripion");
                        foreach (var item in db.Categories)
                        {
                            table.AddRow(item.CategoryName, item.Description);
                        }

                        Console.WriteLine(table.ToString());
                    }
                    else if (choice == "2")
                    {
                        Category category = new Category();
                        Console.WriteLine("Enter Category Name:");
                        category.CategoryName = Console.ReadLine();

                        ValidationContext       context = new ValidationContext(category, null, null);
                        List <ValidationResult> results = new List <ValidationResult>();

                        var isValid = Validator.TryValidateObject(category, context, results, true);
                        if (isValid)
                        {
                            var db = new NorthwindContext();
                            // check for unique name
                            if (db.Categories.Any(c => c.CategoryName == category.CategoryName))
                            {
                                // generate validation error
                                isValid = false;
                                results.Add(new ValidationResult("Name exists", new string[] { "CategoryName" }));
                            }
                            else
                            {
                                Console.WriteLine("Enter the Category Description:");
                                category.Description = Console.ReadLine();
                                logger.Info("Validation passed");
                                db.AddCategory(category);
                                logger.Info("Category added - {title}", category.CategoryName);
                            }
                        }
                        if (!isValid)
                        {
                            foreach (var result in results)
                            {
                                logger.Error($"{result.MemberNames.First()} : {result.ErrorMessage}");
                            }
                        }
                    }
                    else if (choice == "3")
                    {
                        Category.EditCategory();
                    }
                    else if (choice == "4")
                    {
                        var db    = new NorthwindContext();
                        var query = db.Categories.OrderBy(p => p.CategoryId);
                        foreach (var item in query)
                        {
                            Console.WriteLine($"{item.CategoryId}) {item.CategoryName}");
                        }
                        Console.WriteLine("Select the category whose products you want to display:");

                        int id = int.Parse(Console.ReadLine());
                        Console.Clear();
                        logger.Info($"CategoryId {id} selected");

                        Category category = db.Categories.FirstOrDefault(c => c.CategoryId == id);
                        Console.WriteLine($"{category.CategoryName} - {category.Description}");

                        foreach (Product p in category.Products.Where(p => p.Discontinued != true))
                        {
                            Console.WriteLine(p.ProductName);
                        }
                    }
                    else if (choice == "5")
                    {
                        //Display all Categories and their related active (not discontinued) product data (CategoryName, ProductName)
                        var db    = new NorthwindContext();
                        var query = db.Categories.Include("Products").OrderBy(p => p.CategoryId);
                        foreach (var item in query)
                        {
                            Console.WriteLine($"{item.CategoryName}");
                            foreach (Product p in item.Products)
                            {
                                if (p.Discontinued == false)
                                {
                                    Console.WriteLine($"\t{p.ProductName}");
                                }
                            }
                        }
                    }
                    else if (choice == "6")
                    {
                        var db            = new NorthwindContext();
                        var categoryQuery = db.Categories.OrderBy(p => p.CategoryId);
                        var supplierQuery = db.Suppliers.OrderBy(p => p.SupplierId);

                        Console.WriteLine("Select a product Category");
                        foreach (var item in categoryQuery)
                        {
                            Console.WriteLine($"{item.CategoryId}) {item.CategoryName}");
                        }

                        //check for valid category
                        if (int.TryParse(Console.ReadLine(), out int CategoryId))
                        {
                            if (db.Categories.Any(c => c.CategoryId == CategoryId))
                            {
                                Console.Clear();
                                Console.WriteLine("Enter a product Supplier or \"add\" to enter a new supplier.");
                                foreach (var item in supplierQuery)
                                {
                                    Console.WriteLine($"{item.SupplierId}) {item.CompanyName}");
                                }
                                var supplier = Console.ReadLine();
                                //check for valid supplier
                                if (supplier.ToLower() == "add")
                                {
                                    Supplier.NewSupplier();
                                }
                                else if (int.TryParse(supplier, out int supplierId))
                                {
                                    if (db.Suppliers.Any(s => s.SupplierId == supplierId))
                                    {
                                        Product product = InputProduct(db);
                                        product.CategoryId = CategoryId;
                                        if (product != null)
                                        {
                                            product.SupplierId = supplierId;
                                            db.AddProduct(product);
                                            logger.Info("Product added - {title}", product.ProductName);
                                        }
                                    }
                                    else
                                    {
                                        logger.Error("There are no Suppliers with that Id");
                                    }
                                }
                                else
                                {
                                    logger.Error("Invalid Supplier Id");
                                }
                            }
                            else
                            {
                                logger.Error("There are no Categories with that Id");
                            }
                        }
                        else
                        {
                            logger.Error("Invalid Category Id");
                        }
                    }
                    else if (choice == "7")
                    {
                        var db    = new NorthwindContext();
                        var query = db.Categories.Include("Products").OrderBy(p => p.CategoryId);

                        Console.WriteLine("Select the product category:");
                        foreach (var item in query)
                        {
                            Console.WriteLine($"{item.CategoryId}) {item.CategoryName}");
                        }
                        //check for valid category
                        if (int.TryParse(Console.ReadLine(), out int CategoryId))
                        {
                            if (db.Categories.Any(c => c.CategoryId == CategoryId))
                            {
                                logger.Info($"CategoryId {CategoryId} selected");
                                Console.Clear();
                                Console.WriteLine("Select the product number you wish to edit:");
                                logger.Info($"CategoryId {CategoryId} selected");
                                var productList = db.Products.Where(pl => pl.CategoryId == CategoryId).OrderBy(pl => pl.ProductId);

                                foreach (var item in productList)
                                {
                                    Console.WriteLine($"{item.ProductId}) {item.ProductName}");
                                }

                                //check for valid product id
                                if (int.TryParse(Console.ReadLine(), out int ProductId))
                                {
                                    if (db.Products.Any(p => p.ProductId == ProductId))
                                    {
                                        Product product = db.Products.FirstOrDefault(p => p.ProductId == ProductId);
                                        Product.EditProduct(product, db);
                                    }
                                }
                            }
                        }
                    }
                    else if (choice == "8")
                    {
                        string displayChoice;
                        var    db = new NorthwindContext();

                        Console.Clear();
                        Console.WriteLine("1) Display ALL products");
                        Console.WriteLine("2) Display only DISCONTINUED products");
                        Console.WriteLine("3) Display only ACTIVE products");
                        displayChoice = Console.ReadLine();
                        logger.Info($"Option {choice} selected");

                        if (displayChoice == "1")
                        {
                            logger.Info("{0} records returned", db.Products.Count());
                            Console.WriteLine("ALL Products (Discontinued products in Red)");

                            foreach (var item in db.Products)
                            {
                                Console.BackgroundColor = item.Discontinued ? ConsoleColor.Red : ConsoleColor.Black;
                                Console.WriteLine(item.ProductName);
                            }
                            Console.ResetColor();
                        }

                        if (displayChoice == "2")
                        {
                            var query = db.Products.Where(p => p.Discontinued == true);
                            logger.Info("{0} records returned", query.Count());
                            Console.WriteLine("ALL Discontinued Products");

                            foreach (var item in query)
                            {
                                Console.WriteLine(item.ProductName);
                            }
                        }

                        if (displayChoice == "3")
                        {
                            var query = db.Products.Where(p => p.Discontinued == false);
                            logger.Info("{0} records returned", query.Count());
                            Console.WriteLine("ALL Active Products");

                            foreach (var item in query)
                            {
                                Console.WriteLine(item.ProductName);
                            }
                        }
                    }
                    else if (choice == "9")
                    {
                        string searchTerm;
                        string displayChoice;
                        var    db = new NorthwindContext();

                        Console.Clear();
                        Console.WriteLine("Chose how you wish to select a product:");
                        Console.WriteLine("1) Enter Product Id");
                        Console.WriteLine("2) Search for product name");

                        displayChoice = Console.ReadLine();
                        if (displayChoice == "1")
                        {
                            Console.WriteLine("Enter the Id number of the product you wish to display");
                            if (int.TryParse(Console.ReadLine(), out int productId))
                            {
                                if (db.Products.Any(p => p.ProductId == productId))
                                {
                                    Console.Clear();
                                    Product.DisplayProduct(db.Products.FirstOrDefault(p => p.ProductId == productId));
                                }
                                else
                                {
                                    logger.Error("There are no Products with that Id");
                                }
                            }
                            else
                            {
                                logger.Error("Invalid product Id");
                            }
                        }

                        if (displayChoice == "2")
                        {
                            Console.WriteLine("Enter all or part of the product name");
                            searchTerm = Console.ReadLine();

                            var query = db.Products.Where(p => p.ProductName.Contains(searchTerm)).OrderBy(p => p.ProductName);

                            Console.WriteLine($"{query.Count()} records returned");


                            if (query.Count() == 1)
                            {
                                Console.Clear();
                                Product.DisplayProduct(query.FirstOrDefault());
                            }


                            if (query.Count() > 1)
                            {
                                Console.WriteLine("{0,-8} {1,-50}", "ID", "ProductName");
                                foreach (var item in query)
                                {
                                    Console.WriteLine("{0,-8} {1,-50}", item.ProductId, item.ProductName);
                                }

                                Console.WriteLine("\nEnter the Id number of the product you wish to display");
                                if (int.TryParse(Console.ReadLine(), out int productId))
                                {
                                    if (db.Products.Any(p => p.ProductId == productId))
                                    {
                                        Console.Clear();
                                        Product.DisplayProduct(db.Products.FirstOrDefault(p => p.ProductId == productId));
                                    }
                                    else
                                    {
                                        logger.Error("There are no Products with that Id");
                                    }
                                }
                                else
                                {
                                    logger.Error("Invalid product Id");
                                }
                            }
                        }
                    }
                    else if (choice == "10")
                    {
                        var db = new NorthwindContext();
                        Category.ListCategories();
                        Console.WriteLine("Enter the Category Id that you wish to delete");

                        int id = int.Parse(Console.ReadLine());
                        Console.Clear();
                        logger.Info($"CategoryId {id} selected");

                        Category category = db.Categories.FirstOrDefault(c => c.CategoryId == id);
                        if (db.DeleteCategory(category))
                        {
                            logger.Info("Category {0} successfully deleted", category.CategoryName);
                        }
                        else
                        {
                            logger.Error("Unable to delete a category with associated products.");
                            Console.WriteLine("You may not delete a category with associated products. In order to delete a category, all the associated products must first be placed in another category or deleted.");
                        }
                    }
                    else if (choice == "11")
                    {
                        //Select and display product
                        string searchTerm;
                        string displayChoice;
                        var    db = new NorthwindContext();

                        Console.Clear();
                        Console.WriteLine("Chose how you wish to select a product:");
                        Console.WriteLine("1) Enter Product Id");
                        Console.WriteLine("2) Search for product name");

                        displayChoice = Console.ReadLine();
                        if (displayChoice == "1")
                        {
                            Console.WriteLine("Enter the Id number of the product you wish to delete");
                            if (int.TryParse(Console.ReadLine(), out int productId))
                            {
                                if (db.Products.Any(p => p.ProductId == productId))
                                {
                                    Console.Clear();
                                    //Product.DisplayProduct(db.Products.FirstOrDefault(p => p.ProductId == productId));
                                    db.DeleteProduct(db.Products.FirstOrDefault(p => p.ProductId == productId));
                                    logger.Info("Product Id {0} successfully deleted.", productId);
                                }
                                else
                                {
                                    logger.Error("There are no Products with that Id");
                                }
                            }
                            else
                            {
                                logger.Error("Invalid product Id");
                            }
                        }
                        if (displayChoice == "2")
                        {
                            Console.WriteLine("Enter all or part of the product name");
                            searchTerm = Console.ReadLine();

                            var query = db.Products.Where(p => p.ProductName.Contains(searchTerm)).OrderBy(p => p.ProductName);

                            Console.WriteLine($"{query.Count()} records returned");


                            if (query.Count() == 1)
                            {
                                Console.Clear();
                                Product.DisplayProduct(query.FirstOrDefault());
                                db.DeleteProduct(query.FirstOrDefault());
                                logger.Info("Product id {0} successfully deleted", query.FirstOrDefault().ProductId);
                            }


                            if (query.Count() > 1)
                            {
                                Console.WriteLine("{0,-8} {1,-50}", "ID", "ProductName");
                                foreach (var item in query)
                                {
                                    Console.WriteLine("{0,-8} {1,-50}", item.ProductId, item.ProductName);
                                }

                                Console.WriteLine("\nEnter the Id number of the product you wish to delete");
                                if (int.TryParse(Console.ReadLine(), out int productId))
                                {
                                    if (db.Products.Any(p => p.ProductId == productId))
                                    {
                                        Console.Clear();
                                        Product.DisplayProduct(db.Products.FirstOrDefault(p => p.ProductId == productId));
                                    }
                                    else
                                    {
                                        logger.Error("There are no Products with that Id");
                                    }
                                }
                                else
                                {
                                    logger.Error("Invalid product Id");
                                }
                            }
                        }
                    }
                    Console.WriteLine();
                } while (choice.ToLower() != "q");
            }
            catch (Exception ex)
            {
                logger.Error(ex.Message);
            }
            logger.Info("Program ended");
        }