Ejemplo n.º 1
0
 public void Save()
 {
     _dbContext.SaveChanges();
 }
Ejemplo n.º 2
0
        //make an order********************************************************************************************************
        public static void MakeOrder(int customerId)
        {
            using (var context = new Project0DbContext())
            {
                bool storeexception;
                int  storeChoice = 1;
                do
                {
                    try
                    {
                        Console.WriteLine("Which store would you like to order from?");
                        //gets list of stores from database
                        var storeList = context.Stores;
                        //prints list of store names and prices to console as numbered options
                        foreach (var store in storeList)
                        {
                            //formatted to display price in currency format
                            Console.WriteLine("[" + store.Id + "] " + store.Address);
                        }
                        //gets store of choice from user
                        storeChoice = Convert.ToInt32(Console.ReadLine());
                        //input must keep within range of store list
                        //gets count of stores from database
                        var storeCount = context.Stores.Count();
                        //if number input is greater than number of stores, or 0 or less: returns bad input and loops
                        if (storeChoice > storeCount || storeChoice <= 0)
                        {
                            //throws custom exception to pull out of try before displaying writelines
                            throw new System.ArgumentException("Parameter cannot be less than or greater than number of listed stores", "storeChoice");
                        }
                        //finishes try w/o any exceptions will break out of do while loop
                        storeexception = false;
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e.Message + " Please enter a valid number");
                        storeexception = true;
                    }
                } while (storeexception == true);
                //after choosing store, can then choose items to order

                bool continueOrder;
                //item for each order's cost
                decimal thisOrderItemCost = 0;
                //item to gather the total cost of an instance of orders
                decimal orderCost    = 0;
                int     orderSelect  = 0;
                int     quantity     = 0;
                string  displayOrder = "";
                //adds to id when creating new order item, required b/c sql starts at 1 index, c# starts at 0
                int numOrdersToAdd = 1;
                //create list to put multiple order objects into
                List <Orders> OrderList = new List <Orders>();
                //create list with which to modify multiple inventory objects  UNABLE TO PUT INVENTORY ITEMS INTO LIST AND UPDATE
                List <Inventory> InventoryList = new List <Inventory>();
                do
                {
                    Console.WriteLine("Select product to order: ");
                    //gets list of products from database
                    var productList = context.Products;
                    //prints list of product names and prices to console as numbered options
                    foreach (var product in productList)
                    {
                        //shows product id, name, and formatted to display price in currency format
                        Console.WriteLine("[" + product.Id + "] " + product.Name + "  " + String.Format("{0:C}", product.Price));
                    }
                    //user selects item to add to order - try catch
                    try
                    {
                        //user selects product id
                        orderSelect = Convert.ToInt32(Console.ReadLine());
                        //get price of product according to input id with linq
                        Products productPrice       = productList.First(p => p.Id == orderSelect) /*.Price*/;
                        decimal  chosenProductPrice = productPrice.Price;

                        //query quantity of item selected (do while ensures no orders greater than 10 in quantity)
                        do
                        {
                            //exception handling for quantity of items selected
                            try
                            {
                                Console.WriteLine("And how many of those would you like?");
                                quantity = Convert.ToInt32(Console.ReadLine());
                            }
                            catch (Exception e)
                            {
                                Console.WriteLine(e.Message);
                            }
                            //prevents quantity greater than 10 or a negative quantity
                            if (quantity > 10 || quantity < 0)
                            {
                                Console.WriteLine("May not buy more than 10 or less than 0.");
                            }
                        } while (quantity > 10 || quantity < 0);

                        //get name of product according to input id with linq
                        string productName = productList.First(p => p.Id == orderSelect).Name;
                        //gets cost of just this order item
                        thisOrderItemCost = chosenProductPrice * quantity;
                        //adds this order item to a string for displaying the order
                        displayOrder += productName + " - Quantity: " + quantity + " - Cost: " + String.Format("{0:C}", thisOrderItemCost) + "\n";
                        //add price to variable to add to order item and keeps adding each loop for total
                        orderCost += chosenProductPrice * quantity;
                    }
                    //throws exception with invalid input
                    catch (Exception e)
                    {
                        Console.WriteLine(e.Message);
                        Console.WriteLine("Invalid input, please try ordering again.");
                    }

                    //create new order item and adds to OrderList each loop
                    OrderList.Add(new Orders
                    {
                        //need to add 2 to count because sql counts from 1 and c# counts from 0
                        Id         = context.Orders.Count() + numOrdersToAdd,
                        ProductId  = orderSelect,
                        CustomerId = customerId,
                        StoreId    = storeChoice,
                        Price      = thisOrderItemCost,
                        OrderTime  = DateTime.Now,
                        Quantity   = quantity
                    });
                    //adds to count variable to ensure valid/unique new id
                    numOrdersToAdd++;

                    //exception handling for inventory database update
                    try
                    {
                        //remove quantities of each item selected from given store
                        //gets inventory object that matches currently selected store and product 1 and subtracts quantity from it
                        var inventoryQuantity = context.Inventory.Where(s => s.StoreId == storeChoice && s.ProductId == orderSelect).Single();
                        //subtracts quantity selected from Inventory objects quantity
                        inventoryQuantity.Quantity -= quantity;
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e.Message);
                    }

                    bool   validatedContinueOrderInput;
                    string continueOrderInput = "";
                    //do while continues as long as input response to repeat further orders is invalid
                    do
                    {
                        //checks if user would like to add more items to the order
                        Console.WriteLine("Would you like to continue ordering (y)? Or submit your order (n)?");
                        continueOrderInput          = Console.ReadLine();
                        validatedContinueOrderInput = ValidYN(continueOrderInput);
                    }while (validatedContinueOrderInput == false);
                    //decides whether to go through full order loop again, based on validated continueOrderInput
                    if (continueOrderInput == "y" || continueOrderInput == "Y")
                    {
                        continueOrder = true;
                    }
                    else
                    {
                        continueOrder = false;
                    }
                    //breaks out of full ordering loop when user is finished
                } while (continueOrder == true);

                // shows customer their cart
                //console writeline string that appends the names of products and gets a quantity for each
                Console.WriteLine("Your order:\n" + displayOrder);
                //display the total cost of the order
                Console.WriteLine("The total cost of your order is " + String.Format("{0:C}", orderCost) + "\n");


                //add order item to commit for each item in orderlist
                foreach (var order in OrderList)
                {
                    context.Orders.AddRange(order);
                }
                //save changes to database
                context.SaveChanges();
            }
        }
Ejemplo n.º 3
0
 //setup database if empty********************************************************************************************************
 public static void DbSetup()
 {
     // connect to the database
     using (var context = new Project0DbContext())
     {
         // if there are no stores, then add the initial data.
         if (!context.Stores.Any())
         {
             var store1 = new Stores
             {
                 Id      = 1,
                 Address = "123 1st St, Dallas, TX",
                 //need to create inventory (made of multiple items) based on products ****************************
                 //Store stock removed due to Inventory Quantity
                 //Stock = 111
             };
             var store2 = new Stores
             {
                 Id      = 2,
                 Address = "223 2nd St, Dallas, TX",
                 //need to create inventory (made of multiple items) based on products ****************************
                 //Store stock removed due to Inventory Quantity
                 //Stock = 212
             };
             var store3 = new Stores
             {
                 Id      = 3,
                 Address = "333 3rd St, Dallas, TX",
                 //need to create inventory (made of multiple items) based on products ****************************
                 //Store stock removed due to Inventory Quantity
                 //Stock = 313
             };
             // add created store
             context.Stores.Add(store1);
             context.Stores.Add(store2);
             context.Stores.Add(store3);
             // to apply the changes to the database
             context.SaveChanges();
         }
         // if there are no persons, then add the initial data.
         if (!context.Products.Any())
         {
             var product1 = new Products
             {
                 Id    = 1,
                 Name  = "Book about Something",
                 Price = Convert.ToDecimal(11.95)
             };
             var product2 = new Products
             {
                 Id    = 2,
                 Name  = "Book about Nothing",
                 Price = Convert.ToDecimal(22.95)
             };
             var product3 = new Products
             {
                 Id    = 3,
                 Name  = "Book about Everything",
                 Price = Convert.ToDecimal(39.95)
             };
             // sets new products to be added
             context.Products.Add(product1);
             context.Products.Add(product2);
             context.Products.Add(product3);
             // to apply the changes to the database
             context.SaveChanges();
         }
         // if there are no persons, then add the initial data.
         if (!context.Customers.Any())
         {
             var customer1 = new Customers
             {
                 Id        = 1,
                 Username  = "******",
                 Password  = "******",
                 FirstName = "Amy",
                 LastName  = "Arrigeti"
             };
             var customer2 = new Customers
             {
                 Id        = 2,
                 Username  = "******",
                 Password  = "******",
                 FirstName = "Bob",
                 LastName  = "Builder"
             };
             // this doesn't modify the database YET.
             context.Customers.Add(customer1);
             context.Customers.Add(customer2);
             // to apply the changes that you've "prepped" on this context instance:
             context.SaveChanges();
         }
         // if there are no persons, then add the initial data.
         if (!context.Orders.Any())
         {
             var order1 = new Orders
             {
                 Id         = 1,
                 ProductId  = 2,
                 CustomerId = 1,
                 StoreId    = 1,
                 Price      = 12,
                 OrderTime  = DateTime.Now,
                 Quantity   = 1
             };
             var order2 = new Orders
             {
                 Id         = 2,
                 ProductId  = 3,
                 CustomerId = 2,
                 StoreId    = 3,
                 Price      = 12,
                 OrderTime  = DateTime.Now,
                 Quantity   = 1
             };
             var order3 = new Orders
             {
                 Id         = 3,
                 ProductId  = 1,
                 CustomerId = 2,
                 StoreId    = 2,
                 Price      = 64,
                 OrderTime  = DateTime.Now,
                 Quantity   = 3
             };
             // this doesn't modify the database YET.
             context.Orders.Add(order1);
             context.Orders.Add(order2);
             context.Orders.Add(order3);
             // to apply the changes that you've "prepped" on this context instance:
             context.SaveChanges();
         }
         // if there are no persons, then add the initial data.
         if (!context.Inventory.Any())
         {
             var inventory1 = new Inventory
             {
                 Id        = 1,
                 ProductId = 1,
                 StoreId   = 1,
                 Quantity  = 111
             };
             var inventory2 = new Inventory
             {
                 Id        = 2,
                 ProductId = 2,
                 StoreId   = 1,
                 Quantity  = 224
             };
             var inventory3 = new Inventory
             {
                 Id        = 3,
                 ProductId = 3,
                 StoreId   = 1,
                 Quantity  = 336
             };
             var inventory4 = new Inventory
             {
                 Id        = 4,
                 ProductId = 1,
                 StoreId   = 2,
                 Quantity  = 112
             };
             var inventory5 = new Inventory
             {
                 Id        = 5,
                 ProductId = 2,
                 StoreId   = 2,
                 Quantity  = 224
             };
             var inventory6 = new Inventory
             {
                 Id        = 6,
                 ProductId = 3,
                 StoreId   = 2,
                 Quantity  = 336
             };
             var inventory7 = new Inventory
             {
                 Id        = 7,
                 ProductId = 1,
                 StoreId   = 3,
                 Quantity  = 113
             };
             var inventory8 = new Inventory
             {
                 Id        = 8,
                 ProductId = 2,
                 StoreId   = 3,
                 Quantity  = 224
             };
             var inventory9 = new Inventory
             {
                 Id        = 9,
                 ProductId = 3,
                 StoreId   = 3,
                 Quantity  = 336
             };
             // this doesn't modify the database YET.
             context.Inventory.Add(inventory1);
             context.Inventory.Add(inventory2);
             context.Inventory.Add(inventory3);
             context.Inventory.Add(inventory4);
             context.Inventory.Add(inventory5);
             context.Inventory.Add(inventory6);
             context.Inventory.Add(inventory7);
             context.Inventory.Add(inventory8);
             context.Inventory.Add(inventory9);
             // to apply the changes that you've "prepped" on this context instance:
             context.SaveChanges();
         }
     }
 }
Ejemplo n.º 4
0
        //create new acccount********************************************************************************************************
        public static int CreateAccount()
        {
            //call to database
            using (var context = new Project0DbContext())
            {
                string usernameInput          = "";
                string validatedUsernameInput = "";
                string validatedPasswordInput = "";
                string validatedfnameInput    = "";
                string validatedlnameInput    = "";
                bool   newUsername            = false;
                //while loop allows for repeated username attempts
                while (newUsername == false)
                {
                    //get username input
                    Console.WriteLine("Username: "******"That username is already taken, please try again.");
                            //continues username while loop
                            newUsername = false;
                        }
                    }
                    //if input username is not found in the database, it will throw an InvalidOperationException because user will be null
                    catch (InvalidOperationException)
                    {
                        //breaks out of username while loop
                        newUsername = true;
                    }
                    //any other issues with exceptions will be handled here, and send the while loop back up top
                    catch (Exception e)
                    {
                        Console.WriteLine(e.Message);
                    }
                }
                bool fillsuccess;
                //initializes new customer object before filling it within the do while loop
                var customer = new Customers();
                //do while loop to ensure repeated attempts at inputting information
                do
                {
                    //get input password
                    Console.WriteLine("Password: "******"First Name: ");
                    string fnameInput = Console.ReadLine();
                    //input validation for create account password
                    validatedfnameInput = ValidateString(fnameInput);
                    //get lastname input
                    Console.WriteLine("Last Name: ");
                    string lnameInput = Console.ReadLine();
                    //input validation for create account password
                    validatedlnameInput = ValidateString(lnameInput);
                    try
                    {
                        //need to get id to add number to so primary key doesn't default to 0
                        var idCount = context.Customers.Count() + 1; // need to add 1 because c# index starts at 0, and sql index starts at 1
                        //puts input usr, pwd, fname, lname into new customer item
                        customer = new Customers
                        {
                            Id        = idCount,
                            Username  = validatedUsernameInput,
                            Password  = validatedPasswordInput,
                            FirstName = validatedfnameInput,
                            LastName  = validatedlnameInput
                        };
                        //confirms passed without any exceptions
                        fillsuccess = true;
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e.Message);
                        fillsuccess = false;
                    }
                } while (fillsuccess == false);

                //exception handling for adding customer to server
                try
                {
                    //adds a new customer in the database
                    context.Customers.Add(customer);
                    //saves changes to database
                    context.SaveChanges();
                    Console.WriteLine("Welcome, " + validatedfnameInput + "! Your account has been created.");
                }
                catch (Exception e)
                {
                    Console.WriteLine("Error, Account Creation Failed: " + e.Message);
                    Console.ReadKey();
                }

                //get generated customer id
                int custId = customer.Id;
                //returns name for greeting
                return(custId);
            }
        }