private bool ValidateProducts(List <ProductEntity> products) { ProductValidation productValidation = new ProductValidation(new RepositoryFactory <ProductEntity>(), ConnString); var allProducts = productValidation.GetAllProducts().ProductEntities; var totalPillCount = productValidation.CheckPillCount(products); if (totalPillCount > 38) { return(false); } var inStock = productValidation.CheckStock(allProducts, products); var quantityChanged = false; if (inStock) { foreach (var product in products) { quantityChanged = productValidation.ChangeQuantity(product); } } return(quantityChanged); }
//if admin clicks add then get text box information, validate it and add it to the database private void btnAdd_Click(object sender, EventArgs e) { string title = txtTitle.Text; bool validQuantity = Int32.TryParse(txtQuantity.Text, out var quantity); bool validDate = DateTime.TryParse(txtReleaseDate.Text, out var releaseDate); string console = txtConsole.Text; bool validPrice = Double.TryParse(txtPrice.Text, out var price); bool success = false; //validate product input and get any error messages that may be relevant var pv = new ProductValidation(); bool validateInput = pv.ValidationMessages(title, validQuantity, validDate, console, validPrice); //only insert into database if all data has been validated if (validateInput) { var pd = new ProductDatabase(); success = pd.InsertGameInfo(title, quantity, releaseDate, console, price); } //if successfully inserted into the database, then let user know and reload data if (success) { AdminControls.AdminSetup(); //function that fills admin panel with newly updated data MessageBox.Show($"{quantity} of {title} added to the inventory."); Close(); } else if (!success && validateInput) { MessageBox.Show("There was an issue adding this product."); //show user a message if there's an error. } }
public void ShouldReturnErrorCodes(string name, long category_id, decimal price, decimal discount, string description, long file_id, ProductValidationErrors expectedError) { CreateRequestValidation createRequestValidation = new CreateRequestValidation(); FindRequestValidation findRequestValidation = new FindRequestValidation(); UpdateRequestValidation updateRequestValidation = new UpdateRequestValidation(); DeleteRequestValidation deleteRequestValidation = new DeleteRequestValidation(); ProductValidation validation = new ProductValidation(createRequestValidation, findRequestValidation, updateRequestValidation, deleteRequestValidation); ProductCreateRequest request = new ProductCreateRequest { Name = name, Category_Id = category_id, Price = price, Discount = discount, Description = description, File_Id = file_id }; var listErrors = validation.CreateRequestValidation.Validate(request); foreach (var error in listErrors) { Assert.Equal(expectedError, error); } }
public ProductResponse GetProducts() { ProductValidation productValidation = new ProductValidation(new RepositoryFactory <ProductEntity>(), _appSettings.Value.MongoConnectionString); try { var productValidationStatus = productValidation.GetAllProducts(); if (productValidationStatus.GotAllProducts) { return(new ProductResponse() { Message = "Products found", ProductEntities = productValidationStatus.ProductEntities }); } else { return(new ProductResponse() { Message = "Products not found", ProductEntities = null }); } } catch (KeyNotFoundException keyNotFound) { return(new ProductResponse() { Message = keyNotFound.Message, ProductEntities = null }); } }
//if admin decides to edit, then validate the inputs, update in database and update data seen by admin private void bttEdit_Click(object sender, EventArgs e) { string[] productArr = boxWhichProduct.Text.Split('~'); string gameId = productArr[0].Trim(); string title = txtTitle.Text; bool validQuantity = Int32.TryParse(txtQuantity.Text, out var quantity); bool validDate = DateTime.TryParse(txtReleaseDate.Text, out var releaseDate); string console = txtConsole.Text; bool validPrice = Double.TryParse(txtPrice.Text, out var price); bool success = false; //validate product input and get any error messages that may be relevant var pv = new ProductValidation(); bool validateInput = pv.ValidationMessages(title, validQuantity, validDate, console, validPrice); //if inputs are valid then update the database if (validateInput) { var pd = new ProductDatabase(); success = pd.UpdateGameInfo(gameId, title, quantity, releaseDate, console, price); } //if the database has successfully updated then update admins data if (success) { AdminControls.AdminSetup(); MessageBox.Show($"{gameId} ~ {title} was edited successfully."); Close(); } else if (!success && validateInput) { MessageBox.Show("We are not able to update this product at this time."); } }
public static void SaveProductValidation(ProductValidation product) { using (IDbConnection cnn = new SQLiteConnection(GetDbConnectionString())) { cnn.Execute("INSERT INTO ProductValidation " + "(" + "Id, " + "ProductId, " + "Key, " + "KeyValue, " + "KeyLength, " + "NextKey, " + "DisplayValue" + ") " + "values (" + "@Id, " + "@ProductId, " + "@Key, " + "@KeyValue, " + "@KeyLength, " + "@NextKey, " + "@DisplayValue" + ")", product); } }
public void DiscountCounterCorrectWithDouble() { var actual = ProductValidation.DiscountCounter(102.3, 10.23); int expected = -90; Assert.AreEqual(expected, actual); }
public void DiscountCounterCorrect() { var actual = ProductValidation.DiscountCounter(100, 10); int expected = -90; Assert.AreEqual(expected, actual); }
public void ShouldGetProductById() { _createRequestValidation = new CreateRequestValidation(); _deleteRequestValidation = new DeleteRequestValidation(); _findRequestValidation = new FindRequestValidation(); _updateRequestValidation = new UpdateRequestValidation(); _validation = new ProductValidation(_createRequestValidation, _findRequestValidation, _updateRequestValidation, _deleteRequestValidation); ProductFindRequest request = new ProductFindRequest(); request.Id = 1; var mock = new Mock <IProduct>(); mock.Setup(x => x.ReadSingle(request)) .Returns(new Product { ProductId = 1, Name = "Milk", Category = Category.Milk, Price = 50, Discount = 20, Description = "Milk from latvia" }); _victim = new ProductService(mock.Object, _validation); Product actual = _victim.FindById(request).FoundProduct; string expected = "Milk"; Assert.Equal(expected, actual.Name); }
public async Task <ProductDTO> SaveProduct(ProductDTO product) { ProductValidation validator = new ProductValidation(); ValidationResult results = validator.Validate(product); if (!results.IsValid) { throw new System.ComponentModel.DataAnnotations.ValidationException("Validation failed"); } var p = await _context.Products.FindAsync(product.ID); if (p == null) { p = new Product(); _context.Products.Add(p); } p.Name = product.Name; p.Category = product.Category; p.Active = product.Active; p.Price = product.Price; await _context.SaveChangesAsync(); return(_mapper.Map <ProductDTO>(p)); }
public static void GetProducts() { ProductValidation productValidation = new ProductValidation(); var products = productValidation.CheckProducts(); foreach (var product in products) { Console.WriteLine(product.Name); } }
public bool Add(User ownerID, string title, string shortDescription, string longDescription, double price, List <Byte[]> images) { if (ProductValidation.Validation(ownerID, title, shortDescription, longDescription, price)) { using (StoreContext stContext = new StoreContext()) { var userInDB = (from u in stContext.UserList select u).FirstOrDefault(us => us.ID == ownerID.ID); if (userInDB == null) { return(false); } Product prod = new Product() { OwnerID = userInDB, Title = title, ShortDescription = shortDescription, LongDescription = longDescription, Price = price, Date = DateTime.Now, state = ClassLibrary.State.Available, CartTime = DateTime.Now.AddYears(1) }; if (images.Count > 0) { prod.Picture1 = images[0]; if (images.Count > 1) { prod.Picture2 = images[1]; if (images.Count > 2) { prod.Picture3 = images[2]; } } } stContext.ProductList.Add(prod); stContext.SaveChanges(); //var tmp = (from a in stContext.ProductList select a).FirstOrDefault(a => a == prod); //AddImageToProduct(tmp.ID, images); } return(true); } return(false); }
private void CopyValidationProductCsvToDatabase(string csvPath = @"C:\Users\evan\Desktop\product_validation_data.csv") { string line; var file = new StreamReader(csvPath); while ((line = file.ReadLine()) != null) { try { // Skips lines we don't care about if (line == "\"" || line.Contains("id") || line.Replace("\"", "") == "") { continue; } string[] lineItems = line.Replace("\"", "").Split(','); // Make sure lineItems is in the correct format if (lineItems.Length != 7) { Trace.WriteLine(line); // TODO Possibly write this to another file to be reviewed by a person continue; } // Create the ProductValdation model that will be written to db var productValidation = new ProductValidation() { Id = Convert.ToInt32(lineItems[0]), ProductId = lineItems[1], Key = lineItems[2], KeyValue = lineItems[3], KeyLength = Convert.ToInt32(lineItems[4]), NextKey = lineItems[5], DisplayValue = lineItems[6] }; SqliteDataAccess.SaveProductValidation(productValidation); } catch (Exception e) { Trace.WriteLine($"***** ERROR: {e} *****"); } } }
private void View_UpdateProduct(object sender, EventArgs e) { var check = new ProductValidation(View.Code, View.NameProduct, View.Weight); if (!check.IsValid) { View.WarningMessage(check.WarningMessage); return; } var product = GetProductById(View.Id); FillInProductFromView(product); product.Data_Modyfikacji = DateTime.Now; SaveDBChanges(); }
private void View_AddNewProduct(object sender, EventArgs e) { var check = new ProductValidation(View.Code, View.NameProduct, View.Weight); if (!check.IsValid) { View.WarningMessage(check.WarningMessage); return; } var product = new Towary(); FillInProductFromView(product); product.Data_Utworzenia = DateTime.Now; db.Products.Add(product); SaveDBChanges(); }
public void ShouldUpdateById() { _createRequestValidation = new CreateRequestValidation(); _deleteRequestValidation = new DeleteRequestValidation(); _findRequestValidation = new FindRequestValidation(); _updateRequestValidation = new UpdateRequestValidation(); _validation = new ProductValidation(_createRequestValidation, _findRequestValidation, _updateRequestValidation, _deleteRequestValidation); ProductUpdateRequest request = new ProductUpdateRequest(); request.Id = 2; request.Name = "Pork"; request.Category = Category.Meat; request.Price = 150; request.Discount = 50; request.Description = "Pork from Nigeria."; var mock = new Mock <IProduct>(); mock.Setup(x => x.Update(request)) .Returns(new Product { ProductId = 2, Name = "Pork", Category = Category.Meat, Price = 150, Discount = 50, Description = "Pork from Nigeria." }); _victim = new ProductService(mock.Object, _validation); Product actual = _victim.UpdateById(request).UpdatedProduct; string expectedName = "Pork"; decimal expectedPrice = 150; decimal expectedDiscount = 50; Assert.Equal(expectedName, actual.Name); Assert.Equal(expectedPrice, actual.Price); Assert.Equal(expectedDiscount, actual.Discount); }
public void ShouldGetAllProducts() { _createRequestValidation = new CreateRequestValidation(); _deleteRequestValidation = new DeleteRequestValidation(); _findRequestValidation = new FindRequestValidation(); _updateRequestValidation = new UpdateRequestValidation(); _validation = new ProductValidation(_createRequestValidation, _findRequestValidation, _updateRequestValidation, _deleteRequestValidation); var mock = new Mock <IProduct>(); mock.Setup(x => x.ReadAll()) .Returns(listProducts); _victim = new ProductService(mock.Object, _validation); List <Product> actual = _victim.FindAll().ListOfFoundProducts; int expected = 3; Assert.Equal(expected, actual.Count); }
public void ShouldReturnCreatedProduct() { _createRequestValidation = new CreateRequestValidation(); _deleteRequestValidation = new DeleteRequestValidation(); _findRequestValidation = new FindRequestValidation(); _updateRequestValidation = new UpdateRequestValidation(); _validation = new ProductValidation(_createRequestValidation, _findRequestValidation, _updateRequestValidation, _deleteRequestValidation); var mockDB = new Mock <IProduct>(); mockDB.Setup(x => x.Create(getProduct())) .Returns(getProduct()); _victim = new ProductService(mockDB.Object, _validation); var actual = _victim.AddProduct(request()); var expected = getProduct(); Assert.Equal(expected, actual.Product); }
public void ShouldDeleteById() { _createRequestValidation = new CreateRequestValidation(); _deleteRequestValidation = new DeleteRequestValidation(); _findRequestValidation = new FindRequestValidation(); _updateRequestValidation = new UpdateRequestValidation(); _validation = new ProductValidation(_createRequestValidation, _findRequestValidation, _updateRequestValidation, _deleteRequestValidation); ProductDeleteRequest request = new ProductDeleteRequest(); request.Id = 2; var mock = new Mock <IProduct>(); mock.Setup(x => x.Delete(request)) .Returns(true); _victim = new ProductService(mock.Object, _validation); Assert.True(_victim.Delete(request).HasDeleted); }
public bool Add(User ownerID, string title, string shortDescription, string longDescription, double price) { if (ProductValidation.Validation(ownerID, title, shortDescription, longDescription, price)) { using (StoreContext stContext = new StoreContext()) { stContext.ProductList.Add(new Product() { OwnerID = ownerID, Title = title, ShortDescription = shortDescription, LongDescription = longDescription, Price = price, Date = DateTime.Now, state = ClassLibrary.State.Available }); stContext.SaveChanges(); } return(true); } return(false); }
public ProductManager(IProductDal productDal) { validator = new ProductValidation(); this.productDal = productDal; }
public ProductController(IProductManager productManager, ProductValidation productValidation, CategoryValidation categoryValidation) { _productManager = productManager; _productValidator = productValidation; _categoryValidation = categoryValidation; }
public void Setup() { _manager = new Mock <IProductManager>(); _storeValidator = new StoreValidation(); _validator = new ProductValidation(_manager.Object, _storeValidator); }
public ValidationResult Validate() { var validation = new ProductValidation().Validate(this); return(validation); }
public override bool IsValid() { ValidationResult = new ProductValidation().Validate(this); return(ValidationResult.IsValid); }
public void DiscountCounterWhereAllArgumentsIsNull() { Assert.That(() => ProductValidation.DiscountCounter(null, null), Throws.TypeOf <ArgumentException>()); }
public ProductService(IProduct repository, ProductValidation validation) { _productRepository = repository; _validation = validation; }