import products with variants online

Reza sh asked on November 18, 2015 10:12

hi. i'm using the API for import products in website. i'm ok with API and work well. but my products are Clothes and clothes has Size and Color and i want import Variants of Product too...! i saw the database and realized when the i add variant for one product, the variants add in SKU table in sqlServer. how can i import the variants of product?! every products may has different color and size, shoes size = 36 ... 42, T-Shirt = S-M-L-..., Belts = medium or ...

thanks

Correct Answer

Timothy Fenton answered on November 23, 2015 16:56

hello again Reza, those examples that I was talking about in my previous message are available in API examples you would just use those in that order.

//create the new product 
private bool CreateProduct()
{
    // Get the deparment
    DepartmentInfo department = DepartmentInfoProvider.GetDepartmentInfo("MyNewDepartment", SiteContext.CurrentSiteName);

    // Create new product object
    SKUInfo newProduct = new SKUInfo();

    // Set the properties
    newProduct.SKUName = "MyNewProduct";
    newProduct.SKUPrice = 120;
    newProduct.SKUEnabled = true;
    if (department != null)
    {
        newProduct.SKUDepartmentID = department.DepartmentID;
    }
    newProduct.SKUSiteID = SiteContext.CurrentSiteID;

    // Create the product
    SKUInfoProvider.SetSKUInfo(newProduct);

    return true;
}

//create new product page

private bool CreateProductDocument()
{
    // Get the product
    var product = SKUInfoProvider.GetSKUs()
                            .WhereStartsWith("SKUName", "MyNewProduct")
                            .FirstOrDefault();

    TreeProvider tree = new TreeProvider(MembershipContext.AuthenticatedUser);

    // Get the parent document
    TreeNode parent = tree.SelectSingleNode(SiteContext.CurrentSiteName, "/Products", TreeProvider.ALL_CULTURES, true, "cms.menuitem");

    if ((parent != null) && (product != null))
    {
        // Create a new product document 
        SKUTreeNode node = (SKUTreeNode)TreeNode.New("CMS.Product", tree);

        // Set the document properties
        node.DocumentSKUName = "MyNewProduct";
        node.DocumentCulture = LocalizationContext.PreferredCultureCode;

        // Assign product to document
        node.NodeSKUID = product.SKUID;

        // Save the product document
        node.Insert(parent);

        return true;
    }

    return false;
}

//create new product option category
private bool CreateOptionCategory()
{
    // Create new option category object
    OptionCategoryInfo newCategory = new OptionCategoryInfo();

    // Set the properties
    newCategory.CategoryDisplayName = "My new category";
    newCategory.CategoryName = "MyNewCategory";
    newCategory.CategoryType = OptionCategoryTypeEnum.Products;
    newCategory.CategorySelectionType = OptionCategorySelectionTypeEnum.Dropdownlist;
    newCategory.CategoryDisplayPrice = true;
    newCategory.CategoryEnabled = true;
    newCategory.CategoryDefaultRecord = "";
    newCategory.CategorySiteID = SiteContext.CurrentSiteID;

    // Create the option category
    OptionCategoryInfoProvider.SetOptionCategoryInfo(newCategory);

    return true;
}

//create new product option
private bool CreateOption()
{
    // Get the department
    DepartmentInfo department = DepartmentInfoProvider.GetDepartmentInfo("MyNewDepartment", SiteContext.CurrentSiteName);

    // Get the option category
    OptionCategoryInfo category = OptionCategoryInfoProvider.GetOptionCategoryInfo("MyNewCategory", SiteContext.CurrentSiteName);

    if ((department != null) && (category != null))
    {
        // Create new product option object
        SKUInfo newOption = new SKUInfo();

        // Set the properties
        newOption.SKUName = "MyNewProductOption";
        newOption.SKUPrice = 199;
        newOption.SKUEnabled = true;
        newOption.SKUDepartmentID = department.DepartmentID;
        newOption.SKUOptionCategoryID = category.CategoryID;
        newOption.SKUSiteID = SiteContext.CurrentSiteID;
        newOption.SKUProductType = SKUProductTypeEnum.Product;

        // Create the product option
        SKUInfoProvider.SetSKUInfo(newOption);

        return true;
    }

    return false;
}

//add the product option category to product
private bool AddCategoryToProduct()
{
    // Get the data
    var product = SKUInfoProvider.GetSKUs()
                       .WhereStartsWith("SKUName", "MyNewProduct")
                       .WhereNull("SKUOptionCategoryID")
                       .FirstOrDefault();

    // Get the option category
    OptionCategoryInfo category = OptionCategoryInfoProvider.GetOptionCategoryInfo("MyNewCategory", SiteContext.CurrentSiteName);

    if ((product != null) && (category != null))
    {
        // Add category to product
        SKUOptionCategoryInfoProvider.AddOptionCategoryToSKU(category.CategoryID, product.SKUID);

        return true;
    }

    return false;
}

//add the product option to sku
private bool AllowOptionForProduct()
{
    // Get the data
    var product = SKUInfoProvider.GetSKUs()
                       .WhereStartsWith("SKUName", "MyNewProduct")
                       .WhereNull("SKUOptionCategoryID")
                       .FirstOrDefault();

    // List of options IDs
    List<int> optionIds = new List<int>();

    // Get the data
    var option = SKUInfoProvider.GetSKUs()
                       .WhereStartsWith("SKUName", "MyNewProduct")
                       .WhereNotNull("SKUOptionCategoryID")
                       .FirstOrDefault();

    // Get the option
    if (option != null)
    {
        optionIds.Add(option.SKUID);
    }

    // Get the option category
    OptionCategoryInfo category = OptionCategoryInfoProvider.GetOptionCategoryInfo("MyNewCategory", SiteContext.CurrentSiteName);

    if ((product != null) && (option != null) && (category != null))
    {
        // Allow options for product
        ProductHelper.AllowOptions(product.SKUID, category.CategoryID, optionIds);

        return true;
    }

    return false;
}

//create a variant 

private bool CreateVariants()
{
    // Get product
    var product = SKUInfoProvider.GetSKUs()
                       .WhereStartsWith("SKUName", "MyNewProduct")
                       .WhereNull("SKUOptionCategoryID")
                       .FirstOrDefault();

    if (product == null)
    {
        return false;
    }

    // List of categories
    List<int> categoryIDs = new List<int>();

    // Create two attribute option categories with options
    for (int i = 1; i <= 2; i++)
    {
        OptionCategoryInfo newCategory = new OptionCategoryInfo
        {
            CategoryDisplayName = "My new attribute category "+ i,
            CategoryName = "MyNewAttributteCategory" + i,
            CategoryType = OptionCategoryTypeEnum.Attribute,
            CategorySelectionType = OptionCategorySelectionTypeEnum.Dropdownlist,
            CategoryDisplayPrice = true,
            CategoryEnabled = true,
            CategoryDefaultRecord = "",
            CategorySiteID = SiteContext.CurrentSiteID
        };

        // Set category and add to product
        OptionCategoryInfoProvider.SetOptionCategoryInfo(newCategory);
        SKUOptionCategoryInfoProvider.AddOptionCategoryToSKU(newCategory.CategoryID, product.SKUID);
        categoryIDs.Add(newCategory.CategoryID);

        // Create two product options for new attribute category
        foreach (var color in new[] { "Black", "White" })
        {
            SKUInfo newOption = new SKUInfo
            {
                SKUName = "MyNewColorOption" + color,
                SKUPrice = 0,
                SKUEnabled = true,
                SKUOptionCategoryID = newCategory.CategoryID,
                SKUSiteID = SiteContext.CurrentSiteID,
                SKUProductType = SKUProductTypeEnum.Product
            };

            // Set option and add to product
            SKUInfoProvider.SetSKUInfo(newOption);
            SKUAllowedOptionInfoProvider.AddOptionToProduct(product.SKUID, newOption.SKUID);
        }
    }

    // Generate variants
    List<ProductVariant> variants = VariantHelper.GetAllPossibleVariants(product.SKUID, categoryIDs);

    // Set variants
    foreach (var variant in variants)
    {
        VariantHelper.SetProductVariant(variant);
    }

    return true;
}

it seemed like a lot of code to put in here, but these are the API examples for each item, of course if you are doing them all together at one time, you wont need to keep calling the objectqueries to get the current product or current product option because you will already have them from creating them.

Hope this helps

0 votesVote for this answer Unmark Correct answer

Recent Answers


Timothy Fenton answered on November 23, 2015 12:50 (last edited on November 23, 2015 12:50)

Hello Reza, there are actually some api examples for handling product options / variants you can see the API Examples in the API Examples application. You should look at the following examples under the Ecommerce tab:

Product option category > Create category

Product option > Create Option

Option for Product > Allow option for product

Product variants > Create Product Variants

If you do not have the API Examples module installed, I would recommend installing it on a fresh instance as it has tons of exmamples like these.

Hope this helps

0 votesVote for this answer Mark as a Correct answer

Reza sh answered on November 23, 2015 13:09

hello Timothy. thanks for your answer. so can you give me an example from import product with variant please? i already use an Api from import product , and work well, but we have 2 product option and many variant for product, how can i import these attribute with product? again , i don't want kentico import toolkid , i want api.

thanksssss :X

0 votesVote for this answer Mark as a Correct answer

Reza sh answered on November 23, 2015 17:18

well thanks a lot :X

0 votesVote for this answer Mark as a Correct answer

Reza sh answered on December 6, 2015 07:25

dear timothy. i founded the api used in kentico 7 for import product with variant and option. i want use this in kentico 8.2 but it seems the 8.2 classes has changed. would you help me to change the classes for use in kentico 8.2? thanks.

using System;

using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.HtmlControls; using System.IO;

using CMS.Ecommerce; using CMS.DocumentEngine; using CMS.CMSHelper; using CMS.FormEngine; using CMS.IDataConnectionLibrary; using CMS.SettingsProvider; using CMS.GlobalHelper; using CMS.DataEngine; using CMS.SiteProvider; using CMS.PortalEngine; using System.Collections.Generic; using System.Data.OleDb; using System.Linq; using CMS.PortalControls;

public partial class CMSWebParts_JeansWest_ImportProductsData : System.Web.UI.UserControl { #region "Private variables"

// Document owner
private string userName = "Administrator";
private CMS.DocumentEngine.TreeProvider tree = null;
private string siteName = "";
private string cultureCode = "fa-IR";
private int siteId = 0;

#endregion

#region "Methods"

protected void Page_Load(object sender, EventArgs e)
{
    btnUpload.OnClientClick = "this.disabled = true; " + Page.ClientScript.GetPostBackEventReference(btnUpload, null) + ";";
}


private void DeleteOptions(int skuId)
{
    string wheresoci = "SKUID = " + skuId;
    InfoDataSet<SKUOptionCategoryInfo> optionCategoryInfos =
        SKUOptionCategoryInfoProvider.GetSKUOptionCategories(wheresoci, "");
    if (!DataHelper.DataSourceIsEmpty(optionCategoryInfos))
    {
        foreach (DataRow rowsoci in optionCategoryInfos.Tables[0].Rows)
        {
            //string wheresi = "SKUOptionCategoryID = " + rowsoci["CategoryID"];
            //InfoDataSet<SKUInfo> skuInfos = SKUInfoProvider.GetSKUs(wheresi, "");
            //if (!DataHelper.DataSourceIsEmpty(skuInfos))
            //{
            //    foreach (DataRow rowsi in skuInfos.Tables[0].Rows)
            //    {
            //        SKUInfoProvider.DeleteSKUInfo(int.Parse(rowsi["SKUID"].ToString()));
            //    }
            //}
            SKUOptionCategoryInfo sociItem =
                SKUOptionCategoryInfoProvider.GetSKUOptionCategoryInfo(int.Parse(rowsoci["CategoryID"].ToString()),
                    skuId);
            SKUOptionCategoryInfoProvider.DeleteSKUOptionCategoryInfo(sociItem);
            //OptionCategoryInfoProvider.DeleteOptionCategoryInfo(sociItem.CategoryID);
        }
    }
}


/// <summary>
/// Imports products from the specified file in *.csv format
/// </summary>
/// <param name="filePath"></param>
/// <returns></returns>
private string Import(List<ProductStruct> lstProducts, string parentDoc, string doc)
{
    string ptiWhere = "PageTemplateCodeName = N'JeansWestProductDetail'";
    DataSet temps = PageTemplateInfoProvider.GetTemplates(ptiWhere, null);
    PageTemplateInfo pti = new PageTemplateInfo(temps.Tables[0].Rows[0]);

    string error = "";
    if (error == "")
    {
        // Get product default department
        //DepartmentInfo defaultDepartment = GetDefaultDepartment();

        // Get product parent document
        TreeNode parentDocument = GetProductParentDocument(parentDoc, doc);

        // Get default product document type
        DataClassInfo productDocumentType = GetProductDocumentType();


        if ((parentDocument == null) || (productDocumentType == null))
        {
            error = "Unable to create products, information missing: default department or parent document or document type";
        }
        else
        {

            #region AddProduct

            var CodeGroupBy = from p in lstProducts
                              group p by p.JWCodeTemp into g
                              select g;
            foreach (var cdeItemList in CodeGroupBy)
            {
                List<ProductStruct> TempCodeGroupedBy = new List<ProductStruct>();
                foreach (var codeItem in cdeItemList)
                {

                    ProductStruct ps = new ProductStruct();
                    ps.Category = codeItem.Category;
                    ps.Color = codeItem.Color;
                    ps.Desc = codeItem.Desc;
                    ps.JWCodeTemp = codeItem.JWCodeTemp;
                    ps.MainCode = codeItem.MainCode;
                    ps.Size = codeItem.Size;
                    ps.Type = codeItem.Type;
                    ps.Title = codeItem.Title;
                    ps.ENColor = codeItem.ENColor;
                    ps.FAColor = codeItem.FAColor;

                    TempCodeGroupedBy.Add(ps);

                }

                #region CreateMainSKU

                SKUInfo sku = new SKUInfo();
                int idx = TempCodeGroupedBy[0].MainCode.ToString().IndexOf('-');
                string where = "";
                if (idx == -1)
                    where = "SKUNumber = N'" + TempCodeGroupedBy[0].MainCode.Substring(0, 8) + "'";
                else
                    where = "SKUNumber = N'" + TempCodeGroupedBy[0].MainCode.Substring(0, idx) + "'";
                DataSet existSku = SKUInfoProvider.GetSKUs(where, null);

                if (existSku.Tables[0].Rows.Count < 1)
                {
                    // Creat product (SKU)
                    if (idx == -1)
                    {
                        sku.SKUName = TempCodeGroupedBy[0].Title + " " +
                                      TempCodeGroupedBy[0].MainCode.Substring(0, 8);
                        sku.SKUNumber = TempCodeGroupedBy[0].MainCode.Substring(0, 8);
                    }
                    else
                    {
                        sku.SKUName = TempCodeGroupedBy[0].Title + " " +
                                      TempCodeGroupedBy[0].MainCode.Substring(0, idx);
                        sku.SKUNumber = TempCodeGroupedBy[0].MainCode.Substring(0, idx);
                    }

                    sku.SKUDescription = TempCodeGroupedBy[0].Desc;
                    //sku.SetValue("SKUProductCode", TempCodeGroupedBy[0].JWCodeTemp);
                    sku.SKUPrice = 0;
                    sku.SKUEnabled = true;
                    sku.SKUNeedsShipping = true;
                    sku.SKUSiteID = siteId;
                    sku.SKUProductType = SKUProductTypeEnum.Product;

                    DepartmentInfo department = null;
                    if (department != null)
                    {
                        // Assign product to its department
                        sku.SKUDepartmentID = department.DepartmentID;
                    }
                    else
                    {
                        // Assign product to the default department
                        sku.SKUDepartmentID = 0;
                    }

                    try
                    {
                        SKUInfoProvider.SetSKUInfo(sku);

                    }
                    catch
                    {
                        error += "Unable to create product '" + sku.SKUName + "'. <br />";
                    }
                }
                else
                {
                    sku = new SKUInfo(existSku.Tables[0].Rows[0]);
                }

                #endregion


                var ColorGroupBy = from p in TempCodeGroupedBy
                                   group p by new { p.Color, p.ENColor, p.FAColor } into g
                                   select g;
                List<OptionCategoryInfo> lstOCColor = new List<OptionCategoryInfo>();
                foreach (var colorItemList in ColorGroupBy)
                {
                    bool IsExist;
                    OptionCategoryInfo OCColor = CreateOptionCategory("{$=" + colorItemList.Key.ENColor.ToString() + "|fa-IR=" + colorItemList.Key.FAColor + "$}", TempCodeGroupedBy[0].JWCodeTemp + colorItemList.Key.Color.Replace(" ", "").Replace("/", "").Replace(".", ""), out IsExist);
                    //if (!IsExist)
                    lstOCColor.Add(OCColor);

                    List<ProductStruct> TempColorGroupedBy = new List<ProductStruct>();
                    foreach (var colorItem in colorItemList)
                    {
                        ProductStruct ps = new ProductStruct();
                        ps.Category = colorItem.Category;
                        ps.Color = colorItem.Color;
                        ps.Desc = colorItem.Desc;
                        ps.JWCodeTemp = colorItem.JWCodeTemp;
                        ps.MainCode = colorItem.MainCode;
                        ps.Size = colorItem.Size;
                        ps.Type = colorItem.Type;
                        ps.Title = colorItem.Title;

                        TempColorGroupedBy.Add(ps);
                    }
                    var SizeGroupBy = from p in TempColorGroupedBy
                                      group p by p.Size into g
                                      select g;

                    bool IsFirst = true;
                    foreach (var sizeItemList in SizeGroupBy)
                    {
                        foreach (var item in sizeItemList)
                        {

                            CreateOption(item.Size, item.MainCode, OCColor.CategoryName, OCColor.CategoryID, IsFirst);
                            IsFirst = false;
                        }
                    }
                }



                foreach (var item in lstOCColor)
                {
                    AddCategoryToProduct(sku.SKUID, item.CategoryID);
                }
                // If product was create succesfully
                if (existSku.Tables[0].Rows.Count < 1)
                {
                    if (sku.SKUID > 0)
                    {
                        // Create product document type and assign SKU to it
                        TreeNode productDoc = TreeNode.New("Document.JeansWestProduct", tree);
                        productDoc.SetValue("ProductName", sku.SKUName);
                        productDoc.SetValue("ProductPrice", sku.SKUPrice);
                        productDoc.SetValue("ProductCategory", 0);
                        productDoc.SetValue("ProductType", 0);
                        productDoc.SetValue("NodeTemplateID", pti.PageTemplateId);
                        productDoc.SetValue("DocumentPageTemplateID", pti.PageTemplateId);
                        productDoc.SetValue("DocumentMenuItemHideInNavigation", 1);

                        productDoc.DocumentName = sku.SKUName;
                        productDoc.NodeSKUID = sku.SKUID;
                        productDoc.DocumentCulture = cultureCode;

                        try
                        {
                            productDoc.Insert(parentDocument, true);
                        }
                        catch
                        {
                            error += "Unable to create document '" + sku.SKUName + "'. <br />";
                            SKUInfoProvider.DeleteSKUInfo(sku.SKUID);
                        }
                    }
                }
            }
            #endregion


            // Close file


            // Display number of created products
            //lblInfo.Text = "Number of created products: " + count;
        }
    }

    return error;
}


/// <summary>
/// Ensures default department exists.
/// </summary>    
private DepartmentInfo GetDefaultDepartment()
{
    // Try to get default department    
    DepartmentInfo defaultDepartment = DepartmentInfoProvider.GetDepartmentInfo("DefaultDepartment", siteName);

    // If default department doesnt exist, create new one
    if (defaultDepartment == null)
    {
        defaultDepartment = new DepartmentInfo();
        defaultDepartment.DepartmentDisplayName = "Default department";
        defaultDepartment.DepartmentName = "DefaultDepartment";
        defaultDepartment.DepartmentDefaultTaxClassID = 0;
        defaultDepartment.DepartmentSiteID = siteId;
        DepartmentInfoProvider.SetDepartmentInfo(defaultDepartment);
    }

    return defaultDepartment;
}


/// <summary>
/// Ensures parent document for product documents exists.
/// </summary>
private TreeNode GetProductParentDocument(string parentDoc, string doc)
{
    TreeNode parent = null;

    // Try to get products' parent document
    if (parentDoc.Contains("Accessories"))
    {
        if (parentDoc.Length > 12)
            parent = tree.SelectSingleNode(siteName, "/Products/Accessories/" + parentDoc.Substring(12) + "/" + doc, cultureCode, false, "Document.JeansWestProductCategory");
        else
            parent = tree.SelectSingleNode(siteName, "/Products/Accessories/Other/" + doc, cultureCode, false, "Document.JeansWestProductCategory");
    }
    else
        parent = tree.SelectSingleNode(siteName, "/Products/" + parentDoc + "/" + doc, cultureCode, false, "Document.JeansWestProductCategory");

    // Parent not found
    if (parent == null)
    {
        // Get products parent
        TreeNode productparent = null;
        if (parentDoc.Contains("Accessories"))
        {
            if (parentDoc.Length > 12)
                productparent = tree.SelectSingleNode(siteName, "/Products/Accessories/" + parentDoc.Substring(12), cultureCode, false, "Document.JeansWestProductCategory");
            else
                productparent = tree.SelectSingleNode(siteName, "/Products/Accessories/Other", cultureCode, false, "Document.JeansWestProductCategory");
        }
        else
            productparent = tree.SelectSingleNode(siteName, "/Products/" + parentDoc, cultureCode, false, "Document.JeansWestProductCategory");

        if (productparent != null)
        {
            // Create new parent document
            parent = TreeNode.New("Document.JeansWestProductCategory", tree);
            parent.SetValue("MenuItemName", doc);
            parent.DocumentName = doc;
            parent.DocumentCulture = cultureCode;
            parent.Insert(productparent, true);
        }
    }

    return parent;
}


/// <summary>
/// Ensures default product document type exists.
/// </summary>    
private DataClassInfo GetProductDocumentType()
{
    // Try to get default product document type
    string className = "Document.JeansWestProduct";
    DataClassInfo defaultProductType = DataClassInfoProvider.GetDataClass(className);

    // Default product document type not found -> create new one
    if (defaultProductType == null)
    {
        string tableName = "Document.JeansWestProduct";
        string primaryKey = "DefaultProductID";

        // Initialize new product type
        defaultProductType = new DataClassInfo();
        defaultProductType.ClassDisplayName = "Default product";
        defaultProductType.ClassName = "custom.defaultproduct";
        defaultProductType.ClassIsDocumentType = true;
        defaultProductType.ClassUsePublishFromTo = true;
        defaultProductType.ClassTableName = tableName;
        defaultProductType.ClassIsProduct = true;

        try
        {
            // Save document type 
            DataClassInfoProvider.SetDataClass(defaultProductType);

            TableManager tm = new TableManager(defaultProductType.ClassConnectionString);

            // Create document type table
            tm.CreateTable(tableName, primaryKey);

            // Add table columns                
            tm.AddTableColumn(tableName, "ProductName", "nvarchar(200)", false, null);

            // Create document type form definition
            FormInfo form = new FormInfo("<form></form>");
            FormFieldInfo field = new FormFieldInfo();

            // Create primary key field
            field.Name = primaryKey;
            field.Caption = primaryKey;
            field.DataType = FormFieldDataTypeEnum.Integer;
            field.DefaultValue = "";
            field.Description = "";
            field.FieldType = FormFieldControlTypeEnum.LabelControl;
            field.PrimaryKey = true;
            field.System = false;
            field.Visible = true;
            field.Size = 0;
            field.AllowEmpty = false;

            // Add primary key field
            form.AddFormField(field);

            // Update document type
            defaultProductType.ClassXmlSchema = tm.GetXmlSchema(tableName);
            defaultProductType.ClassFormDefinition = form.GetXmlDefinition();
            defaultProductType.ClassNodeNameSource = "ProductName";
            defaultProductType.ClassIsCoupledClass = true;
            DataClassInfoProvider.SetDataClass(defaultProductType);


            // Ensure default permissions
            PermissionNameInfoProvider.CreateDefaultClassPermissions(defaultProductType.ClassID);

            // Genereate default view for document type
            SqlGenerator.GenerateDefaultView(defaultProductType, siteName);  // Since version 3.1a

            // Allow product type to be inserted as a child of the menu item type
            DataClassInfo parentClass = DataClassInfoProvider.GetDataClass("cms.menuitem");
            if (parentClass != null)
            {
                AllowedChildClassInfoProvider.AddAllowedChildClass(parentClass.ClassID, defaultProductType.ClassID);
            }

            // Add product type to site
            ClassSiteInfoProvider.AddClassToSite(defaultProductType.ClassID, siteId);

            // Create product default transformation
            TransformationInfo ti = new TransformationInfo();
            ti.TransformationName = ResHelper.GetString("TransformationName.Default");
            ti.TransformationFullName = className + "." + ti.TransformationName;
            ti.TransformationCode = TransformationInfoProvider.GenerateTransformationCode(defaultProductType.ClassFormDefinition, TransformationTypeEnum.Ascx, className);
            ti.TransformationType = TransformationTypeEnum.Ascx;
            ti.TransformationClassID = defaultProductType.ClassID;
            TransformationInfoProvider.SetTransformation(ti);

            // Document type icon
            try
            {
                // Get default icon path
                string sourceFile = "~/App_Themes/Images/DocumentTypeIcons/default.png";

                // Get document type icon path
                string destFile = "~/App_Themes/Images/DocumentTypeIcons/" + className.Replace(".", "_") + ".png";

                // Create new document type icon via copying default icon    
                File.Copy(Server.MapPath(sourceFile), Server.MapPath(destFile), false);
            }
            catch (Exception e)
            {
                lblError.Text = e.Message;
            }

        }
        // Error while creating default product document type
        catch (Exception e)
        {
            // Remove all product type data
            DataClassInfoProvider.DeleteDataClass(className);
            lblError.Text = e.Message;
            return null;
        }
    }

    return defaultProductType;
}

#endregion

protected void btnUpload_Click(object sender, EventArgs e)
{
    if (flupld.HasFile)
    {
        //Page.ClientScript.RegisterStartupScript(this.GetType(), "label", "<script>document.getElementById('lblInfo').innerHTML = 'your tip has been submitted!';</script>");

        List<ProductStruct> lstProducts = new List<ProductStruct>();

        siteName = CMSContext.CurrentSiteName;
        siteId = CMSContext.CurrentSiteID;

        // Get user info
        UserInfo ui = UserInfoProvider.GetUserInfo(userName);
        if (ui != null)
        {
            tree = new TreeProvider(ui);
        }
        else
        {
            tree = new TreeProvider();
        }

        // Import products
        string fn = System.IO.Path.GetFileName(flupld.PostedFile.FileName);
        string SaveLocation = Server.MapPath("") + "\\" + fn;
        flupld.PostedFile.SaveAs(SaveLocation);

        #region ReadFile

        //Coneection String by default empty  
        string ConStr = "";
        //Extantion of the file upload control saving into ext because   
        //there are two types of extation .xls and .xlsx of Excel   
        string ext = Path.GetExtension(flupld.FileName).ToLower();
        //getting the path of the file   
        string path = Server.MapPath("~/CMSSiteUtils/Import/" + flupld.FileName);
        //saving the file inside the MyFolder of the server  
        flupld.SaveAs(path);
        //checking that extantion is .xls or .xlsx  
        if (ext.Trim() == ".xls")
        {
            //connection string for that file which extantion is .xls  
            ConStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\"";
        }
        else if (ext.Trim() == ".xlsx")
        {
            //connection string for that file which extantion is .xlsx  
            ConStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";
        }
        OleDbConnection conn = new OleDbConnection(ConStr);
        conn.Open();
        //making query 
        DataTable dtSchema = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
        string Sheet1 = dtSchema.Rows[0].Field<string>("TABLE_NAME");

        // Create OleDbCommand object and select data from worksheet Sheet1
        string query = "SELECT * FROM [" + Sheet1 + "]";
        //Providing connection  
        //checking that connection state is closed or not if closed the   
        //open the connection  
        if (conn.State == ConnectionState.Closed)
        {
            conn.Open();
        }
        //create command object  
        OleDbCommand cmd = new OleDbCommand(query, conn);
        // create a data adapter and get the data into dataadapter  
        OleDbDataAdapter da = new OleDbDataAdapter(cmd);
        DataSet ds = new DataSet();
        //fill the Excel data to data set  
        da.Fill(ds);
        #endregion

        try
        {
            // Specify file with product data
            foreach (DataRow row in ds.Tables[0].Rows)
            {
                if (row.ItemArray.Length > 6 && row.ItemArray[1].ToString() != "" && row.ItemArray[0].ToString() != "كد كالا")
                {
                    ProductStruct ps = new ProductStruct();
                    if (row.ItemArray[0].ToString().Contains('-'))
                    {
                        int idx = row.ItemArray[0].ToString().IndexOf('-');
                        ps.JWCodeTemp = row.ItemArray[0].ToString().Substring(0, idx);
                        ps.MainCode = row.ItemArray[0].ToString();
                    }
                    else
                    {
                        ps.JWCodeTemp = row.ItemArray[0].ToString().Substring(0, 8);
                        ps.MainCode = row.ItemArray[0].ToString();
                    }
                    ps.Category = row.ItemArray[6].ToString();
                    ps.Color = row.ItemArray[7].ToString().Replace(" ", "");
                    ps.Type = GetTypeByName(row.ItemArray[9].ToString());
                    ps.Size = row.ItemArray[8].ToString();
                    ps.Desc = row.ItemArray[3].ToString();
                    ps.Title = row.ItemArray[1].ToString();
                    ps.ENColor = row.ItemArray[13].ToString();
                    ps.FAColor = row.ItemArray[14].ToString();

                    lstProducts.Add(ps);
                }

            }
        }
        catch (Exception ex)
        {
            lblError.Text = "Error adding file '" + SaveLocation + "': " + ex.Message;
        }

        conn.Close();




        var CodeGroupBy = from p in lstProducts
                          group p by p.JWCodeTemp into g
                          select g;
        foreach (var cdeItemList in CodeGroupBy)
        {
            List<ProductStruct> TempCodeGroupedBy = new List<ProductStruct>();
            foreach (var codeItem in cdeItemList)
            {

                ProductStruct ps = new ProductStruct();
                ps.Category = codeItem.Category;
                ps.Color = codeItem.Color;
                ps.Desc = codeItem.Desc;
                ps.JWCodeTemp = codeItem.JWCodeTemp;
                ps.MainCode = codeItem.MainCode;
                ps.Size = codeItem.Size;
                ps.Type = codeItem.Type;
                ps.Title = codeItem.Title;
                ps.ENColor = codeItem.ENColor;
                ps.FAColor = codeItem.FAColor;

                TempCodeGroupedBy.Add(ps);

            }

            #region CreateMainSKU

            SKUInfo sku = new SKUInfo();
            int idx = TempCodeGroupedBy[0].MainCode.ToString().IndexOf('-');
            string where = "";
            if (idx == -1)
                where = "SKUNumber = N'" + TempCodeGroupedBy[0].MainCode.Substring(0, 8) + "'";
            else
                where = "SKUNumber = N'" + TempCodeGroupedBy[0].MainCode.Substring(0, idx) + "'";
            DataSet existSku = SKUInfoProvider.GetSKUs(where, null);

            if (existSku.Tables[0].Rows.Count > 0)
            {
                sku = new SKUInfo(existSku.Tables[0].Rows[0]);
            }

            #endregion

            DeleteOptions(sku.SKUID);
        }





        var tmp = from p in lstProducts
                  group p by new { p.Category, p.Type } into g
                  select g;

        foreach (var lstItem in tmp)
        {
            List<ProductStruct> lstTempPS = new List<ProductStruct>();
            foreach (var item in lstItem)
            {
                ProductStruct ps = new ProductStruct();
                ps.Category = item.Category;
                ps.Color = item.Color;
                ps.Desc = item.Desc;
                ps.JWCodeTemp = item.JWCodeTemp;
                ps.MainCode = item.MainCode;
                ps.Size = item.Size;
                ps.Type = item.Type;
                ps.Title = item.Title;
                ps.ENColor = item.ENColor;
                ps.FAColor = item.FAColor;

                lstTempPS.Add(ps);
            }
            lblError.Text = Import(lstTempPS, lstItem.Key.Type, lstItem.Key.Category);
        }
        lblSuccess.Visible = true;
    }
}
public class ProductStruct
{
    public string JWCodeTemp { get; set; }
    public string MainCode { get; set; }
    public string Category { get; set; }
    public string Color { get; set; }
    public string Type { get; set; }
    public string Size { get; set; }
    public string Desc { get; set; }
    public string Title { get; set; }
    public string ENColor { get; set; }
    public string FAColor { get; set; }
}
public enum ProductCategoryEnum
{
    Jacket = 1,
    Tshirts = 2,
    Shirt = 3,
    Pants = 4,
    Tee = 5,
    Socks = 6,
    Bag = 7,
    Underwear = 8,
    Shoes = 9,
    Sweater = 10,
    Blouse = 11,
    Unknown = 12
}
//public static ProductCategoryEnum GetCategoryByName(string categoryName)
//{
//    switch (categoryName)
//    {
//        case "Jacket":
//            return ProductCategoryEnum.Jacket;
//        case "Tshirts":
//            return ProductCategoryEnum.Tshirts;
//        case "Shirt":
//            return ProductCategoryEnum.Shirt;
//        case "Pants":
//            return ProductCategoryEnum.Pants;
//        case "Tee":
//            return ProductCategoryEnum.Tee;
//        case "Socks":
//            return ProductCategoryEnum.Socks;
//        case "Bag":
//            return ProductCategoryEnum.Bag;
//        case "Underwear":
//            return ProductCategoryEnum.Underwear;
//        case "Shoes":
//            return ProductCategoryEnum.Shoes;
//        case "Sweater":
//            return ProductCategoryEnum.Sweater;
//        case "Blouse":
//            return ProductCategoryEnum.Blouse;
//        default:
//            return ProductCategoryEnum.Unknown;
//    }
//}
public static string GetTypeByName(string type)
{
    switch (type)
    {
        case "M":
            return "Men";
        case "W":
            return "Women";
        case "ACC":
            return "Accessories";
        case "ACC-M":
            return "Accessories-Men";
        case "ACC-W":
            return "Accessories-Women";
        default:
            return type;
    }
}

private OptionCategoryInfo CreateOptionCategory(string category, string categoryNumber, out bool isExist)
{
    try
    {
        string where = "CategoryName = N'" + categoryNumber.Replace("+", "-") + "'";
        DataSet OptionCategories = OptionCategoryInfoProvider.GetOptionCategories(where, null);

        if (OptionCategories.Tables[0].Rows.Count < 1)
        {
            // Create new option category object
            OptionCategoryInfo newCategory = new OptionCategoryInfo();

            // Set the properties
            newCategory.CategoryDisplayName = category;
            newCategory.CategoryName = categoryNumber.Replace("+", "-");
            newCategory.CategorySelectionType = OptionCategorySelectionTypeEnum.RadioButtonsHorizontal;
            newCategory.CategoryEnabled = true;
            newCategory.CategoryDefaultRecord = "";
            newCategory.CategorySiteID = CMSContext.CurrentSiteID;
            newCategory.CategoryDisplayPrice = false;
            newCategory.CategoryDefaultOptions = "";

            // Create the option category
            OptionCategoryInfoProvider.SetOptionCategoryInfo(newCategory);
            isExist = false;
            return newCategory;
        }
        else
        {
            isExist = true;
            OptionCategoryInfo existItem = new OptionCategoryInfo(OptionCategories.Tables[0].Rows[0]);
            return existItem;
        }
    }
    catch (Exception)
    {
        throw;
    }

}

private SKUInfo CreateOption(string option, string optionNumber, string definedcategory, int definedcategoryId, bool isFirst)
{
    // Get the department
    DepartmentInfo department = DepartmentInfoProvider.GetDepartmentInfo("MyNewDepartment", CMSContext.CurrentSiteName);

    // Get the option category
    OptionCategoryInfo category = OptionCategoryInfoProvider.GetOptionCategoryInfo(definedcategory, CMSContext.CurrentSiteName);

    if ((category != null))
    {
        string where = "SKUNumber = N'" + optionNumber + "'";
        DataSet Options = SKUInfoProvider.GetSKUs(where, null);

        if (Options.Tables[0].Rows.Count < 1)
        {

            // Create new product option object
            SKUInfo newOption = new SKUInfo();

            // Set the properties
            newOption.SKUName = option;
            newOption.SKUNumber = optionNumber;
            newOption.SKUPrice = 0;
            newOption.SKUEnabled = true;
            newOption.SKUDepartmentID = 0;
            newOption.SKUOptionCategoryID = category.CategoryID;
            newOption.SKUSiteID = CMSContext.CurrentSiteID;
            newOption.SKUProductType = SKUProductTypeEnum.Product;
            newOption.SKUSellOnlyAvailable = true;
            newOption.SKUNeedsShipping = true;


            // Create the product option
            SKUInfoProvider.SetSKUInfo(newOption);

            if (isFirst)
            {
                string whereCO = "CategoryID = " + definedcategoryId;
                DataSet categories = OptionCategoryInfoProvider.GetOptionCategories(whereCO, null);
                OptionCategoryInfo info = new OptionCategoryInfo(categories.Tables[0].Rows[0]);
                if (info.CategoryDefaultOptions == "")
                {
                    info.CategoryDefaultOptions = newOption.SKUID.ToString();
                    OptionCategoryInfoProvider.SetOptionCategoryInfo(info);
                }
            }

            return newOption;
        }
        else
        {
            SKUInfo existItem = new SKUInfo(Options.Tables[0].Rows[0]);
            existItem.SKUOptionCategoryID = category.CategoryID;
            SKUInfoProvider.SetSKUInfo(existItem);

            if (isFirst)
            {
                string whereCO = "CategoryID = " + definedcategoryId;
                DataSet categories = OptionCategoryInfoProvider.GetOptionCategories(whereCO, null);
                OptionCategoryInfo info = new OptionCategoryInfo(categories.Tables[0].Rows[0]);
                if (info.CategoryDefaultOptions == "")
                {
                    info.CategoryDefaultOptions = existItem.SKUID.ToString();
                    OptionCategoryInfoProvider.SetOptionCategoryInfo(info);
                }
            }
            return existItem;
        }
    }

    return null;
}

private bool AddCategoryToProduct(int skuId, int categoryId)
{
    SKUOptionCategoryInfoProvider.AddOptionCategoryToSKU(categoryId, skuId);
    return true;
}

}

0 votesVote for this answer Mark as a Correct answer

   Please, sign in to be able to submit a new answer.