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);
            }
        }
        protected void gridProducts_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            using (CatalogDataContext dct = new CatalogDataContext())
            {
                gridProducts.PageIndex = e.NewPageIndex;

                //gridProducts.DataSource = from product in dct.SS_Products  select new { ID = product.product_id, Name = product.name, Brand = product.SS_Brand.brand_name, Retailer = product.SS_Retailer.name, Price = product.price_label, Sale = product.sale_price_label, IsInStock = product.in_stock, IsTranslated = product.istranslated, ProductSet = product.product_set_name, ProductImage = (from image in dct.SS_Images where image.image_id == product.image_id && image.size_name == "Small" select image.url ).FirstOrDefault() };
                //gridProducts.DataBind();
                applyFilters();
            }
        }
        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();
            }
        }
        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();
            }
        }
        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);
            }
        }
        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            using (CatalogDataContext dct = new CatalogDataContext())
            {
                var u = dct.Users.SingleOrDefault(o => o.Name == tbName.Text && o.Password == tbPassword.Text);

                if (u != null)
                {
                    Session["SessionUsername"] = u.Name;
                    Response.Redirect("DownloadSetting.aspx");
                }
                else
                {
                    ScriptManager.RegisterStartupScript(this, this.GetType(), "aa", "alert('用户名或者密码不正确')", 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 BindData()
        {
            using (CatalogDataContext dct = new CatalogDataContext())
            {

                #region Populate two DropDownLists

                ddlTitlePrefixs.DataSource = dct.TB_Title_Prefixes;
                ddlTitlePrefixs.DataTextField = "title_prefix";
                ddlTitlePrefixs.DataValueField = "id";
                ddlTitlePrefixs.DataBind();
                ddlTitlePrefixs.Items.Insert(0, new ListItem("", "NA"));

                ddlModels.DataSource = dct.TB_Models;
                ddlModels.DataTextField = "model_name";
                ddlModels.DataValueField = "id";
                ddlModels.DataBind();
                ddlModels.Items.Insert(0, new ListItem("", "NA"));

                #endregion

                #region Populate SS_Product
                var product = dct.SS_Products.SingleOrDefault(o => o.product_id == productid);

                if (product != null)
                {
                    lbID.Text = product.product_id.ToString();
                    lbTitle.Text = product.name;
                    lbDescription.Text = product.description;
                    tbTitle.Text = product.chinese_name; ////TODO:建立起名短语
                    lbUrl.NavigateUrl = product.click_url;
                    FCKeditor1.Value = product.chinese_description;

                    btnSubmit.Enabled = true;
                }
                else
                {
                    btnSubmit.Enabled = false;
                }
                #endregion
            }
        }
        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();
                }

            }
        }
        private void findAndHightLightNode(string ssCid)
        {
            if (!String.IsNullOrEmpty(ssCid))
            {
                using (CatalogDataContext dct = new CatalogDataContext())
                {
                    var matchedTBCat = (from mapping in dct.Mapping_Categories where mapping.ss_cat_id == ssCid select mapping.tb_cid).FirstOrDefault();

                    if (matchedTBCat != null)
                    {
                        string valuePath = getTreeViewValuePath(matchedTBCat.Value);

                        highLightNode(valuePath.Substring(2, valuePath.Length - 2));
                    }
                    else
                    {
                        if (tvCats.SelectedNode != null)
                        {
                            tvCats.SelectedNode.Parent.Expanded = false;
                            tvCats.SelectedNode.Selected = false;

                        }

                        tvCats.ExpandDepth = 0;

                    }

                }
            }
            else
                throw new ArgumentNullException("SS商品类ID不能为空");
        }
 /// <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;
                 }
             }
         }
     }
 }
        private string getTreeViewValuePath(long tbCid)
        {
            StringBuilder valuePath = new StringBuilder();
            valuePath.Append(tvCats.PathSeparator + tbCid.ToString());

            using (CatalogDataContext dct = new CatalogDataContext())
            {
                var parentCat = (from cat in dct.TB_ItemCats where cat.Cid == tbCid && cat.ParentCid != 0 select cat.ParentCid).FirstOrDefault();
                if (parentCat != null)
                    valuePath.Insert(0, tvCats.PathSeparator + getTreeViewValuePath(parentCat.Value));

            }

            return valuePath.ToString();
        }
        private void populateDropdownList(DateTime? dt)
        {
            using (CatalogDataContext dct = new CatalogDataContext())
            {

                ddlProductSet.DataSource = dt == null ? dct.SS_Product_Sets : dct.SS_Product_Sets.Where(p => ((DateTime)p.datetimecreated).Date == dt.Value.Date)   ;
                ddlProductSet.DataTextField = "product_set_name";
                ddlProductSet.DataValueField = "id";
                ddlProductSet.DataBind();
                ddlProductSet.Items.Insert(0, new ListItem("--全部--", "NA"));
            }
        }
        private bool IsPassValidation()
        {
            try
            {
                if (ddlProductSet.SelectedValue == "NA")
                {
                    ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "infoMessage", "alert('请您选择一个产品组')", true);
                    return false;
                }

                using (CatalogDataContext dct = new CatalogDataContext())
                {
                    var p = dct.SS_Products.Where(o => o.product_set_name_id == new Guid(ddlProductSet.SelectedValue));
                    var isTranNum = p.Count(o => o.istranslated.Value == true);
                    if (p.Count() == isTranNum)
                    {
                        return true;
                    }
                    else
                    {
                        ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "infoMessage", "alert('需要把商品组下面的所有商品全部翻译才可上传')", true);
                        return false;
                    }
                }
            }
            catch (Exception ex)
            {

                string message = ex.Message.Replace("\n", "\\n").Replace("\r", "");
                ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('" + message + "')", true);
            }

            return false;
        }
        private void applyFilters()
        {
            try
            {
                using (CatalogDataContext dct = new CatalogDataContext())
                {
                    var products = from product in dct.SS_Products where !dct.TB_Products.Any(tp => tp.IsUploaded == true && tp.SSProductID == product.product_id) select product;

                    if (ddlProductSet.SelectedValue != "NA")
                    {
                        products = from product in products where product.product_set_name_id == new Guid(ddlProductSet.SelectedValue) select product;
                    }

                    if (ddlProdctState.SelectedValue != "NA")
                    {
                        var trans = bool.Parse(ddlProdctState.SelectedValue);
                        if (trans)
                        {
                            products = products.Where(o => o.istranslated.Value == true);
                        }
                        else
                        {
                            products = products.Where(o => o.istranslated.Value == false || o.istranslated == null);
                        }
                    }

                    if (!string.IsNullOrEmpty(txtDownloadDate.Text))
                    {
                        DateTime dt = Convert.ToDateTime(txtDownloadDate.Text);
                        products = from product in products where product.datetimecreated.Value.Date == dt.Date select product;
                    }

                    gridProducts.DataSource = from product in products select new { ID = product.product_id, Name = product.name, Brand = product.SS_Brand.brand_name, Retailer = product.SS_Retailer.name, Price = product.price_label, Sale = product.sale_price_label, IsInStock = product.in_stock, IsTranslated = product.istranslated, ProductSet = product.SS_Product_Set.product_set_name, ProductImage = (from image in dct.SS_Images where image.image_id == product.image_id && image.size_name == "Small" select image.url).FirstOrDefault() };
                    gridProducts.DataBind();

                }
            }
            catch (Exception ex)
            {
                string message = ex.Message.Replace("\n", "\\n").Replace("\r", "");
                ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('" + message + "')", true);
            }
        }
        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);
            }
        }
        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);
            }
        }
        //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;
            }
        }
 /// <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();
     }
 }
        /// <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();
            }
        }
 private void populateNode(TreeNode node)
 {
     using (CatalogDataContext dct = new CatalogDataContext())
     {
         var cats = from cat in dct.TB_ItemCats where cat.ParentCid == long.Parse(node.Value) select cat;
         foreach (var item in cats)
         {
             TreeNode n = new TreeNode(item.Name, item.Cid.ToString());
             node.ChildNodes.Add(n);
         }
         foreach (TreeNode item in node.ChildNodes)
         {
             populateNode(item);
         }
     }
 }
        private void populateProps(long tbCatId)
        {
            using (CatalogDataContext dct = new CatalogDataContext())
            {
                long tbCid = long.Parse(tvCats.SelectedValue);

                #region 显示销售属性匹配区

                var saleProps = from prop in dct.TB_ItemProps where prop.Cid == tbCid && prop.IsSaleProp == true select prop;

                HtmlGenericControl saleDiv = new HtmlGenericControl("div");
                saleDiv.ID = "SalePropsSection";
                saleDiv.Attributes.Add("class", "dynamicdiv");

                foreach (var prop in saleProps)
                {
                    //找到该淘宝分类下的颜色属性,匹配没有匹配过的shopstyle颜色和该分类下的颜色属性值,插入新的匹配到Mapping_Colors表
                    if (prop.Name.Contains("颜色"))
                    {
                        HtmlGenericControl divColor = new HtmlGenericControl("div");
                        divColor.ID = "color";
                        divColor.Attributes.Add("class", "dynamicdiv");

                        var newColors = (from color in dct.SS_Product_Color_Image_Mappings.Where(c => (c.SS_Product.SS_Product_Category_Mappings.Where(cat => cat.cat_id == ddlSSCats.SelectedValue).Single().cat_id == ddlSSCats.SelectedValue)) where !dct.Mapping_Colors.Any(m => m.ss_color == color.color_name && m.tb_cid == prop.Cid) select new { ColorName = color.color_name }).Distinct();

                        int counter = newColors.Count();
                        ViewState["NewColorsCouter"] = counter;

                        for (int i = 0; i < counter;i++)
                        {
                            HtmlGenericControl div = new HtmlGenericControl("div");
                            div.ID = "color" + i;
                            div.Attributes.Add("class", "dynamicdiv");

                            Table t = new Table();
                            TableRow r = new TableRow();
                            TableCell c1 = new TableCell();
                            c1.Attributes.Add("width", "200px");
                            TableCell c2 = new TableCell();

                            Label lbl = new Label();
                            lbl.ID = "lblColor" + i;
                            lbl.Text = newColors.ToArray()[i].ColorName;
                            c1.Controls.Add(lbl);

                            DropDownList ddl = new DropDownList();
                            ddl.ID = "ddlColor" + i;
                            ddl.DataSource = from color in dct.TB_PropValues where color.Cid == tbCid && color.Pid == prop.Pid select new { Name = color.Name, Vid = color.Vid };
                            ddl.DataTextField = "Name";
                            ddl.DataValueField = "Vid";
                            ddl.DataBind();
                            c2.Controls.Add(ddl);

                            c1.Controls.Add(lbl);
                            c2.Controls.Add(ddl);
                            r.Cells.Add(c1);
                            r.Cells.Add(c2);
                            t.Rows.Add(r);

                            div.Controls.Add(t);
                            divColor.Controls.Add(div);

                        }

                        Button btnSubmit = new Button() { Text = "添加颜色匹配" };
                        btnSubmit.ID = "btnSubmit";
                        btnSubmit.Click += btnColorSubmit_Click;

                        if (counter == 0)
                        {
                            HtmlGenericControl div = new HtmlGenericControl("div");
                            div.ID = "divNoNewColor";
                            div.InnerText = "没有需要匹配的SS颜色";
                            divColor.Controls.Add(div);
                        }
                        else
                        {
                            divColor.Controls.Add(btnSubmit);
                        }

                        saleDiv.Controls.Add(divColor);

                    } //找到该淘宝分类下的尺码属性,匹配没有匹配过的shopstyle尺码和该分类下的尺码属性值,插入新的匹配到Mapping_Sizes表
                    else if (prop.Name.Contains("尺寸") || prop.Name.Contains("尺码") || prop.Name.Contains("鞋尺码") || prop.Name.Contains("帽围尺码") || prop.Name.Contains("周长") || prop.Name.Contains("包袋大小"))
                    {
                        //var newSizes = (from size in dct.SS_Product_Size_Mappings.Where(m => m.SS_Product.SS_Product_Category_Mappings.Where(c => c.cat_id == ddlSSCats.SelectedValue).Single().cat_id == ddlSSCats.SelectedValue) where !dct.Mapping_Sizes.Any(ms => ms.ss_size_name == size.SS_Size.name && ms.tb_cid == tbCid) select new { SizeName = size.SS_Size.name }).Distinct();

                        var newSizes = (from size in dct.SS_Product_Size_Mappings.Where(m => m.SS_Product.SS_Product_Category_Mappings.Where(c => c.cat_id == ddlSSCats.SelectedValue).Single().cat_id == ddlSSCats.SelectedValue) where !dct.Mapping_Sizes.Any(ms => ms.ss_size_name == size.SS_Size.name && ms.tb_cid == tbCid) select new { SizeName = size.SS_Size.name }).Distinct();

                        HtmlGenericControl divSize = new HtmlGenericControl("div");
                        divSize.ID = "size";
                        divSize.Attributes.Add("class", "dynamicdiv");

                        int counter = newSizes.Count();
                        ViewState["NewSizesCounter"] = counter;

                        for (int i = 0; i < counter; i++)
                        {
                            HtmlGenericControl div = new HtmlGenericControl("div");
                            div.ID = "size" + i;
                            div.Attributes.Add("class", "dynamicdiv");

                            Table t = new Table();
                            TableRow r = new TableRow();
                            TableCell c1 = new TableCell();
                            c1.Attributes.Add("width", "200px");
                            TableCell c2 = new TableCell();

                            Label lbl = new Label();
                            lbl.ID = "lblSize" + i;
                            lbl.Text = newSizes.ToArray()[i].SizeName;
                            c1.Controls.Add(lbl);

                            DropDownList ddl = new DropDownList();
                            ddl.ID = "ddlSize" + i;
                            ddl.DataSource = from size in dct.TB_PropValues where size.Pid == prop.Pid && size.Cid == tbCid select new { Name = size.Name, Vid = size.Vid };
                            ddl.DataTextField = "Name";
                            ddl.DataValueField = "Vid";
                            ddl.DataBind();
                            c2.Controls.Add(ddl);

                            c1.Controls.Add(lbl);
                            c2.Controls.Add(ddl);
                            r.Cells.Add(c1);
                            r.Cells.Add(c2);
                            t.Rows.Add(r);

                            div.Controls.Add(t);
                            divSize.Controls.Add(div);
                        }

                        Button btnSubmit = new Button() { Text = "添加尺码匹配" };
                        btnSubmit.ID = "btnSizeSubmit";
                        btnSubmit.Click += btnSizeSubmit_Click;

                        if (counter == 0)
                        {
                            HtmlGenericControl div = new HtmlGenericControl("div");
                            div.ID = "divNoNewSize";
                            div.InnerText = "没有需要匹配的SS尺码";
                            divSize.Controls.Add(div);
                        }
                        else
                        {
                            divSize.Controls.Add(btnSubmit);
                        }

                        saleDiv.Controls.Add(divSize);
                    }
                    phPropsMapping.Controls.Add(saleDiv);
                }
                #endregion

                #region 显示必须属性
                var mustProps = from p in (from prop in dct.TB_ItemProps where prop.Cid == tbCid && prop.Must == true select prop) where !dct.Mapping_Categories_Props.Any(m => m.Mapping_Category.tb_cid == p.Cid && m.pid == p.Pid) select p;

                HtmlGenericControl mustDiv = new HtmlGenericControl("div");
                mustDiv.ID = "MustPropsSection";
                mustDiv.Attributes.Add("class", "dynamicdiv");

                int mustPropsCounter =  mustProps.Count();
                ViewState["MustPropsCounter"] = mustPropsCounter;

                for (int i = 0; i < mustPropsCounter; i++)
                {
                    if (mustProps.ToArray()[i].Name.Contains("尺码") || mustProps.ToArray()[i].Name.Contains("鞋尺码"))
                        continue;

                    HtmlGenericControl div = new HtmlGenericControl("div");
                    div.ID = "must" + i;
                    div.Attributes.Add("class", "dynamicdiv");

                    Table t = new Table();
                    TableRow r = new TableRow();
                    TableCell c1 = new TableCell();
                    c1.Attributes.Add("width", "200px");
                    TableCell c2 = new TableCell();

                    Label lbl = new Label();
                    lbl.ID = "lblMust" + i;
                    lbl.Text = mustProps.ToArray()[i].Name;
                    c1.Controls.Add(lbl);

                    DropDownList ddl = new DropDownList();
                    ddl.ID = "ddlMust" + i;
                    ddl.DataSource = from value in dct.TB_PropValues where value.Pid == mustProps.ToArray()[i].Pid && value.Cid == tbCatId select new { Name = value.Name, Vid = value.Vid };
                    ddl.DataTextField = "Name";
                    ddl.DataValueField = "Vid";
                    ddl.DataBind();
                    c2.Controls.Add(ddl);

                    c1.Controls.Add(lbl);
                    c2.Controls.Add(ddl);
                    r.Cells.Add(c1);
                    r.Cells.Add(c2);
                    t.Rows.Add(r);

                    div.Controls.Add(t);
                    mustDiv.Controls.Add(div);

                }

                Button btnMustSubmit = new Button() { Text = "添加必须属性匹配" };
                btnMustSubmit.ID = "btnMustSubmit";
                btnMustSubmit.Click += btnMustSubmit_Click;

                if (mustPropsCounter == 0)
                {
                    HtmlGenericControl div = new HtmlGenericControl("div");
                    div.ID = "divNoMustProp";
                    div.InnerText = "没有需要匹配的必须属性";
                    mustDiv.Controls.Add(div);
                }
                else
                {
                    mustDiv.Controls.Add(btnMustSubmit);
                }

                phPropsMapping.Controls.Add(mustDiv);

                #endregion

            }
        }
        protected void ddlModels_SelectedIndexChanged(object sender, EventArgs e)
        {
            using (CatalogDataContext dct = new CatalogDataContext())
            {
                var model = dct.TB_Models.SingleOrDefault(o => o.model_name == "拍前必读");

                FCKeditor1.Value = FCKeditor1.Value + model.model_html;
            }
        }
        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();
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {

                string pid = Request.Params["Pid"];
                string catid = Request.Params["CatId"];
                string fts = Request.Params["Fts"];
                string prosetName = Request.Params["ProSetName"];
                if (!string.IsNullOrWhiteSpace(pid))
                {
                    try
                    {
                        using (var ssService = new ShopStyleService())
                        {
                            var pids = pid.Split(',').Select(m => m.Trim()).ToList();
                            var searchList = Cache[SearchKey] as List<Product>;
                            if (searchList == null)
                            {
                                Response.Write("{'data':'0'}");
                                Response.End();
                            }
                            var selectList = new List<Product>();
                            if (pid.Contains(","))
                            {
                                selectList =
                                    searchList.Where(
                                        m => pids.Contains(m.getId().ToString(CultureInfo.InvariantCulture)))
                                        .ToList();

                            }
                            else
                            {
                                long id;
                                if (long.TryParse(pid, out id))
                                {
                                    selectList = searchList.Where(m => m.getId() == id).ToList();

                                }
                            }
                            if (selectList.Count > 0)
                            {
                                ssService.DownloadProductsByProducts(fts, catid, prosetName,
                                    selectList);
                                Response.Write("{'data':'1'}");
                                return;
                            }
                            else
                            {
                                Response.Write("{'data':'0'}");
                                return;
                            }
                        }
                    }
                    catch (ShopStyle.APIException ex)
                    {
                        string message = ex.getMessage()
                            .Replace("\n", "\\n")
                            .Replace("\r", "")
                            .Replace("'", "\\'");
                        Response.Write("{'data':'-1','msg':'" + message + "'}");
                        return;
                    }
                    catch (Exception ex)
                    {
                        string message = ex.Message.Replace("\n", "\\n").Replace("\r", "").Replace("'", "\\'");
                        Response.Write("{'data':'-1','msg':'" + message + "'}");
                        return;
                    }
                    finally
                    {
                        Response.End();
                    }

                }
                #region 初始化下拉框数据
                using (CatalogDataContext dct = new CatalogDataContext())
                {
                    ddlBrands.DataSource = dct.SS_Brands.OrderBy(b => b.brand_name);
                    ddlBrands.DataTextField = "brand_name";
                    ddlBrands.DataValueField = "brand_id";
                    ddlBrands.DataBind();
                    ddlBrands.Items.Insert(0, new ListItem("", ""));

                    ddlCategories.DataSource = dct.SS_Categories.OrderBy(c => c.cat_id);
                    ddlCategories.DataTextField = "cat_id";
                    ddlCategories.DataValueField = "cat_id";
                    ddlCategories.DataBind();
                    ddlCategories.Items.Insert(0, new ListItem("", ""));

                    ddlRetailers.DataSource = dct.SS_Retailers.OrderBy(r => r.name);
                    ddlRetailers.DataTextField = "name";
                    ddlRetailers.DataValueField = "retailer_id";
                    ddlRetailers.DataBind();
                    ddlRetailers.Items.Insert(0, new ListItem("", ""));

                    ddlColors.DataSource = dct.SS_Colors.OrderBy(c => c.color_name);
                    ddlColors.DataTextField = "color_name";
                    ddlColors.DataValueField = "color_id";
                    ddlColors.DataBind();
                    ddlRetailers.Items.Insert(0, new ListItem("", ""));

                }
                #endregion
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                CatalogDataContext dct = new CatalogDataContext();

                if (!this.IsPostBack)
                {

                    //获取所有SS_Product的分类
                    var ssCats = (from mapping in dct.SS_Product_Category_Mappings select new { Name = mapping.SS_Category.name, CatID = mapping.cat_id}).Distinct();
                    if (ssCats != null)
                    {
                        ddlSSCats.DataSource = ssCats;
                        ddlSSCats.DataTextField = "CatID";
                        ddlSSCats.DataValueField = "CatID";
                        ddlSSCats.DataBind();
                    }

                    //获取淘宝分类列表
                    var tbParentCats = from cat in dct.TB_ItemCats where new[] { 16L, 50013864L, 50011740L, 30L, 50006842L, 50010404L, 50006843L }.Contains(cat.Cid) select cat;
                    tvCats.Nodes.Clear();

                    foreach (var cat in tbParentCats)
                    {
                        TreeNode node = new TreeNode(cat.Name, cat.Cid.ToString());
                        tvCats.Nodes.Add(node);
                    }

                    foreach (TreeNode node in tvCats.Nodes)
                    {
                        populateNode(node);
                    }

                    if (ddlSSCats.SelectedItem != null)
                    {
                        string ssCid = ddlSSCats.SelectedItem.Value;
                        findAndHightLightNode(ssCid);
                    }
                }

                if ( this.IsPostBack && !string.IsNullOrEmpty(tvCats.SelectedValue) && (string.IsNullOrEmpty(this.GetPostBackControlId()) || this.GetPostBackControlId() == "btnSaveCat"))
                    populateProps(long.Parse(tvCats.SelectedValue));

            }
            catch (Exception ex)
            {
                string message = ex.Message.Replace("\n", "\\n").Replace("\r", "").Replace("'", "\\'");
                ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('" + message + "')", true);
            }
        }