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 ImportUnit : 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 ImportUnit()
{
//
// 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";
//
// ImportUnit
//
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 = "ImportUnit";
this.Text = "Unit 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 htWholeSalers = new Hashtable();
Hashtable htManufacturers = new Hashtable();
Hashtable htClients = new Hashtable();
Hashtable htModels = new Hashtable();
Hashtable htUnits = 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ź unit 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;
try
{
//Load cached lists
VendorPickList vp = VendorPickList.GetList();
foreach (VendorPickList.VendorPickListInfo i in vp)
{
if (i.VendorType == VendorTypes.Manufacturer)
//case 3606
if (!htManufacturers.ContainsKey(i.Name))
htManufacturers.Add(i.Name, i.ID);
else if (i.VendorType == VendorTypes.Wholesaler)
//case 3606
if (!htWholeSalers.ContainsKey(i.Name))
htWholeSalers.Add(i.Name, i.ID);
}
ClientPickList p = ClientPickList.GetList();
foreach (ClientPickList.ClientPickListInfo i in p)
{
//case 3606
if (!htClients.ContainsKey(i.Name))
htClients.Add(i.Name, i.ID);
}
UnitModelPickList upl = UnitModelPickList.GetList();
foreach (UnitModelPickList.UnitModelPickListInfo i in upl)
{
//case 3606
if (!htModels.ContainsKey(i.Name))
htModels.Add(i.Name, i.ID);
}
UnitPickList unpl = UnitPickList.GetListOfAll();
foreach (UnitPickList.UnitPickListInfo i in unpl)
{
//case 3606
if (!htUnits.ContainsKey(i.Serial))
htUnits.Add(i.Serial, i.ID);
}
}
catch (Exception ex)
{
if (ex is System.ArgumentException)
{
MessageBox.Show(
"An error has occurred while attempting to retrieve the lists of objects\r\n" +
"already stored in AyaNova which are used to match to the data being imported.\r\n" +
"(Clients, Unit Models, Vendors Units etc)\r\n\r\n" +
"A duplicate record was found with the same name and must be removed or changed\r\n" +
"before you can proceed with this utility. Details below:\r\n\r\n" +
ex.Message, "Duplicate object name in AyaNova");
}
else
MessageBox.Show("An error has occurred while attempting to retrieve the lists of objects\r\n" +
"already stored in AyaNova which are used to match to the data being imported.\r\n" +
"The import utility can not proceed, details below:\r\n\r\n", ex.Message);
this.Close();
return;
}
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 dtUnits;
private void mnuOpen_Click(object sender, System.EventArgs e)
{
if (dlgOpen.ShowDialog() != DialogResult.OK) return;
this.mnuImport.Enabled = false;
Util.ReadCSV(dataGrid1, ref dtUnits, RootObjectTypes.Unit, 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.Unit);
if (dtUnits.Rows.Count < 1)
{
MessageBox.Show("There are no records to import");
return;
}
//Get the map
lsMap = Util.BuildGridImportMap(dataGrid1);
if (!lsMap.ContainsKey("Serial"))
{
MessageBox.Show("\"Serial\" is a required field to uniquely identify units. Select a column to be used as the unique unit serial number to proceed with import.");
return;
}
if (!lsMap.ContainsKey("Client"))
{
MessageBox.Show("\"Client\" is a required field. Select a column that identifies the client name of unit owner to proceed with import.");
return;
}
if (!lsMap.ContainsKey("UnitModel"))
{
MessageBox.Show("\"UnitModel\" is a required field. Select a column that identifies the unit model to proceed with import.");
return;
}
long lBadCount = 0;
long lGoodCount = 0;
long lUpdatedCount = 0;
Waiting w = new Waiting();
w.Show();
w.Ops = "Importing Unit";
foreach (DataRow dr in dtUnits.Rows)
{
if (string.IsNullOrEmpty(fld(dr, "UnitModel", 255)) || string.IsNullOrEmpty(fld(dr, "Client", 255)) || string.IsNullOrEmpty(fld(dr, "Serial", 255))) continue;
Unit u = null;
string sSerial = fld(dr, "Serial", 255);
if (htUnits.Contains(sSerial))
{
//case 1404 Open existing for update?
if (Util.LicensedMode && Util.IEData.UnitUpdate)
{
//update existing unit
u = Unit.GetItem((Guid)htUnits[sSerial]);
}
else//not licensed or nothing chosen to update
{
lBadCount++;
continue;
}
}
else
{
u = Unit.NewItem();
}
w.Step = sSerial;
if (u.IsNew)
u.Serial = sSerial;
if (u.IsNew || Util.IEData.UnitClientID)
u.ClientID = GetClientIDByName(fld(dr, "Client", 255));
if (u.IsNew || Util.IEData.UnitModelID)
u.UnitModelID = GetModelIDByName(fld(dr, "UnitModel", 255));
if (u.IsNew || Util.IEData.UnitNotes)
u.Notes = fld(dr, "Notes", 32767);// t(32767, f.Notes);
if (u.IsNew || Util.IEData.UnitPurchasedFromVendor)
{
string sPurchasedFrom = fld(dr, "PurchasedFromVendor", 255);
if (string.IsNullOrWhiteSpace(sPurchasedFrom))
u.BoughtHere = true;
else
u.PurchasedFromID = GetWholeSalerIDByName(sPurchasedFrom);
}
if (u.IsNew || Util.IEData.UnitReceipt)
u.Receipt = fld(dr, "SalesReceiptNumber", 255);
if (u.IsNew || Util.IEData.UnitPurchasedDate)
{
//Case 887
if (!string.IsNullOrEmpty(fld(dr, "PurchasedDate", 255)))
u.PurchasedDate = new CSLA.SmartDate(System.Convert.ToDateTime(fld(dr, "PurchasedDate", 255))).DBValue;
}
if (u.IsNew || Util.IEData.UnitDescription)
u.Description = fld(dr, "Description", 255);
if (u.IsNew || Util.IEData.UnitMetered)
u.Metered = StringToBool(fld(dr, "Metered", 255));
if (u.IsNew || Util.IEData.UnitWarrantyLength)
{
int nWarrantyLength = 0;
if (int.TryParse(fld(dr, "WarrantyLength", 255), out nWarrantyLength))
{
u.OverrideModelWarranty = true;
u.WarrantyLength = nWarrantyLength;
}
}
if (u.IsSavable)
{
bool bWasNew = u.IsNew;
u.Save();
if (bWasNew)
htUnits.Add(sSerial, u.ID);
if (bWasNew)
lGoodCount++;
else
lUpdatedCount++;
}
else
{
lBadCount++;
}
}
w.Close();
if (Util.LicensedMode && Util.IEData.UnitUpdate)
{
if (lBadCount > 0)
MessageBox.Show(lGoodCount.ToString() + " Units were imported / " + lUpdatedCount + " duplicate Units were updated sucessfully.\r\n" +
lBadCount.ToString() + " Units were not imported because they had no serial number at all or did not pass the business / update rules for a Unit object.");
else
MessageBox.Show(lGoodCount.ToString() + " Units were imported / " + lUpdatedCount + " duplicate Units were updated sucessfully.");
}
else
{
if (lBadCount > 0)
MessageBox.Show(lGoodCount.ToString() + " Units were imported sucessfully.\r\n" +
lBadCount.ToString() + " Units were not imported because a unit with the same serial number already\r\n" +
"exists or they had no serial number at all or did not pass the rules for a unit object.");
else
MessageBox.Show(lGoodCount.ToString() + " Units 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;
}
}
///
/// Identify and fetch an existing ID or add a new Client if necessary
///
///
///
private Guid GetClientIDByName(string sName)
{
foreach (DictionaryEntry de in htClients)
{
if (de.Key.ToString().ToUpper() == sName.ToUpper())
return (Guid)de.Value;
}
//Not there so add a new record for it
Client c = Client.NewItem();
c.Name = sName;
c.Save();
htClients.Add(sName, c.ID);
return c.ID;
}
///
/// Identify and fetch an existing ID or add a new Model if necessary
///
///
///
private Guid GetModelIDByName(string sName)
{
foreach (DictionaryEntry de in htModels)
{
//Starts with necessary because unit model list includes model number after
//name
if (de.Key.ToString().ToUpper().StartsWith(sName.ToUpper()))
return (Guid)de.Value;
}
//Not there so add a new record for it
UnitModel c = UnitModel.NewItem();
c.Name = sName;
c.Save();
htModels.Add(sName, c.ID);
return c.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;
}
#endregion
#region Export data
///
/// Exports all existing Units 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 = "units.csv";
if (sf.ShowDialog() != DialogResult.OK) return;
Cursor = Cursors.WaitCursor;
FileHelperEngine engine = new FileHelperEngine(typeof(FHUnit));
System.Collections.ArrayList alUnits = new ArrayList();
FHUnit fhc;
Unit u;
UnitPickList ppl = UnitPickList.GetListOfAll();
Waiting w = new Waiting();
w.Show();
w.Ops = "Exporting units";
foreach (UnitPickList.UnitPickListInfo i in ppl)
{
u = Unit.GetItem(i.ID);
fhc = new FHUnit();
w.Step = u.Serial;
fhc.Serial = u.Serial;
fhc.Client = GetClientByID(u.ClientID);
fhc.Description = u.Description;
fhc.Metered = (u.Metered ? "TRUE" : "FALSE");
fhc.Notes = u.Notes;
if (u.PurchasedDate == System.DBNull.Value)
fhc.PurchasedDate = "";
else
{
DateTime dtPurchased = System.Convert.ToDateTime(u.PurchasedDate);
fhc.PurchasedDate = dtPurchased.ToString();
}
fhc.PurchasedFromVendor = GetPurchasedFromByID(u.PurchasedFromID);
fhc.SalesReceiptNumber = u.Receipt;
fhc.UnitModel = GetModelByID(u.UnitModelID);
fhc.WarrantyLength = u.WarrantyLength.ToString();//case 1739
alUnits.Add(fhc);
}
w.Close();
try
{
engine.WriteFile(sf.FileName, (object[])alUnits.ToArray(typeof(FHUnit)));
}
catch (Exception ex)
{
MessageBox.Show("Error writing the export file:\r\n\r\n" + ex.Message);
return;
}
Cursor = Cursors.Default;
MessageBox.Show("All units in current AyaNova database have been exported to file:\r\n" +
sf.FileName);
}
private string GetPurchasedFromByID(Guid ID)
{
foreach (DictionaryEntry de in htWholeSalers)
{
if ((Guid)de.Value == ID)
return de.Key.ToString();
}
return "";
}
private string GetClientByID(Guid ID)
{
foreach (DictionaryEntry de in htClients)
{
if ((Guid)de.Value == ID)
return de.Key.ToString();
}
return "";
}
private string GetModelByID(Guid ID)
{
foreach (DictionaryEntry de in this.htModels)
{
if ((Guid)de.Value == ID)
return de.Key.ToString();
}
return "";
}
#endregion
private void mnuImportOptions_Click(object sender, EventArgs e)
{
Util.ShowOptionsDialog();
}
#region case 1588
private void dataGrid1_BindingContextChanged(object sender, EventArgs e)
{
// Continue only if the data source has been set.
if (dataGrid1.DataSource == null)
{
return;
}
//these are the columns that can be selected by the user to import into
List ls = new List();
ls.Add("Serial");
ls.Add("Client");
ls.Add("UnitModel");
ls.Add("Notes");
ls.Add("PurchasedFromVendor");
ls.Add("SalesReceiptNumber");
ls.Add("PurchasedDate");
ls.Add("Description");
ls.Add("Metered");
ls.Add("WarrantyLength");//case 1739
// 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
//------------------------------------------------------------------------
}
}