Наследование: System.Web.UI.Page
Пример #1
0
 public Product(string name, decimal unitPrice, ProductCategory category, ImageInfo image)
 {
     this.Name = name;
     this.UnitPrice = unitPrice;
     this.Category = category;
     this.Image = image;
 }
Пример #2
0
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            //if (((DataView)odsTinTuc.Select()).Count <= DataPager1.PageSize)
            //{
            //    DataPager1.Visible = false;
            //}

            string strTitle, strDescription, strMetaTitle, strMetaDescription;
            if (!string.IsNullOrEmpty(Request.QueryString["pi"]))
            {
                var oProduct = new Product();
                var oProductCategory = new ProductCategory();
                var dv = oProduct.ProductSelectOne(Request.QueryString["pi"]).DefaultView;

                if (dv != null && dv.Count <= 0) return;
                var row = dv[0];

                strTitle = Server.HtmlDecode(row["ProductName"].ToString());
                strDescription = Server.HtmlDecode(row["Description"].ToString());
                strMetaTitle = Server.HtmlDecode(row["MetaTittle"].ToString());
                strMetaDescription = Server.HtmlDecode(row["MetaDescription"].ToString());
            }
            else
            {
                strTitle = strMetaTitle = "Sản Phẩm";
                strDescription = "";
                strMetaDescription = "";
            }
            Page.Title = !string.IsNullOrEmpty(strMetaTitle) ? strMetaTitle : strTitle;
            var meta = new HtmlMeta() { Name = "description", Content = !string.IsNullOrEmpty(strMetaDescription) ? strMetaDescription : strDescription };
            Header.Controls.Add(meta);
        }
    }
Пример #3
0
 public ProductCategory(string code, string name, string description, ProductCategory parentCategory)
     : base(code)
 {
     _name = name;
     _description = description;
     _parentCategory = parentCategory;
 }
Пример #4
0
 public ProductListItem(ProductCategory model,int Belong)
 {
     this.ID = model.ID;
     this.Title = model.Content;
     this.Url = "/Product/Index?Category="+model.ID+"&Belong="+(int)model.Belong;
     this.FacePath = "/Product/ProductCategoryImgage/" + model.ID;
 }
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            string strTitle, strDescription, strMetaTitle, strMetaDescription;
            if (!string.IsNullOrEmpty(Request.QueryString["ni"]))
            {
                var oProduct = new Product();
                var oProductCategory = new ProductCategory();
                var dv = oProduct.ProductSelectOne(Request.QueryString["ni"]).DefaultView;

                if (dv != null && dv.Count <= 0) return;
                var row = dv[0];

                var dv2 = oProductCategory.ProductCategorySelectOne(row["CategoryID"].ToString()).DefaultView;
                
                strTitle = Server.HtmlDecode(row["ProductName"].ToString());
                strDescription = Server.HtmlDecode(row["Description"].ToString());
                strMetaTitle = Server.HtmlDecode(row["MetaTittle"].ToString());
                strMetaDescription = Server.HtmlDecode(row["MetaDescription"].ToString());

                lblTitleProduct.Text = dv2[0]["ProductCategoryName"].ToString();
            }
            else
            {
                strTitle = strMetaTitle = "Nghiên Cứu Phát Triển";
                strDescription = "";
                strMetaDescription = "";
            }
            Page.Title = !string.IsNullOrEmpty(strMetaTitle) ? strMetaTitle : strTitle;
            var meta = new HtmlMeta() { Name = "description", Content = !string.IsNullOrEmpty(strMetaDescription) ? strMetaDescription : strDescription };
            Header.Controls.Add(meta);
        }
    }
Пример #6
0
        public static void AddProductCategory(KetchupContext context)
        {
            var price = context.ProductAttributeTypes.First(pat => pat.Name == "Price");
            var name = context.ProductAttributeTypes.First(pat => pat.Name == "Name");

            var category = new ProductCategory
            {
                Name = "Default Product Category"
            };

            context.ProductCategorys.AddOrUpdate(pc => pc.Name, category);

            var specifications = new []
            {
                new ProductCategorySpecificationAttribute
                {
                    Attribute = price,
                    ProductCategory = category,
                    ProductAttributeTypeId = price.Id,
                    ProductCategoryId = category.Id
                },
                new ProductCategorySpecificationAttribute
                {
                    Attribute = name,
                    ProductCategory = category,
                    ProductAttributeTypeId = price.Id,
                    ProductCategoryId = category.Id
                },
            };

            context.ProductCategorySpecificationAttributes.AddOrUpdate(
                pcsa => new { pcsa.ProductAttributeTypeId, pcsa.ProductCategoryId },
                specifications);
        }
        public ActionResult Create(ProductCategory model)
        {
            if (ModelState.IsValid)
            {
                var retry = 0;
                Exception exception = null;
                while(retry < 5)
                {
                    try
                    {
                        model.ModifiedDate = DateTime.Now;
                        model.rowguid = Guid.NewGuid();
                        _context.ProductCategories.Add(model);
                        _context.SaveChanges();
                        return RedirectToAction("Query");
                    }
                    catch (Exception ex)
                    {
                        exception = ex;
                        retry++;
                    }
                }
                if(exception != null)
                    ModelState.AddModelError("", exception.ToString());
            }

            AddCategoriesDDL();
            return View(model);         
        }
 /// <summary>
 /// Get all order items
 /// </summary>
 /// <remarks>Returns all three order items we've got here</remarks>
 /// <response code="200">OK</response>
 /// <response code="401">Unauthorized</response>
 /// <returns></returns>
 public IEnumerable<OrderItem> GetAll(int orderId, ProductCategory? category = null)
 {
     return new[]
         {
             new OrderItem {LineNo = 1, Product = "Test Product 1", Quantity = 2},
             new OrderItem {LineNo = 2, Product = "Test Product 2", Quantity = 4},
             new OrderItem {LineNo = 3, Product = "Test Product 3", Quantity = 3}
         };
 }
Пример #9
0
 public Product(string code, Inventory inventory, ProductCategory category, long sellPrice)
     : base(code)
 {
     _inventory = inventory;
     _category = category;
     _volume = 1;
     _sellPrice = sellPrice;
     _name = _inventory.Name;
     _description = _inventory.Description;
 }
Пример #10
0
        public void Insert(ProductCategory productCategory)
        {
            productCategory = Validate(productCategory);

            if (_productCategories.Any(i => i.Description.Equals(productCategory.Description, StringComparison.InvariantCultureIgnoreCase)))
                throw new BusinessLogicException("A product category with that name already exists.");

            _productCategories.Add(productCategory);
            _repository.SaveChanges();
        }
Пример #11
0
        public IList<ProductCategory> Select(ProductCategory data)
        {

                IList<ProductCategory> datos = new List<ProductCategory>();
                datos = GetHsql(data).List<ProductCategory>();
                if (!Factory.IsTransactional)
                    Factory.Commit();
                return datos;
            
        }
Пример #12
0
 public AuctionItem(string description, ProductCategory category, int startPrice, DateTime startDate, User owner, SpecialFeatures specialFeatures)
 {
     this.description = description;
     this.category = category;
     this.startPrice = startPrice;
     this.startDate = startDate;
     this.owner = owner;
     this.specialFeatures = specialFeatures;
     this.bids = new ObservableCollection<Bid>();
 }
Пример #13
0
        public Product(string productName, int productcode, string description, decimal price, PriceType priceType, ProductCategory[] categories, int internalID)
        {
            this.productName = productName;
            this.productCode = productcode;
            this.description = description;
            this.price = price;
            this.priceType = priceType;
            this.categories = categories;

            this.internalID = internalID;
        }
Пример #14
0
 private static void AddParentCategories(this InventoryItem @this, ProductCategory productCategory)
 {
     if (productCategory.ExistParents)
     {
         foreach (ProductCategory parent in productCategory.Parents)
         {
             @this.AddDerivedProductCategory(parent);
             @this.AddParentCategories(parent);
         }
     }
 }
Пример #15
0
        public ActionResult Create(ProductCategory productcategory)
        {
            if (ModelState.IsValid)
            {
                db.ProductCategories.Add(productcategory);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            return View(productcategory);
        }
Пример #16
0
 public AuctionItem(string description, ProductCategory category, int startPrice, DateTime startDate, User owner,
     SpecialFeatures specialFeatures)
 {
     _description = description;
     _category = category;
     _startPrice = startPrice;
     _startDate = startDate;
     Owner = owner;
     _specialFeatures = specialFeatures;
     _bids = new ObservableCollection<Bid>();
 }
Пример #17
0
        public void OneToManyReadTest()
        {
            using (EasySession easySession = new EasySession())
            {
                ///[Test Read] - one-to-many relationship
                ProductCategory productCategory = new ProductCategory();
                IList resultList = productCategory.FindAll(easySession);

                Assert.AreEqual(4, resultList.Count);
            }
        }
 public override object CreateProduct(ProductCategory category)
 {
     switch (category)
       {
     case ProductCategory.ProductA:
       return new ConcreteProductA();
     case ProductCategory.ProductB:
       return new ConcreteProductB();
     default:
       throw new NotSupportedException();
       }
 }
        // PUT api/awbuildversion/5
        public void Put(ProductCategory value)
        {
            var GetActionType = Request.Headers.Where(x => x.Key.Equals("ActionType")).FirstOrDefault();

            if (GetActionType.Key != null)
            {
                if (GetActionType.Value.ToList()[0].Equals("DELETE"))
                    adventureWorks_BC.ProductCategoryDelete(value);
                if (GetActionType.Value.ToList()[0].Equals("UPDATE"))
                    adventureWorks_BC.ProductCategoryUpdate(value);
            }
        }
 public virtual AbstractOrInterfaceOfProduct CreateProduct(ProductCategory category)
 {
     switch (category)
       {
     case ProductCategory.GoodProduct:
       return new ConcreteGoodProduct();
     case ProductCategory.BadProduct:
       return new ConcreteBadProduct();
     default:
       throw new NotSupportedException();
       }
 }
Пример #21
0
 public bool AddCategory(ProductCategory category)
 {
     using (IDbConnection connection = MySQLDAOFactory.GetDatabase().CreateOpenConnection())
     {
         using (IDbTransaction transaction = connection.BeginTransaction())
         {
             try
             {
                 string query = "INSERT INTO category (categoryname, categorydescription) VALUES "
                 + "('" + category.name.Trim().ToLower() + "', '" + category.description + "')";
                 using (IDbCommand command = MySQLDAOFactory.GetDatabase().CreateCommand(query, connection))
                 {
                     if (command.ExecuteNonQuery() <= 0)
                     {
                         transaction.Rollback();
                         return false;
                     }
                 }
                 string queryID = "SELECT LAST_INSERT_ID();";
                 using (IDbCommand commandID = MySQLDAOFactory.GetDatabase().CreateCommand(queryID, connection))
                 {
                     using (IDataReader reader = commandID.ExecuteReader())
                     {
                         if (reader.Read())
                         {
                             category.internalID = Convert.ToInt32(reader[0]);
                         }
                     }
                     if (category.internalID.Equals(-1) == false)
                     {
                         transaction.Commit();
                         return true;
                     }
                     else
                     {
                         transaction.Rollback();
                         throw new Exception("category inserted succesfully, but could not retrieve ID afterwards. Rolled back.");
                     }
                 }
             }
             catch (MySqlException ex)
             {
                 transaction.Rollback();
                 throw new DatabaseException(ex.Message, ex);
             }
             catch (Exception ex)
             {
                 transaction.Rollback();
                 throw ex;
             }
         }
     }
 }
Пример #22
0
        public ActionResult CreatePost(string productName, string productEnergy, ProductCategory productCategory)
        {
            var product = new Product()
            {
                Name = productName,
                KcalPer100Grams = float.Parse(productEnergy),
                Category = productCategory
            };

            ProductService.Repository.AddToUser(product, UserService.LoggedUser);

            return RedirectToAction("Index", "Products");
        }
Пример #23
0
    private void BindData_PriceList1()
    {
        int nProductCat = 14;
        int nPageCount = 0;
        ProductCategory objProductCategory = new ProductCategory();
        objProductCategory.LoadById(nProductCat);
        lblCatname.Text = objProductCategory.Data.ProductCategoryName;

        Products objProduct = new Products();
        DataTable dtb = objProduct.Search("", 0, 1000000000, nProductCat, 1, 1, 3, ref nPageCount);
        rptPriceList1.DataSource = dtb;
        rptPriceList1.DataBind();
    }
Пример #24
0
        public ActionResult CreateCategory(ProductCategory productCategory)
        {
            if (!IsAdministrator()) return View("Error");
            if (productCategory.Name != null)
            {
                productCategory.ModifiedDate = DateTime.Now;
                productCategory.rowguid = Guid.NewGuid();
                _productCategoryRepository.SaveToProductCategory(productCategory);
                return RedirectToAction("Index");
            }

            return View(new ProductCategory());
        }
Пример #25
0
        public void TestCreateProduct()
        {
            var fakeCategory = new ProductCategory();
            var fakeSpecification = new ProductSpecification();

            var actual = this._target.CreateProduct(fakeSpecification, fakeCategory);

            Assert.IsNotNull(actual);
            Assert.AreEqual(fakeCategory, actual.Category);
            Assert.IsTrue(actual.ProductSpecifications.Any(ps => ps == fakeSpecification));

            Assert.IsTrue(this._products.Any());
        }
Пример #26
0
 int GetColumnIndex(ProductCategory category) {
     switch(category) {
         case ProductCategory.Televisions:
             return 0;
         case ProductCategory.Monitors:
             return 1;
         case ProductCategory.VideoPlayers:
             return 2;
         case ProductCategory.Automation:
             return 3;
         default:
             return -1;
     }
 }
        public void Insert_Add_An_Element()
        {
            int count = _catRepo.GetAll().Count();

            ProductCategory pcat = new ProductCategory { Name = "New product category" };
            _catRepo.Insert(pcat);

            _ctx.SaveChanges();

            int count2 = _catRepo.GetAll().Count();

            Assert.That(pcat, Has.Property("Id").GreaterThan(0));
            Assert.That(count2, Is.GreaterThan(count));
        }
Пример #28
0
        public ProductCategory Save()
        {
            ProductCategory productCategory = null;
            var session = NHibernateSessionManager.GetLocalSession();

            session.DoTransactional(sess =>
                {
                    productCategory = new ProductCategory(_form.Code, _form.CategoryName, _form.CategoryDescription);

                    productCategory = _categoryRepository.Insert(productCategory);
                });

            return productCategory;
        }
Пример #29
0
 public bool AddCategory(ProductCategory category)
 {
     CategoryDAO dao = daoFactory.GetCategoryDAO();
     try
     {
         return dao.AddCategory(category);
     }
     catch (DatabaseException ex)
     {
         throw ex;
     }
     catch (Exception ex)
     {
         throw ex;
     }
 }
Пример #30
0
        public void Commit_Store_Elements()
        {
            ProductCategory cat = new ProductCategory {Name = "Temporary cat"};
            _catRepo.Insert(cat);
            _unitOfWork.Commit();

            Assert.That(cat, Has.Property("Id").GreaterThan(0));

            using (var ctx = new Context())
            {
                var adp = new DbContextAdapter(ctx);
                var repo = new Repository<ProductCategory>(adp);

                Assert.That(repo.First(pc => pc.Name == cat.Name), Is.Not.Null);
            }
        }
Пример #31
0
        public async Task ShouldImportWithOverrider()
        {
            var dbContext        = GetDb();
            var categoryName     = "Cookies";
            var categoryToSelect = new ProductCategory {
                CategoryCode = "CK", CategoryName = categoryName
            };
            var unselectedCategory = new ProductCategory {
                CategoryCode = "UC", CategoryName = "Unrelated Category"
            };

            await PersistToDatabase(categoryToSelect, unselectedCategory);

            var existingProduct = new Product {
                ProductCategoryId = unselectedCategory.Id, ProductName = "Vanilla Wafers"
            };

            await PersistToDatabase(existingProduct);


            var overrider = new ProductPropertyOverrider <Product>(dbContext);


            var excelIoWrapper = new FakeExcelIo();

            excelIoWrapper.Rows.Clear();
            var cookieType = "Mint Cookies";

            excelIoWrapper.Rows.Add(new Dictionary <string, string>
            {
                { "xlsCol1", "CK" },
                { "xlsCol2", cookieType },
                { "xlsCol5", "" },
            });
            var updatedCookieName = "Strawberry Wafers";

            excelIoWrapper.Rows.Add(new Dictionary <string, string>
            {
                { "xlsCol1", "CK" },
                { "xlsCol2", updatedCookieName },
                { "xlsCol5", existingProduct.Id.ToString() },
            });


            var importer = new XlsxToTableImporter(dbContext, excelIoWrapper);

            var prod = new Product();
            var importMatchingData = new DataMatchesForImportingOrderData
            {
                FileName = "foo.xlsx",
                Sheet    = "mysheet",
                Selected = new List <XlsToEfColumnPair>
                {
                    XlsToEfColumnPair.Create(() => prod.Id, "xlsCol5"),
                    XlsToEfColumnPair.Create("ProductCategory", "xlsCol1"),
                    XlsToEfColumnPair.Create(() => prod.ProductName, "xlsCol2"),
                },
            };


            Func <int, Expression <Func <Product, bool> > > finderExpression = selectorValue => entity => entity.Id.Equals(selectorValue);
            var result = await importer.ImportColumnData(importMatchingData, finderExpression, overridingMapper : overrider);

            var newItem = GetDb().Set <Product>().Include(x => x.ProductCategory).First(x => x.ProductName == cookieType);

            newItem.ProductCategory.CategoryName.ShouldBe("Cookies");
            newItem.ProductName.ShouldBe(cookieType);

            var updated = GetDb().Set <Product>().Include(x => x.ProductCategory).First(x => x.Id == existingProduct.Id);

            updated.ProductName.ShouldBe(updatedCookieName);
        }
Пример #32
0
 public void Insert(ProductCategory category)
 {
     productCategories.Add(category);
 }
Пример #33
0
 public ProductCategory Delete(ProductCategory model)
 {
     return(_productCategoryRepository.Delete(model));
 }
Пример #34
0
        public JObject addProduct(JObject request)
        {
            //Get arguments
            string productID;
            string manufacturer;
            string categoryID;

            request.TryGetValue("productID", out JToken productIDValue);
            request.TryGetValue("categoryID", out JToken categoryIDValue);
            request.TryGetValue("manufacturer", out JToken manufacturerValue);
            request.TryGetValue("description", out JToken descriptionValue);
            request.TryGetValue("name", out JToken nameValue);

            // Verify presence of arguments
            List <string> failedVerifications = new List <string>();

            if (productIDValue == null)
            {
                failedVerifications.Add("productID");
            }
            if (categoryIDValue == null)
            {
                failedVerifications.Add("categoryID");
            }
            if (manufacturerValue == null)
            {
                failedVerifications.Add("manufacturer");
            }
            if (nameValue == null)
            {
                failedVerifications.Add("name");
            }

            if (failedVerifications.Any())
            {
                return(Templates.MissingArguments(failedVerifications.ToArray()));
            }

            // Verify arguments
            if (productIDValue.Type != JTokenType.String)
            {
                failedVerifications.Add("productID");
            }
            if (categoryIDValue.Type != JTokenType.String)
            {
                failedVerifications.Add("categoryID");
            }
            if (manufacturerValue.Type != JTokenType.String)
            {
                failedVerifications.Add("manufacturer");
            }
            if (nameValue.Type != JTokenType.Object)
            {
                failedVerifications.Add("name");
            }

            if (failedVerifications.Any())
            {
                return(Templates.InvalidArguments(failedVerifications.ToArray()));
            }

            // Prepare values
            productID    = productIDValue.ToObject <string>();
            manufacturer = manufacturerValue.ToObject <string>();
            categoryID   = categoryIDValue.ToObject <string>();

            // Get image
            request.TryGetValue("image", out JToken imageValue);
            string extension = null;

            byte[] imageData = null;
            if (imageValue != null && imageValue.Type == JTokenType.Object)
            {
                JObject image = imageValue.ToObject <JObject>();
                image.TryGetValue("data", out JToken dataValue);
                image.TryGetValue("extension", out JToken extensionValue);
                if (extensionValue != null && extensionValue.Type == JTokenType.String &&
                    dataValue != null && dataValue.Type == JTokenType.String)
                {
                    extension = extensionValue.ToObject <string>();
                    imageData = (byte[])dataValue;
                    if (!Image.ImageFormats.Contains(extension))
                    {
                        return(Templates.InvalidArgument("extension"));
                    }
                }
                else
                {
                    return(Templates.MissingArguments("data, extension"));
                }
            }

            // Get languages
            string  en;
            string  nl    = null;
            string  ar    = null;
            JObject names = nameValue.ToObject <JObject>();

            names.TryGetValue("en", out JToken nameEnValue);
            names.TryGetValue("nl", out JToken nameNlValue);
            names.TryGetValue("ar", out JToken nameArValue);
            if (nameEnValue != null && nameEnValue.Type == JTokenType.String)
            {
                en = names["en"].ToObject <string>();
            }
            else
            {
                return(Templates.MissingArguments("name: en"));
            }
            if (nameNlValue != null && nameNlValue.Type == JTokenType.String)
            {
                nl = names["nl"].ToObject <string>();
            }
            if (nameArValue != null && nameArValue.Type == JTokenType.String)
            {
                ar = names["ar"].ToObject <string>();
            }
            LanguageItem name = new LanguageItem(productID + "_name", en, nl, ar);

            LanguageItem description;

            if (descriptionValue != null && descriptionValue.Type == JTokenType.Object)
            {
                //Get description
                JObject desc = descriptionValue.ToObject <JObject>();
                desc.TryGetValue("en", out JToken descEnValue);
                desc.TryGetValue("nl", out JToken descNlValue);
                desc.TryGetValue("ar", out JToken descArValue);
                if (descEnValue != null && descEnValue.Type == JTokenType.String)
                {
                    en = desc["en"].ToObject <string>();
                }
                else
                {
                    return(Templates.MissingArguments("description: en"));
                }
                if (descNlValue != null && descNlValue.Type == JTokenType.String)
                {
                    nl = desc["nl"].ToObject <string>();
                }
                if (descArValue != null && descArValue.Type == JTokenType.String)
                {
                    ar = desc["ar"].ToObject <string>();
                }
                description = new LanguageItem(productID + "_description", en, nl, ar);
            }
            else
            {
                description = new LanguageItem(productID + "_description", null);
            }

            //Check if product already exists
            Product product = GetObject <Product>(productID);

            if (product != null)
            {
                return(Templates.AlreadyExists(productID));
            }

            //Check if category exists
            ProductCategory category = GetObject <ProductCategory>(categoryID);

            if (category == null)
            {
                return(Templates.NoSuchProductCategory(categoryID));
            }

            //Create product, languageItem, image
            name.Upload(Connection);
            description.Upload(Connection);
            if (imageData != null)
            {
                Image image = new Image(productID + "_image", imageData, extension);
                image.Upload(Connection);
                product = new Product(productID, manufacturer, categoryID, productID + "_name", productID + "_description", image.Id);
            }
            else
            {
                product = new Product(productID, manufacturer, categoryID, productID + "_name", productID + "_description");
            }
            product.Upload(Connection);

            //Create response
            return(new JObject()
            {
                { "reason", null },
            });
        }
 public Select2ViewModel RecursiveSelect(ProductCategory ent)
 {
   return this.InternalSelect(ent);
 }
Пример #36
0
 public AskToCreateProductCategory(ProductCategory category)
 {
     ProductCategory = category;
 }
Пример #37
0
        public ActionResult Index()
        {
            if (User.IsInRole("CanManageApplication"))
            {
                return(View("AdminPanel"));
            }

            if (User.IsInRole("Rider"))
            {
                return(RedirectToAction("OrdersForRider", "Orders"));
            }

            var memberId = User.Identity.GetUserId();
            var user     = _context.Users.Where(c => c.Id == memberId).SingleOrDefault();

            var             productCategories = _context.ProductCategories.ToList();
            ProductCategory dhamakaoffer      = new ProductCategory()
            {
                Id           = 4,
                CategoryName = "Dhamaka Offers",
                Priority     = 4
            };

            productCategories.Add(dhamakaoffer);

            var recomendations = _context.Recommendations.SingleOrDefault(c => c.ApplicationUserId == memberId && c.Count == 1);

            if (recomendations != null)
            {
                var id            = recomendations.ProductId;
                var recommendedId = _context.Products.Where(c => c.ProductId == id).Select(c => c.ProductCategoryId).SingleOrDefault();
                if (recommendedId != 0)
                {
                    ProductCategory recommended = new ProductCategory()
                    {
                        Id = recommendedId,
                        CategoryDescription = "Recommendations For You",
                        Priority            = 5
                    };

                    productCategories.Add(recommended);
                }
            }
            //for search history
            recomendations = _context.Recommendations.SingleOrDefault(c => c.ApplicationUserId == memberId && c.Count == 0);
            if (recomendations != null)
            {
                var id            = recomendations.ProductId;
                var recommendedId = _context.Products.Where(c => c.ProductId == id).Select(c => c.ProductCategoryId).SingleOrDefault();
                if (recommendedId != 0)
                {
                    ProductCategory recommended = new ProductCategory()
                    {
                        Id = recommendedId,
                        CategoryDescription = "We inspire from your search",
                        Priority            = 8
                    };
                    productCategories.Add(recommended);
                }
            }

            productCategories = productCategories.OrderBy(x => x.Priority).ToList();

            CategoryProductsViewModel model = new CategoryProductsViewModel()
            {
                UserId   = "",
                UserName = "******",
            };

            if (user != null)
            {
                model.UserId   = user.Id;
                model.UserName = user.FirstName;
            }
            List <Shaska.ViewModel.CategoryProductsViewModel.CategoryProductViewModel> cp = new List <CategoryProductsViewModel.CategoryProductViewModel>();

            for (int a = 0; a < productCategories.Count; a++)
            {
                int            id             = productCategories[a].Id;
                List <Product> listofproducts = _context.Products.Where(c => c.ProductCategoryId == id).ToList();
                for (int c1 = 0; c1 < listofproducts.Count; c1++)
                {
                    id = listofproducts[c1].ProductId;
                    listofproducts[c1].Image = _context.Images.Where(c => c.ProductId == id).ToList();
                }

                Shaska.ViewModel.CategoryProductsViewModel.CategoryProductViewModel categoryproduct = new Shaska.ViewModel.CategoryProductsViewModel.CategoryProductViewModel()
                {
                    ProductCategory = productCategories[a],
                    Products        = listofproducts
                };
                cp.Add(categoryproduct);
            }

            model.CategoriesProductViewModel = cp;

            return(View("Home", model));
        }
Пример #38
0
 public void Insert(ProductCategory p)
 {
     productCategories.Add(p);
 }
        public ActionResult AddProductCategory()
        {
            ProductCategory product = new ProductCategory();

            return(View(product));
        }
Пример #40
0
        protected override void Seed(Orders.Models.OrdersContext context)
        {
            //  This method will be called after migrating to the latest version.

            //  You can use the DbSet<T>.AddOrUpdate() helper extension method 
            //  to avoid creating duplicate seed data. E.g.
            //
            //    context.People.AddOrUpdate(
            //      p => p.FullName,
            //      new Person { FullName = "Andrew Peters" },
            //      new Person { FullName = "Brice Lambson" },
            //      new Person { FullName = "Rowan Miller" }
            //    );
            //

            Product pr1 = new Product { Name = "The Lord of the Rings", Description = "By J.R.R. Tolkien", Price = 15 };
            Product pr2 = new Product { Name = "The Godfather", Description = "By Mario Puzo", Price = 10 };
            Product pr3 = new Product { Name = "The Martian", Description = "By Andy Weir", Price = 9 };
            Product pr4 = new Product { Name = "The Name of the Wind", Description = "By Patrick Rothfuss", Price = 12 };
            Product pr5 = new Product { Name = "Harry Potter and the Sorcerer's Stone", Description = "By J.K. Rowling", Price = 13 };
            Product pr6 = new Product { Name = "To Kill a Mockingbird", Description = "By Harper Lee", Price = 7 };

            Category ct1 = new Category { Name = "Fantasy" };
            Category ct2 = new Category { Name = "Adventure" };
            Category ct3 = new Category { Name = "Drama" };
            Category ct4 = new Category { Name = "Sci-Fi" };
            Category ct5 = new Category { Name = "Kids" };
            Category ct6 = new Category { Name = "Crime" };

            ProductCategory pc1 = new ProductCategory { Product = pr1, Category = ct1 };
            ProductCategory pc2 = new ProductCategory { Product = pr1, Category = ct2 };
            ProductCategory pc3 = new ProductCategory { Product = pr2, Category = ct6 };
            ProductCategory pc4 = new ProductCategory { Product = pr2, Category = ct3 };
            ProductCategory pc5 = new ProductCategory { Product = pr3, Category = ct4 };
            ProductCategory pc6 = new ProductCategory { Product = pr4, Category = ct1 };
            ProductCategory pc7 = new ProductCategory { Product = pr4, Category = ct2 };
            ProductCategory pc8 = new ProductCategory { Product = pr5, Category = ct1 };
            ProductCategory pc9 = new ProductCategory { Product = pr5, Category = ct5 };
            ProductCategory pc10 = new ProductCategory { Product = pr5, Category = ct2 };
            ProductCategory pc11 = new ProductCategory { Product = pr6, Category = ct6 };

            context.ProductCategories.Add(pc1);
            context.ProductCategories.Add(pc2);
            context.ProductCategories.Add(pc3);
            context.ProductCategories.Add(pc4);
            context.ProductCategories.Add(pc5);
            context.ProductCategories.Add(pc6);
            context.ProductCategories.Add(pc7);
            context.ProductCategories.Add(pc8);
            context.ProductCategories.Add(pc9);
            context.ProductCategories.Add(pc10);

            //*******************************************************************************

            OrderStatus os1 = new OrderStatus { Name = "Not Submitted" };
            OrderStatus os2 = new OrderStatus { Name = "Waiting For Delivery" };
            OrderStatus os3 = new OrderStatus { Name = "On It's Way" };
            OrderStatus os4 = new OrderStatus { Name = "Delivered" };

            var td = DateTime.Today;

            ShopOrder so1 = new ShopOrder { OrderStatus = os1, SubmissionDate = td };
            ShopOrder so2 = new ShopOrder { OrderStatus = os2, SubmissionDate = td.AddDays(-4) };
            ShopOrder so3 = new ShopOrder { OrderStatus = os3, SubmissionDate = td.AddDays(-8) };
            ShopOrder so4 = new ShopOrder { OrderStatus = os4, SubmissionDate = td.AddDays(-12) };

            Customer customer = new Customer
            {
                FirstName = "John",
                LastName = "Doe",
                Address = "Birmingham, AL",
                Email = "*****@*****.**",
                Phone = "555-123-4567",
                Orders = new List<ShopOrder> { so1, so2, so3, so4 }
            };

            context.Customers.Add(customer);

            //********************************************************************************************

            ProductOrder po1 = new ProductOrder { Product = pr1, ShopOrder = so1, Quantity = 1 };
            ProductOrder po2 = new ProductOrder { Product = pr2, ShopOrder = so1, Quantity = 2 };
            ProductOrder po3 = new ProductOrder { Product = pr2, ShopOrder = so2, Quantity = 3 };
            ProductOrder po4 = new ProductOrder { Product = pr3, ShopOrder = so3, Quantity = 1 };
            ProductOrder po5 = new ProductOrder { Product = pr4, ShopOrder = so4, Quantity = 1 };
            ProductOrder po6 = new ProductOrder { Product = pr3, ShopOrder = so2, Quantity = 2 };

            context.ProductOrders.Add(po1);
            context.ProductOrders.Add(po2);
            context.ProductOrders.Add(po3);
            context.ProductOrders.Add(po4);
            context.ProductOrders.Add(po5);
            context.ProductOrders.Add(po6);
        }
Пример #41
0
        private IList <Product> GetProducts(string sWhere)
        {
            Product         tmpData  = null;
            IList <Product> list     = new List <Product>();
            IList <Unit>    unitList = GetAllUnits();
            IList <Unit>    curList  = unitList;
            Unit            curUnit;
            ProductCategory curCategory;
            string          flag = "";


            try
            {
                //Lamar los documents que necesita del Erp usando econnect
                //sWhere = string.IsNullOrEmpty(sWhere) ? "ITEMTYPE=1" : "ITEMTYPE=1 AND " + sWhere;

                ds = DynamicsGP_ec.GetDataSet(DynamicsGP_ec.RetreiveData("Item", false, 2, 0, sWhere, true));

                Console.WriteLine(ds.Tables.Count.ToString());

                if (ds.Tables.Count == 0)
                {
                    return(list);
                }

                //Company company = WType.GetDefaultCompany();
                //Status status = WType.GetStatus(new Status { StatusID = EntityStatus.Active });

                //En el dataset, Tables: 1 - Item
                foreach (DataRow dr in ds.Tables[1].Rows)
                {
                    try
                    {
                        //Map Properties
                        tmpData = new Product();

                        flag = "BASE";

                        tmpData.Company     = CurCompany;
                        tmpData.Name        = dr["ITEMDESC"].ToString();
                        tmpData.ProductCode = dr["ITEMNMBR"].ToString();
                        tmpData.Description = dr["ITEMDESC"].ToString();
                        tmpData.IsKit       = (dr["ITEMTYPE"].ToString() == "4") ? true : false;
                        tmpData.ErpTrackOpt = short.Parse(dr["ITMTRKOP"].ToString());

                        tmpData.Manufacturer = dr["ITMSHNAM"].ToString();
                        tmpData.Reference    = dr["ITMGEDSC"].ToString();


                        try { tmpData.CountRank = short.Parse(dr["ABCCODE"].ToString()); }
                        catch { }

                        try { tmpData.ProductCost = double.Parse(dr["CURRCOST"].ToString()); }
                        catch { }

                        tmpData.Status = GetProductStatus(int.Parse(dr["ITEMTYPE"].ToString()));
                        try { tmpData.Weight = double.Parse(dr["ITEMSHWT"].ToString()) / 100; }
                        catch { }

                        //Basic Unit
                        flag                 = "BASEUNIT";
                        curUnit              = new Unit();
                        curUnit.Company      = CurCompany;
                        curUnit.ErpCodeGroup = dr["UOMSCHDL"].ToString();
                        curUnit.BaseAmount   = 1;
                        tmpData.BaseUnit     = WType.GetUnit(curUnit);
                        tmpData.IsFromErp    = true;
                        tmpData.PrintLabel   = true;


                        //Product Category
                        if (!string.IsNullOrEmpty(dr["ITMCLSCD"].ToString()))
                        {
                            flag = "CATEGORY";
                            try
                            {
                                curCategory         = new ProductCategory();
                                curCategory.Company = CurCompany;
                                curCategory.ErpCode = dr["ITMCLSCD"].ToString();
                                tmpData.Category    = WType.GetProductCategory(curCategory);
                            }
                            catch { }
                        }

                        //Purchase Units
                        if (!string.IsNullOrEmpty(dr["PRCHSUOM"].ToString()))
                        {
                            try
                            {
                                curUnit              = new Unit();
                                curUnit.Company      = CurCompany;
                                curUnit.ErpCodeGroup = dr["UOMSCHDL"].ToString();
                                curUnit.ErpCode      = dr["PRCHSUOM"].ToString();
                                tmpData.PurchaseUnit = WType.GetUnit(curUnit);
                            }
                            catch { }
                        }

                        //Sale Unit
                        if (!string.IsNullOrEmpty(dr["SELNGUOM"].ToString()))
                        {
                            try
                            {
                                curUnit              = new Unit();
                                curUnit.Company      = CurCompany;
                                curUnit.ErpCodeGroup = dr["UOMSCHDL"].ToString();
                                curUnit.ErpCode      = dr["SELNGUOM"].ToString();
                                tmpData.SaleUnit     = WType.GetUnit(curUnit);
                            }
                            catch { }
                        }

                        //Obteniendo las unidades que ese producto puede tener
                        flag    = "UNITLIST";
                        curList = unitList.Where(unit => unit.ErpCodeGroup == dr["UOMSCHDL"].ToString()).ToList();

                        flag = "PRODUCT_TRACK";
                        tmpData.ProductTrack = GetProductTrack(int.Parse(dr["ITMTRKOP"].ToString()), tmpData);

                        flag = "PRODUCT_UNITS";
                        tmpData.ProductUnits = GetProductUnits(tmpData, curList);

                        flag = "VENDORS";
                        tmpData.ProductAccounts = GetProductVendors(tmpData);

                        //Productos Alternos.
                        flag = "ALTERN";
                        try
                        {
                            tmpData.AlternProducts = GetAlternateProducts(tmpData, dr["ALTITEM1"].ToString().Trim(),
                                                                          dr["ALTITEM2"].ToString().Trim());
                        }
                        catch (Exception ex) { Console.WriteLine(flag + " " + ex.Message); }

                        list.Add(tmpData);
                    }
                    catch (Exception ex) {
                        Console.WriteLine(flag + " " + ex.Message);
                    }
                }

                return(list);
            }
            catch (Exception ex)
            {
                ExceptionMngr.WriteEvent("GetProducts" + tmpData.ProductCode + "," + flag, ListValues.EventType.Error, ex, null, ListValues.ErrorCategory.ErpConnection);
                //throw;
                return(null);
            }
        }
 public void Update(ProductCategory productCategory)
 {
     _productCategoryRepository.Update(productCategory);
 }
 public ProductCategory Add(ProductCategory productCategory)
 {
     return(_productCategoryRepository.Add(productCategory));
 }
Пример #44
0
 public Product(string name, ProductCategory category)
 {
     Name     = name;
     Category = category;
 }
Пример #45
0
        /// <summary>
        /// Runs the code example.
        /// </summary>
        /// <param name="user">The AdWords user.</param>
        public void Run(AdWordsUser user)
        {
            // Get the ConstantDataService.
            ConstantDataService constantDataService = (ConstantDataService)user.GetService(
                AdWordsService.v201607.ConstantDataService);

            Selector selector = new Selector()
            {
                predicates = new Predicate[] {
                    Predicate.In(ProductBiddingCategoryData.Fields.Country, new string[] { "US" })
                }
            };

            try {
                ProductBiddingCategoryData[] results =
                    constantDataService.getProductBiddingCategoryData(selector);

                Dictionary <long, ProductCategory> biddingCategories =
                    new Dictionary <long, ProductCategory>();
                List <ProductCategory> rootCategories = new List <ProductCategory>();

                foreach (ProductBiddingCategoryData productBiddingCategory in results)
                {
                    long   id       = productBiddingCategory.dimensionValue.value;
                    long   parentId = 0;
                    string name     = productBiddingCategory.displayValue[0].value;

                    if (productBiddingCategory.parentDimensionValue != null)
                    {
                        parentId = productBiddingCategory.parentDimensionValue.value;
                    }

                    if (!biddingCategories.ContainsKey(id))
                    {
                        biddingCategories.Add(id, new ProductCategory());
                    }

                    ProductCategory category = biddingCategories[id];

                    if (parentId != 0)
                    {
                        if (!biddingCategories.ContainsKey(parentId))
                        {
                            biddingCategories.Add(parentId, new ProductCategory());
                        }
                        ProductCategory parent = biddingCategories[parentId];
                        parent.Children.Add(category);
                    }
                    else
                    {
                        rootCategories.Add(category);
                    }

                    category.Id   = id;
                    category.Name = name;
                }

                DisplayProductCategories(rootCategories, "");
            } catch (Exception e) {
                throw new System.ApplicationException("Failed to set shopping product category.", e);
            }
        }
Пример #46
0
 public ProductCategory Add(ProductCategory model)
 {
     return(_productCategoryRepository.Add(model));
 }
Пример #47
0
        public ProductCategory ProductsForCategory(String guid)
        {
            ProductCategory cat = this.ProductCategoryForGuid(guid);

            return(this.ProductsForCategory(cat));
        }
Пример #48
0
        private void setUpMocks()
        {
            fridgeProductForDbSetList = new List <FridgeProduct>();
            recipeProductForDbSetList = new List <RecipeProduct>();
            recipeForDbSetList        = new List <Recipe>();


            user = new User
            {
                Id      = Guid.NewGuid(),
                Fridges = new List <Fridge>()
            };

            recipe1 = new Recipe
            {
                Id             = Guid.NewGuid(),
                Title          = "Recipe1",
                UserId         = user.Id,
                Description    = "test",
                RecipeProducts = new List <RecipeProduct>()
            };
            recipe2 = new Recipe
            {
                Id             = Guid.NewGuid(),
                Title          = "Recipe2",
                UserId         = user.Id,
                Description    = "test",
                RecipeProducts = new List <RecipeProduct>()
            };
            recipe3 = new Recipe
            {
                Id             = Guid.NewGuid(),
                Title          = "Recipe3",
                UserId         = user.Id,
                Description    = "test",
                RecipeProducts = new List <RecipeProduct>()
            };
            recipe4 = new Recipe
            {
                Id             = Guid.NewGuid(),
                Title          = "Recipe4",
                UserId         = user.Id,
                Description    = "test",
                RecipeProducts = new List <RecipeProduct>()
            };

            productCategory = new ProductCategory
            {
                Id   = Guid.NewGuid(),
                Name = "ProductCategory1"
            };

            product1 = new Product
            {
                Id   = Guid.NewGuid(),
                Name = "Product1",
                ProductCategoryId = productCategory.Id,
                Description       = "test"
            };
            product2 = new Product
            {
                Id   = Guid.NewGuid(),
                Name = "Product2",
                ProductCategoryId = productCategory.Id,
                Description       = "test"
            };
            product3 = new Product
            {
                Id   = Guid.NewGuid(),
                Name = "Product3",
                ProductCategoryId = productCategory.Id,
                Description       = "test"
            };
            product4 = new Product
            {
                Id   = Guid.NewGuid(),
                Name = "Product4",
                ProductCategoryId = productCategory.Id,
                Description       = "test"
            };

            fridge = new Fridge
            {
                Id             = Guid.NewGuid(),
                UserId         = user.Id,
                FridgeProducts = new List <FridgeProduct>()
            };

            fridgeProduct1 = new FridgeProduct
            {
                Id        = Guid.NewGuid(),
                FridgeId  = fridge.Id,
                ProductId = product1.Id
            };
            fridgeProduct2 = new FridgeProduct
            {
                Id        = Guid.NewGuid(),
                FridgeId  = fridge.Id,
                ProductId = product2.Id
            };
            fridgeProduct3 = new FridgeProduct
            {
                Id        = Guid.NewGuid(),
                FridgeId  = fridge.Id,
                ProductId = product3.Id
            };
            fridgeProduct4 = new FridgeProduct
            {
                Id        = Guid.NewGuid(),
                FridgeId  = fridge.Id,
                ProductId = product4.Id
            };

            recipe1Product1 = new RecipeProduct
            {
                Id        = Guid.NewGuid(),
                ProductId = product1.Id,
                RecipeId  = recipe1.Id,
                Recipe    = recipe1,
                Product   = product1
            };
            recipe1Product2 = new RecipeProduct
            {
                Id        = Guid.NewGuid(),
                ProductId = product2.Id,
                RecipeId  = recipe1.Id,
                Recipe    = recipe1,
                Product   = product2
            };
            recipe1Product3 = new RecipeProduct
            {
                Id        = Guid.NewGuid(),
                ProductId = product3.Id,
                RecipeId  = recipe1.Id,
                Recipe    = recipe1,
                Product   = product3
            };
            recipe1Product4 = new RecipeProduct
            {
                Id        = Guid.NewGuid(),
                ProductId = product4.Id,
                RecipeId  = recipe1.Id,
                Recipe    = recipe1,
                Product   = product4
            };

            recipe2Product1 = new RecipeProduct
            {
                Id        = Guid.NewGuid(),
                ProductId = product1.Id,
                RecipeId  = recipe2.Id,
                Recipe    = recipe2,
                Product   = product1
            };
            recipe2Product2 = new RecipeProduct
            {
                Id        = Guid.NewGuid(),
                ProductId = product2.Id,
                RecipeId  = recipe2.Id,
                Recipe    = recipe2,
                Product   = product2
            };
            recipe2Product3 = new RecipeProduct
            {
                Id        = Guid.NewGuid(),
                ProductId = product3.Id,
                RecipeId  = recipe2.Id,
                Recipe    = recipe2,
                Product   = product3
            };
            recipe2Product4 = new RecipeProduct
            {
                Id        = Guid.NewGuid(),
                ProductId = product4.Id,
                RecipeId  = recipe2.Id,
                Recipe    = recipe2,
                Product   = product4
            };

            recipe3Product1 = new RecipeProduct
            {
                Id        = Guid.NewGuid(),
                ProductId = product1.Id,
                RecipeId  = recipe3.Id,
                Recipe    = recipe3,
                Product   = product1
            };
            recipe3Product2 = new RecipeProduct
            {
                Id        = Guid.NewGuid(),
                ProductId = product2.Id,
                RecipeId  = recipe3.Id,
                Recipe    = recipe3,
                Product   = product2
            };
            recipe3Product3 = new RecipeProduct
            {
                Id        = Guid.NewGuid(),
                ProductId = product3.Id,
                RecipeId  = recipe3.Id,
                Recipe    = recipe3,
                Product   = product3
            };
            recipe3Product4 = new RecipeProduct
            {
                Id        = Guid.NewGuid(),
                ProductId = product4.Id,
                RecipeId  = recipe3.Id,
                Recipe    = recipe3,
                Product   = product4
            };

            recipe4Product1 = new RecipeProduct
            {
                Id        = Guid.NewGuid(),
                ProductId = product1.Id,
                RecipeId  = recipe4.Id,
                Recipe    = recipe4,
                Product   = product1
            };
            recipe4Product2 = new RecipeProduct
            {
                Id        = Guid.NewGuid(),
                ProductId = product2.Id,
                RecipeId  = recipe4.Id,
                Recipe    = recipe4,
                Product   = product2
            };
            recipe4Product3 = new RecipeProduct
            {
                Id        = Guid.NewGuid(),
                ProductId = product3.Id,
                RecipeId  = recipe4.Id,
                Recipe    = recipe4,
                Product   = product3
            };
            recipe4Product4 = new RecipeProduct
            {
                Id        = Guid.NewGuid(),
                ProductId = product4.Id,
                RecipeId  = recipe4.Id,
                Recipe    = recipe4,
                Product   = product4
            };
        }
Пример #49
0
 public bool Add(ProductCategory productCategory)
 {
     return(repository.Add(productCategory));
 }
Пример #50
0
 public async Task <CategoryService> AddAsync(ProductCategory category)
 {
 }
Пример #51
0
        public virtual void TestDeleteListElements2()
        {
            string baseName = GetBaseName();

            NeoDatis.Odb.ODB odb     = Open(baseName);
            Catalog          catalog = new Catalog
                                           ("Fnac");
            ProductCategory books = new ProductCategory
                                        ("Books");

            books.GetProducts().Add(new Product
                                        ("Book1", new System.Decimal(10.1)));
            books.GetProducts().Add(new Product
                                        ("Book2", new System.Decimal(10.2)));
            books.GetProducts().Add(new Product
                                        ("Book3", new System.Decimal(10.3)));
            ProductCategory computers = new ProductCategory
                                            ("Computers");

            computers.GetProducts().Add(new Product
                                            ("MacBook", new System.Decimal(1300.1)));
            computers.GetProducts().Add(new Product
                                            ("BookBookPro", new System.Decimal(2000.2)));
            computers.GetProducts().Add(new Product
                                            ("MacMini", new System.Decimal(1000.3)));
            catalog.GetCategories().Add(books);
            catalog.GetCategories().Add(computers);
            odb.Store(catalog);
            odb.Close();
            odb = Open(baseName);
            NeoDatis.Odb.Objects objects = odb.GetObjects(typeof(Catalog
                                                                 ));
            Println(objects.Count + " catalog(s)");
            while (objects.HasNext())
            {
                Catalog c = (Catalog
                             )objects.Next();
                System.Collections.IList pCategories = c.GetCategories();
                Println(c.GetCategories().Count + " product categories");
                for (int j = 0; j < pCategories.Count; j++)
                {
                    ProductCategory pc = (ProductCategory
                                          )pCategories[j];
                    Println("\tProduct Category : " + pc.GetName() + " : " + pc.GetProducts().Count +
                            " products");
                    for (int k = 0; k < pc.GetProducts().Count; k++)
                    {
                        Product p = pc.GetProducts()[k];
                        Println("\t\tProduct " + p.GetName());
                        odb.Delete(p);
                    }
                    odb.Delete(pc);
                }
                odb.Delete(c);
            }
            odb.Close();
            odb = Open(baseName);
            NeoDatis.Odb.Objects <Catalog>         catalogs          = odb.GetObjects <Catalog>();
            NeoDatis.Odb.Objects <ProductCategory> productCategories = odb.GetObjects <ProductCategory>();
            NeoDatis.Odb.Objects <Product>         products          = odb.GetObjects <Product>();
            AssertTrue(catalogs.Count == 0);
            AssertTrue(productCategories.Count == 0);
            AssertTrue(products.Count == 0);
            DeleteBase(baseName);
        }
Пример #52
0
        public void CreateProduct_SuccessTest()
        {
            #region define product
            var product = new Good();
            #endregion

            #region define product category
            var category1 = new ProductCategory()
            {
                Name = "Category 1"
            };
            var category1_1 = new ProductCategory()
            {
                Name = "Category 1.1"
            };
            var category2 = new ProductCategory()
            {
                Name = "Category 2"
            };
            #endregion

            #region bind categories with product
            var clasificatin1 = new ProductCategoryClassification();
            clasificatin1.ProductCategory = category1_1;
            clasificatin1.Product         = product;
            clasificatin1.FromDate        = DateTime.Now;
            clasificatin1.ThruDate        = DateTime.Now;

            var clasificatin2 = new ProductCategoryClassification();
            clasificatin2.ProductCategory = category2;
            clasificatin2.Product         = product;
            clasificatin2.FromDate        = DateTime.Now;
            clasificatin2.ThruDate        = DateTime.Now;
            clasificatin2.PrimaryFlag     = true;
            #endregion

            #region define subcategory
            var rollup = new ProductCategoryRollup
            {
                Name = "Subcategory"
            };
            rollup.CategoriesOwner.Add(category1);
            rollup.CategoriesChild.Add(category1_1);
            #endregion

            #region define product features
            var featureCategory = new ProductFeatureCategory()
            {
                Id = "1", Name = "feature category"
            };

            var optionalFeatures = new ProductFeatureApplicability
            {
                Product           = product,
                ApplicabilityType = FeatureApplicabilityType.OptionalFeature
            };
            var colorFeature = new ProductFeature
            {
                Name = "Color",
                ProductFeatureCategory = featureCategory
            };
            //colorFeature.UnitOfMeasure = UnitOfMeasure.
            optionalFeatures.ProductFeature.Add(colorFeature);

            var sizeFeature = new ProductFeature
            {
                Name = "Size",
                ProductFeatureCategory = featureCategory
            };
            sizeFeature.UnitOfMeasure = UnitOfMeasure.Santimeter;
            optionalFeatures.ProductFeature.Add(sizeFeature);

            var hardwareFeatures = new ProductFeatureApplicability
            {
                Product           = product,
                ApplicabilityType = FeatureApplicabilityType.RequiredFeature
            };
            hardwareFeatures.ProductFeature.Add(ProductFeature.HardwareFeature);
            #endregion

            #region define relationship dependence for product features
            var c = new ProductFeatureInteraction
            {
                Product = product
            };
            c.ProductFeatures1.Add(colorFeature);
            c.ProductFeatures2.Add(sizeFeature);
            c.ProductInteractionType = ProductInteractionType.Dependency;
            #endregion
        }
Пример #53
0
 public void Update(ProductCategory model)
 {
     _productCategoryRepository.Update(model);
 }
        public async Task <ActionResult> UpdateProduct([FromForm] ProductDTO req)
        {
            var options = new JsonSerializerOptions
            {
                PropertyNameCaseInsensitive = true,
            };
            //json으로 전송된 제품 정보를 객체로 역직렬화
            var product = JsonSerializer.Deserialize <Product>(req.Product, options);

            long id = 0;

            if (!long.TryParse(req.Id, out id))
            {
                return(BadRequest());
            }

            //업로드된 이미지들을 /images/products로 옮기고
            //옮긴 경로를 목록으로 가져오기
            var pis = await GetProductImages(id, req.Photos);

            //기존 이미지 경로 목록에 업로드된 목록을 합친다
            product.PhotoUrls.AddRange(
                pis.Select(pi => pi.PhotoUrl));

            //DB에서 기존에 등록된 이미지 목록 가져오기
            var productImages = _context.ProductImages
                                .Where(pi => pi.ProductId == id);

            //기존에는 있었지만 없어진 이미지는 삭제
            var toDeleteProductImageList = productImages
                                           .Where(pi => product.PhotoUrls.Contains(pi.PhotoUrl) == false);

            _context.ProductImages.RemoveRange(toDeleteProductImageList);

            foreach (var pu in product.PhotoUrls)
            {
                var _pi = await productImages
                          .FirstOrDefaultAsync(pi => pi.PhotoUrl == pu);

                if (_pi == null)
                {
                    //기존에 없던 항목들은 새로 추가
                    _pi = new ProductImage
                    {
                        PhotoUrl  = pu,
                        ProductId = product.Id
                    };
                    await _context.ProductImages.AddAsync(_pi);
                }
            }

            //product 엔티티를 수정된 상태로 설정
            //수정된 내용을 자동으로 체크해서 DB에 업데이트 해준다.
            _context.Entry(product).State = EntityState.Modified;
            //CreatedDate는 수정되지 않도록 설정
            _context.Entry(product).Property(p => p.CreatedDate).IsModified = false;

            //DB에서 제품에 대한 기존의 Category목록 가져오기
            var productCategories = _context.ProductCategories
                                    .Where(pc => pc.ProductId == id);

            //기존에는 있었지만 수정된 카테고리 목록에 없는 것들은 삭제
            var toDeleteProductCategoryList = productCategories
                                              .Where(pc => product.CategoryIds.Contains(pc.CategoryId) == false);

            _context.ProductCategories.RemoveRange(toDeleteProductCategoryList);

            foreach (var cid in product.CategoryIds)
            {
                var _pc = await productCategories
                          .FirstOrDefaultAsync(pc => pc.ProductId == id && pc.CategoryId == cid);

                if (_pc == null)
                {
                    var sortOrder = await productCategories.Where(pc => pc.ProductId == id).CountAsync();

                    //기존에 없던 항목들은 새로 추가
                    _pc = new ProductCategory
                    {
                        CategoryId = cid,
                        ProductId  = product.Id,
                        SortOrder  = sortOrder
                    };
                    await _context.ProductCategories.AddAsync(_pc);
                }
            }

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!ProductExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(Ok(new
            {
                Id = product.Id
            }));
        }
Пример #55
0
 public static int Insert(ProductCategory ProductCategory)
 {
     return(WebApi <int> .PostAsync(controllerName, ProductCategory, "SinglePost").Result);
 }
 public void AddProductCategory(ProductCategory productCategory)
 {
     _context.ProductCategories.Add(productCategory);
 }
Пример #57
0
 public static bool Update(ProductCategory ProductCategory)
 {
     return(WebApi <bool> .PutAsync(controllerName, ProductCategory, "Put").Result);
 }
Пример #58
0
        public ActionResult Create()
        {
            ProductCategory productCategory = new ProductCategory();

            return(View(productCategory));
        }
 public void DeleteProductCategory(ProductCategory productCategory)
 {
     _context.ProductCategories.Remove(productCategory);
 }
Пример #60
0
        /// <summary>
        /// Import products from XLSX file
        /// </summary>
        /// <param name="stream">Stream</param>
        public virtual void ImportProductsFromXlsx(Stream stream)
        {
            // ok, we can run the real code of the sample now
            using (var xlPackage = new ExcelPackage(stream))
            {
                // get the first worksheet in the workbook
                var worksheet = xlPackage.Workbook.Worksheets.FirstOrDefault();
                if (worksheet == null)
                {
                    throw new NopException("No worksheet found");
                }

                //the columns
                var properties = new []
                {
                    "ProductTypeId",
                    "ParentGroupedProductId",
                    "VisibleIndividually",
                    "Name",
                    "ShortDescription",
                    "FullDescription",
                    "VendorId",
                    "ProductTemplateId",
                    "ShowOnHomePage",
                    "MetaKeywords",
                    "MetaDescription",
                    "MetaTitle",
                    "SeName",
                    "AllowCustomerReviews",
                    "Published",
                    "SKU",
                    "ManufacturerPartNumber",
                    "Gtin",
                    "IsGiftCard",
                    "GiftCardTypeId",
                    "RequireOtherProducts",
                    "RequiredProductIds",
                    "AutomaticallyAddRequiredProducts",
                    "IsDownload",
                    "DownloadId",
                    "UnlimitedDownloads",
                    "MaxNumberOfDownloads",
                    "DownloadActivationTypeId",
                    "HasSampleDownload",
                    "SampleDownloadId",
                    "HasUserAgreement",
                    "UserAgreementText",
                    "IsRecurring",
                    "RecurringCycleLength",
                    "RecurringCyclePeriodId",
                    "RecurringTotalCycles",
                    "IsRental",
                    "RentalPriceLength",
                    "RentalPricePeriodId",
                    "IsShipEnabled",
                    "IsFreeShipping",
                    "ShipSeparately",
                    "AdditionalShippingCharge",
                    "DeliveryDateId",
                    "IsTaxExempt",
                    "TaxCategoryId",
                    "IsTelecommunicationsOrBroadcastingOrElectronicServices",
                    "ManageInventoryMethodId",
                    "UseMultipleWarehouses",
                    "WarehouseId",
                    "StockQuantity",
                    "DisplayStockAvailability",
                    "DisplayStockQuantity",
                    "MinStockQuantity",
                    "LowStockActivityId",
                    "NotifyAdminForQuantityBelow",
                    "BackorderModeId",
                    "AllowBackInStockSubscriptions",
                    "OrderMinimumQuantity",
                    "OrderMaximumQuantity",
                    "AllowedQuantities",
                    "AllowAddingOnlyExistingAttributeCombinations",
                    "DisableBuyButton",
                    "DisableWishlistButton",
                    "AvailableForPreOrder",
                    "PreOrderAvailabilityStartDateTimeUtc",
                    "CallForPrice",
                    "Price",
                    "OldPrice",
                    "ProductCost",
                    "SpecialPrice",
                    "SpecialPriceStartDateTimeUtc",
                    "SpecialPriceEndDateTimeUtc",
                    "CustomerEntersPrice",
                    "MinimumCustomerEnteredPrice",
                    "MaximumCustomerEnteredPrice",
                    "BasepriceEnabled",
                    "BasepriceAmount",
                    "BasepriceUnitId",
                    "BasepriceBaseAmount",
                    "BasepriceBaseUnitId",
                    "Weight",
                    "Length",
                    "Width",
                    "Height",
                    "CreatedOnUtc",
                    "CategoryIds",
                    "ManufacturerIds",
                    "Picture1",
                    "Picture2",
                    "Picture3"
                };


                int iRow = 2;
                while (true)
                {
                    bool allColumnsAreEmpty = true;
                    for (var i = 1; i <= properties.Length; i++)
                    {
                        if (worksheet.Cells[iRow, i].Value != null && !String.IsNullOrEmpty(worksheet.Cells[iRow, i].Value.ToString()))
                        {
                            allColumnsAreEmpty = false;
                            break;
                        }
                    }
                    if (allColumnsAreEmpty)
                    {
                        break;
                    }

                    int      productTypeId          = Convert.ToInt32(worksheet.Cells[iRow, GetColumnIndex(properties, "ProductTypeId")].Value);
                    int      parentGroupedProductId = Convert.ToInt32(worksheet.Cells[iRow, GetColumnIndex(properties, "ParentGroupedProductId")].Value);
                    bool     visibleIndividually    = Convert.ToBoolean(worksheet.Cells[iRow, GetColumnIndex(properties, "VisibleIndividually")].Value);
                    string   name                 = ConvertColumnToString(worksheet.Cells[iRow, GetColumnIndex(properties, "Name")].Value);
                    string   shortDescription     = ConvertColumnToString(worksheet.Cells[iRow, GetColumnIndex(properties, "ShortDescription")].Value);
                    string   fullDescription      = ConvertColumnToString(worksheet.Cells[iRow, GetColumnIndex(properties, "FullDescription")].Value);
                    int      vendorId             = Convert.ToInt32(worksheet.Cells[iRow, GetColumnIndex(properties, "VendorId")].Value);
                    int      productTemplateId    = Convert.ToInt32(worksheet.Cells[iRow, GetColumnIndex(properties, "ProductTemplateId")].Value);
                    bool     showOnHomePage       = Convert.ToBoolean(worksheet.Cells[iRow, GetColumnIndex(properties, "ShowOnHomePage")].Value);
                    string   metaKeywords         = ConvertColumnToString(worksheet.Cells[iRow, GetColumnIndex(properties, "MetaKeywords")].Value);
                    string   metaDescription      = ConvertColumnToString(worksheet.Cells[iRow, GetColumnIndex(properties, "MetaDescription")].Value);
                    string   metaTitle            = ConvertColumnToString(worksheet.Cells[iRow, GetColumnIndex(properties, "MetaTitle")].Value);
                    string   seName               = ConvertColumnToString(worksheet.Cells[iRow, GetColumnIndex(properties, "SeName")].Value);
                    bool     allowCustomerReviews = Convert.ToBoolean(worksheet.Cells[iRow, GetColumnIndex(properties, "AllowCustomerReviews")].Value);
                    bool     published            = Convert.ToBoolean(worksheet.Cells[iRow, GetColumnIndex(properties, "Published")].Value);
                    string   sku = ConvertColumnToString(worksheet.Cells[iRow, GetColumnIndex(properties, "SKU")].Value);
                    string   manufacturerPartNumber = ConvertColumnToString(worksheet.Cells[iRow, GetColumnIndex(properties, "ManufacturerPartNumber")].Value);
                    string   gtin                             = ConvertColumnToString(worksheet.Cells[iRow, GetColumnIndex(properties, "Gtin")].Value);
                    bool     isGiftCard                       = Convert.ToBoolean(worksheet.Cells[iRow, GetColumnIndex(properties, "IsGiftCard")].Value);
                    int      giftCardTypeId                   = Convert.ToInt32(worksheet.Cells[iRow, GetColumnIndex(properties, "GiftCardTypeId")].Value);
                    bool     requireOtherProducts             = Convert.ToBoolean(worksheet.Cells[iRow, GetColumnIndex(properties, "RequireOtherProducts")].Value);
                    string   requiredProductIds               = ConvertColumnToString(worksheet.Cells[iRow, GetColumnIndex(properties, "RequiredProductIds")].Value);
                    bool     automaticallyAddRequiredProducts = Convert.ToBoolean(worksheet.Cells[iRow, GetColumnIndex(properties, "AutomaticallyAddRequiredProducts")].Value);
                    bool     isDownload                       = Convert.ToBoolean(worksheet.Cells[iRow, GetColumnIndex(properties, "IsDownload")].Value);
                    int      downloadId                       = Convert.ToInt32(worksheet.Cells[iRow, GetColumnIndex(properties, "DownloadId")].Value);
                    bool     unlimitedDownloads               = Convert.ToBoolean(worksheet.Cells[iRow, GetColumnIndex(properties, "UnlimitedDownloads")].Value);
                    int      maxNumberOfDownloads             = Convert.ToInt32(worksheet.Cells[iRow, GetColumnIndex(properties, "MaxNumberOfDownloads")].Value);
                    int      downloadActivationTypeId         = Convert.ToInt32(worksheet.Cells[iRow, GetColumnIndex(properties, "DownloadActivationTypeId")].Value);
                    bool     hasSampleDownload                = Convert.ToBoolean(worksheet.Cells[iRow, GetColumnIndex(properties, "HasSampleDownload")].Value);
                    int      sampleDownloadId                 = Convert.ToInt32(worksheet.Cells[iRow, GetColumnIndex(properties, "SampleDownloadId")].Value);
                    bool     hasUserAgreement                 = Convert.ToBoolean(worksheet.Cells[iRow, GetColumnIndex(properties, "HasUserAgreement")].Value);
                    string   userAgreementText                = ConvertColumnToString(worksheet.Cells[iRow, GetColumnIndex(properties, "UserAgreementText")].Value);
                    bool     isRecurring                      = Convert.ToBoolean(worksheet.Cells[iRow, GetColumnIndex(properties, "IsRecurring")].Value);
                    int      recurringCycleLength             = Convert.ToInt32(worksheet.Cells[iRow, GetColumnIndex(properties, "RecurringCycleLength")].Value);
                    int      recurringCyclePeriodId           = Convert.ToInt32(worksheet.Cells[iRow, GetColumnIndex(properties, "RecurringCyclePeriodId")].Value);
                    int      recurringTotalCycles             = Convert.ToInt32(worksheet.Cells[iRow, GetColumnIndex(properties, "RecurringTotalCycles")].Value);
                    bool     isRental                         = Convert.ToBoolean(worksheet.Cells[iRow, GetColumnIndex(properties, "IsRental")].Value);
                    int      rentalPriceLength                = Convert.ToInt32(worksheet.Cells[iRow, GetColumnIndex(properties, "RentalPriceLength")].Value);
                    int      rentalPricePeriodId              = Convert.ToInt32(worksheet.Cells[iRow, GetColumnIndex(properties, "RentalPricePeriodId")].Value);
                    bool     isShipEnabled                    = Convert.ToBoolean(worksheet.Cells[iRow, GetColumnIndex(properties, "IsShipEnabled")].Value);
                    bool     isFreeShipping                   = Convert.ToBoolean(worksheet.Cells[iRow, GetColumnIndex(properties, "IsFreeShipping")].Value);
                    bool     shipSeparately                   = Convert.ToBoolean(worksheet.Cells[iRow, GetColumnIndex(properties, "ShipSeparately")].Value);
                    decimal  additionalShippingCharge         = Convert.ToDecimal(worksheet.Cells[iRow, GetColumnIndex(properties, "AdditionalShippingCharge")].Value);
                    int      deliveryDateId                   = Convert.ToInt32(worksheet.Cells[iRow, GetColumnIndex(properties, "DeliveryDateId")].Value);
                    bool     isTaxExempt                      = Convert.ToBoolean(worksheet.Cells[iRow, GetColumnIndex(properties, "IsTaxExempt")].Value);
                    int      taxCategoryId                    = Convert.ToInt32(worksheet.Cells[iRow, GetColumnIndex(properties, "TaxCategoryId")].Value);
                    bool     isTelecommunicationsOrBroadcastingOrElectronicServices = Convert.ToBoolean(worksheet.Cells[iRow, GetColumnIndex(properties, "IsTelecommunicationsOrBroadcastingOrElectronicServices")].Value);
                    int      manageInventoryMethodId       = Convert.ToInt32(worksheet.Cells[iRow, GetColumnIndex(properties, "ManageInventoryMethodId")].Value);
                    bool     useMultipleWarehouses         = Convert.ToBoolean(worksheet.Cells[iRow, GetColumnIndex(properties, "UseMultipleWarehouses")].Value);
                    int      warehouseId                   = Convert.ToInt32(worksheet.Cells[iRow, GetColumnIndex(properties, "WarehouseId")].Value);
                    int      stockQuantity                 = Convert.ToInt32(worksheet.Cells[iRow, GetColumnIndex(properties, "StockQuantity")].Value);
                    bool     displayStockAvailability      = Convert.ToBoolean(worksheet.Cells[iRow, GetColumnIndex(properties, "DisplayStockAvailability")].Value);
                    bool     displayStockQuantity          = Convert.ToBoolean(worksheet.Cells[iRow, GetColumnIndex(properties, "DisplayStockQuantity")].Value);
                    int      minStockQuantity              = Convert.ToInt32(worksheet.Cells[iRow, GetColumnIndex(properties, "MinStockQuantity")].Value);
                    int      lowStockActivityId            = Convert.ToInt32(worksheet.Cells[iRow, GetColumnIndex(properties, "LowStockActivityId")].Value);
                    int      notifyAdminForQuantityBelow   = Convert.ToInt32(worksheet.Cells[iRow, GetColumnIndex(properties, "NotifyAdminForQuantityBelow")].Value);
                    int      backorderModeId               = Convert.ToInt32(worksheet.Cells[iRow, GetColumnIndex(properties, "BackorderModeId")].Value);
                    bool     allowBackInStockSubscriptions = Convert.ToBoolean(worksheet.Cells[iRow, GetColumnIndex(properties, "AllowBackInStockSubscriptions")].Value);
                    int      orderMinimumQuantity          = Convert.ToInt32(worksheet.Cells[iRow, GetColumnIndex(properties, "OrderMinimumQuantity")].Value);
                    int      orderMaximumQuantity          = Convert.ToInt32(worksheet.Cells[iRow, GetColumnIndex(properties, "OrderMaximumQuantity")].Value);
                    string   allowedQuantities             = ConvertColumnToString(worksheet.Cells[iRow, GetColumnIndex(properties, "AllowedQuantities")].Value);
                    bool     allowAddingOnlyExistingAttributeCombinations = Convert.ToBoolean(worksheet.Cells[iRow, GetColumnIndex(properties, "AllowAddingOnlyExistingAttributeCombinations")].Value);
                    bool     disableBuyButton      = Convert.ToBoolean(worksheet.Cells[iRow, GetColumnIndex(properties, "DisableBuyButton")].Value);
                    bool     disableWishlistButton = Convert.ToBoolean(worksheet.Cells[iRow, GetColumnIndex(properties, "DisableWishlistButton")].Value);
                    bool     availableForPreOrder  = Convert.ToBoolean(worksheet.Cells[iRow, GetColumnIndex(properties, "AvailableForPreOrder")].Value);
                    DateTime?preOrderAvailabilityStartDateTimeUtc      = null;
                    var      preOrderAvailabilityStartDateTimeUtcExcel = worksheet.Cells[iRow, GetColumnIndex(properties, "PreOrderAvailabilityStartDateTimeUtc")].Value;
                    if (preOrderAvailabilityStartDateTimeUtcExcel != null)
                    {
                        preOrderAvailabilityStartDateTimeUtc = DateTime.FromOADate(Convert.ToDouble(preOrderAvailabilityStartDateTimeUtcExcel));
                    }
                    bool    callForPrice      = Convert.ToBoolean(worksheet.Cells[iRow, GetColumnIndex(properties, "CallForPrice")].Value);
                    decimal price             = Convert.ToDecimal(worksheet.Cells[iRow, GetColumnIndex(properties, "Price")].Value);
                    decimal oldPrice          = Convert.ToDecimal(worksheet.Cells[iRow, GetColumnIndex(properties, "OldPrice")].Value);
                    decimal productCost       = Convert.ToDecimal(worksheet.Cells[iRow, GetColumnIndex(properties, "ProductCost")].Value);
                    decimal?specialPrice      = null;
                    var     specialPriceExcel = worksheet.Cells[iRow, GetColumnIndex(properties, "SpecialPrice")].Value;
                    if (specialPriceExcel != null)
                    {
                        specialPrice = Convert.ToDecimal(specialPriceExcel);
                    }
                    DateTime?specialPriceStartDateTimeUtc      = null;
                    var      specialPriceStartDateTimeUtcExcel = worksheet.Cells[iRow, GetColumnIndex(properties, "SpecialPriceStartDateTimeUtc")].Value;
                    if (specialPriceStartDateTimeUtcExcel != null)
                    {
                        specialPriceStartDateTimeUtc = DateTime.FromOADate(Convert.ToDouble(specialPriceStartDateTimeUtcExcel));
                    }
                    DateTime?specialPriceEndDateTimeUtc      = null;
                    var      specialPriceEndDateTimeUtcExcel = worksheet.Cells[iRow, GetColumnIndex(properties, "SpecialPriceEndDateTimeUtc")].Value;
                    if (specialPriceEndDateTimeUtcExcel != null)
                    {
                        specialPriceEndDateTimeUtc = DateTime.FromOADate(Convert.ToDouble(specialPriceEndDateTimeUtcExcel));
                    }

                    bool     customerEntersPrice         = Convert.ToBoolean(worksheet.Cells[iRow, GetColumnIndex(properties, "CustomerEntersPrice")].Value);
                    decimal  minimumCustomerEnteredPrice = Convert.ToDecimal(worksheet.Cells[iRow, GetColumnIndex(properties, "MinimumCustomerEnteredPrice")].Value);
                    decimal  maximumCustomerEnteredPrice = Convert.ToDecimal(worksheet.Cells[iRow, GetColumnIndex(properties, "MaximumCustomerEnteredPrice")].Value);
                    bool     basepriceEnabled            = Convert.ToBoolean(worksheet.Cells[iRow, GetColumnIndex(properties, "BasepriceEnabled")].Value);
                    decimal  basepriceAmount             = Convert.ToDecimal(worksheet.Cells[iRow, GetColumnIndex(properties, "BasepriceAmount")].Value);
                    int      basepriceUnitId             = Convert.ToInt32(worksheet.Cells[iRow, GetColumnIndex(properties, "BasepriceUnitId")].Value);
                    decimal  basepriceBaseAmount         = Convert.ToDecimal(worksheet.Cells[iRow, GetColumnIndex(properties, "BasepriceBaseAmount")].Value);
                    int      basepriceBaseUnitId         = Convert.ToInt32(worksheet.Cells[iRow, GetColumnIndex(properties, "BasepriceBaseUnitId")].Value);
                    decimal  weight          = Convert.ToDecimal(worksheet.Cells[iRow, GetColumnIndex(properties, "Weight")].Value);
                    decimal  length          = Convert.ToDecimal(worksheet.Cells[iRow, GetColumnIndex(properties, "Length")].Value);
                    decimal  width           = Convert.ToDecimal(worksheet.Cells[iRow, GetColumnIndex(properties, "Width")].Value);
                    decimal  height          = Convert.ToDecimal(worksheet.Cells[iRow, GetColumnIndex(properties, "Height")].Value);
                    DateTime createdOnUtc    = DateTime.FromOADate(Convert.ToDouble(worksheet.Cells[iRow, GetColumnIndex(properties, "CreatedOnUtc")].Value));
                    string   categoryIds     = ConvertColumnToString(worksheet.Cells[iRow, GetColumnIndex(properties, "CategoryIds")].Value);
                    string   manufacturerIds = ConvertColumnToString(worksheet.Cells[iRow, GetColumnIndex(properties, "ManufacturerIds")].Value);
                    string   picture1        = ConvertColumnToString(worksheet.Cells[iRow, GetColumnIndex(properties, "Picture1")].Value);
                    string   picture2        = ConvertColumnToString(worksheet.Cells[iRow, GetColumnIndex(properties, "Picture2")].Value);
                    string   picture3        = ConvertColumnToString(worksheet.Cells[iRow, GetColumnIndex(properties, "Picture3")].Value);



                    var  product    = _productService.GetProductBySku(sku);
                    bool newProduct = false;
                    if (product == null)
                    {
                        product    = new Product();
                        newProduct = true;
                    }
                    product.ProductTypeId          = productTypeId;
                    product.ParentGroupedProductId = parentGroupedProductId;
                    product.VisibleIndividually    = visibleIndividually;
                    product.Name                 = name;
                    product.ShortDescription     = shortDescription;
                    product.FullDescription      = fullDescription;
                    product.VendorId             = vendorId;
                    product.ProductTemplateId    = productTemplateId;
                    product.ShowOnHomePage       = showOnHomePage;
                    product.MetaKeywords         = metaKeywords;
                    product.MetaDescription      = metaDescription;
                    product.MetaTitle            = metaTitle;
                    product.AllowCustomerReviews = allowCustomerReviews;
                    product.Sku = sku;
                    product.ManufacturerPartNumber = manufacturerPartNumber;
                    product.Gtin                             = gtin;
                    product.IsGiftCard                       = isGiftCard;
                    product.GiftCardTypeId                   = giftCardTypeId;
                    product.RequireOtherProducts             = requireOtherProducts;
                    product.RequiredProductIds               = requiredProductIds;
                    product.AutomaticallyAddRequiredProducts = automaticallyAddRequiredProducts;
                    product.IsDownload                       = isDownload;
                    product.DownloadId                       = downloadId;
                    product.UnlimitedDownloads               = unlimitedDownloads;
                    product.MaxNumberOfDownloads             = maxNumberOfDownloads;
                    product.DownloadActivationTypeId         = downloadActivationTypeId;
                    product.HasSampleDownload                = hasSampleDownload;
                    product.SampleDownloadId                 = sampleDownloadId;
                    product.HasUserAgreement                 = hasUserAgreement;
                    product.UserAgreementText                = userAgreementText;
                    product.IsRecurring                      = isRecurring;
                    product.RecurringCycleLength             = recurringCycleLength;
                    product.RecurringCyclePeriodId           = recurringCyclePeriodId;
                    product.RecurringTotalCycles             = recurringTotalCycles;
                    product.IsRental                         = isRental;
                    product.RentalPriceLength                = rentalPriceLength;
                    product.RentalPricePeriodId              = rentalPricePeriodId;
                    product.IsShipEnabled                    = isShipEnabled;
                    product.IsFreeShipping                   = isFreeShipping;
                    product.ShipSeparately                   = shipSeparately;
                    product.AdditionalShippingCharge         = additionalShippingCharge;
                    product.DeliveryDateId                   = deliveryDateId;
                    product.IsTaxExempt                      = isTaxExempt;
                    product.TaxCategoryId                    = taxCategoryId;
                    product.IsTelecommunicationsOrBroadcastingOrElectronicServices = isTelecommunicationsOrBroadcastingOrElectronicServices;
                    product.ManageInventoryMethodId       = manageInventoryMethodId;
                    product.UseMultipleWarehouses         = useMultipleWarehouses;
                    product.WarehouseId                   = warehouseId;
                    product.StockQuantity                 = stockQuantity;
                    product.DisplayStockAvailability      = displayStockAvailability;
                    product.DisplayStockQuantity          = displayStockQuantity;
                    product.MinStockQuantity              = minStockQuantity;
                    product.LowStockActivityId            = lowStockActivityId;
                    product.NotifyAdminForQuantityBelow   = notifyAdminForQuantityBelow;
                    product.BackorderModeId               = backorderModeId;
                    product.AllowBackInStockSubscriptions = allowBackInStockSubscriptions;
                    product.OrderMinimumQuantity          = orderMinimumQuantity;
                    product.OrderMaximumQuantity          = orderMaximumQuantity;
                    product.AllowedQuantities             = allowedQuantities;
                    product.AllowAddingOnlyExistingAttributeCombinations = allowAddingOnlyExistingAttributeCombinations;
                    product.DisableBuyButton      = disableBuyButton;
                    product.DisableWishlistButton = disableWishlistButton;
                    product.AvailableForPreOrder  = availableForPreOrder;
                    product.PreOrderAvailabilityStartDateTimeUtc = preOrderAvailabilityStartDateTimeUtc;
                    product.CallForPrice = callForPrice;
                    product.Price        = price;
                    product.OldPrice     = oldPrice;
                    product.ProductCost  = productCost;
                    product.SpecialPrice = specialPrice;
                    product.SpecialPriceStartDateTimeUtc = specialPriceStartDateTimeUtc;
                    product.SpecialPriceEndDateTimeUtc   = specialPriceEndDateTimeUtc;
                    product.CustomerEntersPrice          = customerEntersPrice;
                    product.MinimumCustomerEnteredPrice  = minimumCustomerEnteredPrice;
                    product.MaximumCustomerEnteredPrice  = maximumCustomerEnteredPrice;
                    product.BasepriceEnabled             = basepriceEnabled;
                    product.BasepriceAmount     = basepriceAmount;
                    product.BasepriceUnitId     = basepriceUnitId;
                    product.BasepriceBaseAmount = basepriceBaseAmount;
                    product.BasepriceBaseUnitId = basepriceBaseUnitId;
                    product.Weight       = weight;
                    product.Length       = length;
                    product.Width        = width;
                    product.Height       = height;
                    product.Published    = published;
                    product.CreatedOnUtc = createdOnUtc;
                    product.UpdatedOnUtc = DateTime.UtcNow;
                    if (newProduct)
                    {
                        _productService.InsertProduct(product);
                    }
                    else
                    {
                        _productService.UpdateProduct(product);
                    }

                    //search engine name
                    _urlRecordService.SaveSlug(product, product.ValidateSeName(seName, product.Name, true), 0);

                    //category mappings
                    if (!String.IsNullOrEmpty(categoryIds))
                    {
                        foreach (var id in categoryIds.Split(new [] { ';' }, StringSplitOptions.RemoveEmptyEntries).Select(x => Convert.ToInt32(x.Trim())))
                        {
                            if (product.ProductCategories.FirstOrDefault(x => x.CategoryId == id) == null)
                            {
                                //ensure that category exists
                                var category = _categoryService.GetCategoryById(id);
                                if (category != null)
                                {
                                    var productCategory = new ProductCategory
                                    {
                                        ProductId         = product.Id,
                                        CategoryId        = category.Id,
                                        IsFeaturedProduct = false,
                                        DisplayOrder      = 1
                                    };
                                    _categoryService.InsertProductCategory(productCategory);
                                }
                            }
                        }
                    }

                    //manufacturer mappings
                    if (!String.IsNullOrEmpty(manufacturerIds))
                    {
                        foreach (var id in manufacturerIds.Split(new [] { ';' }, StringSplitOptions.RemoveEmptyEntries).Select(x => Convert.ToInt32(x.Trim())))
                        {
                            if (product.ProductManufacturers.FirstOrDefault(x => x.ManufacturerId == id) == null)
                            {
                                //ensure that manufacturer exists
                                var manufacturer = _manufacturerService.GetManufacturerById(id);
                                if (manufacturer != null)
                                {
                                    var productManufacturer = new ProductManufacturer
                                    {
                                        ProductId         = product.Id,
                                        ManufacturerId    = manufacturer.Id,
                                        IsFeaturedProduct = false,
                                        DisplayOrder      = 1
                                    };
                                    _manufacturerService.InsertProductManufacturer(productManufacturer);
                                }
                            }
                        }
                    }

                    //pictures
                    foreach (var picturePath in new [] { picture1, picture2, picture3 })
                    {
                        if (String.IsNullOrEmpty(picturePath))
                        {
                            continue;
                        }

                        var mimeType             = GetMimeTypeFromFilePath(picturePath);
                        var newPictureBinary     = File.ReadAllBytes(picturePath);
                        var pictureAlreadyExists = false;
                        if (!newProduct)
                        {
                            //compare with existing product pictures
                            var existingPictures = _pictureService.GetPicturesByProductId(product.Id);
                            foreach (var existingPicture in existingPictures)
                            {
                                var existingBinary = _pictureService.LoadPictureBinary(existingPicture);
                                //picture binary after validation (like in database)
                                var validatedPictureBinary = _pictureService.ValidatePicture(newPictureBinary, mimeType);
                                if (existingBinary.SequenceEqual(validatedPictureBinary))
                                {
                                    //the same picture content
                                    pictureAlreadyExists = true;
                                    break;
                                }
                            }
                        }

                        if (!pictureAlreadyExists)
                        {
                            product.ProductPictures.Add(new ProductPicture
                            {
                                Picture      = _pictureService.InsertPicture(newPictureBinary, mimeType, _pictureService.GetPictureSeName(name)),
                                DisplayOrder = 1,
                            });
                            _productService.UpdateProduct(product);
                        }
                    }

                    //update "HasTierPrices" and "HasDiscountsApplied" properties
                    _productService.UpdateHasTierPricesProperty(product);
                    _productService.UpdateHasDiscountsApplied(product);



                    //next product
                    iRow++;
                }
            }
        }