using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Data; using GZTW.AyaNova.BLL; using System.Threading; using CSLA.Security; using FileHelpers; using System.Collections.Generic; using System.IO; namespace AyaNova.PlugIn.ImportExportCSV { /// /// Summary description for Form1. /// public class ImportPart : System.Windows.Forms.Form { private System.Windows.Forms.DataGridView dataGrid1; private System.Windows.Forms.MainMenu mainMenu1; private System.Windows.Forms.MenuItem mnuOpen; private System.Windows.Forms.MenuItem mnuImport; private System.Windows.Forms.OpenFileDialog dlgOpen; private System.Windows.Forms.MenuItem mnuExport; private MenuItem mnuImportOptions; private IContainer components; public ImportPart() { // // Required for Windows Form Designer support // InitializeComponent(); this.Icon = Resource.ImportExportCSV16icon; } /// /// Clean up any resources being used. /// protected override void Dispose( bool disposing ) { if( disposing ) { if (components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Windows Form Designer generated code /// /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// private void InitializeComponent() { this.components = new System.ComponentModel.Container(); this.dataGrid1 = new System.Windows.Forms.DataGridView(); this.mainMenu1 = new System.Windows.Forms.MainMenu(this.components); this.mnuOpen = new System.Windows.Forms.MenuItem(); this.mnuImport = new System.Windows.Forms.MenuItem(); this.mnuExport = new System.Windows.Forms.MenuItem(); this.mnuImportOptions = new System.Windows.Forms.MenuItem(); this.dlgOpen = new System.Windows.Forms.OpenFileDialog(); ((System.ComponentModel.ISupportInitialize)(this.dataGrid1)).BeginInit(); this.SuspendLayout(); // // dataGrid1 // this.dataGrid1.Dock = System.Windows.Forms.DockStyle.Fill; this.dataGrid1.Location = new System.Drawing.Point(0, 0); this.dataGrid1.Name = "dataGrid1"; this.dataGrid1.ReadOnly = true; this.dataGrid1.Size = new System.Drawing.Size(632, 433); this.dataGrid1.TabIndex = 1; this.dataGrid1.BindingContextChanged += new System.EventHandler(this.dataGrid1_BindingContextChanged); // // mainMenu1 // this.mainMenu1.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] { this.mnuOpen, this.mnuImport, this.mnuExport, this.mnuImportOptions}); // // mnuOpen // this.mnuOpen.Index = 0; this.mnuOpen.Text = "&Open CSV file"; this.mnuOpen.Click += new System.EventHandler(this.mnuOpen_Click); // // mnuImport // this.mnuImport.Enabled = false; this.mnuImport.Index = 1; this.mnuImport.Text = "&Import data"; this.mnuImport.Click += new System.EventHandler(this.mnuImport_Click); // // mnuExport // this.mnuExport.Index = 2; this.mnuExport.Text = "&Export data"; this.mnuExport.Click += new System.EventHandler(this.mnuExport_Click); // // mnuImportOptions // this.mnuImportOptions.Index = 3; this.mnuImportOptions.Text = "&Duplicate import options"; this.mnuImportOptions.Visible = false; this.mnuImportOptions.Click += new System.EventHandler(this.mnuImportOptions_Click); // // dlgOpen // this.dlgOpen.DefaultExt = "csv"; this.dlgOpen.Filter = "CSV files|*.csv"; this.dlgOpen.Title = "Comma separated values part file"; // // ImportPart // this.AutoScaleBaseSize = new System.Drawing.Size(6, 15); this.ClientSize = new System.Drawing.Size(632, 433); this.Controls.Add(this.dataGrid1); this.Menu = this.mainMenu1; this.Name = "ImportPart"; this.Text = "Part importer v2.0.0.0"; this.WindowState = System.Windows.Forms.FormWindowState.Maximized; this.Load += new System.EventHandler(this.Form1_Load); ((System.ComponentModel.ISupportInitialize)(this.dataGrid1)).EndInit(); this.ResumeLayout(false); } #endregion //----------------------------------------------------------------------------- // // _________ __ // \_ ___ \ __ __ _______/ |_ ____ _____ // / \ \/ | | \ / ___/\ __\ / _ \ / \ // \ \____| | / \___ \ | | ( <_> )| Y Y \ // \______ /|____/ /____ > |__| \____/ |__|_| / // \/ \/ \/ // _________ .___ // \_ ___ \ ____ __| _/ ____ // / \ \/ / _ \ / __ | _/ __ \ // \ \____( <_> )/ /_/ | \ ___/ // \______ / \____/ \____ | \___ > // \/ \/ \/ #region list objects //These are name value lists used to //keep track of the id's of existing items //that are either pre-existing or have been created during import //this supports the code that matches text names of objects to their id's //i.e. "IBM" as a manufacturer to the IBM record in AyaNova already //case is not taken into account during comparison to ensure no little //mismatches due to a small typo in the import file Hashtable htManufacturers=new Hashtable(); Hashtable htWholesalers=new Hashtable(); UnitOfMeasures Measures;//=UnitOfMeasures.GetItems(); PartCategories Categories;//=PartCategories.GetItems(); Hashtable htPartNumbers=new Hashtable(); #endregion #region Form load and login private void Form1_Load(object sender, System.EventArgs e) { { System.Reflection.Assembly a = System.Reflection.Assembly.GetExecutingAssembly(); string sVersion = "AyaNovaź part import / export " + AyaBizUtils.DisplayVersion(a.GetName().Version); System.Diagnostics.FileVersionInfo fileVersion = System.Diagnostics.FileVersionInfo.GetVersionInfo(a.Location); if (fileVersion.FileBuildPart > 0) sVersion += " (Patch " + fileVersion.FileBuildPart.ToString() + ")"; this.Text = sVersion; } mnuImportOptions.Visible = Util.LicensedMode; //Load cached lists //case 3606 // System.Text.StringBuilder sbDupes = new System.Text.StringBuilder(); VendorPickList vp=VendorPickList.GetList(); foreach(VendorPickList.VendorPickListInfo i in vp) { switch(i.VendorType) { case VendorTypes.Manufacturer: //case 3606 Util.AddItemWithDupeCheck("Vendor.Manufacturer.Name", htManufacturers, i.ID, i.Name); break; case VendorTypes.Wholesaler: //case 3606 Util.AddItemWithDupeCheck("Vendor.Wholesaler.Name", htWholesalers, i.ID, i.Name); break; default: break; } } PartPickList p=PartPickList.GetAllParts(); foreach(PartPickList.PartPickListInfo i in p) { //case 3606 Util.AddItemWithDupeCheck("Part.Number", htPartNumbers, i.ID, i.PartNumber); // htPartNumbers.Add(i.PartNumber,i.ID); } Measures=UnitOfMeasures.GetItems(); Categories=PartCategories.GetItems(); MessageBox.Show( "Confirm that you have a backup copy of your AyaNova database before proceeding.\r\n\r\n" + "There is no undo function for importing data other than restoring from a pre-import backup copy.\r\n\r\n" + "** If you are not 100% certain that you have a *working* backup copy ready, stop now **", "ACCIDENTS HAPPEN: DO NOT IMPORT WITHOUT A GOOD BACKUP!"); } #endregion #region Read import file private DataTable dtParts; private void mnuOpen_Click(object sender, System.EventArgs e) { if (dlgOpen.ShowDialog() != DialogResult.OK) return; this.mnuImport.Enabled = false; Util.ReadCSV(dataGrid1, ref dtParts, RootObjectTypes.Part, dlgOpen.FileName); this.mnuImport.Enabled = true; } #endregion #region Import data Dictionary lsMap = null; private void mnuImport_Click(object sender, System.EventArgs e) { //Save grid settings Util.SaveGridMappings(dataGrid1, RootObjectTypes.Part); if (dtParts.Rows.Count < 1) { MessageBox.Show("There are no records to import"); return; } //Get the map lsMap = Util.BuildGridImportMap(dataGrid1); if (!lsMap.ContainsKey("Number")) { MessageBox.Show("\"Number\" is a required field to uniquely identify parts. Select a column to be used as the unique part number to proceed with import."); return; } long lBadCount = 0; long lGoodCount = 0; long lUpdatedCount = 0; Waiting w = new Waiting(); w.Show(); w.Ops = "Importing parts"; foreach (DataRow dr in dtParts.Rows) { string sPartNumber = fld(dr, "Number", 255); if (string.IsNullOrWhiteSpace(sPartNumber)) continue; Part p = null; if (htPartNumbers.Contains(sPartNumber)) { //case 1404 Open existing for update? if (Util.LicensedMode && Util.IEData.PartUpdate) { //update existing part p = Part.GetItem((Guid)htPartNumbers[sPartNumber]); } else//not licensed or nothing chosen to update { lBadCount++; continue; } } else { p = Part.NewItem(); } w.Step = sPartNumber; if (p.IsNew) p.PartNumber = sPartNumber; if (p.IsNew || Util.IEData.PartName) p.Name = fld(dr, "Name", 255); //alternative wholesaler? if (p.IsNew || Util.IEData.PartAlternativeWholesaler) { p.AlternativeWholesalerID = GetWholeSalerIDByName(fld(dr, "AlternativeWholeSaler", 255)); p.AlternativeWholesalerNumber = fld(dr, "AlternativeWholeSalerNumber", 255); } if (p.IsNew || Util.IEData.PartCategoryID) p.PartCategoryID = GetPartCategoryByName(fld(dr, "Category", 255)); if (p.IsNew || Util.IEData.PartCost) p.Cost = StringToDecimal(fld(dr, "Cost", 255)); if (p.IsNew || Util.IEData.PartManufacturer) { p.ManufacturerID = GetManufacturerIDByName(fld(dr, "Manufacturer", 255)); p.ManufacturerNumber = fld(dr, "ManufacturerNumber", 255); } if (p.IsNew || Util.IEData.PartNotes) p.Notes = fld(dr, "Notes", 32767);// t(32767, f.Notes); if (p.IsNew || Util.IEData.PartRetail) p.Retail = StringToDecimal(fld(dr, "Retail", 255)); if (p.IsNew || Util.IEData.PartTrackSerialNumber) p.TrackSerialNumber = StringToBool(fld(dr, "TrackSerialNumber", 255)); if (p.IsNew || Util.IEData.PartUnitOfMeasureID) p.UnitOfMeasureID = GetPartUnitOfMeasureByName(fld(dr, "UnitOfMeasure", 255)); if (p.IsNew || Util.IEData.PartUPC) p.UPC = (fld(dr, "UPC", 15)); if (p.IsNew || Util.IEData.PartWholesaler) { p.WholesalerID = GetWholeSalerIDByName(fld(dr, "WholeSaler", 255)); p.WholesalerNumber = (fld(dr, "WholeSalerNumber", 255)); } if (p.IsSavable) { bool bWasNew = p.IsNew; p.Save(); if(bWasNew) htPartNumbers.Add(sPartNumber, p.ID); if (bWasNew) lGoodCount++; else lUpdatedCount++; } else { lBadCount++; } } w.Close(); if (Util.LicensedMode && Util.IEData.PartUpdate)//case 1891 { if (lBadCount > 0) MessageBox.Show(lGoodCount.ToString() + " Parts were imported / " + lUpdatedCount + " duplicate parts were updated sucessfully.\r\n" + lBadCount.ToString() + " Parts were not imported because they had no number at all or did not pass the business / update rules for a part object."); else MessageBox.Show(lGoodCount.ToString() + " Parts were imported / " + lUpdatedCount + " duplicate parts were updated sucessfully."); } else { if (lBadCount > 0) MessageBox.Show(lGoodCount.ToString() + " Parts were imported sucessfully.\r\n" + lBadCount.ToString() + " Parts were not imported because a part with the same number already\r\n" + "exists or they had no number at all or did not pass the rules for a part object."); else MessageBox.Show(lGoodCount.ToString() + " Parts were imported sucessfully"); } } /// /// Get a field from the current data row /// /// /// /// private string fld(DataRow dr, string sColumnNameKey, int nLength) { if (lsMap.ContainsKey(sColumnNameKey)) { return t(nLength, dr[lsMap[sColumnNameKey]].ToString()); } else return ""; } /// /// /// /// /// /// private static string t(int nLength, string s) { if (string.IsNullOrWhiteSpace(s)) return ""; if (s.Length <= nLength) return s; else return s.Substring(0, nLength); } /// /// /// /// /// private bool StringToBool(string s) { if(s==null || s=="") return false; if(s.ToUpper().StartsWith("T")) return true; if(s=="1") return true; return false; } private decimal StringToDecimal(string s) { if(s==null || s=="") return 0M; try { return System.Convert.ToDecimal(s); } catch { return 0M; } } /// /// Match and fetch an existing part category or create a new one /// /// /// private Guid GetPartCategoryByName(string sName) { if(sName=="") return Guid.Empty; foreach(PartCategory pc in Categories) { if(pc.Name.ToUpper()==sName.ToUpper()) return pc.ID; } //Not found so add it PartCategory newpc=Categories.Add(); newpc.Name=sName; // try // { //case 1412 Categories = (PartCategories)Categories.Save(); //} //catch (Exception ex) //{ // ex.ToString(); //} return newpc.ID; } /// /// Match and fetch an existing part UnitOfMeasure or create a new one /// /// /// private Guid GetPartUnitOfMeasureByName(string sName) { if(sName=="") return Guid.Empty; foreach(UnitOfMeasure uom in Measures) { if(uom.Name.ToUpper()==sName.ToUpper()) return uom.ID; } //Not found so add it UnitOfMeasure newuom=Measures.Add(); newuom.Name=sName; //case 1412 Measures = (UnitOfMeasures)Measures.Save(); return newuom.ID; } /// /// Identify and fetch an existing ID or add a new wholesaler if necessary /// /// /// private Guid GetWholeSalerIDByName(string sName) { if(sName=="") sName="Unspecified wholesaler"; foreach(DictionaryEntry de in htWholesalers) { if(de.Key.ToString().ToUpper()==sName.ToUpper()) return (Guid)de.Value; } //Not there so add a new record for it Vendor v=Vendor.NewItem(); v.Active=true; v.VendorType=VendorTypes.Wholesaler; v.Name=sName; v.Save(); htWholesalers.Add(sName,v.ID); return v.ID; } /// /// Identify and fetch an existing ID or add a new Manufacturer if necessary /// /// /// private Guid GetManufacturerIDByName(string sName) { if(sName=="") sName="Unspecified manufacturer"; foreach(DictionaryEntry de in htManufacturers) { if(de.Key.ToString().ToUpper()==sName.ToUpper()) return (Guid)de.Value; } //Not there so add a new record for it Vendor v=Vendor.NewItem(); v.Active=true; v.VendorType=VendorTypes.Manufacturer; v.Name=sName; v.Save(); htManufacturers.Add(sName,v.ID); return v.ID; } #endregion #region Export data /// /// Exports all existing clients to CSV format identical /// to that required for import /// /// /// private void mnuExport_Click(object sender, System.EventArgs e) { SaveFileDialog sf = new SaveFileDialog(); sf.DefaultExt = ".csv"; sf.FileName = "parts.csv"; if (sf.ShowDialog() != DialogResult.OK) return; Cursor=Cursors.WaitCursor; FileHelperEngine engine = new FileHelperEngine(typeof(FHPart)); System.Collections.ArrayList alParts=new ArrayList(); FHPart fhc; Part p; PartPickList ppl=PartPickList.GetAllParts(); Waiting w=new Waiting(); w.Show(); w.Ops="Exporting parts"; foreach(PartPickList.PartPickListInfo i in ppl) { p=Part.GetItem(i.ID); fhc=new FHPart(); w.Step=p.Name + " " + p.PartNumber; fhc.Number=p.PartNumber; fhc.Name=p.Name; fhc.AlternativeWholeSaler=GetWholesalerByID(p.AlternativeWholesalerID); fhc.AlternativeWholeSalerNumber=p.AlternativeWholesalerNumber; fhc.Category=""; for(int x=0;x ls = new List(); ls.Add("Name"); ls.Add("Number"); ls.Add("UnitOfMeasure"); ls.Add("Cost"); ls.Add("Retail"); ls.Add("Category"); ls.Add("UPC"); ls.Add("TrackSerialNumber"); ls.Add("WholeSaler"); ls.Add("WholeSalerNumber"); ls.Add("AlternativeWholeSaler"); ls.Add("AlternativeWholeSalerNumber"); ls.Add("Manufacturer"); ls.Add("ManufacturerNumber"); ls.Add("Notes"); // Add the AutoFilter header cell to each column. foreach (DataGridViewColumn col in dataGrid1.Columns) { col.HeaderCell = new GZDataGridViewComboColumnHeaderCell(col.HeaderCell, ls); } // Resize the columns to fit their contents. dataGrid1.AutoResizeColumns(); } #endregion case 1588 //------------------------------------------------------------------------ } }