示例#1
0
        public async Task <IActionResult> CheckoutCart()
        {
            /// <summary>
            /// Adds cart items to orderitems db then empties cart
            /// </summary>
            List <OrderItemViewModel> CurrentCart = (List <OrderItemViewModel>)_cache.Get("customerCart");

            foreach (OrderItemViewModel thisOIVM in CurrentCart)
            {
                //OrderItem(int CustomerIdIn, int LocationIdIn, int ProductIdIn, double TotalPriceWhenOrderedIn, int OrderCountIn)
                OrderItem thisOrderItem = new OrderItem(
                    thisOIVM.CustomerId,
                    thisOIVM.LocationId,
                    thisOIVM.ProductId,
                    thisOIVM.TotalPriceWhenOrdered,
                    thisOIVM.OrderCount
                    );
                _context.Add(thisOrderItem);
                _context = UtilMethods.DecrementStockItem(thisOrderItem, _context);
            }
            await _context.SaveChangesAsync();

            System.Diagnostics.Debug.WriteLine($"Orders updated");
            _cache.Set("customerCart", new List <OrderItemViewModel>());
            return(Redirect("/Home/History"));
        }
        public async Task <EIGENAAR> VoegToe(EIGENAAR eigenaar)
        {
            _dbContextClass.Add(eigenaar);
            await _dbContextClass.SaveChangesAsync();

            return(eigenaar);
        }
        public void BuildStockItemViewModelFromLocStockWorks()
        {
            // Act
            //// Service setup
            var services = new ServiceCollection();

            services.AddMemoryCache();
            services.AddDbContext <DbContextClass>(options => options.UseInMemoryDatabase("testDb"));
            var serviceProvider = services.BuildServiceProvider();
            //// DbContext setup
            DbContextClass testContext = serviceProvider.GetService <DbContextClass>();
            //// DbContext populating
            Location  testLocation  = new Location();
            StockItem testStockItem = new StockItem();

            testStockItem.DiscountPercent = 50;
            Product testProduct = new Product();

            testProduct.BasePrice = 6;
            testContext.Add(testProduct);
            testContext.SaveChanges();
            // Arrange
            StockItemViewModel testStockItemViewModel = RevatureP1.UtilMethods.BuildStockItemViewModelFromLocStock(
                testLocation, testStockItem, testContext);
            var resultVal   = testStockItemViewModel.SaleString;
            var expectedVal = "50% Off!";

            //Assert
            Assert.Equal(expectedVal, resultVal);
        }
        public void GetStockItemByIdHandlesFailureCorrectly()
        {
            // Act
            //// Service setup
            var services = new ServiceCollection();

            services.AddMemoryCache();
            services.AddDbContext <DbContextClass>(options => options.UseInMemoryDatabase("testDb"));
            var serviceProvider = services.BuildServiceProvider();
            //// DbContext setup
            DbContextClass testContext = serviceProvider.GetService <DbContextClass>();
            //// DbContext populating
            StockItem testStockItem = new StockItem();
            int       testInt       = 102;
            int       testInt2      = 202;
            int       testInt3      = 302;

            //string testString = "testVal";
            testStockItem.LocationId = testInt;
            testStockItem.ProductId  = testInt2;
            testStockItem.StockCount = testInt3;
            testContext.Add(testStockItem);
            testContext.SaveChanges();
            // Arrange
            StockItem gottenStockItem = RevatureP1.UtilMethods.GetStockItemByIds(4, 4, testContext);
            var       resultVal       = gottenStockItem.StockCount;
            var       expectedVal     = new StockItem().StockCount;

            //Assert
            Assert.Equal(expectedVal, resultVal);
        }
        public void ProductCountReturnsFalseWhenItShould()
        {
            // Act
            //// Service setup
            var services = new ServiceCollection();

            services.AddMemoryCache();
            services.AddDbContext <DbContextClass>(options => options.UseInMemoryDatabase("testDb"));
            var serviceProvider = services.BuildServiceProvider();
            //// DbContext setup
            DbContextClass testContext = serviceProvider.GetService <DbContextClass>();
            //// DbContext populating
            StockItem testStockItem = new StockItem();
            int       testInt       = 104;
            int       testInt2      = 204;
            int       testInt3      = 304;
            int       testint4      = 404;

            //string testString = "testVal";
            testStockItem.LocationId = testInt;
            testStockItem.ProductId  = testInt2;
            testStockItem.StockCount = testInt3;
            testContext.Add(testStockItem);
            testContext.SaveChanges();
            // Arrange
            bool enoughInStock = RevatureP1.UtilMethods.CheckProductCount(testInt, testInt2, testint4, testContext);
            var  resultVal     = enoughInStock;
            var  expectedVal   = false;

            //Assert
            Assert.Equal(expectedVal, resultVal);
        }
        public void GetProductByIdHandlesFailureCorrectly()
        {
            // Act
            //// Service setup
            var services = new ServiceCollection();

            services.AddMemoryCache();
            services.AddDbContext <DbContextClass>(options => options.UseInMemoryDatabase("testDb"));
            var serviceProvider = services.BuildServiceProvider();
            //// DbContext setup
            DbContextClass testContext = serviceProvider.GetService <DbContextClass>();
            //// DbContext populating
            Product testProduct = new Product();
            int     testInt     = 15;
            string  testString  = "testVal";

            testProduct.ProductId = testInt;
            testProduct.Name      = testString;
            testContext.Add(testProduct);
            testContext.SaveChanges();
            // Arrange
            Product gottenProduct = RevatureP1.UtilMethods.GetProductById(2, testContext);
            var     resultVal     = gottenProduct.Name;
            var     expectedVal   = new Product().Name;

            //Assert
            Assert.Equal(expectedVal, resultVal);
        }
        public void GetLocationByIdHandlesFailureCorrectly()
        {
            // Act
            //// Service setup
            var services = new ServiceCollection();

            services.AddMemoryCache();
            services.AddDbContext <DbContextClass>(options => options.UseInMemoryDatabase("testDb"));
            var serviceProvider = services.BuildServiceProvider();
            //// DbContext setup
            DbContextClass testContext = serviceProvider.GetService <DbContextClass>();
            //// DbContext populating
            Location testLocation = new Location();
            int      testInt      = 12;
            string   testString   = "testVal";

            testLocation.LocationId      = testInt;
            testLocation.LocationAddress = testString;
            testContext.Add(testLocation); // Already done
            testContext.SaveChanges();
            // Arrange
            Location gottenLocation = RevatureP1.UtilMethods.GetLocationById(111, testContext);
            var      resultVal      = gottenLocation.LocationAddress;
            var      expectedVal    = new Location().LocationAddress;

            //Assert
            Assert.Equal(expectedVal, resultVal);
        }
        public void GetCustomerByUserNameHandlesFailuteCorrectly()
        {
            // Act
            //// Service setup
            var services = new ServiceCollection();

            services.AddMemoryCache();
            services.AddDbContext <DbContextClass>(options => options.UseInMemoryDatabase("testDb"));
            var serviceProvider = services.BuildServiceProvider();
            //// DbContext setup
            DbContextClass testContext = serviceProvider.GetService <DbContextClass>();
            //// DbContext populating
            Customer testCustomer = new Customer();
            string   testString   = "testUserName";

            testCustomer.UserName = testString;
            testContext.Add(testCustomer);
            testContext.SaveChanges();
            // Arrange
            Customer gottenCustomer = RevatureP1.UtilMethods.GetCustomerByUserName("otherName", testContext);
            var      resultVal      = gottenCustomer.UserName;
            var      expectedVal    = new Customer().UserName;

            //Assert
            Assert.Equal(expectedVal, resultVal);
        }
        public void GetCustomerByUserNameWorks()
        {
            // Act
            //// Service setup
            var services = new ServiceCollection();

            services.AddMemoryCache();
            services.AddDbContext <DbContextClass>(options => options.UseInMemoryDatabase("testDb"));
            var serviceProvider = services.BuildServiceProvider();
            //// Cache setup
            //var memoryCache = serviceProvider.GetService<IMemoryCache>();
            //IMemoryCache _cache = RevatureP1.UtilMethods.InitializeCacheIfNeeded(memoryCache);
            //// DbContext setup
            DbContextClass testContext = serviceProvider.GetService <DbContextClass>();
            //// Cache populating
            //_cache.Set("thisCustomer", testCustomer);
            //// DbContext populating
            Customer testCustomer = new Customer();
            string   testString   = "testUserNameA";

            testCustomer.UserName = testString;
            testContext.Add(testCustomer); // already done
            testContext.SaveChanges();
            // Arrange
            Customer gottenCustomer = RevatureP1.UtilMethods.GetCustomerByUserName(testString, testContext);
            var      resultVal      = gottenCustomer.UserName;
            var      expectedVal    = testString;

            //Assert
            Assert.Equal(expectedVal, resultVal);
        }
示例#10
0
        //get the users data
        public void GetPlayersName()
        {
            _logger.LogInformation("LogInformation = Hello. My name is Log LogInformation");
            _logger.LogWarning("LogWarning = At {time} Now I'm Loggy McLoggerton", DateTime.Now);
            _logger.LogCritical("LogCritical = As of now, I'm Scrog McLog");
            _logger.LogDebug("Log Debug");                             //not printed to console
            _logger.LogError("LogError");
            _logger.LogTrace("Log Trace = Tracing my way back home."); //not printed to console

            Console.WriteLine("Enter Player1 Name: ");                 //prompts user to input player 1 name
            String player = Console.ReadLine();                        //takes input from user and stores it as player 1 name

            p1.Name = player;

            Console.WriteLine("Enter Player2 Name: "); //prompts user to input player 1 name
            player  = Console.ReadLine();              //takes input from user and stores it as player 1 name
            p2.Name = player;

            db.Add(p1);
            db.Add(p2);
            db.SaveChanges();
        }
        public void BuildOrderItemViewModelFromCustOrderWorks()
        {
            // Act
            //// Service setup
            var services = new ServiceCollection();

            services.AddMemoryCache();
            services.AddDbContext <DbContextClass>(options => options.UseInMemoryDatabase("testDb"));
            var serviceProvider = services.BuildServiceProvider();
            //// DbContext setup
            DbContextClass testContext = serviceProvider.GetService <DbContextClass>();
            //// DbContext populating
            Customer testCustomer = new Customer();

            testCustomer.FirstName = "fn";
            testCustomer.LastName  = "ln";
            Location  testLocation  = new Location();
            StockItem testStockItem = new StockItem();

            testStockItem.DiscountPercent = 50;
            Product   testProduct   = new Product();
            OrderItem testOrderItem = new OrderItem();

            testOrderItem.TotalPriceWhenOrdered = 3;
            testProduct.BasePrice = 6;
            testContext.Add(testProduct);
            testContext.Add(testLocation);
            testContext.SaveChanges();
            // Arrange
            OrderItemViewModel testOrderItemViewModel = RevatureP1.UtilMethods.BuildOrderItemViewModelFromCustOrder(
                testCustomer, testOrderItem, testContext);
            var resultVal   = testOrderItemViewModel.CustomerName;
            var expectedVal = "fn ln";

            //Assert
            Assert.Equal(expectedVal, resultVal);
        }
        public async Task <IActionResult> Register([Bind("CustomerId,UserName,FirstName,LastName,Password,DateAdded")] Customer customer)
        {
            /// <summary>
            /// Registers a new customer
            /// </summary>
            if (ModelState.IsValid)
            {
                Customer checkCust = UtilMethods.GetCustomerByUserName(customer.UserName, _context);
                if (checkCust.UserName != null)
                {
                    System.Diagnostics.Debug.WriteLine($"Customer with user name {customer.UserName} already exists");
                    return(Redirect("/Login/Register?warn=duplicate"));
                }
                else
                {
                    customer.DateAdded = DateTime.Now;
                    _context.Add(customer);
                    await _context.SaveChangesAsync();

                    return(RedirectToAction(nameof(Index)));
                }
            }
            return(View(customer));
        }
示例#13
0
        public void Test1()
        {
            //Arrange
            //configure the inmemory DB. This is done in every test.
            var options = new DbContextOptionsBuilder <DbContextClass>()
                          .UseInMemoryDatabase(databaseName: "CustomNameForThisTestsInMemoryDb")
                          .Options;

            //use the using() to arrange the Db.
            using (var context = new DbContextClass(options))
            {
                Player p1 = new Player
                {
                    Name     = "Geralt",
                    PlayerId = 11,
                    Losses   = 2,
                    Wins     = 3
                };
                context.Add(p1);
                context.SaveChanges();
            }//end the context to make sure the correct player wAS SAVED TO THE DB


            //Act
            // Use a separate instance of the context to verify correct data was saved to database


            //Assert
            using (var context = new DbContextClass(options))
            {
                Assert.Equal(1, context.Players.Count());

                var p1Name = context.Players.Where(p => p.PlayerId == 11).FirstOrDefault();
                Assert.Equal("Geralt", p1Name.Name);
            }
        }
示例#14
0
 public void Add(Customer customer)
 {
     db.Add(customer);
     db.SaveChanges();
 }
        static void Main(string[] args)
        {
            using (var context = new DbContextClass())
            {
                Console.WriteLine("Enter 10 to start wtih a fresh Db or anything else to play with the existing records.");
                string userInput = Console.ReadLine();
                int    usersNumber;
                if (int.TryParse(userInput, out usersNumber))
                {
                    if (usersNumber == 10)
                    {
                        context.Games.FromSqlRaw("TRUNCATE TABLE Games");
                        context.Rounds.FromSqlRaw("TRUNCATE TABLE Rounds");
                        context.Players.FromSqlRaw("DELETE FROM Players WHERE PlayerId > 0 AND PlayerId < 100");
                    }
                }

                int    choice;//this is be out variable choice of the player to 1 (play) or 2 (quit)
                Player computer = new Player()
                {
                    Name = "Computer"
                };                                                   //instantiate a Player and give a value to the Name all at once.

                //Try to find an existing player named computer
                if (context.Players.Any(x => x.Name == "Computer"))
                {
                    computer = context.Players.Where(x => x.Name == "Computer").FirstOrDefault();
                }
                else
                {
                    computer.Name = "Computer";
                    context.Players.Add(computer);
                    context.SaveChanges();
                }


                int gameCounter = 1;                          //to keep track of how many games have been played so far in this compilation

                do                                            //game loop
                {
                    choice = RpsGameMethods.GetUsersIntent(); //get a choice from the user (play or quit)
                    if (choice == 2)
                    {
                        break;
                    }                            //if the user chose 2, break out of the game.

                    Console.WriteLine($"\n\t\tThis is game #{gameCounter++}");

                    string playerName = RpsGameMethods.GetPlayerName();//get the player name. this is a place to make sure the user isn't using forbidden words or symbols

                    // if the player name is not already in the Db, add him
                    Player p1 = new Player();
                    if (!RpsGameMethods.VerifyPlayer(context.Players.ToList(), playerName))
                    {
                        p1.Name = playerName;
                        context.Add(p1);
                        context.SaveChanges();
                    }
                    else
                    {
                        p1 = context.Players.Where(x => x.Name == playerName).FirstOrDefault();
                    }

                    Game game = new Game();   // create a game
                    game.Player1  = p1;       //
                    game.Computer = computer; //

                    //play rounds till one player has 2 wins
                    //assign the winner to the game and check that property to break out of the loop.
                    while (game.winner.Name == "null")
                    {
                        Round round = new Round(); //declare a round for this iteration
                        round.player1  = p1;       // add user (p1) to this round
                        round.Computer = computer; // add computer to this round

                        //get the choices for the 2 players and insert the players choices directly into the round
                        round.p1Choice       = RpsGameMethods.GetRandomChoice();     //this will give a random number starting at 0 to arg-1;
                        round.ComputerChoice = RpsGameMethods.GetRandomChoice();
                        round.Outcome        = RpsGameMethods.GetRoundWinner(round); //check the choices to see who won.
                        context.Add(round);
                        context.SaveChanges();
                        game.rounds.Add(round);//add this round to the games' List of rounds

                        Console.WriteLine($"\tFor this Game so far:\n\t\tp1wins => {game.rounds.Count(x => x.Outcome == 1)} \n\t\tcomputer wins {game.rounds.Count(x => x.Outcome == 2)}");

                        int gameWinner = RpsGameMethods.GetWinner(game);//get a number ot say is p1(1) or computer(2) won
                        //assign the winner to the game and increment wins and losses for both
                        if (gameWinner == 1)
                        {
                            game.winner = p1;
                            p1.Wins++;         //increments wins and losses.
                            computer.Losses++; //increments wins and losses.
                            Console.WriteLine($"The winner of this game was Player1\n");
                        }
                        else if (gameWinner == 2)
                        {
                            game.winner = computer;
                            p1.Losses++;     //increments wins and losses.
                            computer.Wins++; //increments wins and losses.
                            Console.WriteLine($"The winner of this game was the computer\n");
                        }
                    }//end of rounds loop
                    context.Add(game);//save the game
                    context.SaveChanges();
                } while (choice != 2);//end of game loop
                RpsGameMethods.PrintAllCurrentData(context.Games.ToList(), context.Players.ToList(), context.Rounds.ToList());
            }
        } //end of main
示例#16
0
        static void Main(string[] args)
        {
            using (var context = new DbContextClass())
            {
                int    choice;
                Player computer = new Player()
                {
                    Name = "Computer"
                };                                           //instantiate a Player and give a value to the Name all at once.
                context.Players.Add(computer);
                int gameCounter = 1;

                do//game loop
                {
                    choice = RpsGameMethods.GetUserIntent();
                    if (choice == 2)
                    {
                        break;
                    }

                    Console.WriteLine($"\n\tThis is game #{gameCounter++}\n");

                    //get the player name
                    string playerName = RpsGameMethods.GetPlayerName();

                    // check the list of players to see if this payer is a returning player.
                    Player p1 = RpsGameMethods.VerifyPlayer(context.Players.ToList(), playerName);

                    Game game = new Game();   // create a game
                    game.Player1  = p1;       //
                    game.Computer = computer; //
                    //context.Add(p1);
                    //context.SaveChanges();

                    //play rounds till one player has 2 wins
                    //assign the winner to the game and check that property to break out of the loop.
                    while (game.winner.Name == "null")
                    {
                        Round round = new Round(); //declare a round for this iteration
                        round.game     = game;     // add the game to this round
                        round.player1  = p1;       // add user (p1) to this round
                        round.Computer = computer; // add computer to this round

                        // Player choice for game
                        round.p1Choice = RpsGameMethods.GetPlayerChoice();
                        // Random player choice for game
                        round.ComputerChoice = RpsGameMethods.GetRandomChoice();

                        //check the choices to see who won.
                        RpsGameMethods.GetRoundWinner(round);

                        game.rounds.Add(round);//add this round to the games List of rounds
                        context.Rounds.Add(round);

                        //search the game.rounds List<> to see if one player has 2 wins
                        //if not loop to another round
                        int whoWon = RpsGameMethods.GetWinner(game);

                        //assign the winner to the game and increment wins and losses for both
                        //RpsGameMethods.WhoWon(game, p1, computer, whoWon);
                        if (whoWon == 1)
                        {
                            game.winner = p1;
                            p1.Wins++;         //increments wins and losses.
                            computer.Losses++; //increments wins and losses.
                            Console.WriteLine($"The winner of this game was Player1\n");
                            context.Add(round);
                            //context.SaveChanges();
                        }
                        else if (whoWon == 2)
                        {
                            game.winner = computer;
                            p1.Losses++;     //increments wins and losses.
                            computer.Wins++; //increments wins and losses.
                            Console.WriteLine($"The winner of this game was computer\n");
                            context.Add(round);
                            //context.SaveChanges();
                        }
                    }//end of rounds loop

                    context.Games.Add(game);
                    context.SaveChanges();
                } while (choice != 2);//end of game loop
                // Print current game data
                RpsGameMethods.PrintAllCurrentData(context.Games.ToList(), context.Players.ToList(), context.Rounds.ToList());
            }
        } //end of main