protected void btnColorSubmit_Click(object sender, EventArgs e)
        {
            try
            {
                if (ViewState["NewColorsCouter"] != null && tvCats.SelectedValue != null)
                {
                    using (CatalogDataContext dct = new CatalogDataContext())
                    {
                        int counter = int.Parse(ViewState["NewColorsCouter"].ToString());

                        for (int i = 0; i < counter; i++)
                        {
                            Label lbl = (Label)this.Master.FindControl("MainContent").FindControl("lblColor" + i);
                            DropDownList ddl = (DropDownList)this.Master.FindControl("MainContent").FindControl("ddlColor" + i);

                            Mapping_Color mColor = new Mapping_Color() { id = System.Guid.NewGuid(), ss_color = lbl.Text, tb_color = ddl.SelectedItem.Text, tb_vid = long.Parse(ddl.SelectedItem.Value), tb_cid = long.Parse(tvCats.SelectedValue) };

                            dct.Mapping_Colors.InsertOnSubmit(mColor);
                        }

                        dct.SubmitChanges();
                    }
                }
                else
                    throw new ArgumentNullException("ViewState中没有NewColorsCounter");
            }
            catch (Exception ex)
            {

                string message = ex.Message.Replace("\n", "\\n").Replace("\r", "").Replace("'", "\\'");
                ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('" + message + "')", true);
            }
        }
        public void ConvertSSProductToTaoBao(long ProductID)
        {
            using (CatalogDataContext dct = new CatalogDataContext())
            {
                var p = dct.SS_Products.Single(o => o.product_id == ProductID);
                List<TB_Product> tbproductlist = new List<TB_Product>();
                TBProductAdapterService tbproductadapater = new TBProductAdapterService();

                var tbproduct = tbproductadapater.ProductConvert(p);
                dct.TB_Products.InsertOnSubmit(tbproduct);
                dct.SubmitChanges();
            }
        }
        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            try
            {
                if (tbTitle.Text.Length <= 30)
                {
                    using (CatalogDataContext dct = new CatalogDataContext())
                    {
                        var p = dct.SS_Products.SingleOrDefault(o => o.product_id == productid);

                        if (p != null)
                        {
                            p.chinese_name = tbTitle.Text;
                            p.chinese_description = FCKeditor1.Value;
                            p.istranslated = true;
                            dct.SubmitChanges();

                            var tbp = dct.TB_Products.SingleOrDefault(t => t.SSProductID == productid);

                            if (tbp == null)
                            {

                                TBProductUploadService toTaobao = new TBProductUploadService();
                                toTaobao.ConvertSSProductToTaoBao(productid);
                            }
                            else
                            {
                                tbp.Title = tbTitle.Text;
                                tbp.Desc = FCKeditor1.Value;
                                dct.SubmitChanges();
                            }

                            ScriptManager.RegisterStartupScript(this, this.GetType(), "aa", "alert('提交成功');", true);
                        }

                        //ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "Close", "window.close()", true);

                    }
                }
                else
                    throw new ApplicationException("商品题目超过30个字节");
            }
            catch (Exception ex)
            {

                string message = ex.Message.Replace("\n", "\\n").Replace("\r", "").Replace("'", "\\'");
                ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('" + message + "')", true);
            }
        }
 /// <summary>
 /// 初始化产品分类表 TB_ItemCat
 /// </summary>
 public void InitializationItemCat()
 {
     List<ItemCat> itemcatlist = GetItemCats();
     using (CatalogDataContext dct = new CatalogDataContext())
     {
         var allItemCat = dct.TB_ItemCats;
         List<ItemCat> itemcatinsert = new List<ItemCat>();
         //先判断数据库里是否存在,不存在的数据才需要插入
         if (allItemCat != null && allItemCat.Count() > 0)
         {
             foreach (var itemcat in itemcatlist)
             {
                 if (allItemCat.Where(i => i.Cid == itemcat.Cid && i.Name == itemcat.Name).FirstOrDefault() == null)
                 {
                     itemcatinsert.Add(itemcat);
                 }
             }
         }
         else
         {
             itemcatinsert.AddRange(itemcatlist);
         }
         //遍历获取到的淘宝分类数据插入TB_ItemCat
         foreach (var item in itemcatinsert)
         {
             TB_ItemCat obj = new TB_ItemCat();
             obj.ID = Guid.NewGuid();
             obj.Cid = item.Cid;
             obj.Name = item.Name;
             obj.IsParent = item.IsParent;
             if (string.IsNullOrEmpty(item.ModifiedTime) == false)
             {
                 obj.ModifiedTime = DateTime.Parse(item.ModifiedTime);
             }
             obj.ModifiedType = item.ModifiedType;
             obj.ParentCid = item.ParentCid;
             obj.SortOrder = item.SortOrder;
             obj.Status = item.Status;
             dct.TB_ItemCats.InsertOnSubmit(obj);
         }
         dct.SubmitChanges();
     }
 }
        protected void btnMustSubmit_Click(object sender, EventArgs e)
        {
            try
            {
                if (ViewState["MustPropsCounter"] != null && tvCats.SelectedNode != null)
                {
                    using (CatalogDataContext dct = new CatalogDataContext())
                    {
                        var mCat = from mapping in dct.Mapping_Categories where mapping.tb_cid == long.Parse(tvCats.SelectedValue) && mapping.ss_cat_id == ddlSSCats.SelectedValue select mapping;

                        if (mCat.Single() != null)
                        {
                            int counter = int.Parse(ViewState["MustPropsCounter"].ToString());

                            for (int i = 0; i < counter; i++)
                            {
                                Label lbl = (Label)this.Master.FindControl("MainContent").FindControl("lblMust" + i);
                                DropDownList ddl = (DropDownList)this.Master.FindControl("MainContent").FindControl("ddlMust" + i);

                                var prop = (from pv in dct.TB_ItemProps where pv.Cid == long.Parse(tvCats.SelectedValue) && pv.Name == lbl.Text select pv).Single();

                                Mapping_Categories_Prop mMust = new Mapping_Categories_Prop() { id = System.Guid.NewGuid(), mapping_categories_id = mCat.Single().id, pid = prop.Pid, vid = long.Parse(ddl.SelectedValue) };

                                dct.Mapping_Categories_Props.InsertOnSubmit(mMust);

                                dct.SubmitChanges();

                            }
                        }
                        else
                            throw new ArgumentException("还未匹配ss分类,淘宝分类为空");

                    }
                }
            }
            catch (Exception ex)
            {

                string message = ex.Message.Replace("\n", "\\n").Replace("\r", "").Replace("'", "\\'");
                ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('" + message + "')", true);
            }
        }
        public static void DownloadSizes(string catParentID)
        {
            ShopStyle api = new ShopStyle("uid8409-24047347-36", ShopStyle.UK_API_HOSTNAME);

            using (CatalogDataContext dc = new CatalogDataContext())
            {
                var ssCatList = dc.SS_Categories.Where(c => c.parentid == catParentID);
                if (ssCatList != null)
                {
                    foreach (var cat in ssCatList)
                    {
                        try
                        {
                            var sizeResponse = api.getSizes(cat.cat_id);

                            foreach (var s in sizeResponse.getSizes())
                            {
                                SS_Size size = new SS_Size() { id = System.Guid.NewGuid(), cat_id = cat.cat_id, name = s.getName(), size_id = s.getId() };
                                dc.SS_Sizes.InsertOnSubmit(size);
                            }
                        }
                        catch (ShopStyle.APIException ex)
                        {
                            if (ex.getMessage().Contains("SizeFilter cannot be shown for category"))
                            {
                                DownloadSizes(cat.cat_id);
                            }
                            continue;
                        }

                    }
                    dc.SubmitChanges();
                }

            }
        }
        public void DownloadBrands()
        {
            var brandResponse = api.getBrands();
            using (CatalogDataContext dc = new CatalogDataContext())
            {
                foreach (Brand brand in brandResponse.getBrands())
                {
                    SS_Brand ssBrand = new SS_Brand() { id = System.Guid.NewGuid(), brand_id = brand.getId(), brand_name = brand.getName(), url = brand.getUrl() };
                    dc.SS_Brands.InsertOnSubmit(ssBrand);
                }

                dc.SubmitChanges();
            }
        }
 /// <summary>
 /// 初始化 属性表 TB_ItemProp
 /// </summary>
 public void InitializationItemProp()
 {
     using (CatalogDataContext dct = new CatalogDataContext())
     {
         //先清空TB_ItemProp表
         var allItemProp = dct.TB_ItemProps;
         List<ItemProp> itemproplist = new List<ItemProp>();
         var itemcatlist = dct.TB_ItemCats;
         List<ItemProp> itempropinsert = new List<ItemProp>();
         //获取ItemProp中所有字段
         string fieldsitemprop = @"child_template,cid,is_allow_alias,is_color_prop,is_enum_prop,is_input_prop,is_item_prop,is_key_prop,
     is_sale_prop,modified_time,modified_type,multi,must,name,parent_pid,parent_vid,pid,required,sort_order,status,type";
         foreach (var item in itemcatlist)
         {
             if (item.IsParent == false)
             {
                 //如果是叶子类目 调用API获取属性列表
                 List<ItemProp> tempitemprop = ProductService.GetItemprops(item.Cid, fieldsitemprop, null, null, null, null, null, null, null, null, null, 1, null);
                 foreach (var tempitem in tempitemprop)
                 {
                     tempitem.Cid = item.Cid;
                 }
                 itemproplist.AddRange(tempitemprop);
             }
         }
         //先判断数据库里是否存在,不存在的数据才需要插入
         if (allItemProp != null && allItemProp.Count() > 0)
         {
             foreach (var itemprop in itemproplist)
             {
                 if (allItemProp.Where(i => i.Pid == itemprop.Pid && i.Cid == itemprop.Cid && i.Name == itemprop.Name).FirstOrDefault() == null)
                 {
                     itempropinsert.Add(itemprop);
                 }
             }
         }
         else
         {
             itempropinsert.AddRange(itemproplist);
         }
         if (itempropinsert != null && itempropinsert.Count > 0)
         {
             //插入TB_ItemProp表
             foreach (var item in itempropinsert)
             {
                 TB_ItemProp obj = new TB_ItemProp();
                 obj.ID = Guid.NewGuid();
                 obj.Cid = item.Cid;
                 obj.Pid = item.Pid;
                 obj.ParentPid = item.ParentPid;
                 obj.ParentVid = item.ParentVid;
                 obj.ChildTemplate = item.ChildTemplate;
                 obj.IsAllowAlias = item.IsAllowAlias;
                 obj.IsColorProp = item.IsColorProp;
                 obj.IsEnumProp = item.IsEnumProp;
                 obj.IsInputProp = item.IsInputProp;
                 obj.IsItemProp = item.IsItemProp;
                 obj.IsKeyProp = item.IsKeyProp;
                 obj.IsSaleProp = item.IsSaleProp;
                 if (string.IsNullOrEmpty(item.ModifiedTime) == false)
                 {
                     obj.ModifiedTime = DateTime.Parse(item.ModifiedTime);
                 }
                 obj.ModifiedType = item.ModifiedType;
                 obj.Multi = item.Multi;
                 obj.Must = item.Must;
                 obj.Name = item.Name;
                 obj.Required = item.Required;
                 obj.SortOrder = item.SortOrder;
                 obj.Status = item.Status;
                 dct.TB_ItemProps.InsertOnSubmit(obj);
             }
         }
         dct.SubmitChanges();
     }
 }
        //public void ConvertSSProductToTaoBao(string productSetName)
        //{
        //    if (!String.IsNullOrEmpty(productSetName))
        //    {
        //        using (CatalogDataContext dct = new CatalogDataContext())
        //        {
        //            //获取ssCat_ID=puffer-coats的数据存入tb数据库
        //            var SS = dct.SS_Categories;
        //            //List<SS_Product> ssproductlist = _SSCategoryRepository.Find(Specification<SS_Category>.Eval(o => o.Cat_ID == "puffer-coats")).ProductCollection.ToList();
        //            var ssProductList = from product in dct.SS_Products where product.SS_Product_Set.product_set_name == productSetName select product;
        //            List<TB_Product> tbproductlist = new List<TB_Product>();
        //            TBProductAdapterService tbproductadapater = new TBProductAdapterService();
        //            foreach (var item in ssProductList)
        //            {
        //                var tbproduct = tbproductadapater.ProductConvert(item);
        //                dct.TB_Products.InsertOnSubmit(tbproduct);
        //            }
        //            dct.SubmitChanges();
        //        }
        //    }
        //    else
        //        throw new ArgumentNullException("商品组名称不能为空");
        //}
        public void UploadProduct(string productSetName)
        {
            try
            {
                if (!string.IsNullOrEmpty(productSetName))
                {
                    using (CatalogDataContext dct = new CatalogDataContext())
                    {
                        var tbProductList = from tbProduct in dct.TB_Products where tbProduct.SS_Product.SS_Product_Set.product_set_name == productSetName && tbProduct.IsUploaded == false select tbProduct;
                        foreach (var item in tbProductList)
                        {
                            try
                            {
                                Item product = ProductService.AddItem(item);

                                dct.SubmitChanges();

                                if (!String.IsNullOrEmpty(item.SkuProperties))
                                {
                                    string[] skus = item.SkuProperties.Split(new char[] { ',' });

                                    foreach (var sku in skus)
                                    {
                                        string colorPV = getColorProperties(sku);

                                        if (!string.IsNullOrEmpty(colorPV))
                                        {
                                            string[] cVid = colorPV.Split(new char[] { ':' });

                                            var ssPicUrl = (from color in dct.SS_Product_Color_Image_Mappings join ssImage in dct.SS_Images on color.image_id equals ssImage.image_id join tbColor in dct.Mapping_Colors on color.color_name equals tbColor.ss_color where color.product_id == item.SSProductID && ssImage.size_name == "Original" && tbColor.tb_vid == long.Parse(cVid[1]) select new { url = ssImage.url }).FirstOrDefault().url;
                                            string ImgFilePath = "";
                                            Utils.SaveImage(ssPicUrl, out ImgFilePath);
                                            ProductService.UploadItemPropImg(product.NumIid, colorPV, ConfigurationManager.AppSettings["ImageFolderPath"] + ImgFilePath);
                                        }
                                    }
                                }
                            }
                            catch (Exception)
                            {

                                continue;
                            }

                        }
                    }
                }
                else
                    throw new ArgumentNullException("商品组名称不能为空");

            }
            catch
            {
                throw;
            }
        }
        protected void btnSaveCat_Click(object sender, EventArgs e)
        {
            try
            {
                if (tvCats.SelectedNode != null)
                {
                    using (CatalogDataContext dct = new CatalogDataContext())
                    {
                        Mapping_Category mc = new Mapping_Category() { id = System.Guid.NewGuid(), ss_cat_id = ddlSSCats.SelectedValue, ss_cat_name = ddlSSCats.SelectedItem.Text, tb_cid = long.Parse(tvCats.SelectedValue), tb_name = tvCats.SelectedNode.Text };
                        dct.Mapping_Categories.InsertOnSubmit(mc);
                        dct.SubmitChanges();
                    }

                }
                else
                    throw new ApplicationException("请选择淘宝分类");
            }
            catch (Exception ex)
            {

                string message = ex.Message.Replace("\n", "\\n").Replace("\r", "").Replace("'", "\\'");
                ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('" + message + "')", true);
            }
        }
 /// <summary>
 /// 初始化 属性值表 TB_PropValue
 /// </summary>
 public void InitializationPropValue()
 {
     using (CatalogDataContext dct = new CatalogDataContext())
     {
         //清空TB_PropValue表
         var allPropValue = dct.TB_PropValues;
         List<PropValue> propvaluelist = new List<PropValue>();
         var itemcatlist = dct.TB_ItemCats;
         var itemproplist = dct.TB_ItemProps;
         List<PropValue> propvalueinsert = new List<PropValue>();
         //获取PropValue需要的字段.
         string fieldspropvalue = @"cid,pid,prop_name,vid,name,name_alias,status,sort_order";
         foreach (var item in itemcatlist)
         {
             if (item.IsParent == false)
             {
                 //如果是叶子类目 调用API获取属性列表
                 var tempitemprop = itemproplist.Where(i => i.Cid == item.Cid).ToList();
                 //如果是叶子类目,根据获取的属性列表
                 string pids = GetItemPropIDS(tempitemprop);
                 List<PropValue> tempprovalue = ProductService.GetItempropValues(fieldspropvalue, item.Cid, pids, 1, null);
                 propvaluelist.AddRange(tempprovalue);
             }
         }
         //先判断数据库里是否存在,不存在的数据才需要插入
         if (allPropValue != null && allPropValue.Count() > 0)
         {
             foreach (var propvalue in propvaluelist)
             {
                 if (allPropValue.Where(i => i.Vid == propvalue.Vid && i.Pid == propvalue.Pid && i.Cid == propvalue.Cid && i.Name == propvalue.Name).FirstOrDefault() == null)
                 {
                     propvalueinsert.Add(propvalue);
                 }
             }
         }
         else
         {
             propvalueinsert.AddRange(propvaluelist);
         }
         if (propvalueinsert != null && propvalueinsert.Count > 0)
         {
             //插入TB_PropValue表
             int i = 0;
             foreach (var item in propvaluelist)
             {
                 i++;
                 TB_PropValue obj = new TB_PropValue();
                 obj.ID = Guid.NewGuid();
                 obj.Cid = item.Cid;
                 obj.IsParent = item.IsParent;
                 if (string.IsNullOrEmpty(item.ModifiedTime) == false)
                 {
                     obj.ModifiedTime = DateTime.Parse(item.ModifiedTime);
                 }
                 obj.ModifiedType = item.ModifiedType;
                 obj.Name = item.Name;
                 obj.NameAlias = item.NameAlias;
                 obj.Pid = item.Pid;
                 obj.PropName = item.PropName;
                 obj.SortOrder = item.SortOrder;
                 obj.Status = item.Status;
                 obj.Vid = item.Vid;
                 dct.TB_PropValues.InsertOnSubmit(obj);
                 if (i == 1000)
                 {
                     dct.SubmitChanges();
                     i = 0;
                 }
             }
         }
     }
 }
        protected void gridProducts_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            try
            {

                foreach (DictionaryEntry kv in e.Keys)
                {
                    var productId = kv.Value;
                    using (CatalogDataContext dct = new CatalogDataContext())
                    {
                        var ssProduct = dct.SS_Products.FirstOrDefault(p => p.product_id == long.Parse(productId.ToString()));

                        if (ssProduct != null)
                        {
                            dct.SS_Products.DeleteOnSubmit(ssProduct);

                            //delete images, no foreign key cascade
                            foreach (var m in ssProduct.SS_Product_Color_Image_Mappings)
                            {
                                var images = dct.SS_Images.Where(i => i.image_id == m.image_id);

                                foreach (var image in images)
                                {
                                    dct.SS_Images.DeleteOnSubmit(image);
                                }

                            }
                        }
                        dct.SubmitChanges();
                    }
                }

                applyFilters();
            }
            catch (Exception ex)
            {

                string message = ex.Message.Replace("\n", "\\n").Replace("\r", "").Replace("'", "\\'");
                ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('" + message + "')", true);
            }
        }
        public void DownloadCategories()
        {
            var catResponse = api.getCategories("clothes-shoes-and-jewelry", 20);
            using (CatalogDataContext dc = new CatalogDataContext())
            {
                foreach (Category cat in catResponse.getCategories())
                {
                    SS_Category ssCat = new SS_Category() { id = System.Guid.NewGuid(), cat_id = cat.getId(), name = cat.getName(), parentid = cat.getParentId() };
                    dc.SS_Categories.InsertOnSubmit(ssCat);
                }

                dc.SubmitChanges();
            }
        }
        /// <summary>
        /// 下载选择的商品
        /// </summary>
        /// <param name="fts">关键词</param>
        /// <param name="catId">分类</param>
        /// <param name="productSetName">商品组名称</param>
        /// <param name="selectList"></param>
        internal void DownloadProductsByProducts(string fts, string catId, string productSetName, List<Product> selectList)
        {
            var productSetID = new Guid();
            foreach (var product in selectList)
            {
                using (var dc = new CatalogDataContext())
                {
                    if (dc.SS_Products.FirstOrDefault(x => x.product_id == product.getId()) != null)
                    {
                        continue;
                    }
                }

                using (var context = new CatalogDataContext())
                {
                    var ps = (from set in context.SS_Product_Sets where set.product_set_name == productSetName select set).SingleOrDefault();
                    if (ps == null)
                    {
                        var productSet = new SS_Product_Set()
                        {
                            id = System.Guid.NewGuid(),
                            product_set_name = productSetName,
                            tb_seller_cid = ProductService.AddSellerCat(productSetName).Cid,
                            datetimecreated = (DateTime?)DateTime.Now
                        };

                        context.SS_Product_Sets.InsertOnSubmit(productSet);
                        context.SubmitChanges();
                        productSetID = productSet.id;
                    }
                    else
                        productSetID = ps.id;

                }

                #region SS_Products
                using (var dc = new CatalogDataContext())
                {
                    var ssProduct = new SS_Product()
                    {
                        id = System.Guid.NewGuid(),
                        brand_id = (int?)product.getBrand().getId(),
                        click_url = product.getClickUrl(),
                        currency = product.getCurrency().getCurrencyCode(),
                        description = product.getDescription(),
                        chinese_description = getTranslateResult(stripOffHTMLTags(product.getDescription()), true) ?? string.Empty,
                        image_id = product.getImage().getId(),
                        in_stock = product.isInStock(),
                        locale = product.getLocale().getDisplayCountry(),
                        name = product.getName(),
                        chinese_name = product.getBrand().getName() + getTranslateResult(product.getName(), false) ?? string.Empty,
                        price = (decimal?)product.getPrice(),
                        price_label = product.getPriceLabel(),
                        retailer_id = (int?)product.getRetailer().getId(),
                        product_id = (int)product.getId(),
                        sale_price = (decimal?)product.getSalePrice() == 0 ? null : (decimal?)product.getSalePrice(),
                        sale_price_label = product.getSalePriceLabel(),
                        istranslated = false,
                        keyword = fts,
                        datetimecreated = DateTime.Now,
                        product_set_name_id = productSetID
                    };
                    dc.SS_Products.InsertOnSubmit(ssProduct);
                    dc.SubmitChanges();
                }
                #endregion

                #region SS_Product_Category_Mapping
                using (CatalogDataContext dc = new CatalogDataContext())
                {
                    SS_Product ssProduct = dc.SS_Products.FirstOrDefault(x => x.product_id == product.getId());

                    //Insert categories and product-category mapping records
                    if (!string.IsNullOrEmpty(catId))
                    {
                        SS_Product_Category_Mapping pcMapping = new SS_Product_Category_Mapping()
                        {
                            id = System.Guid.NewGuid(),
                            product_id = ssProduct.product_id,
                            cat_id = catId
                        };
                        dc.SS_Product_Category_Mappings.InsertOnSubmit(pcMapping);
                        dc.SubmitChanges();
                    }
                    else
                    {
                        foreach (var category in product.getCategories())
                        {
                            if (ssProduct != null)
                            {
                                SS_Product_Category_Mapping pcMapping = new SS_Product_Category_Mapping() { id = System.Guid.NewGuid(), product_id = ssProduct.product_id, cat_id = category.getId() };
                                dc.SS_Product_Category_Mappings.InsertOnSubmit(pcMapping);
                                dc.SubmitChanges();
                            }
                            else
                            {
                                throw new ArgumentNullException("Could not find the newly inserted product");
                            }
                        }
                    }
                }
                #endregion

                //insert main image
                #region insert main image
                foreach (ImageSize imageSize in product.getImage().getSizes().values().toArray())
                {
                    using (CatalogDataContext dc1 = new CatalogDataContext())
                    {
                        SS_Product ssProduct = dc1.SS_Products.FirstOrDefault(x => x.product_id == product.getId());

                        SS_Image image = new SS_Image()
                        {
                            id = System.Guid.NewGuid(),
                            size_name = imageSize.getSizeName().toString(),
                            image_id = ssProduct.image_id,
                            url = imageSize.getUrl(),
                            height = imageSize.getHeight(),
                            width = imageSize.getWidth()
                        };
                        dc1.SS_Images.InsertOnSubmit(image);
                        dc1.SubmitChanges();

                    }
                }
                #endregion

                //Isert product_color_image_mapping records
                #region Colors
                foreach (var color in product.getColors())
                {
                    using (CatalogDataContext dc = new CatalogDataContext())
                    {

                        SS_Product ssProduct = dc.SS_Products.FirstOrDefault(x => x.product_id == product.getId());

                        SS_Product_Color_Image_Mapping pciMapping = new SS_Product_Color_Image_Mapping();
                        pciMapping.id = System.Guid.NewGuid();
                        pciMapping.color_name = color.getName();
                        pciMapping.product_id = (int)product.getId();

                        if (color.getImage() == null)
                        {
                            pciMapping.image_id = ssProduct.image_id;//if there's no image element inside color element, that means only one color available.
                        }
                        else
                        {
                            pciMapping.image_id = color.getImage().getId();
                        }

                        if (color.getImage() != null)
                        {
                            var ssImage = (from image in dc.SS_Images where image.image_id == color.getImage().getId() select image).FirstOrDefault();

                            if (ssImage == null)
                            {
                                foreach (ImageSize imageSize in color.getImage().getSizes().values().toArray())
                                {
                                    using (CatalogDataContext dc1 = new CatalogDataContext())
                                    {

                                        SS_Image image = new SS_Image()
                                        {
                                            id = System.Guid.NewGuid(),
                                            size_name = imageSize.getSizeName().toString(),
                                            image_id = pciMapping.image_id,
                                            url = imageSize.getUrl(),
                                            height = imageSize.getHeight(),
                                            width = imageSize.getWidth()
                                        };
                                        dc1.SS_Images.InsertOnSubmit(image);
                                        dc1.SubmitChanges();

                                    }
                                }
                            }
                        }

                        dc.SS_Product_Color_Image_Mappings.InsertOnSubmit(pciMapping);
                        dc.SubmitChanges();
                    }

                }
                #endregion

                //Insert size and product_size_mapping
                #region Size
                foreach (var size in product.getSizes())
                {
                    using (CatalogDataContext dc = new CatalogDataContext())
                    {
                        SS_Size result = dc.SS_Sizes.FirstOrDefault(x => x.name == size.getName());

                        if (result == null)
                        {
                            System.Guid sizeId;
                            using (CatalogDataContext dc1 = new CatalogDataContext())
                            {
                                SS_Size s = new SS_Size() { id = System.Guid.NewGuid(), name = size.getName() };
                                dc1.SS_Sizes.InsertOnSubmit(s);
                                dc1.SubmitChanges();

                                sizeId = s.id;
                            }

                            using (CatalogDataContext dc2 = new CatalogDataContext())
                            {
                                SS_Product_Size_Mapping psMapping = new SS_Product_Size_Mapping() { id = System.Guid.NewGuid(), product_id = (int)product.getId(), size_id = sizeId };
                                dc2.SS_Product_Size_Mappings.InsertOnSubmit(psMapping);
                                dc2.SubmitChanges();
                            }

                        }
                        else
                        {
                            SS_Product_Size_Mapping psMapping = new SS_Product_Size_Mapping() { id = System.Guid.NewGuid(), product_id = (int)product.getId(), size_id = result.id };
                            dc.SS_Product_Size_Mappings.InsertOnSubmit(psMapping);
                            dc.SubmitChanges();
                        }
                    }

                }
                #endregion
            }
        }
        public void DownloadRetailers()
        {
            var retailerResponse = api.getRetailers();
            using (CatalogDataContext dc = new CatalogDataContext())
            {
                foreach (Retailer retailer in retailerResponse.getRetailers())
                {
                    SS_Retailer ssRetailer = new SS_Retailer() { id = System.Guid.NewGuid(), name = retailer.getName(), retailer_id = (int)retailer.getId(), url = retailer.getUrl() };
                    dc.SS_Retailers.InsertOnSubmit(ssRetailer);
                }

                dc.SubmitChanges();
            }
        }
        public void DownloadProducts(string fts, string catID, string brandFilterID, string retailerFilterID, string priceFilterID, string discountFilterID, string productSetName)
        {
            ProductQuery query = new ProductQuery();
            if (!string.IsNullOrEmpty(fts))
                query.withFreeText(fts);
            if (!string.IsNullOrEmpty(catID))
                query.withCategory(catID); // Category jackets
            if (!string.IsNullOrEmpty(brandFilterID))
                query.withFilter(brandFilterID); // Brand filter id
            if (!string.IsNullOrEmpty(retailerFilterID))
                query.withFilter(retailerFilterID);// Retailer filter id
            if (!string.IsNullOrEmpty(priceFilterID))
                query.withFilter(priceFilterID); // Price filter id
            if (!string.IsNullOrEmpty(discountFilterID))
                query.withFilter(discountFilterID); // Discount filter id

            var response = api.getProducts(query);

            ProductSearchMetadata metadata = response.getMetadata();
            int total = metadata.getTotal(); // pageCounter = total/limit, these three values are being used to calculate paging.
            int limit = metadata.getLimit();
            int offset = metadata.getOffset();
            int pageCount = (int)Math.Ceiling((double)total / 100);

            System.Guid productSetID;

            using (CatalogDataContext context = new CatalogDataContext())
            {
                var ps = (from set in context.SS_Product_Sets where set.product_set_name == productSetName select set).SingleOrDefault();
                if (ps == null)
                {
                    SS_Product_Set productSet = new SS_Product_Set()
                    {
                        id = System.Guid.NewGuid(),
                        product_set_name = productSetName,
                        tb_seller_cid = ProductService.AddSellerCat(productSetName).Cid,
                        datetimecreated = (DateTime?)DateTime.Now
                    };

                    context.SS_Product_Sets.InsertOnSubmit(productSet);
                    context.SubmitChanges();
                    productSetID = productSet.id;
                }
                else
                    productSetID = ps.id;

            }

            for (int i = 0; i < pageCount; i++)
            {
                PageRequest page = new PageRequest().withLimit(100).withOffset(offset);
                var productResponse = api.getProducts(query, page, ProductSort.PriceLoHi);

                foreach (var product in productResponse.getProducts())
                {
                    try
                    {
                         using (CatalogDataContext dc = new CatalogDataContext())
                    {
                        if (dc.SS_Products.FirstOrDefault(x => x.product_id == product.getId()) != null)
                        {
                            continue;
                        }
                    }

                    using (CatalogDataContext dc = new CatalogDataContext())
                    {

                        SS_Product ssProduct = new SS_Product()
                        {
                            id = System.Guid.NewGuid(),
                            brand_id = (int?)product.getBrand().getId(),
                            click_url = product.getClickUrl(),
                            currency = product.getCurrency().getCurrencyCode(),
                            description = product.getDescription(),
                            chinese_description = getTranslateResult(stripOffHTMLTags(product.getDescription()), true) ?? string.Empty,
                            image_id = product.getImage().getId(),
                            in_stock = product.isInStock(),
                            locale = product.getLocale().getDisplayCountry(),
                            name = product.getName(),
                            chinese_name = product.getBrand().getName() + getTranslateResult(product.getName(), false) ?? string.Empty,
                            price = (decimal?)product.getPrice(),
                            price_label = product.getPriceLabel(),
                            retailer_id = (int?)product.getRetailer().getId(),
                            product_id = (int)product.getId(),
                            sale_price = (decimal?)product.getSalePrice() == 0 ? null : (decimal?)product.getSalePrice(),
                            sale_price_label = product.getSalePriceLabel(),
                            istranslated = false,
                            keyword = fts,
                            datetimecreated = DateTime.Now,
                            product_set_name_id = productSetID
                        };
                        dc.SS_Products.InsertOnSubmit(ssProduct);
                        dc.SubmitChanges();

                    }

                    using (CatalogDataContext dc = new CatalogDataContext())
                    {
                        SS_Product ssProduct = dc.SS_Products.FirstOrDefault(x => x.product_id == product.getId());

                        //Insert categories and product-category mapping records
                        if (!string.IsNullOrEmpty(catID))
                        {
                            SS_Product_Category_Mapping pcMapping = new SS_Product_Category_Mapping() { id = System.Guid.NewGuid(), product_id = ssProduct.product_id, cat_id = catID };
                            dc.SS_Product_Category_Mappings.InsertOnSubmit(pcMapping);
                            dc.SubmitChanges();
                        }
                        else
                        {
                            foreach (var category in product.getCategories())
                            {
                                if (ssProduct != null)
                                {
                                    SS_Product_Category_Mapping pcMapping = new SS_Product_Category_Mapping() { id = System.Guid.NewGuid(), product_id = ssProduct.product_id, cat_id = category.getId() };
                                    dc.SS_Product_Category_Mappings.InsertOnSubmit(pcMapping);
                                    dc.SubmitChanges();
                                }
                                else
                                {
                                    throw new ArgumentNullException("Could not find the newly inserted product");
                                }
                            }
                        }
                    }

                    //insert main image
                    foreach (ImageSize imageSize in product.getImage().getSizes().values().toArray())
                    {
                        using (CatalogDataContext dc1 = new CatalogDataContext())
                        {
                            SS_Product ssProduct = dc1.SS_Products.FirstOrDefault(x => x.product_id == product.getId());

                            SS_Image image = new SS_Image()
                            {
                                id = System.Guid.NewGuid(),
                                size_name = imageSize.getSizeName().toString(),
                                image_id = ssProduct.image_id,
                                url = imageSize.getUrl(),
                                height = imageSize.getHeight(),
                                width = imageSize.getWidth()
                            };
                            dc1.SS_Images.InsertOnSubmit(image);
                            dc1.SubmitChanges();

                        }
                    }

                    //Isert product_color_image_mapping records
                    foreach (var color in product.getColors())
                    {
                        using (CatalogDataContext dc = new CatalogDataContext())
                        {

                            SS_Product ssProduct = dc.SS_Products.FirstOrDefault(x => x.product_id == product.getId());

                            SS_Product_Color_Image_Mapping pciMapping = new SS_Product_Color_Image_Mapping();
                            pciMapping.id = System.Guid.NewGuid();
                            pciMapping.color_name = color.getName();
                            pciMapping.product_id = (int)product.getId();

                            if (color.getImage() == null)
                            {
                                pciMapping.image_id = ssProduct.image_id;//if there's no image element inside color element, that means only one color available.
                            }
                            else
                            {
                                pciMapping.image_id = color.getImage().getId();
                            }

                            if (color.getImage() != null)
                            {
                                var ssImage = (from image in dc.SS_Images where image.image_id == color.getImage().getId() select image).FirstOrDefault();

                                if (ssImage == null)
                                {
                                    foreach (ImageSize imageSize in color.getImage().getSizes().values().toArray())
                                    {
                                        using (CatalogDataContext dc1 = new CatalogDataContext())
                                        {

                                            SS_Image image = new SS_Image()
                                            {
                                                id = System.Guid.NewGuid(),
                                                size_name = imageSize.getSizeName().toString(),
                                                image_id = pciMapping.image_id,
                                                url = imageSize.getUrl(),
                                                height = imageSize.getHeight(),
                                                width = imageSize.getWidth()
                                            };
                                            dc1.SS_Images.InsertOnSubmit(image);
                                            dc1.SubmitChanges();

                                        }
                                    }
                                }
                            }

                            dc.SS_Product_Color_Image_Mappings.InsertOnSubmit(pciMapping);
                            dc.SubmitChanges();
                        }

                    }

                    //Insert size and product_size_mapping
                    foreach (var size in product.getSizes())
                    {
                        using (CatalogDataContext dc = new CatalogDataContext())
                        {
                            SS_Size result = dc.SS_Sizes.FirstOrDefault(x => x.name == size.getName());

                            if (result == null)
                            {
                                System.Guid sizeId;
                                using (CatalogDataContext dc1 = new CatalogDataContext())
                                {
                                    SS_Size s = new SS_Size() { id = System.Guid.NewGuid(), name = size.getName() };
                                    dc1.SS_Sizes.InsertOnSubmit(s);
                                    dc1.SubmitChanges();

                                    sizeId = s.id;
                                }

                                using (CatalogDataContext dc2 = new CatalogDataContext())
                                {
                                    SS_Product_Size_Mapping psMapping = new SS_Product_Size_Mapping() { id = System.Guid.NewGuid(), product_id = (int)product.getId(), size_id = sizeId };
                                    dc2.SS_Product_Size_Mappings.InsertOnSubmit(psMapping);
                                    dc2.SubmitChanges();
                                }

                            }
                            else
                            {
                                SS_Product_Size_Mapping psMapping = new SS_Product_Size_Mapping() { id = System.Guid.NewGuid(), product_id = (int)product.getId(), size_id = result.id };
                                dc.SS_Product_Size_Mappings.InsertOnSubmit(psMapping);
                                dc.SubmitChanges();
                            }
                        }
                    }
                    }
                    catch (Exception)
                    {
                        continue;
                    }
                }
                offset += 100;
            }
        }
        public void DownloadColors()
        {
            var colorResponse = api.getColors();
            using (CatalogDataContext dc = new CatalogDataContext())
            {
                foreach (Color color in colorResponse.getColors())
                {
                    SS_Color ssColor = new SS_Color() { id = System.Guid.NewGuid(), color_id = color.getId(), color_name = color.getName(), url = color.getUrl() };
                    dc.SS_Colors.InsertOnSubmit(ssColor);
                }

                dc.SubmitChanges();
            }
        }