import Api Code in kentico 7 ,how to use for kentico 8.2

Reza sh asked on December 6, 2015 07:31

hi. there is the Api for import with variant in kentico 7. this api use for clothes product. i want use this for kentico 8.2 but i don't know how! because the classes has changed. is there anybody help me to use this?! 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;
}

}

Correct Answer

David te Kloese answered on December 6, 2015 20:01

Hi,

I advise you to take a look at the api changes if you run into any code errors here:

http://devnet.kentico.com/documentation/api-changes/kentico-8

On top of the same page you can also find the 'Kentico 8.0 code upgrade tool'. If you run this on your old code it will try to change all incompatible code.

Greets,

David

1 votesVote for this answer Unmark Correct answer

Recent Answers


Reza sh answered on December 6, 2015 21:42

hi. i checked this url but i can't to fix it. i'm a web designer (template and css html) not a professional developer. please help me or fix these codes. thanks.

0 votesVote for this answer Mark as a Correct answer

Reza sh answered on December 7, 2015 09:51

for example an error : DataSet products = SKUInfoProvider.GetSKUs(formatted, null);

in that article , said use GetSKUs(string , string) but it doesn't work!!!

some of the changed are deleted and said contact to support!!!

i want you change the 10 line of this error!!! its just 10 minutes for someone who know kentico classes!

0 votesVote for this answer Mark as a Correct answer

David te Kloese answered on December 7, 2015 11:51

Hi,

I understand it can be frustrating for a non-developer. But I don't think posting whole code files online is the solution. Don't you have a colleague who is a developer you can ask for help?

http://devnet.kentico.com/documentation/api-changes/kentico-8/1518 The api changes page reports the GetSKUs was removed. And you should now use object query method.

Details on how to use object query can be found here: http://devnet.kentico.com/articles/kentico-8-technology-dataquery-api

In your case it comes down to:

var skus = 
    SKUInfoProvider.GetSKUs()
        .Where("SKUNumber", QueryOperator.Equals, "123");

Greets,

David

0 votesVote for this answer Mark as a Correct answer

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