public async void GetCustomerByEmail() { //Arrange var options = BuildInMemoryDb("GetsCustomerByEmail"); string fName = "Bob", lName = "Dole", email = "*****@*****.**"; int id = 1; //Act using (var context = new ShoppingDbContext(options)) { var customer = new Customer { CustomerId = id, FirstName = fName, LastName = lName, Email = email }; context.Add(customer); context.SaveChanges(); } //Assert using (var context = new ShoppingDbContext(options)) { var customerRepo = new CustomerRepository(context); var list = await customerRepo.Find(c => c.Email == email); var customerInfo = list.FirstOrDefault(); Assert.Equal(id, customerInfo.CustomerId); Assert.Equal(fName, customerInfo.FirstName); Assert.Equal(lName, customerInfo.LastName); Assert.Equal(email, customerInfo.Email); } }
public async void AddsCustomerToDb() { //Arrange var options = BuildInMemoryDb("AddsCustomer"); string fName = "Bob", lName = "Dole", email = "*****@*****.**"; var customerInfo = new Customer { Email = email, FirstName = fName, LastName = lName }; //Act using (var context = new ShoppingDbContext(options)) { var customerRepo = new CustomerRepository(context); customerInfo = await customerRepo.Add(customerInfo); } //Assert using (var context = new ShoppingDbContext(options)) { var customer = (from c in context.Customers where c.FirstName == fName && c.LastName == lName select c).Take(1).FirstOrDefault(); Assert.Equal(customer.CustomerId, customerInfo.CustomerId); Assert.Equal(fName, customer.FirstName); Assert.Equal(lName, customer.LastName); Assert.Equal(email, customer.Email); } }
public ActionResult Register(Customer newCustomer) { if (newCustomer.Password != newCustomer.ConfirmPassword) { MessageBox.Show("Password and confirm password do not match!"); return(View()); } if (newCustomer.Dateofbirth.Value > DateTime.Now) { MessageBox.Show("Invalid Date of Birth!"); return(View()); } using (ShoppingDbContext db = new ShoppingDbContext()) { Customer customer = db.Customer.Where(x => x.Username == newCustomer.Username).FirstOrDefault(); if (customer != null) { MessageBox.Show("Username already exists! Please choose another one."); return(View()); } string password = newCustomer.Password; newCustomer.Password = Functions.ComputeSHA256(password); newCustomer.ConfirmPassword = null; newCustomer.JoinDate = DateTime.Now; db.Customer.Add(newCustomer); db.SaveChanges(); } MessageBox.Show("Account successfully registered! You may now login."); return(RedirectToAction("Login", "Home")); }
private void ClearEntitiesInContext(ShoppingDbContext context) { context.Bill.RemoveRange(context.Bill); context.UserBankAccount.RemoveRange(context.UserBankAccount); context.BankAccount.RemoveRange(context.BankAccount); context.User.RemoveRange(context.User); }
public ActionResult ForgotPassword(FormCollection form) { string username = form["Username"]; string email = form["Email"]; string message = ""; using (ShoppingDbContext db = new ShoppingDbContext()) { Customer account = db.Customer.Where(a => a.Email == email && a.Username == username).FirstOrDefault(); if (account != null) { string resetCode = Guid.NewGuid().ToString(); SendVerificationLinkEmail(account.Email, resetCode, "ResetPassword"); account.ResetCode = resetCode; db.SaveChanges(); message = "Reset password link has been sent to your email address!"; } else { message = "Invalid username and/or email! Please try again."; } } MessageBox.Show(message); return(View()); }
public static ShoppingDbContext CreateInMemoryDataContext(Action <ShoppingDbContext> setupCallback = null) { // In-memory database only exists while the connection is open var connection = new SqliteConnection("DataSource=:memory:"); connection.Open(); var options = new DbContextOptionsBuilder <ShoppingDbContext>() .UseSqlite(connection) .Options; // Create the schema in the database var context = new ShoppingDbContext( options); // HACK: ef core wont put data into a rowversion column, but it is not null, so create a fake default var sqlScript = context.Database.GenerateCreateScript(); sqlScript = sqlScript.Replace("\"Version\" BLOB NOT NULL", "\"Version\" BLOB NOT NULL DEFAULT (randomblob(8))"); context.Database.ExecuteSqlRaw(sqlScript); // Invoke callback to enable Test to provide master data if (setupCallback != null) { setupCallback.Invoke(context); context.SaveChanges(); } return(context); }
public async void GetsAllLocations() { //Arrange var options = BuildInMemoryDb("GetsAllLocations"); //Act using (var context = new ShoppingDbContext(options)) { var store = new Store { Location = "Location1" }; context.Add(store); store = new Store { Location = "Location2" }; context.Add(store); store = new Store { Location = "Location3" }; context.Add(store); context.SaveChanges(); } //Assert using (var context = new ShoppingDbContext(options)) { var storeRepo = new StoreRepository(context); var stores = await storeRepo.All(); Assert.Equal(3, stores.Count()); } }
protected override void Establish_context() { LoadConfiguration(); DbProviderFactories.RegisterFactory("System.Data.SqlClient", SqlClientFactory.Instance); var dir = TestContext.CurrentContext.TestDirectory; Directory.SetCurrentDirectory(dir); SetupServiceProvider(); Context = ServiceProvider.GetService <ShoppingDbContext>(); TestCaseService = new TestCaseService(Context); //if (ShouldLoadTestObjects) //{ // MusicObjects = new ShoppingTestsDataObjects(Context); // MusicObjects.LoadObjects(); //} TestStartedDatTime = DateTime.Now; base.Establish_context(); }
public UsersController(ShoppingDbContext context, UserManager <Users> usermanager, SignInManager <Users> signInManager, IOptions <ApplicationSettings> options, RoleManager <IdentityRole> roleManager) { _context = context; this.usermanager = usermanager; this.signInManager = signInManager; RoleManager = roleManager; this.options = options.Value; }
public AdminController(RoleManager <IdentityRole> roleManager, UserManager <Users> usermanager, SignInManager <Users> SignInManager, ShoppingDbContext context) { this._roleManager = roleManager; this._usermanager = usermanager; _SignInManager = SignInManager; _context = context; }
public UnitOfWork(ShoppingDbContext context) { this.context = context ?? throw new ArgumentNullException(nameof(context)); this.BankAccountRepository = new BankAccountRepository(context); this.BillRepository = new BillRepository(context); this.UserRepository = new UserRepository(context); }
public ActionResult ProcessCheckout() { Customer customer = (Customer)Session["Customer"]; Dictionary <int, int> cart = (Dictionary <int, int>)Session["Cart"]; var keyList = cart.Keys; List <Product> productList = new List <Product>(); using (ShoppingDbContext db = new ShoppingDbContext()) { productList = db.Product.Where(p => keyList.Any(k => k == p.ID)).ToList(); double totalPrice = 0.0; foreach (Product p in productList) { totalPrice += (p.Price * cart[p.ID]); } Order order = new Order() { Date = DateTime.Now, Price = totalPrice, Products = new List <Product>() }; order.Customer = db.Customer.Where(c => c.ID == customer.ID).FirstOrDefault(); foreach (Product p in productList) { order.Products.Add(p); } db.Order.Add(order); List <OrderDetail> odList = new List <OrderDetail>(); foreach (Product p in productList) { OrderDetail od = new OrderDetail() { Quantity = cart[p.ID], Order = order, Product = p }; db.OrderDetail.Add(od); odList.Add(od); } foreach (OrderDetail od in odList) { for (int i = 0; i < od.Quantity; i++) { OrderDetailExtended ode = new OrderDetailExtended() { ActivationCode = Guid.NewGuid() }; ode.OrderDetail = od; db.OrderDetailExtended.Add(ode); } } db.SaveChanges(); } Session["Cart"] = new Dictionary <int, int>(); Session["CartQty"] = 0; return(RedirectToAction("Index", "Purchase")); }
public ShoppingDataSource() { ShoppingDbContext context = ShoppingDbContextFactory.GetInstance(); Items = new ItemRepository(context); Carts = new CartRepository(context); Users = new UserRepository(context); Orders = new OrderRepository(context); }
public bool ExistProduct(int id) { using (ShoppingDbContext db = new ShoppingDbContext()) { return(db .Products .Any(p => p.Id == id)); } }
public static void InitializeDbForTests(ShoppingDbContext context) { if (context.Customers.Any() == false) { context.Customers.Add(new Customer { Id = 1, Address = "test address", City = "Berlin", CompanyName = "Benz", ContactName = "Test", ContactTitle = "Test", Country = "Germany", Fax = "32323232", Phone = "333333", PostalCode = "44444" }); } if (context.Products.Any() == false) { var supplier1 = new Supplier { CompanyName = "Benz", ContactName = "Test", ContactTitle = "Test", Address = "Test", City = "Germany", PostalCode = "24322", Fax = "", Phone = "232323", HomePage = "" }; var category1 = new Category { CategoryName = "Test Category", Description = "..." }; context.Products.Add( new Product { ProductName = "Maclaren", Supplier = supplier1, Category = category1, QuantityPerUnit = "1", UnitPrice = 15558.00m, UnitsInStock = 2, UnitsOnOrder = 0, ReorderLevel = 10, Discontinued = false }); } context.SaveChanges(); }
private static void SeedArtistIfNotExists(ShoppingDbContext dbContext, String name) { var genre = dbContext.Artists.FirstOrDefault(x => x.Name == name); if (genre == null) { dbContext.Artists.Add(new ArtistBuilder().WithName(name).Build()); } }
public void ThrowsOnNegativeInventory() { //Arrange var options = BuildInMemoryDb("ThrowsException"); //Act using (var context = new ShoppingDbContext(options)) { CreateOneCustomer(context); CreateTwoproducts(context); var store = new Store { StoreId = 1, Location = "Location1", AvailableProducts = new List <Inventory> { new Inventory { ProductId = 1, StoreId = 1, Quantity = 10 } } }; context.Add(store); context.SaveChanges(); } //Assert using (var context = new ShoppingDbContext(options)) { var unitOfWork = new UnitOfWork(context); var prods = new List <OrderDetails>() { new OrderDetails() { ProductId = 1, Quantity = 12, PricePaid = 5.99 } }; var order = new Order { ProductsOrdered = prods, CusomerId = 1, StoreId = 1 }; //orderId = unitOfWork.OrderRepository.Add(order).Result.OrderId; Assert.ThrowsAny <Exception>(() => unitOfWork.OrderRepository.Add(order).Result); } }
protected void Application_Start() { AreaRegistration.RegisterAllAreas(); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); ShoppingDbContext db = new ShoppingDbContext(); db.Database.Initialize(true); }
public ICollection <ProductViewModel> GetOrderProducts(ICollection <int> productIds) { using (ShoppingDbContext db = new ShoppingDbContext()) { List <ProductViewModel> products = db .Products .Where(p => productIds.Contains(p.Id)) .Select(p => new ProductViewModel(p.Id, p.Name, p.Price, p.ImageUrl)) .ToList(); return(products); } }
public ProductViewModel GetByIdOrNull(int id) { using (var db = new ShoppingDbContext()) { ProductViewModel product = db .Products .Where(p => p.Id == id) .Select(p => new ProductViewModel(p.Id, p.Name, p.Price, p.ImageUrl)) .FirstOrDefault(); return(product); } }
private void CreateOneCustomer(ShoppingDbContext context) { var customer = new Customer { CustomerId = 1, FirstName = "Jim", LastName = "Bob", Email = "*****@*****.**" }; context.Add(customer); context.SaveChanges(); }
public ICollection <ProductViewModel> GetAllBySearchedTerm(string searchTerm) { using (var db = new ShoppingDbContext()) { var allCakes = db .Products .Where(p => p.Name.Contains(searchTerm)) .Select(p => new ProductViewModel(p.Id, p.Name, p.Price, p.ImageUrl)) .ToList(); return(allCakes); } }
public static ShoppingDbContext Create() { var options = new DbContextOptionsBuilder <ShoppingDbContext>() .UseInMemoryDatabase(Guid.NewGuid().ToString()) .Options; var context = new ShoppingDbContext(options); context.Database.EnsureCreated(); context.SaveChanges(); return(context); }
public ICollection <ProductViewModel> GetAllByOrderId(int orderId) { using (ShoppingDbContext db = new ShoppingDbContext()) { return(db .Orders .Include(o => o.Products) .ThenInclude(op => op.Product) .Where(o => o.Id == orderId) .First() .Products .Select(op => new ProductViewModel(op.Product.Id, op.Product.Name, op.Product.Price, op.Product.ImageUrl)) .ToList()); } }
public void Add(int id) { try // tìm thấy trong giỏ -> tăng số lượng lên 1 { var item = Items.Single(i => i.Id == id); item.Quantity++; } catch // chưa có trong giỏ -> truy vấn CSDL và bỏ vào giỏ { var db = new ShoppingDbContext(); var item = db.Products.Find(id); item.Quantity = 1; Items.Add(item); } }
protected override async Task LoadShoppingTestDataAsync() { await ShoppingDbContext.Customers.AddRangeAsync( new Core.Domains.Customer { Id = 2, ContactName = "Ralph R. Rao" }, new Core.Domains.Customer { Id = 3, ContactName = "Edward M. Clay" }, new Core.Domains.Customer { Id = 4, ContactName = "Wendell S. Graney" }); await ShoppingDbContext.SaveChangesAsync(); }
public static IWebHost SeedData(this IWebHost host) { using (var scope = host.Services.CreateScope()) { IServiceProvider services = scope.ServiceProvider; ShoppingDbContext context = services.GetService <ShoppingDbContext>(); UserManager <UserEntity> userManager = services.GetService <UserManager <UserEntity> >(); RoleManager <IdentityRole> roleManager = services.GetService <RoleManager <IdentityRole> >(); IConfiguration config = services.GetService <IConfiguration>(); DatabaseSeeder.SeedRoles(roleManager); DatabaseSeeder.SeedUsers(userManager, config); } return(host); }
public IHttpActionResult Get() { using (ShoppingDbContext context = new ShoppingDbContext("ShoppingCartDatabase")) { context.Items.Add(new Item { Price = 1 }); context.Items.Add(new Item { Price = 1 }); context.Items.Add(new Item { Price = 1 }); context.SaveChanges(); } return(Ok("done")); }
public async Task Should_Throws_DeleteFailure_Exception_With_Valid_Id_And_Exists_Some_Orders() { await ShoppingDbContext.Orders.AddAsync(new Order { Id = 1 }); await ShoppingDbContext.SaveChangesAsync(); var validId = 1; var command = new DeleteCustomerCommand { Id = validId }; await Should.ThrowAsync <DeleteFailureException>(() => _sut.Handle(command, default)); }
public async void GetsAllOrdersForCustomer() { //Arrange var options = BuildInMemoryDb("GetsCustomersOrders"); //Act using (var context = new ShoppingDbContext(options)) { CreateOneCustomer(context); CreateTwoproducts(context); var store = new Store { StoreId = 1, Location = "Location1" }; context.Add(store); context.SaveChanges(); var order = new Order { CusomerId = 1, OrderDateTime = DateTime.Now, OrderId = 1, StoreId = 1, }; context.Add(order); order = new Order { CusomerId = 1, OrderDateTime = DateTime.Now, OrderId = 2, StoreId = 1, }; context.Add(order); context.SaveChanges(); } //Assert using (var context = new ShoppingDbContext(options)) { var orderRepo = new OrderRepository(context); var orders = await orderRepo.Find(o => o.CusomerId == 1); Assert.Equal(2, orders.Count()); } }