public static List<Product> RetrieveProducts(Func<Product, bool> action) { var productsRepository = new ProductsRepository(); return (action == null ? productsRepository.List.Result.ToList() : productsRepository.GetPrdocuts(action).ToList()); }
public void OrderDetails() { var conn = new NHibernateConnection(); var orderRepo = new OrdersRepository(conn); var productRepo = new ProductsRepository(conn); var userRepo = new UserRepository(conn); var deliveryRepo = new DeliveryTypesRepository(conn); Users user = userRepo.Get("*****@*****.**"); var orderDetailsRepo = new OrderDetailsRepository(conn); Products product = productRepo.GetAll().First(); var delivetyType = deliveryRepo.GetAll().First(); if (delivetyType == null) { delivetyType = new DeliveryTypes("Poczta Polska", Convert.ToDecimal(8.99)); deliveryRepo.Save(delivetyType); } var order = new Orders(user, DateTime.Now, Convert.ToDecimal(299.99),delivetyType); orderRepo.Save(order); var orderDetails = new OrderDetails(order, product, 2, Convert.ToDecimal(29.99)); orderDetailsRepo.Save(orderDetails); var fromDB = orderDetailsRepo.Get(orderDetails.ID); Assert.IsNotNull(fromDB); }
public Northwind() { _uow = new UnitOfWork<NorthwindDbContext>(); _category = new CategoryRepository(_uow); _orders = new OrdersRepository(_uow); _customers = new CustomerRepository(_uow); _products = new ProductsRepository(_uow); }
public void When_ProductsList_Greaterthan500_IsRetrieved() { var productsRepository = new ProductsRepository(); var results = productsRepository.GetPrdocuts(x => (x.Price > 1800 && x.Price<3000)); foreach (var product in results) { Console.WriteLine(product.ToString()); } }
public void When_ProductsList_IsRetrieved() { var productsArrayList = new ArrayList(); var productsRepository = new ProductsRepository(); var results = productsRepository.List.Result; productsArrayList.AddRange(results); foreach (var product in productsArrayList) { Console.WriteLine(product.ToString()); } }
public void WhenAProduct_IsCreated() { var productsRepository = new ProductsRepository(); var currencyGenerator = new CurrencyGenerator(); var product = new Product { Name = NameGenerator.GenerateName(), Price = currencyGenerator.GenerateAmount() }; var results = productsRepository.Add(product).Result; Console.WriteLine(results); }
public void When_10Products_AreCreated() { var productsRepository = new ProductsRepository(); var currencyGenerator = new CurrencyGenerator(maximumValue: 15000.0); for (var iCtr = 0; iCtr < 1000; iCtr++) { var product = new Product { Name = NameGenerator.GenerateName(), Price = currencyGenerator.GenerateAmount() }; var results = productsRepository.Add(product).Result; Console.WriteLine(results); } }
public async Task UpdateProduct_Add_Success() { int products_count = 14; // 14 записей согласно начальному значению модели int products_id = default(int); Product product = new Product() { ProductId = products_id, Comment = "Тест", Name = "Тест", Price = 50 }; using (var transaction = testDatabase.Connection.BeginTransaction()) { using (var context = testDatabase.CreateContext(transaction)) { IProducts productsRepository = new ProductsRepository(context); ProductsController controller = new ProductsController(productsRepository); // выполняем тестируемый метод var actionResult = await controller.UpdateProduct(product); var result = actionResult as OkResult; // проверяем результат Assert.IsNotNull(actionResult); Assert.AreEqual(result.StatusCode, 200); // выполняем тестируемый метод var actionResult2 = await controller.GetProducts(); var result2 = actionResult2.Result as OkObjectResult; // проверяем результат // проверяем результат Assert.IsNotNull(result2); Assert.AreEqual(result2.StatusCode, 200); Assert.AreEqual((result2.Value as IQueryable <Product>).Count(), products_count + 1); // проверяем на увеличение количества записей } } }
public void Run(ProductsRepository productsRepository, IEnumerable <IStockEvent> events) { foreach (var stockEvent in events) { if (TryExecute(stockEvent)) { foreach (var syncRule in stockEvent.GetSyncRules()) { if (TryExecute(syncRule)) { foreach (var outputEvent in syncRule.GetOutputEvents()) { TryExecute(outputEvent); _outputLogger.LogMessage(outputEvent.ToJson()); } } } } } _outputLogger.LogMessage(new StockSummary(productsRepository).ToJson()); }
public async Task GetProduct_UnSuccess() { int product_id = 44; // больше 14 using (var transaction = testDatabase.Connection.BeginTransaction()) { using (var context = testDatabase.CreateContext(transaction)) { IProducts productsRepository = new ProductsRepository(context); ProductsController controller = new ProductsController(productsRepository); // выполняем тестируемый метод var actionResult = await controller.GetProduct(product_id); var result = actionResult.Result as NotFoundResult; // проверяем результат Assert.IsNotNull(result); Assert.AreEqual(result.StatusCode, 404); } } }
public void PostShouldAddProduct() { // Arrange IProductsRepository productsRepository = new ProductsRepository(); var product1 = new Product { Id = "1", Brand = "Apple", Description = "Apple Watch 2", Model = "Series 2" }; var controller = new ProductsController(productsRepository); // Act var actionResult = controller.Post(product1); var response = actionResult as CreatedAtRouteNegotiatedContentResult <Product>; // Assert Assert.IsNotNull(response); Assert.AreEqual("DefaultApi", response.RouteName); Assert.AreEqual(response.Content.Id, response.RouteValues["Id"]); }
public void WhenAUserCreateANewProductNullOrEmptyValues() { ////Arrange var valueExpected = false; var product = new Product { Cod = "222", Cost = decimal.Parse("2500000"), Description = null, Name = string.Empty, ImageRef = null }; var chk = new Mock <IProductsDalRepository>(); chk.Setup(x => x.InsertProduct(product)).Returns(false); ////Act var valueActual = new ProductsRepository(chk.Object) .AddProduct(product); ////Assert Assert.Equal(valueExpected, valueActual); }
public void WhenAUserCreateANewProductCorrect() { ////Arrange var valueExpected = true; var product = new Product { Cod = "222", Cost = decimal.Parse("2500000"), Description = "Description", Name = "Name", ImageRef = "localhost:8082/" }; var chk = new Mock <IProductsDalRepository>(); chk.Setup(x => x.InsertProduct(product)).Returns(true); ////Act var valueActual = new ProductsRepository(chk.Object) .AddProduct(product); ////Assert Assert.Equal(valueExpected, valueActual); }
public Product ListProducts(int categoryId, string category) { Clear(); var productsRepository = new ProductsRepository(); var products = productsRepository.GetProductsByCategory(categoryId); Console.WriteLine("Liste des produits de la catégorie : " + category + "\n"); var productBrowser = new ProductBrowser(); var result = productBrowser.SelectFromListOfProductsByCategory(products); switch (result.Key) { case "product": return((Product)result.Value); case "action": switch (result.Value) { case "categories": return(SelectProductByCategory()); case "quit": return(null); default: return(null); } break; default: Clear(); Echo("Une erreur est survenue"); AskKeyPress(); return(DisplayMainMenuWithProduct()); } }
public ActionResult Edit(EditVM model) { GenresRepository genresRepo = new GenresRepository(); if (!ModelState.IsValid) { model.Genres = new SelectList ( genresRepo.GetAll(), "Id", "Name", model.GenreId ); return(View(model)); } ProductsRepository repo = new ProductsRepository(); Product item = new Product(); item.Id = model.Id; item.GenreId = model.GenreId; item.Artist = model.Artist; item.Title = model.Title; item.Price = (decimal)model.Price; item.VinylImgPath = model.VinylImgPath; item.OnSale = model.OnSale; if (item.Id > 0) { repo.Update(item); } else { repo.Insert(item); } return(RedirectToAction("Index", "Products")); }
private static async Task ProgramAsync() { var ctx = new ProductContext(); var repository = new ProductsRepository(ctx); await repository.AddShopsAsync(InitialData.Shops); var shops = await repository.GetShopsAsync(); var victoryInfo = shops.First(s => s.Brand == ShopBrand.Victory); var ybitanInfo = shops.First(s => s.Brand == ShopBrand.YBitan); var coobInfo = shops.First(s => s.Brand == ShopBrand.Coob); var parser = new XmlParser(); var victoryProducts = parser.ParseFile("../../../ShoppingCart.Server.XMLEngine/Xml/VictorySample.Xml", new VictoryUnitsParser(), "/Prices/Products/Product", victoryInfo); var ybitanProducts = parser.ParseFile("../../../ShoppingCart.Server.XMLEngine/Xml/YbitanSample.Xml", new YbUnitsParser(), "/Root/Items/Item", ybitanInfo); var coobProducts = parser.ParseFile("../../../ShoppingCart.Server.XMLEngine/Xml/CoobSample.Xml", new CoobUnitsParser(), "/root/Items/item", coobInfo); victoryProducts = victoryProducts.ToList(); ybitanProducts = ybitanProducts.ToList(); coobProducts = coobProducts.ToList(); await repository.AddCategoiesAsync(Categorizer.Categories); await repository.AddProductsAsync(victoryProducts); await repository.AddProductsAsync(ybitanProducts); await repository.AddProductsAsync(coobProducts); Task.WaitAll(new ProductsRepository(new ProductContext()).FindAndAddSimilarProductsAsync(victoryInfo), new ProductsRepository(new ProductContext()).FindAndAddSimilarProductsAsync(ybitanInfo), new ProductsRepository(new ProductContext()).FindAndAddSimilarProductsAsync(coobInfo)); }
public Orders Calculate(Orders order) { Products selectedProduct = ProductsRepository.LoadProducts() .FirstOrDefault(p => p.ProductType == order.ProductType); Taxes selectedTax = TaxesRepository.LoadTaxes() .FirstOrDefault(t => t.StateAbbreviation == order.State); if (selectedProduct == null) { throw new Exception("Product not found!"); } if (selectedTax == null) { throw new Exception("State not found!"); } order.CostPerSquareFoot = selectedProduct.CostPerSquareFoot; order.LaborCostPerSquareFoot = selectedProduct.LaborCostPerSquareFoot; order.TaxRate = selectedTax.TaxRate; return(order); }
public static async Task <ActionResult <string> > Run( [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] HttpRequest request) { var requestBody = await new StreamReader(request.Body).ReadToEndAsync(); var products = JsonConvert.DeserializeObject <Product[]>(requestBody).ToArray(); if (!products.Any()) { return(new OkObjectResult("No products were added")); } // Hard-coded Connection String & Database name, as they are not the point of focus for this exercise var connectionString = "mongodb+srv://muruga:[email protected]/test?retryWrites=true&w=majority"; var databaseName = "IOUCommrate"; var repository = new ProductsRepository( connectionString, databaseName); await repository.AddProducts(products); return(new OkObjectResult("Products added successfully")); }
public async Task GetProducts_Success() { int products_count = 14; // 14 записей согласно начальному значению модели using (var transaction = testDatabase.Connection.BeginTransaction()) { using (var context = testDatabase.CreateContext(transaction)) { IProducts productsRepository = new ProductsRepository(context); ProductsController controller = new ProductsController(productsRepository); // выполняем тестируемый метод var actionResult = await controller.GetProducts(); var result = actionResult.Result as OkObjectResult; // проверяем результат Assert.IsNotNull(result); Assert.AreEqual(result.StatusCode, 200); Assert.AreEqual((result.Value as IQueryable <Product>).Count(), products_count); } } }
public ActionResult RemoveByOne(int id) { if (Session["cart"] == null) { return(new HttpNotFoundResult("You haven't added anything to the cart yet!")); } ProductsRepository repo = new ProductsRepository(); Product product = repo.GetById(id); Dictionary <Product, int> cart = (Dictionary <Product, int>)Session["cart"]; if (cart.ContainsKey(product) && cart[product] > 1) { cart[product]--; } else if (cart.ContainsKey(product) && cart[product] == 1) { return(RedirectToAction("Remove", new { id = id })); } Session["cart"] = cart; return(RedirectToAction("Index", "Account")); }
public bool Match(HttpContext httpContext, IRouter route, string routeKey, RouteValueDictionary values, RouteDirection routeDirection) { var value = values["productid"]; if (value == null) { return(false); } int productId; if (int.TryParse(value.ToString(), out productId)) { var productsRepository = new ProductsRepository(); var product = productsRepository.GetProductById(productId); return(product != null); } else { return(false); } }
public void Apply() { Product product; if (!_parentId.HasValue) { product = new ParentProduct(Id, _stock); } else { var parent = (ParentProduct)ProductsRepository.GetProduct(_parentId.Value); if (parent == null) { throw new ArgumentException($"Unexisting parentId {_parentId}"); } else { product = new ChildProduct(Id, _stock, parent); parent.Children.Add((ChildProduct)product); } } ProductsRepository.AddProduct(product); }
public IEnumerable <Products> ClassifyByCategoryNameAndNullDownTime(string name) { var Product_repository = new ProductsRepository(); var list = Product_repository.GetAll(); var Category_repository = new CategoriesRepository(); var model = Category_repository.GetByName(name); var result = new List <Products>(); var real_result = new List <Products>(); result = list.Where((x) => x.CategoryID == model.CategoryID).ToList(); result = result.Where((x) => x.Downtime == null).ToList(); foreach (var items in result) { if (real_result.Any((x) => x.ProductName == items.ProductName) == false) { real_result.Add(items); } } return(real_result); }
public void Post_WhenPassedAValidProduct_ShouldReturnSame() { // arrange // I'm fudging a bit on the Id here for the sake of time. // in a real app, we'd let SQL Server / EF tell us the new Id value for an added item. const string product = "{ \"id\": 4, \"description\": \"Kiwi\", \"price\": 1.20 }"; // still, in an attempt to get this to work as much like it would in the real world, // I'm going to serialize this into a real object that will then be passed to the // Post() method. var newProduct = JsonConvert.DeserializeObject <ProductItem>(product); var testDataContext = new DataFileData { Products = _testProducts }; var productsRepository = new ProductsRepository(new DatabaseFactory(testDataContext)); var productsServicesInst = new ProductsServices(productsRepository); //var mockStaticLoggerInstWrapper = new Mock<IStaticLoggerInstanceWrapper>(); var productsController = new ProductsController(productsServicesInst); // Act var response = productsController.Post(newProduct); // Assert Assert.IsNotNull(response); Assert.IsInstanceOfType(response, typeof(CreatedAtActionResult)); var foundProduct = (ProductItem)((CreatedAtActionResult)response).Value; Assert.IsInstanceOfType(foundProduct, typeof(ProductItem)); // And just for good measure... Assert.AreEqual(4, foundProduct.Id); Assert.AreEqual("Kiwi", foundProduct.Description); }
public ActionResult AddingProduct(MallOfElectronics.Models.DataBase.Product product, HttpPostedFileBase UploadImage) { if (ModelState.IsValid) { string physicalPath = "", ImageName = "Images/ProductsImages/"; if (UploadImage != null) { physicalPath = Server.MapPath("~") + "Images\\ProductsImages\\" + UploadImage.FileName; UploadImage.SaveAs(physicalPath); ImageName += UploadImage.FileName; } else { ImageName += "EmptyProductsImage.jpg"; } product.Image = ImageName; ProductsRepository productRepository = new ProductsRepository(); if (productRepository.Add(product)) { ViewBag.Message = "This Product Has Been Added"; } else { if (UploadImage != null) { System.IO.File.Delete(physicalPath); } ViewBag.ErrorMessage = "This Product Not Has Been Added"; } } else { ViewBag.ErrorMessage = "This Product Not Has Been Added"; } return(View()); }
public SearchShortDates() { Clear(); string dateSearch = AskForDate(); bool isProductValidated = ValidateProduct(dateSearch); if (isProductValidated) { Clear(); Echo("Liste des produits dont la date de consommation se terminant avant ou le " + dateSearch + " : \n"); PrintTableHeader(true, "Id", "Name", "Prix", "Stock", "Date d'expiration"); StocksRepository stocksRepository = new StocksRepository(); ProductsRepository productsRepository = new ProductsRepository(); var stringDateSearch = stocksRepository.ConvertStringDateToTimeStamp(dateSearch); var listProducts = productsRepository.GetAllProducts(); foreach (Product aProduct in listProducts) { var stockProduct = stocksRepository.GetStockByProductId(aProduct.Id); var stringExpiry = stocksRepository.ConvertTimeStampToStringDate(stockProduct.Expiry); int result = stringDateSearch.CompareTo(stockProduct.Expiry); if (result >= 0) { PrintLineCells(true, $"{aProduct.Id}", aProduct.Name, $"{aProduct.Price}", $"{stockProduct.Quantity}", stringExpiry); } else { } } Echo(PrintLine()); WaitForKeyPress(); } }
public void AddsNewProductToBasicProductsAfter10Times() { FoodNetDbContext ctx = GetContextWithData(); ProductsRepository productsRepository = new ProductsRepository(ctx, GetMapper()); int basicProductsCountBefore = ctx.BasicProducts.Count(); for (int i = 0; i <= 10; i++) { NewProduct newProduct = new NewProduct { Id = Guid.NewGuid(), Name = "NAME", Description = "", ProductCategoryId = productCategory3.Id, UserId = secondUserGuid }; productsRepository.AddNewProduct(newProduct); } int basicProductsCountAfter = ctx.BasicProducts.Count(); Assert.Equal(basicProductsCountBefore + 1, basicProductsCountAfter); }
public HttpResponseMessage PostOrderLineItems(object order) { //if (!ModelState.IsValid) //{ // return BadRequest(ModelState); //} //var lineItemModel = lineItem.ToModel(); var lineItems = new LineItemHelper(); var items = lineItems.Parse(order); var postCount = 0; foreach (LineItem item in items) { var repo = new LineItemsRepository(); repo.Post(item); var adjustInventory = new ProductsRepository(); adjustInventory.DecrementProductCount(item.VariantId, item.Quantity); postCount += 1; } return(items.Count == postCount?Request.CreateResponse(HttpStatusCode.Created) : Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "Could not process your order, try again later...")); }
public ActionResult Index(string order) { List <Product> products = ProductsRepository.GetProducts(); if (order == "name") { products = (from p in products orderby p.Title select p).ToList(); } else if (order == "date") { products = (from p in products orderby p.Date select p).ToList(); } var LoginSignModel = new LoginSignModel() { Products = products }; return(View(LoginSignModel)); }
public ActionResult EditingProduct(MallOfElectronics.Models.DataBase.Product product) { MallOfElectronics.Models.DataBase.Product previousProduct = (MallOfElectronics.Models.DataBase.Product)TempData["prviousProduct"]; ProductsRepository productRepository = new ProductsRepository(); CheckEqualForProducts check = new CheckEqualForProducts(); if (!check.IsEqual(previousProduct, product)) { if (productRepository.update(product)) { ViewBag.message = "This Product Has Been Updated"; } else { ViewBag.ErrorMessage = "Not Item Of Product To Change"; } } else { ViewBag.ErrorMessage = "This Product Not Has Been Updated"; } return(View()); }
static void Main(string[] args) { var efContext = new EfContext(); var productsRepository = new ProductsRepository(efContext); productsRepository.InitializeMockData(); var mediator = new Mediator(productsRepository); var actionsRegistry = new ActionsRegistry(mediator); while (true) { Console.Write("\nCommand: "); var command = Console.ReadLine(); if (string.IsNullOrWhiteSpace(command)) { WriteError("Please choose command, query or pass 'exit' to leave an application."); continue; } if (command.ToLower() == "exit") { break; } try { actionsRegistry.Run(command); WriteSuccess(); } catch (Exception e) { WriteError(e.Message); } } }
private List <MallOfElectronics.Models.DataBase.Product> MobileProduct(bool Apple, bool Sony, bool Black, bool Blue, bool Red) { List <MallOfElectronics.Models.DataBase.Product> listOfProducts = new List <Models.DataBase.Product>(); ProductsRepository productRepository = new ProductsRepository(); if (Black) { listOfProducts.AddRange(productRepository.where (id => id.ProductType == 1 && id.Color == "black")); } if (Blue) { listOfProducts.AddRange(productRepository.where (id => id.ProductType == 1 && id.Color == "blue")); } if (Red) { listOfProducts.AddRange(productRepository.where (id => id.ProductType == 1 && id.Color == "red")); } if (!Blue && !Red && !Blue) { listOfProducts.AddRange(productRepository.where (id => id.ProductType == 1)); } return(listOfProducts); }
public void GetById_WhenExistingIdPassed_ShouldReturnCorrectItem() { // Arrange var testDataContext = new DataFileData { Products = _testProducts }; var theRepository = new ProductsRepository(new DatabaseFactory(testDataContext)); var productsServicesInst = new ProductsServices(theRepository); //var mockStaticLoggerInstWrapper = new Mock<IStaticLoggerInstanceWrapper>(); var productsController = new ProductsController(productsServicesInst); // Act var response = productsController.GetById(1); // Assert Assert.IsNotNull(response); var foundOrder = (ProductItem)((OkObjectResult)response).Value; Assert.IsInstanceOfType(foundOrder, typeof(ProductItem)); }
public void GetProducts_IsValid() { // Arrange var retailer = new Retailer { Name = "Test Retailer 1" }; var expected = new List <Product> { new Product { Brand = "test", Caliber = "9mm", Casing = "brass", Description = "9mm ammo description", Grain = "120", Inventory = 10, IsAvailable = true, Name = "9mm Ammo", Price = 10.99m, RoundCount = "50", RoundType = "FMJ", RetailerProductId = "product1", RetailerId = 1, UpdatedOn = DateTime.Now, Url = "https://test.test/test-product" }, new Product { Brand = "test", Caliber = "9mm", Casing = "brass", Description = "9mm ammo description", Grain = "120", Inventory = 10, IsAvailable = true, Name = "9mm Ammo", Price = 10.99m, RoundCount = "50", RoundType = "FMJ", RetailerProductId = "product2", RetailerId = 1, UpdatedOn = DateTime.Now, Url = "https://test.test/test-product" } }; var mapper = CreateMapper(); DbContext.Retailers.Add(retailer); DbContext.SaveChanges(); DbContext.Products.AddRange(expected); DbContext.SaveChanges(); var productsRepository = new ProductsRepository(DbContext, mapper); // Act var actual = productsRepository.GetProducts(); // Assert Assert.IsAssignableFrom <IEnumerable <ProductModel> >(actual); Assert.Equal(expected.Count(), actual.Count()); }
public static void Main() { var optionsBuilder = new DbContextOptionsBuilder <PizzaOrdersContext>(); optionsBuilder.UseSqlServer(SecretConfiguration.ConnectionString); var options = optionsBuilder.Options; var dbContext = new PizzaOrdersContext(options); UserRepository userRepository = new UserRepository(dbContext); OrderRepository orderRepository = new OrderRepository(dbContext); ProductsRepository productsRepository = new ProductsRepository(dbContext); AddressRepository addressRepository = new AddressRepository(dbContext); StoreRepository storeRepository = new StoreRepository(dbContext); Console.WriteLine("Welcome to Ita D'Pizza!"); List <Order> orderAddressList = orderRepository.DisplayOrderHistoryAddress(1).ToList(); Console.WriteLine(orderAddressList); List <User> userList = userRepository.GetUsers().ToList(); bool bigLoop = true; while (bigLoop == true) { for (int i = 1; i < userList.Count() + 1; i++) { User userlist = userList[i - 1]; string userFirstNameString = $"{i}: \"{userlist.firstName}\""; string userLastNameString = $"\"{userlist.lastName}\""; Console.Write(userFirstNameString + " "); Console.Write(userLastNameString); Console.WriteLine(); } Console.WriteLine("Please sign in."); Console.WriteLine("To exit, type 'exit' as either a first name or a last name"); Console.Write("First Name: "); string signInFName = Console.ReadLine(); Console.Write("Last Name: "); string signInLName = Console.ReadLine(); if (signInFName.ToLower() == "exit" || signInLName.ToLower() == "exit") { break; } // exception handling for not a valid sign in name // also include way to exit the console app List <User> signedInList = userRepository.GetUsersByName(signInFName, signInLName).ToList(); User signedIn = signedInList[0]; bool smallLoop = true; while (smallLoop == true) { Console.WriteLine("What do you want to do?"); Console.WriteLine("o - place an order"); Console.WriteLine("u - look up a user"); Console.WriteLine("h - display order history"); Console.WriteLine("x - go back to login screen"); string choice = Console.ReadLine(); if (choice == "o") { List <Order> orderSuggestList = orderRepository.DisplayOrderHistoryUser(signedIn.userID).OrderByDescending(o => o.orderDate).ToList(); Order orderSuggest = orderSuggestList[0]; Console.WriteLine("So you want to place an order?"); Console.WriteLine("Your most recent order on record is "); string orderSuggestID = $"\"{"Order ID: " + orderSuggest.orderID}\""; string orderSuggestTotalCost = $"\"{"Total Cost: " + orderSuggest.totalCost}\""; string orderSuggestStoreID = $"\"{"Store ID: " + orderSuggest.storeId}\""; Console.WriteLine(orderSuggestID); Console.Write("Products "); // what is there is no previous order? simple loop/conditional // still need to figure out how to populate orderProducts from OrderHeader List <Product> productListToPrint = orderRepository.GetProductsOfOrderByID(orderSuggest.orderID).ToList(); foreach (var item in productListToPrint) { Console.Write(item.productName + " "); } Console.WriteLine(orderSuggestTotalCost); Console.WriteLine(orderSuggestStoreID); Console.WriteLine("Would you like to resubmit this order? Type 'yes' or 'no'."); string resubmit = Console.ReadLine(); while (!(resubmit.ToLower() == "yes" || resubmit.ToLower() == "no")) { Console.WriteLine("Not an available choice."); Console.WriteLine("Would you like to resubmit this order? Type 'yes' or 'no'."); resubmit = Console.ReadLine(); } if (resubmit.ToLower() == "yes") { Order order1 = new Order(); order1.orderAddressID = orderSuggest.orderAddressID; order1.userID = signedIn.userID; order1.totalCost = 0; order1.orderDate = DateTime.Now; order1.storeId = orderSuggest.storeId; List <Product> listOfProductsToAdd = orderRepository.GetProductsOfOrderByID(orderSuggest.orderID).ToList(); foreach (var item in listOfProductsToAdd) { order1.AddToOrder(item); } Console.WriteLine("Successfully recreated the order"); Console.WriteLine("Your order details"); orderRepository.InsertOrder(order1); orderRepository.Save(); orderRepository.DisplayOrderDetailsByOrderID(orderRepository.getLastId()); } else if (resubmit.ToLower() == "no") { Console.WriteLine("Okay, we will build a new order for you."); // Instantiating new order with default values Order order1 = new Order(); order1.orderAddressID = orderSuggest.orderAddressID; order1.userID = signedIn.userID; order1.totalCost = 0; order1.orderDate = DateTime.Now; order1.storeId = orderSuggest.storeId; // displaying available addresses Console.WriteLine("Here are our available addresses."); List <Library.Address> addressList = addressRepository.GetAddresses().ToList(); for (int i = 1; i < addressList.Count() + 1; i++) { Library.Address addresslist = addressList[i - 1]; string addressIdString = $"{i}: \"{addresslist.addressID}\""; string addressLine1String = $"{i}: \"{addresslist.addressLine1}\""; string addressLine2String = $"{i}: \"{addresslist.addressLine2}\""; string addressCityString = $"{i}: \"{addresslist.city}\""; string addressStateString = $"{i}: \"{addresslist.state}\""; string addressZipCodeString = $"{i}: \"{addresslist.zipCode}\""; Console.Write(addressIdString + " "); Console.Write(addressLine1String + " "); Console.Write(addressLine2String + " "); Console.Write(addressCityString + " "); Console.Write(addressStateString + " "); Console.WriteLine(addressZipCodeString); } // Parsing addressID choice Console.WriteLine("Please type the Address ID of the address you would like the order to be delivered to."); string addressAddChoice = Console.ReadLine(); bool parseSuccessAddress = Int32.TryParse(addressAddChoice, out int addressAddInt); while (parseSuccessAddress == false || (parseSuccessAddress == true && addressAddInt > addressList.Count())) { Console.WriteLine("Not a valid choice. Please enter a valid integer."); Console.WriteLine("Please type the Product ID of the product you would like to add to your order."); addressAddChoice = Console.ReadLine(); parseSuccessAddress = Int32.TryParse(addressAddChoice, out addressAddInt); } // adding choice to order order1.orderAddressID = addressAddInt; ////////////////////////////////////////////////////////////////////////////////////////// // displaying available stores Console.WriteLine("Here are our available stores."); List <Library.Store> storeList = storeRepository.GetStores().ToList(); for (int i = 1; i < addressList.Count() + 1; i++) { Library.Store storelist = storeList[i - 1]; string storeIDString = $"{i}: \"{storelist.storeID}\""; string storeAddressLine1String = $"{i}: \"{storelist.sAddressLine1}\""; string storeAddressLine2String = $"{i}: \"{storelist.sAddressLine2}\""; string storeCityString = $"{i}: \"{storelist.sCity}\""; string storeStateString = $"{i}: \"{storelist.sState}\""; string storeZipCodeString = $"{i}: \"{storelist.sZipCode}\""; Console.Write(storeIDString + " "); Console.Write(storeAddressLine1String + " "); Console.Write(storeAddressLine2String + " "); Console.Write(storeCityString + " "); Console.Write(storeStateString + " "); Console.WriteLine(storeZipCodeString); } // Parsing storeID choice Console.WriteLine("Please type the Store ID of the store you would like to order from"); string storeAddChoice = Console.ReadLine(); bool parseSuccessStore = Int32.TryParse(storeAddChoice, out int storeAddInt); while (parseSuccessStore == false || (parseSuccessStore == true && storeAddInt > storeList.Count())) { Console.WriteLine("Not a valid choice. Please enter a valid integer."); Console.WriteLine("Please type the Store ID of the store you would like to order from."); storeAddChoice = Console.ReadLine(); parseSuccessStore = Int32.TryParse(storeAddChoice, out storeAddInt); } // adding choice to order order1.storeId = storeAddInt; //////////////////////////////////////////////////////////////// // displaying available products Console.WriteLine("Here are our available products."); List <Product> productList = productsRepository.GetProducts().ToList(); for (int i = 1; i < productList.Count() + 1; i++) { Product productlist = productList[i - 1]; string productIdString = $"{i}: \"{productlist.productName}\""; string productNameString = $"{i}: \"{productlist.productName}\""; Console.Write(productIdString + " "); Console.WriteLine(productNameString); } // deciding if user wants to add a product to order Console.WriteLine("Would you like to add a product to your order? Type 'yes' or 'no'."); string addAProduct = Console.ReadLine(); while (!(addAProduct.ToLower() == "yes" || addAProduct.ToLower() == "no")) { Console.WriteLine("Not an available choice."); Console.WriteLine("Would you like to add a product to your order? Type 'yes' or 'no'."); addAProduct = Console.ReadLine(); } // adding product to order if (addAProduct.ToLower() == "yes") { while (addAProduct.ToLower() == "yes") { // getting user input for which product to add Console.WriteLine("Please type the Product ID of the product you would like to add to your order."); string productAddChoice = Console.ReadLine(); bool parseSuccessProduct = Int32.TryParse(productAddChoice, out int productAddInt); while (parseSuccessProduct == false || (parseSuccessProduct == true && productAddInt > productList.Count())) { Console.WriteLine("Not a valid choice. Please enter a valid integer."); Console.WriteLine("Please type the Product ID of the product you would like to add to your order."); productAddChoice = Console.ReadLine(); parseSuccessProduct = Int32.TryParse(productAddChoice, out productAddInt); } Product productToAdd = productsRepository.GetProductByID(productAddInt); order1.AddToOrder(productToAdd); // logic to enable indefinite product adding Console.WriteLine("Would you like to add another product to your order? Type 'yes' or 'no'."); addAProduct = Console.ReadLine(); while (!(addAProduct.ToLower() == "yes" || addAProduct.ToLower() == "no")) { Console.WriteLine("Not an available choice."); Console.WriteLine("Would you like to add another product to your order? Type 'yes' or 'no'."); addAProduct = Console.ReadLine(); } } // Inserting, Saving and displaying order orderRepository.InsertOrder(order1); orderRepository.Save(); orderRepository.DisplayOrderDetailsByOrderID(orderRepository.getLastId()); } } } else if (choice == "u") { Console.WriteLine("So you want to look up a user?"); Console.WriteLine("How do you want to look up?"); Console.WriteLine("n - Look up by name"); Console.WriteLine("i - Look up by user ID"); string lookUpChoice = Console.ReadLine(); while (!(lookUpChoice.ToLower() == "n" || lookUpChoice.ToLower() == "i")) { Console.WriteLine("Invalid choice. Please select either 'n' or 'i'."); Console.WriteLine("How do you want to look up?"); Console.WriteLine("n - Look up by name"); Console.WriteLine("i - Look up by user ID"); lookUpChoice = Console.ReadLine(); } if (lookUpChoice.ToLower() == "n") { Console.WriteLine("To look up by name, type the first name and last name."); //Console.WriteLine("If you only want to search by first name, leave last name blank."); //Console.WriteLine("If you only want to search by last name, leave first name blank."); Console.Write("First Name: "); string inputFirstNameSearch = Console.ReadLine(); Console.Write("Last Name: "); string inputLastNameSearch = Console.ReadLine(); List <User> returnedUsers = userRepository.GetUsersByName(inputFirstNameSearch, inputLastNameSearch).ToList(); for (int i = 1; i < returnedUsers.Count() + 1; i++) { int displayUserID = returnedUsers[i - 1].userID; string displayUserFirstName = returnedUsers[i - 1].firstName; string displayUserLastName = returnedUsers[i - 1].lastName; Console.WriteLine(displayUserID + " " + displayUserFirstName + " " + displayUserLastName); } } //else if (lookUpChoice.ToLower() == "i") //{ // Console.WriteLine("To look up by user ID, type the user ID"); // Console.Write("User ID: "); // string inputUserIDSearch = Console.ReadLine(); // bool parseSuccess = Int32.TryParse(inputUserIDSearch, out int userIdSearchInt); // while (parseSuccess == false) // { // Console.WriteLine("Not a valid choice. Please enter a valid integer."); // Console.WriteLine("To look up by user ID, type the user ID"); // Console.Write("User ID: "); // inputUserIDSearch = Console.ReadLine(); // parseSuccess = Int32.TryParse(inputUserIDSearch, out userIdSearchInt); // } //} } else if (choice == "h") { Console.WriteLine("So you want to look up order history."); Console.WriteLine("How do you want to look up orders?"); Console.WriteLine("l - location"); Console.WriteLine("u - user"); Console.WriteLine("s - sort all"); string lookUpChoice = Console.ReadLine(); while (!(lookUpChoice.ToLower() == "l" || lookUpChoice.ToLower() == "u" || lookUpChoice.ToLower() == "s")) { Console.WriteLine("Not a valid choice. Please type either 'l', 'u', or 's'."); Console.WriteLine("How do you want to look up orders?"); Console.WriteLine("l - location"); Console.WriteLine("u - user"); Console.WriteLine("s - sort all"); lookUpChoice = Console.ReadLine(); } if (lookUpChoice.ToLower() == "l") { Console.WriteLine("Please provide store ID"); Console.Write("Store ID: "); string storeIdToLookUp = Console.ReadLine(); bool parseSuccess = Int32.TryParse(storeIdToLookUp, out int storeIdToLookUpInt); while (parseSuccess == false) { Console.WriteLine("Not a valid choice. Please enter a valid Store ID."); Console.WriteLine("Please provide Store ID"); Console.Write("Store ID: "); storeIdToLookUp = Console.ReadLine(); parseSuccess = Int32.TryParse(storeIdToLookUp, out storeIdToLookUpInt); } List <Order> orderHistory = orderRepository.DisplayOrderHistoryStore(storeIdToLookUpInt).ToList(); Console.Write("(Order ID) "); Console.Write("(Order Address ID) "); Console.Write("(Total Cost) "); Console.Write("(Order DateTime) "); Console.Write("(Order Store ID) "); Console.WriteLine(); for (int i = 1; i < orderHistory.Count() + 1; i++) { Order orderhistory = orderHistory[i - 1]; string orderIdString = $"{i}: \"{orderhistory.orderID}\""; string orderAddressIdString = $"\"{orderhistory.orderAddressID}\""; string orderTotalCostString = $"\"{orderhistory.totalCost}\""; string orderDateTimeString = $"\"{orderhistory.orderDate}\""; string orderStoreIdString = $"\"{orderhistory.storeId}\""; Console.Write(orderIdString + " "); Console.Write(orderAddressIdString + " "); Console.Write(orderTotalCostString + " "); Console.Write(orderDateTimeString + " "); Console.Write(orderStoreIdString + " "); Console.WriteLine(); } } else if (lookUpChoice.ToLower() == "u") { Console.WriteLine("Please provide User ID"); Console.Write("User ID: "); string userIdToLookUp = Console.ReadLine(); bool parseSuccess = Int32.TryParse(userIdToLookUp, out int userIdToLookUpInt); while (parseSuccess == false) { Console.WriteLine("Not a valid choice. Please enter a valid User ID."); Console.WriteLine("Please provide User ID"); Console.Write("User ID: "); userIdToLookUp = Console.ReadLine(); parseSuccess = Int32.TryParse(userIdToLookUp, out userIdToLookUpInt); } List <Order> orderHistory = orderRepository.DisplayOrderHistoryUser(userIdToLookUpInt).ToList(); Console.Write("(Order ID) "); Console.Write("(Order Address ID) "); Console.Write("(Total Cost) "); Console.Write("(Order DateTime) "); Console.Write("(Order Store ID) "); Console.WriteLine(); for (int i = 1; i < orderHistory.Count() + 1; i++) { Order orderhistory = orderHistory[i - 1]; string orderIdString = $"{i}: \"{orderhistory.orderID}\""; string orderAddressIdString = $"\"{orderhistory.orderAddressID}\""; string orderTotalCostString = $"\"{orderhistory.totalCost}\""; string orderDateTimeString = $"\"{orderhistory.orderDate}\""; string orderStoreIdString = $"\"{orderhistory.storeId}\""; Console.Write(orderIdString + " "); Console.Write(orderAddressIdString + " "); Console.Write(orderTotalCostString + " "); Console.Write(orderDateTimeString + " "); Console.Write(orderStoreIdString + " "); Console.WriteLine(); } } else if (lookUpChoice.ToLower() == "s") { Console.WriteLine("So you want to look up all users."); Console.WriteLine("How would you like to sort the results?"); Console.WriteLine("e - earliest first"); Console.WriteLine("l - latest first"); Console.WriteLine("c - cheapest first"); Console.WriteLine("x - most expensive first"); string lookUpSortChoice = Console.ReadLine(); while (!(lookUpSortChoice.ToLower() == "e" || lookUpSortChoice.ToLower() == "l" || lookUpSortChoice.ToLower() == "c" || lookUpSortChoice.ToLower() == "x")) { Console.WriteLine("Invalid choice. Please type either 'e', 'l' 'c', or 'x'."); Console.WriteLine("How would you like to sort the results?"); Console.WriteLine("e - earliest first"); Console.WriteLine("l - latest first"); Console.WriteLine("c - cheapest first"); Console.WriteLine("x - most expensive first"); lookUpSortChoice = Console.ReadLine(); } List <Order> collectionOfOrders = orderRepository.DisplayOrderHistory(lookUpSortChoice).ToList(); foreach (var item in collectionOfOrders) { Console.Write("Order ID: " + item.orderID + " "); Console.Write("User ID: " + item.userID + " "); Console.Write("Order Address ID: " + item.orderAddressID + " "); Console.Write("Total Cost: " + item.totalCost + " "); Console.Write("Order DateTime: " + item.orderDate + " "); Console.Write("Store ID: " + item.storeId); Console.WriteLine(); } } } else if (choice == "x") { smallLoop = false; } } } }
static void Main(string[] args) { PeopleRepository repPeople = new PeopleRepository(); ProductsRepository repProduct = new ProductsRepository(); Console.WriteLine("People"); Console.WriteLine("================================================================================"); Console.WriteLine(repPeople.GetItem("Hunt").ToString()); Console.WriteLine(); foreach (Person p in repPeople.GetItems().OrderBy(p => p.LastName)) Console.WriteLine(p.LastName); Console.WriteLine(); repPeople.AddItem(new Person() { FirstName = "Zbigniew", LastName = "Koziel", Rating = 2, StartDate = DateTime.Now}); foreach (Person p in repPeople.GetItems().OrderBy(p => p.LastName)) Console.WriteLine(p.LastName); Console.WriteLine(); repPeople.DeleteItem("Hunt"); //repPeople.DeleteItem("Koziel"); // repPeople.DeleteItem("Koenig"); foreach (Person p in repPeople.GetItems().OrderBy(p => p.LastName)) Console.WriteLine(p.LastName); Console.WriteLine(); Console.WriteLine(Convert.ToString(repPeople.GetItem("Koziel"))); repPeople.UpdateItem("Koziel", new Person() { FirstName = "Zbigman", LastName = "Koziel", Rating = 9, StartDate = DateTime.Now }); // Convert.ToString() doesn't throw exception if GetItem() returns null reference, in oppose to repPeople.GetItem().ToString() Console.WriteLine(Convert.ToString(repPeople.GetItem("Koziel"))); Console.WriteLine(); repPeople.UpdateItems(new List<Person>() { new Person(){ FirstName = "AAA", LastName = "aaa", StartDate = DateTime.Now, Rating = 1 }, new Person(){ FirstName = "BBB", LastName = "bbb", StartDate = DateTime.Now, Rating = 1 }, new Person(){ FirstName = "CCC", LastName = "ccc", StartDate = DateTime.Now, Rating = 1 }, new Person(){ FirstName = "DDD", LastName = "ddd", StartDate = DateTime.Now, Rating = 1 }, }); foreach (Person p in repPeople.GetItems().OrderBy(p => p.LastName)) Console.WriteLine(p.LastName); Console.WriteLine(); Console.WriteLine(); Console.WriteLine(); Console.WriteLine("Products"); Console.WriteLine("================================================================================"); Console.WriteLine(repProduct.GetItem(3).ToString()); Console.WriteLine(); foreach (Product p in repProduct.GetItems().OrderBy(p => p.ProductName)) Console.WriteLine(p.ProductName); Console.WriteLine(); repProduct.AddItem(new Product() { ProductId = repProduct.GetItems().Max(p => p.ID) + 1, Category = "Instruments", ProductName = "Piano" }); repProduct.AddItem(new Product() { ProductId = repProduct.GetItems().Max(p => p.ID) + 1, Category = "Instruments", ProductName = "Guitar" }); repProduct.AddItem(new Product() { ProductId = repProduct.GetItems().Max(p => p.ID) + 1, Category = "Instruments", ProductName = "Fluet" }); foreach (Product p in repProduct.GetItems().OrderBy(p => p.ProductName)) Console.WriteLine(p.ProductName); Console.WriteLine(); repProduct.DeleteItem(5); repProduct.DeleteItem(6); repProduct.DeleteItem(7); repProduct.DeleteItem(8); foreach (Product p in repProduct.GetItems().OrderBy(p => p.ProductName)) Console.WriteLine(p.ProductName); Console.WriteLine(); Console.WriteLine(Convert.ToString(repProduct.GetItem(1))); repProduct.UpdateItem(1, new Product() { ProductId = 1, Category = "Instruments", ProductName = "Clarinet" }); Console.WriteLine(Convert.ToString(repProduct.GetItem(1))); Console.WriteLine(); repProduct.UpdateItems(new List<Product>() { new Product(){ ProductId = 1, ProductName = "Lozko", Category = "Meble" }, new Product(){ ProductId = 2, ProductName = "Suszarka", Category = "AGD" }, new Product(){ ProductId = 3, ProductName = "Konfitury", Category = "Jedzenie" }, }); foreach (Product p in repProduct.GetItems().OrderBy(p => p.ProductName)) Console.WriteLine(p.ProductName); Console.WriteLine(); //Console.ReadKey(); }
public void ShoppingCart() { var conn = new NHibernateConnection(); var repo = new ShoppingCartRepository(conn); var producRepo = new ProductsRepository(conn); IList<Products> products = producRepo.GetAll(); Products product1 = products.First(); IEnumerable<Products> product2 = products.Where(x => x.IsRecent).Take(1); var shoppingCart = new ShoppingCarts(product1, 1, "12345678", DateTime.Now); repo.Save(shoppingCart); ShoppingCarts fromDB = repo.GetAll().Where(x => x.CartId == "12345678").FirstOrDefault(); Assert.IsNotNull(fromDB); }
public void Orders() { var conn = new NHibernateConnection(); var repo = new OrdersRepository(conn); var productRepo = new ProductsRepository(conn); var userRepo = new UserRepository(conn); Users user = userRepo.Get("*****@*****.**"); var genericRepo = new GenericRepository<Orders>(conn); //var order = new Orders(user, DateTime.Now, // Convert.ToDecimal(299.99)); //repo.Save(order); var fromDB = repo.Get(53); Assert.IsNotNull(fromDB); }
public async Task <ActionResult <Product> > GetByID(int id) { var productRepsitory = new ProductsRepository(_context, _environment); return(await productRepsitory.GetById(id)); }
public static ProductsRepository GetProductsRepository() { var repository = new ProductsRepository(); repository.UnitOfWork = GetUnitOfWork(); return repository; }
public static ProductsRepository GetProductsRepository(IUnitOfWork unitOfWork) { var repository = new ProductsRepository(); repository.UnitOfWork = unitOfWork; return repository; }
public void Products() { var conn = new NHibernateConnection(); var productRepo = new ProductsRepository(conn); var categoryRepo = new CategoryRepository(conn); var manufacturersRepository = new ManufacturersRepository(conn); Categories category = categoryRepo.Get(4); Manufacturers manufacturer = manufacturersRepository.Get(1); var product = new Products("Towar", "Jego opis", Convert.ToDecimal(125.99), category, manufacturer, 100, false, true, false, "Krótki opis"); productRepo.Save(product); Products fromDB = productRepo.Get(product.ID); Assert.AreEqual(product, fromDB); }
public ProductsController(ProductsRepository repository) { _repository = repository; }
public ProductController() { _productsRepo = new ProductsRepository(); }