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"
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)
{
SKUOptionCategoryInfo sociItem =
SKUOptionCategoryInfoProvider.GetSKUOptionCategoryInfo(int.Parse(rowsoci["CategoryID"].ToString()),
skuId);
SKUOptionCategoryInfoProvider.DeleteSKUOptionCategoryInfo(sociItem);
}
}
}
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 == "")
{
TreeNode parentDocument = GetProductParentDocument(parentDoc, doc);
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)
{
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.SKUPrice = 0;
sku.SKUEnabled = true;
sku.SKUNeedsShipping = true;
sku.SKUSiteID = siteId;
sku.SKUProductType = SKUProductTypeEnum.Product;
DepartmentInfo department = null;
if (department != null)
{
sku.SKUDepartmentID = department.DepartmentID;
}
else
{
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);
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 (existSku.Tables[0].Rows.Count < 1)
{
if (sku.SKUID > 0)
{
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
}
}
return error;
}
private DepartmentInfo GetDefaultDepartment()
{
DepartmentInfo defaultDepartment = DepartmentInfoProvider.GetDepartmentInfo("DefaultDepartment", siteName);
if (defaultDepartment == null)
{
defaultDepartment = new DepartmentInfo();
defaultDepartment.DepartmentDisplayName = "Default department";
defaultDepartment.DepartmentName = "DefaultDepartment";
defaultDepartment.DepartmentDefaultTaxClassID = 0;
defaultDepartment.DepartmentSiteID = siteId;
DepartmentInfoProvider.SetDepartmentInfo(defaultDepartment);
}
return defaultDepartment;
}
private TreeNode GetProductParentDocument(string parentDoc, string doc)
{
TreeNode parent = null;
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");
if (parent == null)
{
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)
{
parent = TreeNode.New("Document.JeansWestProductCategory", tree);
parent.SetValue("MenuItemName", doc);
parent.DocumentName = doc;
parent.DocumentCulture = cultureCode;
parent.Insert(productparent, true);
}
}
return parent;
}
private DataClassInfo GetProductDocumentType()
{
string className = "Document.JeansWestProduct";
DataClassInfo defaultProductType = DataClassInfoProvider.GetDataClass(className);
if (defaultProductType == null)
{
string tableName = "Document.JeansWestProduct";
string primaryKey = "DefaultProductID";
defaultProductType = new DataClassInfo();
defaultProductType.ClassDisplayName = "Default product";
defaultProductType.ClassName = "custom.defaultproduct";
defaultProductType.ClassIsDocumentType = true;
defaultProductType.ClassUsePublishFromTo = true;
defaultProductType.ClassTableName = tableName;
defaultProductType.ClassIsProduct = true;
try
{
DataClassInfoProvider.SetDataClass(defaultProductType);
TableManager tm = new TableManager(defaultProductType.ClassConnectionString);
tm.CreateTable(tableName, primaryKey);
tm.AddTableColumn(tableName, "ProductName", "nvarchar(200)", false, null);
FormInfo form = new FormInfo("<form></form>");
FormFieldInfo field = new FormFieldInfo();
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;
form.AddFormField(field);
defaultProductType.ClassXmlSchema = tm.GetXmlSchema(tableName);
defaultProductType.ClassFormDefinition = form.GetXmlDefinition();
defaultProductType.ClassNodeNameSource = "ProductName";
defaultProductType.ClassIsCoupledClass = true;
DataClassInfoProvider.SetDataClass(defaultProductType);
PermissionNameInfoProvider.CreateDefaultClassPermissions(defaultProductType.ClassID);
SqlGenerator.GenerateDefaultView(defaultProductType, siteName);
DataClassInfo parentClass = DataClassInfoProvider.GetDataClass("cms.menuitem");
if (parentClass != null)
{
AllowedChildClassInfoProvider.AddAllowedChildClass(parentClass.ClassID, defaultProductType.ClassID);
}
ClassSiteInfoProvider.AddClassToSite(defaultProductType.ClassID, siteId);
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);
try
{
string sourceFile = "~/App_Themes/Images/DocumentTypeIcons/default.png";
string destFile = "~/App_Themes/Images/DocumentTypeIcons/" + className.Replace(".", "_") + ".png";
File.Copy(Server.MapPath(sourceFile), Server.MapPath(destFile), false);
}
catch (Exception e)
{
lblError.Text = e.Message;
}
}
catch (Exception e)
{
DataClassInfoProvider.DeleteDataClass(className);
lblError.Text = e.Message;
return null;
}
}
return defaultProductType;
}
#endregion
protected void btnUpload_Click(object sender, EventArgs e)
{
if (flupld.HasFile)
{
List<ProductStruct> lstProducts = new List<ProductStruct>();
siteName = CMSContext.CurrentSiteName;
siteId = CMSContext.CurrentSiteID;
UserInfo ui = UserInfoProvider.GetUserInfo(userName);
if (ui != null)
{
tree = new TreeProvider(ui);
}
else
{
tree = new TreeProvider();
}
string fn = System.IO.Path.GetFileName(flupld.PostedFile.FileName);
string SaveLocation = Server.MapPath("") + "\\" + fn;
flupld.PostedFile.SaveAs(SaveLocation);
#region ReadFile
string ConStr = "";
string ext = Path.GetExtension(flupld.FileName).ToLower();
string path = Server.MapPath("~/CMSSiteUtils/Import/" + flupld.FileName);
flupld.SaveAs(path);
if (ext.Trim() == ".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")
{
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();
DataTable dtSchema = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
string Sheet1 = dtSchema.Rows[0].Field<string>("TABLE_NAME");
string query = "SELECT * FROM [" + Sheet1 + "]";
if (conn.State == ConnectionState.Closed)
{
conn.Open();
}
OleDbCommand cmd = new OleDbCommand(query, conn);
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
#endregion
try
{
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 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)
{
OptionCategoryInfo newCategory = new OptionCategoryInfo();
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 = "";
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)
{
DepartmentInfo department = DepartmentInfoProvider.GetDepartmentInfo("MyNewDepartment", CMSContext.CurrentSiteName);
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)
{
SKUInfo newOption = new SKUInfo();
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;
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;
}
}