public ActionResult AddProduct(AddOrUpdateProductModel addOrUpdateProductModel)
 {
     if (ModelState.IsValid)
     {
         if (addOrUpdateProductModel.Images.FirstOrDefault() != null)
         {
             string folderPath = Server.MapPath($"~/Content/image/product/{addOrUpdateProductModel.Product.Id}");
             Directory.CreateDirectory(folderPath);
             foreach (var image in addOrUpdateProductModel.Images)
             {
                 var    FileName  = image.FileName.Length > 100 ? image.FileName.Substring(0, 100).ToString() : image.FileName.ToString();
                 string imagePaht = Server.MapPath($"~/Content/image/product/{addOrUpdateProductModel.Product.Id}/{FileName}");
                 image.SaveAs(imagePaht);
                 addOrUpdateProductModel.Product.Images.Add(new Image()
                 {
                     Paht = $"/Content/image/product/{addOrUpdateProductModel.Product.Id}/{FileName}"
                 });
             }
         }
         pr.AddOrUpdate(addOrUpdateProductModel.Product);
         return(RedirectToAction("ProductList"));
     }
     ViewBag.MainCat = new SelectList(mcr.SelectAll(), "Id", "Name", "00000000-3e66-4dba-99e3-d255f90080cd");
     return(View(addOrUpdateProductModel));
 }
Exemple #2
0
        public static void Init(TestContext tc)
        {
            var productRepository = new ProductRepository();

            productRepository.AddOrUpdate(new Product
            {
                SKU         = "TST_A01",
                Description = "Apple",
                Price       = 0.5m
            });

            productRepository.AddOrUpdate(new Product
            {
                SKU         = "TST_B15",
                Description = "Biscuits",
                Price       = 0.3m
            });

            productRepository.AddOrUpdate(new Product
            {
                SKU         = "TST_C40",
                Description = "Coffee",
                Price       = 1.8m
            });

            productRepository.AddOrUpdate(new Product
            {
                SKU         = "TST_T23",
                Description = "Tissues",
                Price       = 0.99m
            });

            var discountRepository = new DiscountRepository();

            discountRepository.AddOrUpdate(new Discount
            {
                Id         = Guid.NewGuid(),
                ProductSKU = "TST_A01",
                Quantity   = 3,
                Price      = 1.3m
            });

            discountRepository.AddOrUpdate(new Discount
            {
                Id         = Guid.NewGuid(),
                ProductSKU = "TST_B15",
                Quantity   = 2,
                Price      = .45m
            });
        }
Exemple #3
0
        public Product AddorUpdate(Product product)
        {
            _productRepository.AddOrUpdate(product);
            _productRepository.SaveChanges();

            return(product);
        }
        public void TestAddOrUpdate()
        {
            //add
            DateTime dtRegistration = DateTime.Now.Date.AddDays(-2).AddHours(12.50);
            User     user           = new User("Jake", 27, dtRegistration);

            userRepo.AddOrUpdate(user);
            unitOfwork.Save();
            User userInDb = userRepo.FindByName("Jake");

            Assert.AreEqual(user.Name, userInDb.Name);

            //update
            userInDb.Age = 29;
            userRepo.AddOrUpdate(userInDb);


            //add categories to db
            foreach (var item in categories)
            {
                categoryRepo.AddOrUpdate(item);
            }
            unitOfwork.Save();

            //assign the category to products and add to db
            foreach (var item in products)
            {
                if (item.Name.Contains("Sumsung"))
                {
                    item.Category = categories[1];
                }
                else
                {
                    item.Category = categories[0];
                }

                productRepo.AddOrUpdate(item);
            }
            unitOfwork.Save();

            //add products to stores
            Store rozetkaStore = stores[0];

            rozetkaStore.Products.Add(products[0]);
            rozetkaStore.Products.Add(products[2]);
            rozetkaStore.Products.Add(products[1]);

            Store mobidickStore = stores[1];

            mobidickStore.Products.Add(products[0]);
            mobidickStore.Products.Add(products[3]);
            mobidickStore.Products.Add(products[2]);

            //add stores to db
            storeRepo.AddOrUpdate(rozetkaStore);
            storeRepo.AddOrUpdate(mobidickStore);
            unitOfwork.Save();

            unitOfwork.Dispose();
        }
        public ActionResult OrderCompleted(int ShipperId)
        {
            var cart = (CartModel)Session["Cart"];

            if (cart == null)
            {
                return(RedirectToAction("TimeOut"));
            }

            var order = new Order();

            order.ShipperId = ShipperId;
            order.UserId    = ur.SelectAll().FirstOrDefault(i => i.Username == User.Identity.Name).Id;
            foreach (var item in cart.CartLine)
            {
                var orderDetail = new OrderDetail();
                orderDetail.ProductId = item.ProductId;
                orderDetail.Quantity  = item.Quantity;
                orderDetail.UnitPrice = item.SubTotal;
                order.OrderDetails.Add(orderDetail);
            }
            if (or.AddOrUpdate(order))
            {
                foreach (var orderDetail in order.OrderDetails)
                {
                    var product = pr.SelectById(orderDetail.ProductId);
                    product.Stock -= Convert.ToInt16(orderDetail.Quantity);
                    pr.AddOrUpdate(product);
                }
                Session["Order"] = order;
                return(RedirectToAction("OrderInfo"));
            }
            return(RedirectToAction("OrderNotCreated"));
        }
Exemple #6
0
        private static void CreateProducts(StoreContext context)
        {
            var categoryRepository = new CategoryRepository(context);
            var categoryIds        = categoryRepository.GetAll().ToArray();

            var productRepository = new ProductRepository(context);

            if (!productRepository.IsEmpty())
            {
                return;
            }

            for (var i = 1; i <= 100; i++)
            {
                productRepository.AddOrUpdate(new ProductModel {
                    Id                  = i,
                    Category            = RandomHelpers.GetRandom(categoryIds),
                    Title               = string.Format("محصول آزمایشی {0}", i),
                    Slug                = StringHelpers.Slugify(string.Format("Test Product {0}", i)),
                    Summary             = "خلاصه ای در مورد این محصول",
                    Description         = "توضیحات کامل مربوط به این محصول.",
                    Features            = "<ul><li>ویژگی شماره 1</li><li>ویژگی شماره 2</li><li>ویژگی شماره 3</li><li>و...</li></ul>",
                    MetaKeywords        = "کلمه 1, کلمه 2, کلمه 3",
                    MetaDescription     = "توضیحاتی در مورد محصول",
                    UnitPrice           = 55500 * i,
                    ReleaseDateUtc      = RandomHelpers.GetRandom(DateTime.UtcNow.AddYears(-2), DateTime.UtcNow),
                    LastModifiedDateUtc = RandomHelpers.GetRandom(DateTime.UtcNow.AddYears(-1), DateTime.UtcNow),
                    ViewsCount          = 0,
                    AddedToCartCount    = 0
                });
            }

            productRepository.SaveChanges();
        }
Exemple #7
0
        private void menuStripLoad_Click(object sender, System.EventArgs e)
        {
            var dlg = new OpenFileDialog();

            dlg.Filter = "Text files(*.txt)|*.txt|All files(*.*)|*.*";
            if (dlg.ShowDialog() == DialogResult.Cancel)
            {
                return;
            }

            string filename = dlg.FileName;

            if (!File.Exists(filename))
            {
                return;
            }

            List <string> lines = File.ReadAllLines(filename).ToList();

            int count = 0;

            foreach (var line in lines)
            {
                var candidate = line.Split(';');
                try
                {
                    var product = new Product
                    {
                        Number     = Convert.ToInt32(candidate[0]),
                        CategoryId = Convert.ToInt32(candidate[1]),
                        Name       = candidate[2],
                        Price      = Convert.ToDecimal(candidate[3].Replace('.', ',')),
                        AddAmount  = Convert.ToDecimal(candidate[4].Replace('.', ',')),
                        Discount   = Convert.ToDecimal(candidate[5].Replace('.', ',')),
                        Total      = Convert.ToDecimal(candidate[6].Replace('.', ','))
                    };
                    _productRepository.AddOrUpdate(product);
                    count++;
                }
                catch
                {
                    //cannot parse product from the line
                }
            }

            if (count != 0)
            {
                MessageBox.Show("Загрузка " + count + " продуктов завершена. " +
                                (lines.Count - count).ToString() + " линий пропущено. Проверьте корректность загруженных данных.",
                                "Загрузка завершена", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }

            LoadGrid();
        }
        /// <summary>
        /// Add or update a product model
        /// </summary>
        /// <param name="model"></param>
        /// <param name="userName"></param>
        /// <returns></returns>
        public async Task <Operate> AddOrUpdate(ProductModel model, string userName)
        {
            var result = new Operate();

            try
            {
                //check duplicated name
                var dupProduct = await _productRepository.GetProductByName(model.Code, model.Id);

                if (dupProduct != null)
                {
                    result.Status  = -2;
                    result.Message = "Code is already taken";
                    return(result);
                }
                Product product;
                if (model.Id == 0)
                {
                    product            = model.ToProductModel();
                    product.CreateTime = DateTime.UtcNow;
                    product.CreateBy   = userName;
                }
                else
                {
                    product = await _productRepository.GetById(model.Id);

                    if (product == null)
                    {
                        result.Status  = -3;
                        result.Message = "Product does not exist";
                        Logger.WriteErrorLog("ProductService", "AddOrUpdate", new Exception("Product is not existed"));
                        return(result);
                    }
                    product.EditTime   = DateTime.UtcNow;
                    product.EditBy     = userName;
                    product.Vendor     = model.Vendor;
                    product.Code       = model.Code;
                    product.Image      = model.Image;
                    product.LongDesc   = model.LongDesc;
                    product.ShortDesc  = model.ShortDesc;
                    product.UomId      = model.UomId;
                    product.CategoryId = model.CategoryId;
                }
                await _productRepository.AddOrUpdate(product);
            }
            catch (Exception ex)
            {
                result.Status  = -1;
                result.Message = ex.Message;
                Logger.WriteErrorLog("ProductService", "AddOrUpdate", ex);
            }
            return(result);
        }
Exemple #9
0
        private void btnSave_Click(object sender, System.EventArgs e)
        {
            if (cbCategory.SelectedItem == null)
            {
                MessageBox.Show("Выберите категорию!", "Выберите категорию", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            if (string.IsNullOrEmpty(tbProduct.Text))
            {
                MessageBox.Show("Введите название товара!", "Введите название товара", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            if (string.IsNullOrEmpty(tbPrice.Text))
            {
                MessageBox.Show("Введите стоимость товара!", "Введите стоимость товара", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            if (string.IsNullOrEmpty(tbNumber.Text))
            {
                MessageBox.Show("Введите идентификатор товара!", "Введите идентификатор товара", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            if (_productRepository.GetProducts().Any(p => p.Number == Convert.ToInt32(tbNumber.Text)) && product == null)
            {
                MessageBox.Show("Товар с таким идентификатором уже есть в базе!", "Дубликат!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            if (_productRepository.GetProducts().Any(p => p.Number == Convert.ToInt32(tbNumber.Text)) &&
                product != null &&
                product.Number != Convert.ToInt32(tbNumber.Text))
            {
                MessageBox.Show("Товар с таким идентификатором уже есть в базе!", "Дубликат!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            if (product == null)
            {
                product = new Product();
            }
            product.Number     = Convert.ToInt32(tbNumber.Text);
            product.AddAmount  = string.IsNullOrEmpty(tbAdd.Text) ? 0 : Convert.ToDecimal(tbAdd.Text.Replace('.', ','));
            product.Discount   = string.IsNullOrEmpty(tbDisc.Text) ? 0 : Convert.ToDecimal(tbDisc.Text.Replace('.', ','));
            product.Name       = tbProduct.Text;
            product.Price      = string.IsNullOrEmpty(tbPrice.Text) ? 0 : Convert.ToDecimal(tbPrice.Text.Replace('.', ','));
            product.Total      = string.IsNullOrEmpty(tbTotal.Text) ? 0 : Convert.ToDecimal(tbTotal.Text.Replace('.', ','));
            product.CategoryId = _categories.FirstOrDefault(c => c.Name == cbCategory.SelectedItem.ToString()).Id;
            _productRepository.AddOrUpdate(product);
            Close();
        }
Exemple #10
0
        public ActionResult OrderIsOk()
        {
            if ((Order)Session["Order"] == null)
            {
                return(RedirectToAction("TimeOut"));
            }
            var order = (Order)Session["Order"];
            var or    = new OrderRepository();

            if (or.AddOrUpdate(order))
            {
                var pr = new ProductRepository();

                foreach (var orderDetails in order.OrderDetails)
                {
                    var product = pr.SelectById(orderDetails.ProductId);
                    product.Stock -= orderDetails.Quantity;
                    pr.AddOrUpdate(product);
                }

                Session["Cart"] = new Cart();
                var userStore   = new UserStore <User>(DbInstance.Instance);
                var userManager = new UserManager <User>(userStore);
                var user        = userManager.FindByName(User.Identity.Name);
                ViewBag.UserEmail = user.Email;

                //SmtpClient smtp = new SmtpClient();
                //smtp.Port = 587;
                //smtp.Host = "smtp.office365.com";
                //smtp.EnableSsl = true;
                //smtp.Credentials = new NetworkCredential("*****@*****.**", "project321");

                //MailMessage mail = new MailMessage();
                //mail.From = new MailAddress("*****@*****.**", "E-Commerce Project");
                //mail.To.Add(user.Email);
                //mail.Subject = "Siparişiniz Hk.";
                //mail.IsBodyHtml = true;
                //mail.Body = _OrderMailBody().PartialRenderToString(); ;
                //smtp.Send(mail);

                return(View());
            }
            else
            {
                return(View("Error"));
            }
        }
Exemple #11
0
        public ActionResult AddOrUpdate(Product model)
        {
            if (ModelState.IsValid)
            {
                var product = new Product();
                if (model.Id != 0)
                {
                    product = pr.SelectById(model.Id);
                }
                if (model.Img.FirstOrDefault() != null)
                {
                    foreach (var img in model.Img)
                    {
                        string imgPath = "/Content/Images/PLimg/" + img.FileName;
                        img.SaveAs(Server.MapPath(imgPath));
                        var image = new Image();
                        image.ImageUrl = imgPath;
                        product.Images.Add(image);
                    }
                }
                if (model.ImageIds != null)
                {
                    var imageIds = model.ImageIds.Split(',');
                    foreach (var id in imageIds)
                    {
                        if (id != "")
                        {
                            ir.Delete(ir.SelectById(Convert.ToInt32(id)));
                        }
                    }
                }

                product.Name        = model.Name;
                product.Brand       = model.Brand;
                product.Description = model.Description;
                product.Stock       = model.Stock;
                product.Price       = model.Price;
                product.Insales     = model.Insales;
                product.CategoryId  = model.CategoryId;
                pr.AddOrUpdate(product);

                return(RedirectToAction("List"));
            }
            ViewBag.Category = new SelectList(cr.SelectAll(), "Id", "Name");
            return(View(model));
        }
Exemple #12
0
        public void TestAddOrUpdateProduct()
        {
            //add categories to db
            foreach (var item in categories)
            {
                categoryRepo.AddOrUpdate(item);
            }
            categoryRepo.Save();

            //assign the category to products and add to db
            foreach (var item in products)
            {
                if (item.Name.Contains("Sumsung"))
                {
                    item.Category = categories[1];
                }
                else
                {
                    item.Category = categories[0];
                }

                productRepo.AddOrUpdate(item);
            }
            productRepo.Save();

            //add products to stores
            Store rozetkaStore = stores[0];

            rozetkaStore.Products.Add(products[0]);
            rozetkaStore.Products.Add(products[2]);
            rozetkaStore.Products.Add(products[1]);

            Store mobidickStore = stores[1];

            mobidickStore.Products.Add(products[0]);
            mobidickStore.Products.Add(products[3]);
            mobidickStore.Products.Add(products[2]);

            //add stores to db
            storeRepo.AddOrUpdate(rozetkaStore);
            storeRepo.AddOrUpdate(mobidickStore);
            storeRepo.Save();
        }
Exemple #13
0
        public ActionResult AddOrUpdate(Product model)
        {
            if (model.Id == 0)
            {
                model.DateCreation = DateTime.Now;
            }
            model.DateChange = DateTime.Now;

            model.Categories = model.Categories.Where(i => i.Checked == true).ToList();

            _productRepository.AddOrUpdate(model);
            var routeItem = new RouteItem(0, null, (string)ControllerContext.RequestContext.RouteData.Values["controller"],
                                          "Index",
                                          model.Id)
            {
                Type = Common.TypeEntityFromRouteEnum.ProductType
            };

            _routeItemRepository.AddOrUpdate(routeItem);

            return(RedirectToAction("AdminIndex"));
        }