示例#1
0
        public void GetWithWrongIdShouldReturnNotFound()
        {
            // Arrange
            var product1 = new Product
            {
                Id          = "1",
                Brand       = "Apple",
                Description = "Apple Watch 2",
                Model       = "Series 2"
            };
            var product2 = new Product
            {
                Id          = "2",
                Brand       = "Samsung",
                Description = "Galaxy Tab S2",
                Model       = "Version 9.7"
            };
            IProductsRepository productsRepository = new ProductsRepository();

            productsRepository.AddProduct(product1);
            productsRepository.AddProduct(product2);

            var controller = new ProductsController(productsRepository);

            // Act
            var actionResult = controller.Get("3");

            // Assert
            Assert.IsInstanceOfType(actionResult, typeof(NotFoundResult));
        }
示例#2
0
        public void GetWithIdShouldReturnThatProduct()
        {
            // Arrange
            var product1 = new Product
            {
                Id          = "1",
                Brand       = "Apple",
                Description = "Apple Watch 2",
                Model       = "Series 2"
            };
            var product2 = new Product
            {
                Id          = "2",
                Brand       = "Samsung",
                Description = "Galaxy Tab S2",
                Model       = "Version 9.7"
            };
            IProductsRepository productsRepository = new ProductsRepository();

            productsRepository.AddProduct(product1);
            productsRepository.AddProduct(product2);

            var controller = new ProductsController(productsRepository);

            // Act
            var actionResult = controller.Get("2");
            var response     = actionResult as OkNegotiatedContentResult <Product>;

            // Assert
            Assert.IsNotNull(response);
            Assert.AreEqual("2", response.Content.Id);
        }
示例#3
0
        static void Main(string[] args)
        {
            ProductsRepository repo = new ProductsRepository();

            //how do I connect my DBContext with a real DB (SQL Server)?

            //how do I create the DataBase?
            repo.CreateDataBase();

            //how do I add a new Product?
            repo.AddProduct(new Product()
            {
                Name = "Laptop Latitude E5570", Brand = "Dell", Price = 1234
            });

            //how do I list all the products?
            Console.WriteLine("**********************");
            foreach (Product product in repo.GetProducts())
            {
                Console.WriteLine($"{product.Id} - {product.Brand} {product.Name} {product.Price}");
            }

            //how do I get a specific product?
            Product p = repo.GetProductById(1);

            Console.WriteLine($"{p.Id} - {p.Brand} {p.Name} {p.Price}");

            //how do I update an existing Product?
            p.Price = 9999;

            //how do I delete a Product?

            Console.ReadLine();
        }
示例#4
0
        public void PutShouldUpdateProduct()
        {
            // Arrange
            IProductsRepository productsRepository = new ProductsRepository();
            var product1 = new Product
            {
                Id          = "1",
                Brand       = "Apple",
                Description = "Apple Watch 2",
                Model       = "Series 2"
            };
            var product2 = new Product
            {
                Id          = "1",
                Brand       = "Samsung",
                Description = "Galaxy Tab S2",
                Model       = "Version 9.7"
            };

            productsRepository.AddProduct(product1);

            var controller = new ProductsController(productsRepository);
            // Act
            var actionResult = controller.Put("1", product2);
            var response     = actionResult as OkNegotiatedContentResult <Product>;

            // Assert
            Assert.IsNotNull(response);
            var newProduct = response.Content;

            Assert.AreEqual("1", newProduct.Id);
            Assert.AreEqual(product2.Brand, newProduct.Brand);
            Assert.AreEqual(product2.Description, newProduct.Description);
            Assert.AreEqual(product2.Model, newProduct.Model);
        }
示例#5
0
        public void GetShouldReturnAllProducts()
        {
            // Arrange

            /*should use Moq instead if the ProductRepository perform CRUD operation to Database.
             * However, ProductRepository is in-memory persistence so Moq is not important.
             */
            IProductsRepository productsRepository = new ProductsRepository();

            productsRepository.AddProduct(new Product
            {
                Id          = "1",
                Brand       = "Apple",
                Description = "Apple Watch 2",
                Model       = "Series 2"
            });

            var controller = new ProductsController(productsRepository);

            // Act
            var actionResult = controller.Get(string.Empty, string.Empty, string.Empty);
            var response     = actionResult as OkNegotiatedContentResult <List <Product> >;

            // Assert
            Assert.IsNotNull(response);
            var products = response.Content;

            Assert.AreEqual(1, products.Count);
        }
示例#6
0
        public async Task <IActionResult> AddProduct([HttpTrigger(AuthorizationLevel.Function, "post", Route = "products")] HttpRequest request)
        {
            var productModel = await request.DeserializeBody <ProductEditableModel>();

            var newProduct = new Product(productModel.Name, productModel.Price);

            repository.AddProduct(newProduct);

            return(ActionResults.Created($"/api/products/{newProduct.Id}", newProduct));
        }
        public IActionResult OnPost()
        {
            if (!ModelState.IsValid)
            {
                return(Page());
            }

            _productRepository.AddProduct(Product);

            return(RedirectToPage("Index"));
        }
示例#8
0
        public ActionResult AddProduct(CreateProductRequest createRequest)
        {
            if (!_validator.Validate(createRequest))
            {
                return(BadRequest(new { error = "Parting Pets Requests You Fill All Necessary Fields." }));
            }

            var newProduct = _productRepository.AddProduct(createRequest);

            return(Created($"api/products/{newProduct.ID}", newProduct));
        }
示例#9
0
            public void WhenProductAdded_ThenItCanBeReturned()
            {
                var sut          = new ProductsRepository();
                var addedProduct = new ParentProduct(3, 5);

                sut.AddProduct(addedProduct);

                var retrievedProduct = sut.GetProduct(3);

                Assert.Equal(addedProduct, retrievedProduct);
            }
示例#10
0
        public void AddProductDuplicateKeyError()
        {
            var options = EfInMemory.CreateOptions <ProductsContext>();

            using (var context = new ProductsContext(options))
            {
                context.FeedDataContext(ProductMocks.ProductsBaseDataset);
                var logger     = new Mock <ILogger <ProductsRepository> >();
                var repository = new ProductsRepository(context, logger.Object);
                Assert.Throws <InvalidOperationException>(() => repository.AddProduct(ProductMocks.ProductSamsungGalaxyS7));
            }
        }
示例#11
0
        public ActionResult AddProduct(Product p, HttpPostedFileBase SoundFile)
        {
            //string fileName = Guid.NewGuid() + Path.GetExtension(SoundFile.FileName);
            string fileName = SoundFile.FileName;

            SoundFile.SaveAs(Server.MapPath("~/SoundFiles/" + fileName));
            p.SoundFilePath = fileName;
            var repo = new ProductsRepository();

            repo.AddProduct(p);
            return(Redirect("/Products/EnterSizes?pId=" + p.ProductID));
        }
示例#12
0
        public IActionResult OnPost()
        {
            if (!ModelState.IsValid)
            {
                return(Page());
            }

            var addProduct = ProductsRepository.AddProduct(Product);

            ProductMessage = $"Het volgende product is toegevoegd : {addProduct.Name}";

            return(RedirectToPage("Index"));
        }
        public IActionResult AddProduct(Product p, IFormFile imageFile)
        {
            string fileName = $"{Guid.NewGuid()}{Path.GetExtension(imageFile.FileName)}";
            string fullPath = Path.Combine(_environment.WebRootPath, "uploads", fileName);

            using (FileStream stream = new FileStream(fullPath, FileMode.CreateNew))
            {
                imageFile.CopyTo(stream);
            }

            p.ImageFileName = fileName;
            var repo = new ProductsRepository(_connectionString);

            repo.AddProduct(p);
            return(RedirectToAction("Index"));
        }
        public void AddProduct_ShouldAdd_VerifyId()
        {
            // Arrange
            var repository  = new ProductsRepository();
            var tempProduct = repository.GetProduct(1);//To get valid userId
            var product     = new Product()
            {
                Name = "Ventilator", ShortDescription = "Oxygen supplies", LongDescription = "Oxygen supplies", Price = 200, IsActive = true, CreatedOn = DateTime.Now, CreatedBy = tempProduct.CreatedBy
            };

            // Act
            var productId = repository.AddProduct(product);

            // Assert
            Assert.IsTrue(productId > 0);
        }
示例#15
0
 public ActionResult Add(Products product)
 {
     try
     {
         if (ModelState.IsValid)
         {
             ProductsRepository proRepo = new ProductsRepository();
             ModelState.Clear();
             int edite = proRepo.AddProduct(product);
             return(RedirectToAction("GetAllProDetails", "Products"));
         }
         return(View("GetAllProDetails"));
     }
     catch (Exception ex)
     {
         LogError.Error(ex, System.Reflection.MethodBase.GetCurrentMethod().Name);
         return(RedirectToAction("ErrorPage", "Home"));
     }
 }
示例#16
0
        public void AddProductSuccess()
        {
            try
            {
                var options = EfInMemory.CreateOptions <ProductsContext>();
                using (var context = new ProductsContext(options))
                {
                    var logger     = new Mock <ILogger <ProductsRepository> >();
                    var repository = new ProductsRepository(context, logger.Object);
                    repository.AddProduct(ProductMocks.NewProductiPhoneXS);

                    var product = repository.GetProduct(ProductMocks.NewProductiPhoneXS.Id);
                    product.ShouldBeSameAs(ProductMocks.NewProductiPhoneXS);
                }
            }
            catch (Exception ex)
            {
                var s = ex.Message;
            }
        }
示例#17
0
        public IActionResult AddProduct(Product newproduct)
        {
            List <string> temp_errors = new List <string>();

            if (ModelState.IsValid)
            {
                productsFactory.AddProduct(newproduct);
                Console.WriteLine("product is Successfully added");
                return(RedirectToAction("Dashboard"));
            }
            foreach (var error in ModelState.Values)
            {
                if (error.Errors.Count > 0)
                {
                    temp_errors.Add(error.Errors[0].ErrorMessage);
                }
            }
            TempData["errors"] = temp_errors;
            return(RedirectToAction("Products"));
        }
示例#18
0
        public void DeleteReturnsNotFound()
        {
            // Arrange
            IProductsRepository productsRepository = new ProductsRepository();
            var product1 = new Product
            {
                Id          = "1",
                Brand       = "Apple",
                Description = "Apple Watch 2",
                Model       = "Series 2"
            };

            productsRepository.AddProduct(product1);

            var controller = new ProductsController(productsRepository);
            //Act
            var actionResult = controller.Delete("2");

            //Assert
            Assert.IsInstanceOfType(actionResult, typeof(NotFoundResult));
        }
示例#19
0
        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);
        }
示例#20
0
        public ActionResult Add(Product product, HttpPostedFileBase picture)
        {
            if (ModelState.IsValid && picture != null) /*&& product.Picture != null)*/
            {
                string newFileName = "";
                string imagePath   = "";

                newFileName = Guid.NewGuid().ToString() + " "
                              + Path.GetFileName(picture.FileName);
                newFileName = Path.GetFileName(picture.FileName);
                imagePath   = Path.Combine(Server.MapPath("~/Images/"), newFileName);
                picture.SaveAs(imagePath);

                product.Picture = "~/Images/" + newFileName;
                _productsRepository.AddProduct(product);
                return(Redirect("Index"));
            }

            ViewBag.ManufacturersSelectListItems = new SelectList(
                Data.Data.Manufacturers, "Id", "ManufacturerName");

            return(View(product));
        }
示例#21
0
        //Naming convention ok

        public AddProduct()
        {
            Clear();
            int categoryId = AskForCategory();

            Clear();
            string name = AskForName();

            Clear();
            string description = AskCommand("Description (optionnelle):");

            Clear();
            float price = AskForFloat("Entrez le prix (avec une virgule) :");

            Clear();
            int quantity = AskForInteger("Stock de ce produit: ");

            Clear();
            string expirationDate = AskCommand("Rentrez la date limite de consommation du produit (ex: 03/12/2020) :");

            Clear();

            var product = new Product {
                CategoryId = categoryId, Name = name, Description = description, Price = price,
            };

            ProductsRepository productsRepository = new ProductsRepository();
            StocksRepository   stockRepository    = new StocksRepository();
            bool isProductValidated = ValidateProduct(product, expirationDate, quantity);

            if (isProductValidated)
            {
                Clear();
                Echo("Ajout du produit en base...");

                try
                {
                    productsRepository.AddProduct(product);
                } catch (Exception e)
                {
                    Style.SelectColor(ConsoleColor.Red);
                    Echo("Impossible d'ajouter le produit en base");
                    //TODO Message d'erreur ?
                    Echo("Message d'erreur");
                    Echo(e.Message);
                    Style.SelectColor(ConsoleColor.White);
                    AskKeyPress();
                    return;
                }

                Style.Green("Le produit a bien été créé.", true);

                try
                {
                    var timeConvert = stockRepository.ConvertStringDateToTimeStamp(expirationDate);

                    if (timeConvert != 0)
                    {
                        var listProduct = productsRepository.getLastProduct();
                        var stock       = new Stock {
                            Quantity = quantity, ProductId = listProduct.Id, Expiry = timeConvert
                        };
                        stockRepository.AddStock(stock);
                        AskKeyPress();
                    }
                    else
                    {
                        Echo("La date à mal été rentrée, veuillez réessayer");
                        AskKeyPress();
                    }
                } catch (Exception e)
                {
                    Style.SelectColor(ConsoleColor.Red);
                    Echo("Impossible d'ajouter le stock en base");
                    //TODO Message d'erreur ?
                    Echo("Message d'erreur");
                    Echo(e.Message);
                    Style.SelectColor(ConsoleColor.White);
                    AskKeyPress();
                    return;
                }
            }
            else
            {
                Clear();
                Style.Yellow("La création de produit a été annulée.", true);
                AskKeyPress();
            }
        }
示例#22
0
        private void GenerateData()
        {
            Clear();

            //Product
            var            productsRepository = new ProductsRepository();
            List <Product> listProduct        = new List <Product>
            {
                new Product {
                    CategoryId = 2, Name = "Panini Chelou", Description = "Contenu étrange de sucré-salé", Price = 5
                },
                new Product {
                    CategoryId = 2, Name = "Panini Mieux", Description = "Peu import, c'est meilleur", Price = 5
                },
                new Product {
                    CategoryId = 1, Name = "Croissant", Description = "C'est juste un croissant", Price = 1.05F
                },
                new Product {
                    CategoryId = 5, Name = "Brownie", Description = "erverv", Price = 0.99F
                },
                new Product {
                    CategoryId = 5, Name = "Muffin", Description = "ervzrtb", Price = 1F
                },
                new Product {
                    CategoryId = 6, Name = "PastaBox Bolo", Description = "dsdfgfngh,fj;gk", Price = 6.60F
                },
                new Product {
                    CategoryId = 6, Name = "Pizza 4 fromages", Description = "dfbs", Price = 7.90F
                },
                new Product {
                    CategoryId = 4, Name = "Ice Tea", Description = "qr", Price = 4.55F
                },
                new Product {
                    CategoryId = 3, Name = "Salade Piedmontaise", Description = "qrdqdb", Price = 8.45F
                },
                new Product {
                    CategoryId = 5, Name = "Snicker", Description = "qdvqrv", Price = 1.45F
                },
                new Product {
                    CategoryId = 0, Name = "Café", Description = "qrgrqbn", Price = 99F
                }
            };

            foreach (Product aProduct in listProduct)
            {
                Console.WriteLine($"Adding {aProduct.Name}");
                productsRepository.AddProduct(aProduct);
            }

            //One single customer test

            Customer c1 = new Customer()
            {
                Id     = 1,
                Name   = "Amir",
                Orders = new List <CustomerOrder> {
                    new CustomerOrder()
                    {
                        Id         = 1,
                        TotalPrice = 4f,
                        CustomerId = 1,
                        Lines      = new List <OrderLine> {
                            new OrderLine()
                            {
                                Id        = 1,
                                ProductId = 1,
                                OrderId   = 1,
                                Quantity  = 1,
                                Price     = 2f
                            },
                        },
                        TimeCreate = 1578665721,
                        TimeUpdate = 0,
                        TimeDelete = 0
                    },
                },
                TimeCreate = 1578665721,
                TimeUpdate = 0,
                TimeDelete = 0,
            };

            CustomerRepository customerRepository = new CustomerRepository();

            customerRepository.AddCustomer(c1);

            Console.WriteLine("End");
            AskKeyPress();
        }
        public ActionResult Create(Product p, HttpPostedFileBase file)
        {
            //upload image related to product on the bucket
            try
            {
                if (file != null)
                {
                    #region Uploading file on Cloud Storage
                    var    storage = StorageClient.Create();
                    string link    = "";

                    using (var f = file.InputStream)
                    {
                        var filename      = Guid.NewGuid() + System.IO.Path.GetExtension(file.FileName);
                        var storageObject = storage.UploadObject("pfcbrandonbucket", filename, null, f);

                        link = "https://storage.cloud.google.com/pfcbrandonbucket/" + filename;

                        if (null == storageObject.Acl)
                        {
                            storageObject.Acl = new List <ObjectAccessControl>();
                        }


                        storageObject.Acl.Add(new ObjectAccessControl()
                        {
                            Bucket = "pfcbrandonbucket",
                            Entity = $"user-" + User.Identity.Name, //whereas [email protected] has to be replaced by a gmail email address who you want to have access granted
                            Role   = "OWNER",
                        });

                        storageObject.Acl.Add(new ObjectAccessControl()
                        {
                            Bucket = "pfcbrandonbucket",
                            Entity = $"user-" + p.Shareuser, //whereas [email protected] has to be replaced by a gmail email address who you want to have access granted
                            Role   = "READER",               //READER
                        });

                        var updatedObject = storage.UpdateObject(storageObject, new UpdateObjectOptions()
                        {
                            // Avoid race conditions.
                            IfMetagenerationMatch = storageObject.Metageneration,
                        });
                    }
                    //store details in a relational db including the filename/link
                    List <Product> results = new List <Product>();
                    p.File = link;
                    // p.Name = System.IO.Path.GetExtension(model.Shareuser);
                    //p.OwnerFK = User.Identity.Name;
                    //p.Shareuser = Shareuser;
                    // results.Add(p);
                    #endregion
                }
                #region Storing details of product in db [INCOMPLETE]
                p.OwnerFK = User.Identity.Name;

                ProductsRepository pr = new ProductsRepository();


                pr.AddProduct(p);
                #endregion

                #region Updating Cache with latest list of Products from db

                //enable: after you switch on db
                try
                {
                    CacheRepository cr = new CacheRepository();
                    cr.UpdateCache(pr.GetProducts(User.Identity.Name));
                }
                catch (Exception ex)
                {
                    new LogsRepository().LogError(ex);
                }


                #endregion
                PubSubRepository psr = new PubSubRepository();
                psr.AddToEmailQueue(p); //adding it to queue to be sent as an email later on.
                ViewBag.Message = "Product created successfully";
                new LogsRepository().WriteLogEntry("Product created successfully for user: "******"Product failed to be created; " + ex.Message;
            }

            return(View());
            ////upload image related to product on bucket
            //var storage = StorageClient.Create();
            //string link = "";
            //using (var f = file.InputStream)
            //{
            //    var filename = Guid.NewGuid() + System.IO.Path.GetExtension(file.FileName);
            //    var storageObject = storage.UploadObject("pfcbrandonbucket", filename, null, f);
            //    link = storageObject.MediaLink;

            //    if (null == storageObject.Acl)
            //    {
            //        storageObject.Acl = new List<ObjectAccessControl>();
            //    }
            //    storageObject.Acl.Add(new ObjectAccessControl()
            //    {
            //        Bucket = "pfcbrandonbucket",
            //        Entity = $"*****@*****.**",
            //        Role = "READER",
            //    });
            //    storageObject.Acl.Add(new ObjectAccessControl()
            //    {
            //        Bucket = "pfcbrandonbucket",
            //        Entity = $"*****@*****.**",
            //        Role = "OWNER",
            //    });
            //    var updatedObject = storage.UpdateObject(storageObject, new UpdateObjectOptions()
            //    {
            //        // Avoid race conditions.
            //        IfMetagenerationMatch = storageObject.Metageneration,
            //    });
            //}
            ////create p in db
            ////p.Link = link;
            //return View();
        }