Files
ayanova7/utils/AyaImport/Form1.cs

4574 lines
150 KiB
C#

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.IO;
using System.Threading;
using System.Data.OleDb;
using System.Text;
using CSLA.Security;
using GZTW.AyaNova.BLL;
using CSLA;
namespace AyaImport
{
/// <summary>
/// Summary description for ImportForm.
/// </summary>
public class ImportForm : System.Windows.Forms.Form
{
#region Attributes
private System.Windows.Forms.Label label1;
private System.Windows.Forms.ComboBox cbSource;
//private System.ComponentModel.IContainer components;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
//An array to hold AyaNovaDBItem objects (containing path info) to bind to the combo box
private ArrayList ComboItems;
private System.Windows.Forms.TextBox edStatus;
private System.Windows.Forms.Button btnStopSearch;
private bool bFilling = false;
private bool bContinue=true;
private string sOut1="";
private string sOut2="";
private string sOut3="";
private string sOut4="";
private string sOut5="";
private System.Windows.Forms.Button btnImport;
private System.Windows.Forms.OpenFileDialog openFileDialog1;
long lFoundCount=0;
private System.Windows.Forms.ProgressBar pBar;
private System.Windows.Forms.Label lblCurrentOp;
private string strOldDBPath="";
enum OpState
{
Pending,
Calculating,
Canceled,
}
OpState _state = OpState.Pending;
#endregion
#region constructor / dispose
public ImportForm()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
ComboItems = new ArrayList();
PrepareSourceCombo();
//edStatus.BackColor=Color.FromArgb(255,200,200,200);
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#endregion
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.label1 = new System.Windows.Forms.Label();
this.cbSource = new System.Windows.Forms.ComboBox();
this.edStatus = new System.Windows.Forms.TextBox();
this.btnStopSearch = new System.Windows.Forms.Button();
this.btnImport = new System.Windows.Forms.Button();
this.openFileDialog1 = new System.Windows.Forms.OpenFileDialog();
this.pBar = new System.Windows.Forms.ProgressBar();
this.lblCurrentOp = new System.Windows.Forms.Label();
this.SuspendLayout();
//
// label1
//
this.label1.Location = new System.Drawing.Point(0, 0);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(100, 16);
this.label1.TabIndex = 1;
this.label1.Text = "Import from:";
//
// cbSource
//
this.cbSource.Dock = System.Windows.Forms.DockStyle.Top;
this.cbSource.Location = new System.Drawing.Point(0, 0);
this.cbSource.Name = "cbSource";
this.cbSource.Size = new System.Drawing.Size(637, 21);
this.cbSource.TabIndex = 2;
this.cbSource.SelectedIndexChanged += new System.EventHandler(this.cbSource_SelectedIndexChanged);
//
// edStatus
//
this.edStatus.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.edStatus.BackColor = System.Drawing.SystemColors.Window;
this.edStatus.ForeColor = System.Drawing.SystemColors.WindowText;
this.edStatus.Location = new System.Drawing.Point(8, 86);
this.edStatus.Multiline = true;
this.edStatus.Name = "edStatus";
this.edStatus.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
this.edStatus.Size = new System.Drawing.Size(613, 383);
this.edStatus.TabIndex = 3;
this.edStatus.Visible = false;
//
// btnStopSearch
//
this.btnStopSearch.Location = new System.Drawing.Point(206, 19);
this.btnStopSearch.Name = "btnStopSearch";
this.btnStopSearch.Size = new System.Drawing.Size(200, 23);
this.btnStopSearch.TabIndex = 4;
this.btnStopSearch.Text = "Stop searching";
this.btnStopSearch.Visible = false;
this.btnStopSearch.Click += new System.EventHandler(this.btnStopSearch_Click);
//
// btnImport
//
this.btnImport.Enabled = false;
this.btnImport.Location = new System.Drawing.Point(0, 19);
this.btnImport.Name = "btnImport";
this.btnImport.Size = new System.Drawing.Size(200, 23);
this.btnImport.TabIndex = 5;
this.btnImport.Text = "Import";
this.btnImport.Click += new System.EventHandler(this.btnImport_Click);
//
// openFileDialog1
//
this.openFileDialog1.DefaultExt = "sc";
this.openFileDialog1.Filter = "AyaNova files|*.sc|All files|*.*";
this.openFileDialog1.Title = "Open AyaNova database";
//
// pBar
//
this.pBar.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.pBar.Location = new System.Drawing.Point(8, 64);
this.pBar.Name = "pBar";
this.pBar.Size = new System.Drawing.Size(613, 16);
this.pBar.TabIndex = 7;
this.pBar.Visible = false;
//
// lblCurrentOp
//
this.lblCurrentOp.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.lblCurrentOp.Location = new System.Drawing.Point(5, 45);
this.lblCurrentOp.Name = "lblCurrentOp";
this.lblCurrentOp.Size = new System.Drawing.Size(568, 16);
this.lblCurrentOp.TabIndex = 8;
//
// ImportForm
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(637, 482);
this.Controls.Add(this.lblCurrentOp);
this.Controls.Add(this.pBar);
this.Controls.Add(this.btnImport);
this.Controls.Add(this.btnStopSearch);
this.Controls.Add(this.edStatus);
this.Controls.Add(this.cbSource);
this.Controls.Add(this.label1);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.MinimumSize = new System.Drawing.Size(640, 480);
this.Name = "ImportForm";
this.SizeGripStyle = System.Windows.Forms.SizeGripStyle.Show;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
//Case 433
this.Text = "CEImport version " + AyaBizUtils.DisplayVersion(System.Reflection.Assembly.GetExecutingAssembly().GetName().Version);
this.Load += new System.EventHandler(this.ImportForm_Load);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private void ImportForm_Load(object sender, System.EventArgs e)
{
DialogResult result=MessageBox.Show(
"WARNING: Before you import, be aware that it is your responsibility to do four things:\r\n\r\n"+
"1) Carefully read the documentation regarding importing data from AyaNova CE, \r\n" +
"contact AyaNova technical support if you do not understand any part of the process.\r\n\r\n"+
"Due to numerous changes in the new version of AyaNova some items will not import or \r\n"+
"will import in ways that will be unexpected if you do not read the documentation first.\r\n\r\n"+
"2) Keep a permanent copy of your AyaNova CE database (scdata.sc) in case\r\n"+
"you discover at a later date that something has not imported according to documentation.\r\n\r\n"+
"3) After import, carefully inspect the data that was imported, check that all data you \r\n"+
"expect to see in accordance with the import documentation is present. Do not ignore this step!\r\n\r\n"+
"4) Contact technical support immediately if you discover anything that is not working\r\n"+
"as described in the import utility documentation. ** Do not ** start using the new AyaNova\r\n"+
"program until the problem is resolved with the AyaNova technical support department.\r\n\r\n"+
"Do you understand and accept these responsibilities?","Warning",MessageBoxButtons.YesNo,
MessageBoxIcon.Warning,MessageBoxDefaultButton.Button2);
if(result!=DialogResult.Yes)
{
this.Close();
return;
}
GZTW.AyaNova.BLL.AyaBizUtils.Initialize();
if(AyaBizUtils.Trial)
{
MessageBox.Show(
"This utility can only import from a licensed AyaNova CE database\r\n" +
"to a licensed AyaNova database.",
"Incompatible target database",MessageBoxButtons.OK,MessageBoxIcon.Stop);
this.Close();
}
//Case 671
AyaBizUtils.AllowAutomaticMRUOnUpdate = false;
//Case 6 and case 597
AyaBizUtils.AllowAutomaticClosedWorkorderStatus = false;
}
#region app entry point
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.Run(new ImportForm());
}
#endregion
#region SourceCombo related
/// <summary>
/// Add default items to combo box
/// </summary>
private void PrepareSourceCombo()
{
bFilling=true;
ComboItems.Clear();
ComboItems.Add(new AyaNovaDBItem("Choose database..."));
ComboItems.Add(new AyaNovaDBItem("<Browse manually for source database>"));
ComboItems.Add(new AyaNovaDBItem("<Auto search for source databases>"));
//Bind the combo box to the array of AyaNovaDBItem objects
//and set which properties of AyaNovaDBItem to use
//as the display and which as the value
cbSource.DataSource=ComboItems;
cbSource.DisplayMember="Path";
cbSource.ValueMember="Path";
bFilling=false;
}
private void cbSource_SelectedIndexChanged(object sender, System.EventArgs e)
{
if(bFilling) return;
AyaNovaDBItem ADBSelected=(AyaNovaDBItem)cbSource.SelectedItem;
if(ADBSelected.ControlItem)
{
btnImport.Enabled=false;
if(ADBSelected.Path=="<Browse manually for source database>")
{
BrowseForDB();
}
if(ADBSelected.Path=="<Auto search for source databases>")
{
//SearchForDB();
this.btnStopSearch.Text="Stop searching";
this.btnStopSearch.Visible=true;
this.edStatus.Visible=true;
lFoundCount=0;
Thread thrd1;
thrd1=new Thread(new ThreadStart(SearchForDB));
thrd1.Start();
}
}
else
{
//a db was selected, open it up and display extended info about it
btnImport.Enabled=false;
this.edStatus.Visible=true;
strOldDBPath=ADBSelected.Path;
DisplayDBInfo();
return;
}
}
#endregion
#region Old DB related
/// <summary>
/// Display info about selected database
/// </summary>
private void DisplayDBInfo()
{
int nVersion=0;
string sRegTo="";
StringBuilder sb = new StringBuilder();
sb.Append("Information for database:\r\n");
sb.Append(strOldDBPath);
sb.Append("\r\n");
System.Data.OleDb.OleDbConnection conn = new
System.Data.OleDb.OleDbConnection();
// TODO: Modify the connection string and include any
// additional required properties for your database.
conn.ConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;" +
@"Data source= " +strOldDBPath;
try
{
//****************************
// code to process data.
conn.Open();
OleDbCommand cmd = new OleDbCommand(
"SELECT defaults.regto, defaults.versioninfo FROM defaults;",conn);
// "SELECT TOP 1 wo.id, wo.created FROM wo ORDER BY wo.id DESC;"
OleDbDataReader rdr;
rdr = cmd.ExecuteReader();
if(rdr.Read())
{
sb.Append("Registered to: ");
sRegTo=rdr.GetString(0);
sb.Append(sRegTo);
sb.Append(" Version:");
sb.Append(rdr.GetString(1));
nVersion=int.Parse(rdr.GetString(1));
sb.Append("\r\n");
}
rdr.Close();
cmd.CommandText="SELECT TOP 1 wo.id, wo.created FROM wo ORDER BY wo.id DESC;";
rdr=cmd.ExecuteReader();
if(rdr.Read())
{
sb.Append("Last work order ");
sb.Append(rdr.GetInt32(0).ToString());
sb.Append(" created on ");
sb.Append(rdr.GetDateTime(1).ToString());
sb.Append("\r\n");
}
rdr.Close();
if(sRegTo=="SECURITY VIOLATION" || GZHash(sRegTo)==1575153704/*TEAM ESD*/)
{
sb.Append(
"********************\r\n" +
"This database is Locked due to a security violation and can not be imported!\r\nContact AyaNova tech support to proceed." +
"\r\n********************\r\n");
btnImport.Enabled=false;
}
else
{
if(nVersion > 170)
{
//sb.Append("This database version can be imported\r\n");
btnImport.Enabled = true;
}
else
{
sb.Append("********************\r\nThis database version needs to be upgraded\r\n to 171 or higher before it can be imported\r\n********************\r\n");
btnImport.Enabled = false;
}
}
if(sRegTo.IndexOf("Evaluation")!=-1)
{
sb.Append(
"********************************************************\r\n" +
"*** Incompatible source database!\r\n" +
"*** Only a licensed AyaNova CE database can be imported.\r\n" +
"********************************************************\r\n");
btnImport.Enabled = false;
}
//****************************
edStatus.Text=sb.ToString();
}
catch (Exception ex)
{
sb.Append(ex.Message);
MessageBox.Show(ex.Message);
}
finally
{
edStatus.Text=sb.ToString();
conn.Close();
}
}
//Open an openfile dialog and select manually db
//insert into combo box list
//then display info about it
private void BrowseForDB()
{
if(DialogResult.OK==openFileDialog1.ShowDialog())
{
string f=openFileDialog1.FileName;
bFilling=true;
ComboItems.Clear();
cbSource.DataSource=null;
ComboItems.Add(new AyaNovaDBItem("<Browse manually for source database>"));
ComboItems.Add(new AyaNovaDBItem("<Auto search for source databases>"));
//******************************
ComboItems.Add(new AyaNovaDBItem(f,"test",Directory.GetLastWriteTime(f),Directory.GetLastWriteTime(f),69));
//********************************
cbSource.DataSource=ComboItems;
cbSource.DisplayMember="Path";
cbSource.ValueMember="Path";
cbSource.SelectedIndex=0;
bFilling=false;
cbSource.SelectedIndex=2;
}
}
//Search all paths available for any scdata.sc files
//and get info about each one then add to list
private void SearchForDB()
{
bFilling=true;
ComboItems.Clear();
cbSource.DataSource=null;
ComboItems.Add(new AyaNovaDBItem("<Browse manually for source database>"));
ComboItems.Add(new AyaNovaDBItem("<Auto search for source databases>"));
string[] sDrives=Directory.GetLogicalDrives();
foreach(string d in sDrives)
{
if(!bContinue)
break;
try
{
if(d!="A:\\")
DirSearch(d,"*.sc");
}
catch(Exception e)
{
string s=e.Message;
}
}
cbSource.DataSource=ComboItems;
cbSource.DisplayMember="Path";
cbSource.ValueMember="Path";
bFilling=false;
}
/// <summary>
///
/// </summary>
/// <param name="sDir"></param>
void DirSearch(string sDir, string sPattern)
{
try
{
foreach (string d in Directory.GetDirectories(sDir))
{
foreach (string f in Directory.GetFiles(d, sPattern))
{
ComboItems.Add(new AyaNovaDBItem(f,"test",Directory.GetLastWriteTime(f),Directory.GetLastWriteTime(f),69));
lFoundCount++;
}
if(bContinue)
{
//scroll up
sOut5=sOut4;
sOut4=sOut3;
sOut3=sOut2;
sOut2=sOut1;
sOut1=d;
edStatus.Text="Found: " + lFoundCount.ToString() + " files.\r\n=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-\r\n"+sOut5+"\r\n"+sOut4+"\r\n"+sOut3+"\r\n"+sOut2+"\r\n"+sOut1;
DirSearch(d,sPattern);
}
else
{
return;
}
}
}
catch (System.Exception excpt)
{
//Ignore any errors'
string nothing=excpt.Message;
//MessageBox.Show(excpt.Message);
}
}
private void btnStopSearch_Click(object sender, System.EventArgs e)
{
_state = OpState.Canceled;
//_calcButton.Enabled = false;
bContinue=false;
this.btnStopSearch.Visible=false;
}
#endregion
#region IMPORT
private void btnImport_Click(object sender, System.EventArgs e)
{
DialogResult result=MessageBox.Show(
"WARNING: If you proceed all existing data in the \r\n"+
"new AyaNova database will be erased prior to importing\r\n"+
"data from the old AyaNova CE database.\r\n\r\n"+
"If you are not certain of the implications of importing,\r\n"+
"please contact support@ayanova.com before proceeding.\r\n\r\n"+
"There is no way to reverse this process once it has started.\r\n\r\n"+
"Are you certain you wish to proceed?","Warning",MessageBoxButtons.YesNo,
MessageBoxIcon.Warning,MessageBoxDefaultButton.Button2);
if(result!=DialogResult.Yes)
return;
result=MessageBox.Show(
"There is no way to reverse this process once it has started.\r\n\r\n"+
"All existing data in the new AyaNova database *will* be erased.\r\n\r\n"+
"Are you certain you wish to proceed?","Last chance warning",MessageBoxButtons.YesNo,
MessageBoxIcon.Warning,MessageBoxDefaultButton.Button2);
if(result!=DialogResult.Yes)
return;
if(!DoLogin())
{
MessageBox.Show("You will need to provide the new and old \r\nAyaNova manager account passwords to proceed with import.");
return;
}
//this.btnStopSearch.Text="Stop importing";
//this.btnStopSearch.Visible=true;
this.btnImport.Enabled=false;
this.cbSource.Enabled=false;
this.edStatus.Text="";
this.edStatus.Visible=true;
pBar.Visible=true;
bContinue=true;
//ShowProgress("STARTING","Starting import...",0, out cancel);
// Asynch delegate method
DoImportDelegate doi = new DoImportDelegate(DoImport);
doi.BeginInvoke(strOldDBPath, null, null);
//ShowProgress("Starting import....");
// Thread ImportThread;
// ImportThread = new Thread(new ThreadStart(DoImport));
// ImportThread.IsBackground=true;
// ImportThread.Start();
}
delegate void DoImportDelegate(string strOldDB);
private void DoImport(string strOldDB)
{
//Used for diagnosis, is always set to the current id number
//of whatever is being imported, if an exception is thrown it
//can be used to find out what record was being imported at the time.
string sLastOp="Start";
bool cancel = false;
ShowProgress("STARTING","Starting import...",0, out cancel);
System.DateTime dtStart=System.DateTime.Now;
//Set to allow importing objects reference users who are inactive temporarily
AyaBizUtils.CE=true;
//No notification processing during import please
AyaBizUtils.GlobalSettings.UseNotification = false;
//Optimization related to avoid needless forced setting of
//db workorder service autonumber field when next wo is one more than
//the last wo imported
int nLastImportedWorkorderNumber = -1;
double lImported=0;
int lTotalRecords=0;
//authentication sucessful, begin import now
//scratch string
string sTemp="";
// //implement some basic caching so parent objects don't need to be continuously reloaded
// //if the parent is the same as last loop
// //int nPreviousWorkorderItemID=0;
// int nPreviousWorkorderID=0;
// int nCurrentID=0;
//Crypto provider
sLastOp="Instantiating Interop...";
interop.blue.CredClass cryp = new interop.blue.CredClass();
sLastOp="InteropInstantiated, about to open CE database...";
//OPEN UP DATABASE
ShowProgress("","Opening old database...",0, out cancel);
System.Data.OleDb.OleDbConnection conn = new
System.Data.OleDb.OleDbConnection();
conn.ConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;" +
@"Data source= " + strOldDB;
//Second connection Used for workorder items
sLastOp="Opening snSub...";
System.Data.OleDb.OleDbConnection cnSub = new System.Data.OleDb.OleDbConnection();
cnSub.ConnectionString = conn.ConnectionString;
cnSub.Open();
OleDbCommand cmSub = new OleDbCommand();
cmSub.Connection=cnSub;
cmSub.CommandType=System.Data.CommandType.Text;
OleDbDataReader drSub;
//****************************************
//Third connection (used for workorder item children)
sLastOp="Opening snSub2...";
System.Data.OleDb.OleDbConnection cnSub2 = new System.Data.OleDb.OleDbConnection();
cnSub2.ConnectionString = conn.ConnectionString;
cnSub2.Open();
OleDbCommand cmSub2 = new OleDbCommand();
cmSub2.Connection=cnSub2;
cmSub2.CommandType=System.Data.CommandType.Text;
OleDbDataReader drSub2;
//****************************************
try
{
sLastOp="Opening conn...";
conn.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.Connection=conn;
cmd.CommandType=System.Data.CommandType.Text;
OleDbDataReader rdr;
//OleDbDataReader drSub;
//OPEN UP DATABASE
sLastOp="About to erase target database...";
ShowProgress("","Erasing new AyaNova database...",0, out cancel);
// try
// {
DBManager.EraseDatabase("I_UNDERSTAND_ALL_DATA_WILL_BE_ERASED_AND_I_ACCEPT_RESPONSIBILITY");
// }
// catch(Exception ex)
// {
// ShowProgress("!Error erasing new database: " +ex.Message+"\r\n"+ex.InnerException.Message,"",0, out cancel);
// goto BAIL;
// }
sLastOp="Target erased, starting import...";
dtStart=System.DateTime.Now;
#region Import security groups
/*
*
* Security groups
*
*
* */
ShowProgress("","Importing Security Groups...",0, out cancel);
//ShowProgress("","Importing Security Groups...";
cmd.CommandText="SELECT Count(groups.id) AS TotalRecords FROM groups;";
rdr=cmd.ExecuteReader();
rdr.Read();
lTotalRecords=rdr.GetInt32(0);
rdr.Close();if(cancel) goto BAIL;
Hashtable htSecurityGroups=new Hashtable(lTotalRecords);
cmd.CommandText=
"SELECT groups.id, groups.a, groups.b FROM groups;";
rdr=cmd.ExecuteReader();
while(rdr.Read() && !cancel)
{
ShowProgress("","",(int)((lImported/lTotalRecords)*100), out cancel);
sLastOp=rdr.GetInt32(0).ToString();
sTemp=GetString(rdr,1);
cryp.Process(ref sTemp ,false,235);//AyaNova keycodes are index 235
SecurityGroup s = SecurityGroup.NewItem();
htSecurityGroups.Add(rdr.GetInt32(0),s.ID);
// if(sTemp=="<< Manager>>")
// sTemp="OLD AyaNova Administrator";
s.Name=sTemp;
sTemp=GetString(rdr,2);
cryp.Process(ref sTemp ,false,235);//AyaNova keycodes are index 235
sTemp=sTemp.Substring(sTemp.Length-27);
//WORKORDERSTAT=0 Main workorder view list screen
//NO EQUIVALENT RIGHT
//WORKORDER=1
//string stest=sTemp.Substring(1,1);
//case 1655
//SetRight(int.Parse(sTemp.Substring(1,1)),"Object.Workorder",s);
SetRight(int.Parse(sTemp.Substring(1,1)),"Object.WorkorderItem",s);
SetRight(int.Parse(sTemp.Substring(1,1)),"Object.WorkorderItemLabor",s);
SetRight(int.Parse(sTemp.Substring(1,1)),"Object.WorkorderItemMiscExpense",s);
SetRight(int.Parse(sTemp.Substring(1,1)),"Object.WorkorderItemOutsideService",s);
SetRight(int.Parse(sTemp.Substring(1,1)),"Object.WorkorderItemPart",s);
SetRight(int.Parse(sTemp.Substring(1,1)),"Object.WorkorderItemScheduledUser",s);
SetRight(int.Parse(sTemp.Substring(1,1)),"Object.WorkorderItemTask",s);
SetRight(int.Parse(sTemp.Substring(1,1)),"Object.WorkorderItemTravel",s);
SetRight(int.Parse(sTemp.Substring(1,1)),"Object.WorkorderItemLoan",s);
SetRight(int.Parse(sTemp.Substring(1,1)),"Object.WorkorderService",s);
SetRight(int.Parse(sTemp.Substring(1,1)),"Object.WorkorderQuote",s);
SetRight(int.Parse(sTemp.Substring(1,1)),"Object.WorkorderService.CloseByDate",s);
//SHIPPING=2
//NO EQUIVALENT
//MAIL=3//use=the=mail=system=(no=read=only=here)
SetRight(int.Parse(sTemp.Substring(3,1)),"Object.Memo",s);
//DBASEUTILS=4//=use=the=database=utilities
SetRight(int.Parse(sTemp.Substring(4,1)),"Object.Global",s);
SetRight(int.Parse(sTemp.Substring(4,1)),"Object.Region",s);
SetRight(int.Parse(sTemp.Substring(4,1)),"Object.LocalizedText",s);
SetRight(int.Parse(sTemp.Substring(4,1)),"Object.TaxCode",s);
//SECURITYGROUPS=5//=rights=to=create=edit=GROUPS
SetRight(int.Parse(sTemp.Substring(5,1)),"Object.SecurityGroup",s);
//SEARCH=6//=access=to=the=search=screen
//NO EQUIVALENT
//REPORTS=7//=access=to=the=reporting=screen=not=workorder=printing
SetRight(int.Parse(sTemp.Substring(7,1)),"Object.Report",s);
//PRINTING=8//able=to=change=printing=setup
// NO CURRENT EQUIVALENT
//CLIENTS=9//CLIENTS=SCREEN
SetRight(int.Parse(sTemp.Substring(9,1)),"Object.Client",s);
SetRight(int.Parse(sTemp.Substring(9,1)),"Object.HeadOffice",s);
SetRight(int.Parse(sTemp.Substring(9,1)),"Object.ClientGroup",s);
SetRight(int.Parse(sTemp.Substring(9,1)),"Object.Contract",s);
//SetRight(int.Parse(sTemp.Substring(9,1)),"Object.ContractPart",s);
SetRight(int.Parse(sTemp.Substring(9,1)),"Object.ContractRate",s);
SetRight(int.Parse(sTemp.Substring(9,1)),"Object.ServiceBank",s);
//RATES=10//RATES=SCREEN
SetRight(int.Parse(sTemp.Substring(10,1)),"Object.Rate",s);
SetRight(int.Parse(sTemp.Substring(10,1)),"Object.RateUnitChargeDescription",s);
//ZONES=11
SetRight(int.Parse(sTemp.Substring(11,1)),"Object.DispatchZone",s);
//UNITS=12
SetRight(int.Parse(sTemp.Substring(12,1)),"Object.Unit",s);
SetRight(int.Parse(sTemp.Substring(12,1)),"Object.UnitMeterReading",s);
//MODELS=13
SetRight(int.Parse(sTemp.Substring(13,1)),"Object.UnitModel",s);
//PARTS=14
SetRight(int.Parse(sTemp.Substring(14,1)),"Object.Part",s);
SetRight(2,"Object.Part",s);
SetRight(2,"Object.PartAssembly",s);
SetRight(2,"Object.PartCategory",s);
SetRight(2,"Object.PartByWarehouseInventory",s);
SetRight(2,"Object.PartWarehouse",s);
SetRight(2,"Object.PartInventoryAdjustment",s);
SetRight(2,"Object.PurchaseOrder",s);
SetRight(2,"Object.UnitOfMeasure",s);
//TASKS=15
SetRight(int.Parse(sTemp.Substring(15,1)),"Object.Task",s);
SetRight(2,"Object.TaskGroup",s);
SetRight(2,"Object.Task",s);
SetRight(2,"Object.TaskGroupTask",s);
//PROJECTS=16
SetRight(int.Parse(sTemp.Substring(16,1)),"Object.Project",s);
//WOTYPES=17//BLAH
SetRight(int.Parse(sTemp.Substring(17,1)),"Object.WorkorderCategory",s);
SetRight(int.Parse(sTemp.Substring(17,1)),"Object.UnitServiceType",s);
SetRight(int.Parse(sTemp.Substring(17,1)),"Object.WorkorderStatus",s);
SetRight(int.Parse(sTemp.Substring(17,1)),"Object.WorkorderItemType",s);
SetRight(int.Parse(sTemp.Substring(17,1)),"Object.Priority",s);
//ADDRESSBOOKS=18//MODIFY=ADDRESS=BOOKS (vendors)
SetRight(int.Parse(sTemp.Substring(18,1)),"Object.Vendor",s);
//USERS=19//RIGHT=TO=EDIT=USERS=AND=PLACE=IN=GROUPS
//Case 618 SetRight(int.Parse(sTemp.Substring(19,1)),"Object.UserRight",s);
SetRight(int.Parse(sTemp.Substring(19,1)),"Object.User",s);
SetRight(int.Parse(sTemp.Substring(19,1)),"Object.UserCertificationAssigned",s);
SetRight(int.Parse(sTemp.Substring(19,1)),"Object.UserSkillAssigned",s);
SetRight(int.Parse(sTemp.Substring(19,1)),"Object.UserCertification",s);
SetRight(int.Parse(sTemp.Substring(19,1)),"Object.UserSkill",s);
//PM=20//preventative=maintenance=screen
SetRight(int.Parse(sTemp.Substring(20,1)),"Object.WorkorderPreventiveMaintenance",s);
//LOANERS=21//loaner=equipment=screen
SetRight(int.Parse(sTemp.Substring(21,1)),"Object.LoanItem",s);
//SCHEDULE=22//scheduling=screen
SetRight(int.Parse(sTemp.Substring(22,1)),"Object.ScheduleForm",s);
//SCHED_GROUPS=23//schedule=groups=screen
SetRight(int.Parse(sTemp.Substring(23,1)),"Object.ScheduleableUserGroup",s);
SetRight(int.Parse(sTemp.Substring(23,1)),"Object.ScheduleableUserGroupUser",s);
//SCHED_MARKERS=24//schedule=groups=screen
SetRight(int.Parse(sTemp.Substring(24,1)),"Object.ScheduleMarker",s);
//USERPREFS=25//user=preferences
//NO EQUIVALENT
//ARAS_REQUESTS=26//ARAS=service=requests
//SetRight(int.Parse(sTemp.Substring(26,1)),"Object.ClientRequestPart",s);
//SetRight(int.Parse(sTemp.Substring(26,1)),"Object.ClientRequestTech",s);
SetRight(int.Parse(sTemp.Substring(26,1)),"Object.ClientServiceRequest",s);
//SetRight(int.Parse(sTemp.Substring(26,1)),"Object.ClientServiceRequestItem",s);
//SECURITY RIGHTS
s.Save();
lImported++;
}
rdr.Close();if(cancel) goto BAIL;
ShowProgress("Imported: "+ lImported.ToString()+" Security groups.","",100, out cancel);
lImported=0;
lTotalRecords=0;
//END SECURITY GROUPS
//SecurityGroupList sgl = SecurityGroupList.GetList("");
#endregion
#region Import zones
//*********************************************************
// ZONES
ShowProgress("","Importing zones...",0, out cancel);
cmd.CommandText="SELECT Count(zones.id) AS TotalRecords FROM zones;";
rdr=cmd.ExecuteReader();
rdr.Read();
lTotalRecords=rdr.GetInt32(0);
rdr.Close();if(cancel) goto BAIL;
Hashtable htZones=new Hashtable(lTotalRecords);
DispatchZones zones=DispatchZones.GetItems(false);
//ShowProgress("\r\nZONES\r\n******************");
cmd.CommandText="SELECT zones.id, zones.name, zones.zoneinfo FROM zones;";
rdr=cmd.ExecuteReader();
while(rdr.Read() && !cancel)
{
ShowProgress("","",(int)((lImported/lTotalRecords)*100),out cancel );
sLastOp=rdr.GetInt32(0).ToString();
DispatchZone d = zones.Add();
d.Name=GetString(rdr,1);
//ShowProgress("Zone: " + d.Name);
d.Description=GetString(rdr,2);
d.Active=true;
htZones.Add(rdr.GetInt32(0),d.ID);
zones.Save();
lImported++;
}
rdr.Close();if(cancel) goto BAIL;
//END ZONES
ShowProgress("Imported: "+ lImported.ToString()+" Dispatch zones.","",100, out cancel);
lImported=0;
lTotalRecords=0;
zones=null;
//************************************************************************
#endregion
#region Import users
//*********************************************************
// USERS
ShowProgress("","Importing users...",0, out cancel);
cmd.CommandText="SELECT Count(users.id) AS TotalRecords FROM users;";
rdr=cmd.ExecuteReader();
rdr.Read();
lTotalRecords=rdr.GetInt32(0);
rdr.Close();if(cancel) goto BAIL;
Hashtable htUsers=new Hashtable(lTotalRecords+1);
htUsers.Add(1,new Guid("2ECC77FC-69E2-4A7E-B88D-BD0ECAF36AED"));
//ShowProgress("\r\nUSERS\r\n******************");
cmd.CommandText=
"SELECT users.id, users.first, users.last, users.initials, "+
"users.tech, users.active, users.email, users.c, users.defzone "+
"FROM users "+
"WHERE (((users.id)<>1));";
rdr=cmd.ExecuteReader();
while(rdr.Read() && !cancel)
{
ShowProgress("","",(int)((lImported/lTotalRecords)*100),out cancel );
sLastOp=rdr.GetInt32(0).ToString();
User u = User.NewItem();
u.DefaultLanguage="English";
htUsers.Add(rdr.GetInt32(0),u.ID);
u.FirstName=GetString(rdr,1);
u.LastName=GetString(rdr,2);
u.Initials=GetString(rdr,3);
//ShowProgress("User: "+u.FirstName + " " + u.LastName);
if(rdr.GetBoolean(4)==true)//is a tech?
u.UserType=UserTypes.Schedulable;
else
u.UserType=UserTypes.NonSchedulable;
//Import all scheduleable users as inactive
//to avoid license issues during import
if(u.UserType==UserTypes.Schedulable)
u.Active=false;
else
u.Active=rdr.GetBoolean(5);
u.EmailAddress=GetString(rdr,6);
u.RegionID= new Guid("8236E8D1-CAB1-4797-9C34-93861954AE6A");//Default region
if(htZones.Contains(rdr.GetInt32(8)))
u.DispatchZoneID=(Guid)htZones[rdr.GetInt32(8)];
u.MemberOfGroup=(Guid)htSecurityGroups[rdr.GetInt32(7)];// administrators- "FF0DE42A-0EA0-429B-9643-64355703E8D1"
u.Login=u.Initials+System.DateTime.Now.Millisecond.ToString();
u.Password=u.Initials+System.DateTime.Now.Millisecond.ToString();
u.Save();
lImported++;
}
rdr.Close();if(cancel) goto BAIL;
ShowProgress("Imported: "+ lImported.ToString()+" Users.","",100, out cancel);
lImported=0;
lTotalRecords=0;
//END USERS
//************************************************************************
#endregion
#region Import Probstats
//*********************************************************
// PROBSTAT
ShowProgress("","Importing Workorder Status types...",0, out cancel);
cmd.CommandText="SELECT Count(probstat.id) AS TotalRecords FROM probstat;";
rdr=cmd.ExecuteReader();
rdr.Read();
lTotalRecords=rdr.GetInt32(0);
rdr.Close();if(cancel) goto BAIL;
Hashtable htWOStatus=new Hashtable(lTotalRecords);
cmd.CommandText=
"SELECT probstat.id, probstat.notes, probstat.red, probstat.green, "+
"probstat.blue FROM probstat ORDER BY probstat.id;";
rdr=cmd.ExecuteReader();
WorkorderStatuses wostatuses=WorkorderStatuses.GetItems();
while(rdr.Read() && !cancel)
{
ShowProgress("","",(int)((lImported/lTotalRecords)*100),out cancel );
sLastOp=rdr.GetInt32(0).ToString();
WorkorderStatus s = wostatuses.Add();
s.Name=GetString(rdr,1);
htWOStatus.Add(rdr.GetInt32(0),s.ID);
s.Active=true;
s.ARGB=System.Drawing.Color.FromArgb(rdr.GetInt32(2),rdr.GetInt32(3),rdr.GetInt32(4)).ToArgb();
wostatuses.Save();
lImported++;
}
rdr.Close();if(cancel) goto BAIL;
ShowProgress("Imported: "+ lImported.ToString()+" Workorder status items.","",100, out cancel);
lImported=0;
lTotalRecords=0;
wostatuses=null;
//END PROBSTAT
//************************************************************************
#endregion
#region Import wotypes (category)
//*********************************************************
// wotypes
ShowProgress("","Importing wotypes (categories)...",0, out cancel);
cmd.CommandText="SELECT Count(wotypes.id) AS TotalRecords FROM wotypes;";
rdr=cmd.ExecuteReader();
rdr.Read();
lTotalRecords=rdr.GetInt32(0);
rdr.Close();if(cancel) goto BAIL;
Hashtable htCategories=new Hashtable(lTotalRecords);
WorkorderCategories wocats=WorkorderCategories.GetItems();
cmd.CommandText=
"SELECT wotypes.id, wotypes.category FROM wotypes;";
rdr=cmd.ExecuteReader();
while(rdr.Read() && !cancel)
{
ShowProgress("","",(int)((lImported/lTotalRecords)*100),out cancel );
sLastOp=rdr.GetInt32(0).ToString();
WorkorderCategory s = wocats.Add();
s.Name=GetString(rdr,1);
htCategories.Add(rdr.GetInt32(0),s.ID);
s.Active=true;
wocats.Save();
lImported++;
}
rdr.Close();if(cancel) goto BAIL;
ShowProgress("Imported: "+ lImported.ToString()+" Workorder Category items.","",100, out cancel);
lImported=0;
lTotalRecords=0;
wocats=null;
#endregion
#region Import rates
//*********************************************************
// RATES
ShowProgress("","Importing Rates...",0, out cancel);
cmd.CommandText="SELECT Count(rates.id) AS TotalRecords FROM rates;";
rdr=cmd.ExecuteReader();
rdr.Read();
lTotalRecords=rdr.GetInt32(0);
rdr.Close();if(cancel) goto BAIL;
Hashtable htRates=new Hashtable(lTotalRecords);
//ShowProgress("\r\nRATES\r\n******************");
cmd.CommandText=
"SELECT rates.id, rates.name, rates.rate, rates.cost, rates.active, "+
"rates.travelrate, rates.partnum FROM rates;";
rdr=cmd.ExecuteReader();
Guid gDefRateUnitChargeDescriptionID=Guid.Empty;
if(lTotalRecords>0)
{
RateUnitChargeDescriptions rucd=null;
rucd= RateUnitChargeDescriptions.GetItems();
RateUnitChargeDescription rtemp=rucd.Add();
// * COMPROMISE: Created rate unit charge description
// * for imported rates that defaults to "Hour" and "Hours"
// * After import user should modify as required.
rtemp.Name="Hour";
rtemp.NamePlural="Hours";
rucd.Save();
gDefRateUnitChargeDescriptionID=rtemp.ID;
}
Rates rates=Rates.GetItems(false);
while(rdr.Read() && !cancel)
{
ShowProgress("","",(int)((lImported/lTotalRecords)*100),out cancel );
sLastOp=rdr.GetInt32(0).ToString();
Rate r = rates.Add();
htRates.Add(rdr.GetInt32(0),r.ID);
r.Name=GetString(rdr,1);
//ShowProgress("Rate: " + r.Name);
r.AccountNumber=GetString(rdr,6);
r.Active=rdr.GetBoolean(4);
r.ClientGroupID=Guid.Empty;
r.Cost=GetDecimal(rdr,3);
r.Charge=GetDecimal(rdr,2);
if(rdr.GetBoolean(5)!=true)
r.RateType=RateTypes.Service;
else
r.RateType=RateTypes.Travel;
r.RateUnitChargeDescriptionID=gDefRateUnitChargeDescriptionID;
rates.Save();
lImported++;
}
rdr.Close();if(cancel) goto BAIL;
ShowProgress("Imported: "+ lImported.ToString()+" Rates.","",100, out cancel);
lImported=0;
lTotalRecords=0;
rates=null;
//END RATES
//************************************************************************
#endregion
#region Import Head offices
//*********************************************************
// HEAD OFFICES
ShowProgress("","Importing Head offices...",0, out cancel);
cmd.CommandText="SELECT Count(clients.id) AS TotalRecords FROM clients WHERE (((clients.isheadoffice)=True));";
rdr=cmd.ExecuteReader();
rdr.Read();
lTotalRecords=rdr.GetInt32(0);
rdr.Close();if(cancel) goto BAIL;
Hashtable htHeadOffices = new Hashtable(lTotalRecords);
cmd.CommandText=
"SELECT clients.id, clients.company, clients.active, "+
"clients.generalnotes, clients.alert, clients.technotes, "+
"clients.acctnumber, clients.streetaddress, "+
"clients.mailaddress, clients.city, clients.stateprov, "+
"clients.postal, clients.country, clients.bizphone, "+
"clients.extension, clients.fax, clients.email, "+
"clients.phone2, clients.phone3, clients.first, clients.last FROM clients WHERE "+
"(((clients.isheadoffice)=True));";
rdr=cmd.ExecuteReader();
while(rdr.Read() && !cancel)
{
ShowProgress("","",(int)((lImported/lTotalRecords)*100),out cancel );
sLastOp=rdr.GetInt32(0).ToString();
HeadOffice c = HeadOffice.NewItem();
htHeadOffices.Add(rdr.GetInt32(0),c.ID);
c.Name=GetString(rdr,1);
if(c.Name=="")
c.Name="_HeadOffice " + rdr.GetInt32(0).ToString() + "(missing name on import)";
c.Active=rdr.GetBoolean(2);
c.Notes=GetString(rdr,3);
if(GetString(rdr,4).Length>0)
c.Notes=c.Notes+ "\r\nAyaNova CE Popup notes:\r\n" +GetString(rdr,4);
if(GetString(rdr,5).Length>0)
c.Notes=c.Notes+ "\r\nAyaNova CE Tech notes:\r\n" +GetString(rdr,5);
c.AccountNumber=GetString(rdr,6);
c.GoToAddress.DeliveryAddress=GetString(rdr,7);
c.GoToAddress.City=GetString(rdr,9);
c.GoToAddress.StateProv=GetString(rdr,10);
c.GoToAddress.Postal=GetString(rdr,11);
c.GoToAddress.Country=GetString(rdr,12);
c.MailToAddress.DeliveryAddress=GetString(rdr,8);
c.MailToAddress.City=GetString(rdr,9);
c.MailToAddress.StateProv=GetString(rdr,10);
c.MailToAddress.Postal=GetString(rdr,11);
c.MailToAddress.Country=GetString(rdr,12);
c.Email=GetString(rdr,16);
c.Contact=GetString(rdr,19) + " " + GetString(rdr,20);
//bizphone
sTemp=GetString(rdr,13);
if(sTemp.Length>0)
{
c.Phone1 =sTemp + AyaBizUtils.SS(" ext. ",GetString(rdr,14),"");
}
//faxphone
sTemp=GetString(rdr,15);
if(sTemp.Length>0)
{
c.Phone2 = sTemp;
}
//biz2
sTemp=GetString(rdr,17);
if(sTemp.Length>0)
{
c.Phone3 = sTemp;
}
//biz3
sTemp=GetString(rdr,18);
if(sTemp.Length>0)
{
c.Phone4 = sTemp;
}
c.Save();
lImported++;
}
rdr.Close();if(cancel) goto BAIL;
//END Head offices
ShowProgress("Imported: "+ lImported.ToString()+" HeadOffices.","",100, out cancel);
lImported=0;
lTotalRecords=0;
//************************************************************************
#endregion
#region Import clients
//*********************************************************
// CLIENTS
ShowProgress("","Importing Clients...",0, out cancel);
cmd.CommandText="SELECT Count(clients.id) AS TotalRecords FROM clients WHERE (((clients.isheadoffice)=False));";
rdr=cmd.ExecuteReader();
rdr.Read();
lTotalRecords=rdr.GetInt32(0);
rdr.Close();if(cancel) goto BAIL;
Hashtable htClients = new Hashtable(lTotalRecords);
cmd.CommandText=
"SELECT clients.id, clients.company, clients.active, "+
"clients.generalnotes, clients.alert, clients.technotes, "+
"clients.acctnumber, clients.streetaddress, "+
"clients.mailaddress, clients.city, clients.stateprov, "+
"clients.postal, clients.country, clients.bizphone, "+
"clients.extension, clients.fax, clients.email, "+
"clients.phone2, clients.phone3, clients.first, " +
"clients.last, clients.headoffice, clients.billheadoffice, " +
"clients.czone FROM clients WHERE "+
"(((clients.isheadoffice)=False));";
rdr=cmd.ExecuteReader();
while(rdr.Read() && !cancel)
{
ShowProgress("","",(int)((lImported/lTotalRecords)*100),out cancel );
sLastOp=rdr.GetInt32(0).ToString();
Client c = Client.NewItem();
htClients.Add(rdr.GetInt32(0),c.ID);
c.Name=GetString(rdr,1);
if(c.Name=="")
c.Name="_Client " + rdr.GetInt32(0).ToString() + "(missing name on import)";
c.Active=rdr.GetBoolean(2);
c.Notes=GetString(rdr,3);
c.PopUpNotes=GetString(rdr,4);
c.TechNotes=GetString(rdr,5);
c.AccountNumber=GetString(rdr,6);
//Head office?
if(htHeadOffices.Contains(SafeGetInt32(rdr,21)))
{
c.HeadOfficeID=(Guid)htHeadOffices[rdr.GetInt32(21)];
c.BillHeadOffice=rdr.GetBoolean(22);
}
//Dispatch zone
if(htZones.Contains(SafeGetInt32(rdr,23)))
{
c.DispatchZoneID=(Guid)htZones[rdr.GetInt32(23)];
}
c.MailToAddress.DeliveryAddress=GetString(rdr,8);
c.MailToAddress.City=GetString(rdr,9);
c.MailToAddress.StateProv=GetString(rdr,10);
c.MailToAddress.Postal=GetString(rdr,11);
c.MailToAddress.Country=GetString(rdr,12);
c.GoToAddress.DeliveryAddress=GetString(rdr,7);
if(c.GoToAddress.DeliveryAddress.Length<2)
c.GoToAddress.DeliveryAddress=c.MailToAddress.DeliveryAddress;
c.GoToAddress.City=GetString(rdr,9);
c.GoToAddress.StateProv=GetString(rdr,10);
c.GoToAddress.Postal=GetString(rdr,11);
c.GoToAddress.Country=GetString(rdr,12);
c.Email=GetString(rdr,16);
c.Contact= GetString(rdr,19) + " " + GetString(rdr,20);
//bizphone
sTemp=GetString(rdr,13);
if(sTemp.Length>0)
{
c.Phone1 = sTemp + AyaBizUtils.SS(" ext. ", GetString(rdr, 14), "");
}
//faxphone
sTemp=GetString(rdr,15);
if(sTemp.Length>0)
{
c.Phone2 = sTemp;
}
//biz2
sTemp=GetString(rdr,17);
if(sTemp.Length>0)
{
c.Phone3 = sTemp;
}
//biz3
sTemp=GetString(rdr,18);
if(sTemp.Length>0)
{
c.Phone4 = sTemp;
}
c.Save();
lImported++;
}
rdr.Close();if(cancel) goto BAIL;
//END Clients
ShowProgress("Imported: "+ lImported.ToString()+" Clients.","",100, out cancel);
lImported=0;
lTotalRecords=0;
//************************************************************************
#endregion
#region Import ARAS client logins
//*********************************************************
// ARAS CLIENT ACCOUNTS
ShowProgress("","Importing ARAS Client Login Accounts...",0, out cancel);
//
//* COMPROMISE: AyaNova ce's ARAS client accounts have been
//// * superseded by new AyaNova regular user accounts of type "client"
// * All ARAS accounts have been imported as users set as type client
// * with a new security group called "Client login accounts" and defaulted
// * to no rights.
// * After import user will need to adjust rights and set login and passwords.
// *
cmd.CommandText="SELECT Count(clients_aras.id) AS TotalRecords FROM " +
"clients_aras LEFT JOIN clients ON clients_aras.clientlink " +
"= clients.id WHERE (((clients.id) Is Not Null));";
rdr=cmd.ExecuteReader();
rdr.Read();
lTotalRecords=rdr.GetInt32(0);
rdr.Close();if(cancel) goto BAIL;
Hashtable htARAS=new Hashtable(lTotalRecords);
SecurityGroup sgARAS=null;
//Are there any?
if(lTotalRecords>0)
{
//then create a new security group for them
sgARAS = SecurityGroup.NewItem();
sgARAS.Name="Client login accounts";
sgARAS.Save();
}
//ShowProgress("\r\nARAS CLIENT ACCOUNTS\r\n******************");
cmd.CommandText=
"SELECT clients_aras.id, clients_aras.loginid, clients.company "+
"FROM clients_aras LEFT JOIN clients ON clients_aras.clientlink = clients.id WHERE (((clients.company) Is Not Null));";
rdr=cmd.ExecuteReader();
int nclientloginnumber=0;
while(rdr.Read() && !cancel)
{
ShowProgress("","",(int)((lImported/lTotalRecords)*100),out cancel );
sLastOp=rdr.GetInt32(0).ToString();
User u = User.NewItem();
u.DefaultLanguage="English";
htARAS.Add(rdr.GetInt32(0),u.ID);
//Import old ID value to custom2 field
//so it doesn't conflict with users old id imported to custom 1 field
//u.Custom2=rdr.GetInt32(0).ToString();
u.FirstName=GetString(rdr,1);
u.LastName=GetString(rdr,2);
if(u.LastName=="") u.LastName="Missing company";
u.Initials="CLNT"+nclientloginnumber.ToString();
nclientloginnumber++;
//ShowProgress("User: "+u.FirstName + " " + u.LastName);
u.UserType=UserTypes.Client;
u.Active=true;
u.RegionID= new Guid("8236E8D1-CAB1-4797-9C34-93861954AE6A");//Default region
u.MemberOfGroup=sgARAS.ID;
u.Login=u.Initials+System.DateTime.Now.Millisecond.ToString();
u.Password=u.Initials+System.DateTime.Now.Millisecond.ToString();
u.Save();
lImported++;
}
rdr.Close();if(cancel) goto BAIL;
ShowProgress("Imported: "+ lImported.ToString()+" ARAS client accounts.","",100, out cancel);
lImported=0;
lTotalRecords=0;
//END ARAS USERS
//************************************************************************
#endregion
#region Import Client notebook
//*********************************************************
ShowProgress("","Importing Client Notebook records...",0, out cancel);
cmd.CommandText="SELECT Count(contacts.id) AS TotalRecords FROM contacts;";
rdr=cmd.ExecuteReader();
rdr.Read();
lTotalRecords=rdr.GetInt32(0);
rdr.Close();if(cancel) goto BAIL;
ClientNoteType cnt=null;
//Are there any?
if(lTotalRecords>0)
{
ClientNoteTypes cnTemp=ClientNoteTypes.GetItems();
//then create a new note type for them
cnt =cnTemp.Add();
cnt.Name="AyaNova CE Client notebook import";
cnTemp.Save();
}
//ShowProgress("\r\nCLIENT NOTEBOOK RECORDS\r\n******************");
cmd.CommandText=
"SELECT contacts.id, contacts.date, contacts.staff, " +
"contacts.notes, contacts.clientlink, users.first, " +
"users.last FROM (contacts INNER JOIN users ON contacts.staff " +
"= users.id) INNER JOIN clients ON contacts.clientlink " +
"= clients.id WHERE (((clients.isheadoffice)=False)) " +
"ORDER BY contacts.id;";
rdr=cmd.ExecuteReader();
while(rdr.Read() && !cancel)
{
ShowProgress("","",(int)((lImported/lTotalRecords)*100),out cancel );
sLastOp=rdr.GetInt32(0).ToString();
ClientNotes cnotes=ClientNotes.GetItems((Guid)htClients[rdr.GetInt32(4)]);
ClientNote cn = cnotes.Add();
//Get new client ID by name
//ClientList is instantiated at end of Import Clients above
cn.ClientID = (Guid)htClients[rdr.GetInt32(4)];
cn.ClientNoteTypeID=cnt.ID;
cn.NoteDate=GetSmartDate(rdr,1).DBValue;
//Set the note to firstname lastname\r\nNotes
cn.Notes=GetString(rdr,5) + " " +GetString(rdr,6) + "\r\n" + GetString(rdr,3);
//set it's source to be the client record itself
cn.RootObjectID=cn.ClientID;
cn.RootObjectType=RootObjectTypes.Client;
cnotes.Save();
lImported++;
}
rdr.Close();if(cancel) goto BAIL;
ShowProgress("Imported: "+ lImported.ToString()+" Client notebook records.","",100, out cancel);
lImported=0;
lTotalRecords=0;
//END
//************************************************************************
#endregion
#region Import Contracts
//*********************************************************
ShowProgress("","Importing Contracts...",0, out cancel);
cmd.CommandText="SELECT Count(contracts.id) AS TotalRecords FROM contracts;";
rdr=cmd.ExecuteReader();
rdr.Read();
lTotalRecords=rdr.GetInt32(0);
rdr.Close();if(cancel) goto BAIL;
Hashtable htContracts=new Hashtable(lTotalRecords);
//ShowProgress("\r\nContract RECORDS\r\n******************");
cmd.CommandText=
"SELECT contracts.id, contracts.name, contracts.terms FROM contracts;";
rdr=cmd.ExecuteReader();
while(rdr.Read() && !cancel)
{
ShowProgress("","",(int)((lImported/lTotalRecords)*100),out cancel );
sLastOp=rdr.GetInt32(0).ToString();
Contract c = Contract.NewItem();
htContracts.Add(rdr.GetInt32(0),c.ID);
//contract active follows client active
c.Active=true;
c.ContractRatesOnly=false;
c.DiscountParts=0m;
c.Name=GetString(rdr,1);
c.Notes=GetString(rdr,2);
c.Save();
lImported++;
}
rdr.Close();if(cancel) goto BAIL;
ShowProgress("Imported: "+ lImported.ToString()+" Contract records.","",100, out cancel);
lImported=0;
lTotalRecords=0;
//END
//************************************************************************
#endregion
#region Set client contracts
//*********************************************************
ShowProgress("","Setting client's contracts...",0, out cancel);
cmd.CommandText="SELECT Count(clients.id) AS TotalRecords FROM clients WHERE ((Not (clients.contract) Is Null));";
rdr=cmd.ExecuteReader();
rdr.Read();
lTotalRecords=rdr.GetInt32(0);
rdr.Close();if(cancel) goto BAIL;
//ShowProgress("\r\nContract RECORDS\r\n******************");
cmd.CommandText=
"SELECT clients.id, clients.contract, clients.contractexpires " +
"FROM contracts INNER JOIN clients ON contracts.id = clients.contract " +
"WHERE ((Not (clients.contract) Is Null) AND ((clients.isheadoffice)=False));";
rdr=cmd.ExecuteReader();
while(rdr.Read() && !cancel)
{
ShowProgress("","",(int)((lImported/lTotalRecords)*100),out cancel );
sLastOp=rdr.GetInt32(0).ToString();
Client cl=Client.GetItem((Guid)htClients[rdr.GetInt32(0)]);
cl.ContractID=(Guid)htContracts[rdr.GetInt32(1)];
cl.ContractExpires=GetSmartDate(rdr,2).DBValue;
cl.Save();
lImported++;
}
rdr.Close();if(cancel) goto BAIL;
ShowProgress("Set: "+ lImported.ToString()+" client's contract.","",100, out cancel);
lImported=0;
lTotalRecords=0;
//END
//************************************************************************
#endregion
#region Import Non-client contacts
//*********************************************************
ShowProgress("","Importing contacts (Vendors)...",0, out cancel);
cmd.CommandText="SELECT Count(nonclients.id) AS TotalRecords FROM nonclients;";
rdr=cmd.ExecuteReader();
rdr.Read();
lTotalRecords=rdr.GetInt32(0);
rdr.Close();if(cancel) goto BAIL;
Hashtable htVendors=new Hashtable(lTotalRecords);
Hashtable htWholesalers=new Hashtable();
//ShowProgress("\r\nNon-client (vendor) RECORDS\r\n******************");
cmd.CommandText=
"SELECT nonclients.type, nonclients.company_person, " +
"nonclients.contact, nonclients.address, nonclients.phone, " +
"nonclients.fax, nonclients.email, nonclients.website, " +
"nonclients.notes, nonclients.account, nonclients.id FROM " +
"nonclients ORDER BY nonclients.company_person;";
rdr=cmd.ExecuteReader();
while(rdr.Read() && !cancel)
{
ShowProgress("","",(int)((lImported/lTotalRecords)*100),out cancel );
sLastOp=rdr.GetInt32(10).ToString();
Vendor v = Vendor.NewItem();
//----------------
int nVendorType = rdr.GetInt32(0);
switch(nVendorType)
{
case 1://subcontractors
//Deliberately not subcontractor here
//Because in CE it really meant 3rd party repair
//in a new workorder you can select any vendor type but shipping
//for outside service so it's really a moot point anyway
v.VendorType=VendorTypes.ThirdPartyRepair;
htVendors.Add(rdr.GetInt32(10),v.ID);
break;
case 2://Shippers
v.VendorType=VendorTypes.Shipper;
htVendors.Add(rdr.GetInt32(10),v.ID);
break;
case 3://manufacturers/suppliers
//COMPROMISE: AyaNova ce lumped manufacturers and wholesalers together
//They will be imported as both manufacturers and wholesalers (duplicated) in
//separate code below after initial manufacturer import
v.VendorType=VendorTypes.Manufacturer;
htVendors.Add(rdr.GetInt32(10),v.ID);
break;
//no idea where to put this so here it is
//concept is not supported in new version I don't think
case 5://Other resellers (competition)
v.VendorType=VendorTypes.Wholesaler;
htWholesalers.Add(rdr.GetInt32(10),v.ID);
break;
}
v.Name=GetString(rdr,1);
v.GoToAddress.DeliveryAddress=GetString(rdr,3,255);//case 1209
v.MailToAddress.DeliveryAddress = GetString(rdr, 3, 255);//case 1209
v.Notes=GetString(rdr,8);
v.AccountNumber=GetString(rdr,9);
v.WebAddress=GetString(rdr,7);
v.Email=GetString(rdr,6);
v.Contact=GetString(rdr,2);
v.Phone1=GetString(rdr,4);
v.Phone2=GetString(rdr,5);
//---------------
v.Save();
if(v.VendorType==VendorTypes.Manufacturer)
{
v = Vendor.NewItem();
htWholesalers.Add(rdr.GetInt32(10),v.ID);
//Following is same code as above so just
//replace this if changes made, (it was easier this way)
v.Name=GetString(rdr,1);
v.VendorType=VendorTypes.Wholesaler;
v.GoToAddress.DeliveryAddress = GetString(rdr, 3, 255);//case 1209
v.MailToAddress.DeliveryAddress = GetString(rdr, 3, 255);//case 1209
v.Notes=GetString(rdr,8);
v.AccountNumber=GetString(rdr,9);
v.WebAddress=GetString(rdr,7);
v.Email=GetString(rdr,6);
v.Contact=GetString(rdr,2);
v.Phone1=GetString(rdr,4);
v.Phone2=GetString(rdr,5);
v.Save();
}
lImported++;
}
rdr.Close();if(cancel) goto BAIL;
ShowProgress("Imported: "+ lImported.ToString()+" Non-client (vendor) records.","",100, out cancel);
lImported=0;
lTotalRecords=0;
//END
//************************************************************************
#endregion
#region Import Parts
//*********************************************************
ShowProgress("","Importing Parts...",0, out cancel);
cmd.CommandText="SELECT Count(parts.id) AS TotalRecords FROM parts;";
rdr=cmd.ExecuteReader();
rdr.Read();
lTotalRecords=rdr.GetInt32(0);
rdr.Close();if(cancel) goto BAIL;
Hashtable htParts=new Hashtable(lTotalRecords);
Hashtable htPartsRentals=new Hashtable();
//Fetch a list of all unique part id's for parts
//that were rented
Hashtable htTempRentalParts=new Hashtable();
cmd.CommandText=
"SELECT DISTINCT rentals.partlink FROM rentals WHERE (((rentals.partlink)<>0));";
rdr=cmd.ExecuteReader();
while(rdr.Read() && !cancel)
{
htTempRentalParts.Add(rdr.GetInt32(0),1);
}
rdr.Close();if(cancel) goto BAIL;
//ShowProgress("\r\nParts RECORDS\r\n******************");
cmd.CommandText=
"SELECT parts.id, parts.partnumber, parts.description, " +
"parts.supersededby, parts.avgcost, parts.retail, " +
"parts.active, parts.notes, parts.supplier, parts.supplierpart, " +
"parts.upc FROM parts " +
"ORDER BY parts.partnumber;";
rdr=cmd.ExecuteReader();
while(rdr.Read() && !cancel)
{
ShowProgress("","",(int)((lImported/lTotalRecords)*100),out cancel );
sLastOp=rdr.GetInt32(0).ToString();
Part p = Part.NewItem();
//----------------
htParts.Add(rdr.GetInt32(0),p.ID);
p.PartNumber=GetString(rdr,1);
p.Name=GetString(rdr,2);
//could be null
p.Alert=SafeGetInt32(rdr,3).ToString();
p.Cost=GetDecimal(rdr,4);
p.Retail=GetDecimal(rdr,5);
p.Active=rdr.GetBoolean(6);
p.Notes=GetString(rdr,7);
p.UPC=GetString(rdr,10);
p.WholesalerNumber=GetString(rdr,9);
//In AyaNova CE there was a single "supplier" field
//since we've imported suppliers into both wholesalers
//and manufacturers separately we need to (if found) insert one of each
//in the appropriate place from the appropriate source
//wholesalers are in htWholesalers
if(htWholesalers.Contains(SafeGetInt32(rdr,8)))
{
p.WholesalerID=(Guid)htWholesalers[rdr.GetInt32(8)];
}
//Manufacturer - they are in htVendors
//so check for that one
if(htVendors.Contains(SafeGetInt32(rdr,8)))
{
p.ManufacturerID=(Guid)htVendors[rdr.GetInt32(8)];
}
//---------------
p.Save();
//Add a loan item if this is a rented part
if(htTempRentalParts.Contains(rdr.GetInt32(0)))
{
LoanItem li=LoanItem.NewItem();
htPartsRentals.Add(rdr.GetInt32(0),li.ID);
li.Active=true;
li.Name=PartPickList.GetOnePart(p.ID)[0].DisplayName(AyaBizUtils.GlobalSettings.DefaultPartDisplayFormat);
li.Notes=p.Notes;
li.Save();
}
lImported++;
}
rdr.Close();if(cancel) goto BAIL;
ShowProgress("Imported: "+ lImported.ToString()+" Parts records.","",100, out cancel);
lImported=0;
lTotalRecords=0;
//END
//************************************************************************
#endregion
#region Import Projects
//*********************************************************
ShowProgress("","Importing Projects...",0, out cancel);
cmd.CommandText="SELECT Count(projects.id) AS TotalRecords FROM projects;";
rdr=cmd.ExecuteReader();
rdr.Read();
lTotalRecords=rdr.GetInt32(0);
rdr.Close();if(cancel) goto BAIL;
Hashtable htProjects=new Hashtable(lTotalRecords);
//Check for duplicates because projects.name is not indexed unique!@#$%
//if there are, then we are going to append their names with their id value as a string
//to ensure uniqueness, but need to know we did that later on when finding the guid for the
//imported project hence this:
bool bDuplicateProjectNames=false;
if(lTotalRecords>0)
{
cmd.CommandText="SELECT First(projects.name) AS [name Field], Count(projects.name) " +
"AS Duplicates FROM projects GROUP BY " +
"projects.name HAVING (((Count(projects.name))>1));";
rdr=cmd.ExecuteReader();
if(rdr.Read())
{
bDuplicateProjectNames=true;
ShowProgress(
"WARNING: duplicate PROJECT names found!\r\n"+
"Importing with unique ID number added to end of name\r\n" +
"to ensure uniqueness. ","",-1, out cancel);
}
rdr.Close();if(cancel) goto BAIL;
}
//ShowProgress("\r\nProject RECORDS\r\n******************");
cmd.CommandText=
"SELECT projects.id, projects.name, projects.notes, " +
"projects.active FROM projects ORDER BY projects.name;";
rdr=cmd.ExecuteReader();
while(rdr.Read() && !cancel)
{
ShowProgress("","",(int)((lImported/lTotalRecords)*100),out cancel );
sLastOp=rdr.GetInt32(0).ToString();
Project p = Project.NewItem();
//----------------
htProjects.Add(rdr.GetInt32(0),p.ID);
if(bDuplicateProjectNames==false)
p.Name=GetString(rdr,1);
else
p.Name=GetString(rdr,1)+rdr.GetInt32(0).ToString();
p.Active=rdr.GetBoolean(3);
p.Notes=GetString(rdr,2);
p.ProjectOverseerID=Guid.Empty;
//---------------
p.Save();
lImported++;
}
rdr.Close();if(cancel) goto BAIL;
ShowProgress("Imported: "+ lImported.ToString()+" Project records.","",100, out cancel);
lImported=0;
lTotalRecords=0;
//END
//************************************************************************
#endregion
#region Import Schedule groups
//*********************************************************
ShowProgress("","Importing Schedule groups...",0, out cancel);
cmd.CommandText="SELECT Count(schdgrps.id) AS TotalRecords FROM schdgrps;";
rdr=cmd.ExecuteReader();
rdr.Read();
lTotalRecords=rdr.GetInt32(0);
rdr.Close();if(cancel) goto BAIL;
Hashtable htScheduleGroups=new Hashtable(lTotalRecords);
//ShowProgress("\r\nSchedule group RECORDS\r\n******************");
cmd.CommandText=
"SELECT schdgrps.id, schdgrps.name FROM schdgrps;";
rdr=cmd.ExecuteReader();
while(rdr.Read() && !cancel)
{
ShowProgress("","",(int)((lImported/lTotalRecords)*100),out cancel );
sLastOp=rdr.GetInt32(0).ToString();
ScheduleableUserGroup s = ScheduleableUserGroup.NewItem();
//----------------
htScheduleGroups.Add(rdr.GetInt32(0),s.ID);
//save group id number because originally there could be duplicate names
//s.Notes=rdr.GetInt32(0).ToString();
s.Name=GetString(rdr,1);
//---------------
s.Save();
lImported++;
}
rdr.Close();if(cancel) goto BAIL;
ShowProgress("Imported: "+ lImported.ToString()+" Schedule group records.","",100, out cancel);
lImported=0;
lTotalRecords=0;
//END
//************************************************************************
#endregion
#region Import Schedule group users
ShowProgress("","Importing Schedule group users...",0, out cancel);
//*********************************************************
cmd.CommandText="SELECT Count(schdets.grpid) AS TotalRecords FROM (schdgrps " +
"RIGHT JOIN schdets ON schdgrps.id = schdets.grpid) " +
"LEFT JOIN users ON schdets.techid = users.id " +
"WHERE (((users.id) Is Not Null) AND ((schdgrps.id) " +
"Is Not Null));";
rdr=cmd.ExecuteReader();
rdr.Read();
lTotalRecords=rdr.GetInt32(0);
rdr.Close();if(cancel) goto BAIL;
//ShowProgress("\r\nSchedule group user RECORDS\r\n******************");
cmd.CommandText=
"SELECT schdets.grpid, schdets.techid FROM (schdgrps " +
"RIGHT JOIN schdets ON schdgrps.id = schdets.grpid) " +
"LEFT JOIN users ON schdets.techid = users.id " +
"WHERE (((users.id) Is Not Null) AND ((schdgrps.id) " +
"Is Not Null));";
rdr=cmd.ExecuteReader();
while(rdr.Read() && !cancel)
{
ShowProgress("","",(int)((lImported/lTotalRecords)*100),out cancel );
sLastOp=rdr.GetInt32(0).ToString();
if(htScheduleGroups.Contains(rdr.GetInt32(0)))
{
ScheduleableUserGroup s = ScheduleableUserGroup.GetItem((Guid)htScheduleGroups[rdr.GetInt32(0)]);
ScheduleableUserGroupUser grpuser=s.ScheduleableUsers.Add(s);
grpuser.ScheduleableUserGroupID=s.ID;
grpuser.ScheduleableUserID=(Guid)htUsers[rdr.GetInt32(1)];
//---------------
s.Save();
lImported++;
}
}
rdr.Close();if(cancel) goto BAIL;
ShowProgress("Imported: "+ lImported.ToString()+" Schedule group user records.","",100, out cancel);
lImported=0;
lTotalRecords=0;
//END
//************************************************************************
#endregion
#region Import Schedule markers
ShowProgress("","Importing Schedule Markers...",0, out cancel);
//*********************************************************
cmd.CommandText="SELECT Count(schedmarkers.id) AS TotalRecords FROM schedmarkers;";
rdr=cmd.ExecuteReader();
rdr.Read();
lTotalRecords=rdr.GetInt32(0);
rdr.Close();if(cancel) goto BAIL;
cmd.CommandText=
"SELECT schedmarkers.startdate, schedmarkers.enddate, " +
"schedmarkers.notes, schedmarkers.link, schedmarkers.red, " +
"schedmarkers.green, schedmarkers.blue, schedmarkers.id FROM " +
"schedmarkers ORDER BY schedmarkers.startdate;";
rdr=cmd.ExecuteReader();
while(rdr.Read() && !cancel)
{
ShowProgress("","",(int)((lImported/lTotalRecords)*100),out cancel );
sLastOp=(rdr.GetInt32(7)).ToString();
//If it's not a regional marker and the user no longer exists skip it
if(rdr.GetInt32(3)!=0 && !htUsers.Contains(rdr.GetInt32(3)))
continue;
ScheduleMarker m = ScheduleMarker.NewItem();
//----------------
m.ARGB=System.Drawing.Color.FromArgb(rdr.GetInt32(4),rdr.GetInt32(5),rdr.GetInt32(6)).ToArgb();
m.Notes=GetString(rdr,2);
m.Name=GetString(rdr,2);
if(rdr.GetInt32(3)==0)//0=regional
{
m.ScheduleMarkerSourceType=ScheduleMarkerSourceTypes.Regional;
m.SourceID=new Guid("8236E8D1-CAB1-4797-9C34-93861954AE6A");//Default region
}
else
{
m.ScheduleMarkerSourceType=ScheduleMarkerSourceTypes.User;
m.SourceID=(Guid)htUsers[rdr.GetInt32(3)];
}
//---------- DATES ---------------------------
//Added 3.0.2
//Fixup start and stop times so in correct order
//old AyaNova allowed start to be after stop etc
SmartDate sdstart=GetSmartDate(rdr,0);
SmartDate sdstop=GetSmartDate(rdr,1);
if(sdstart.Date > sdstop.Date)
{
//then flip them and retrieve stop in start position
//and vice versa
sdstart=GetSmartDate(rdr,1);
sdstop=GetSmartDate(rdr,0);
}
//Add a minute to the stop time if they are equal
//because the Businessrule for this doesn't allow
//equal start and stop times
if(DBUtil.DatesAreEqualish(sdstart.Date,sdstop.Date))
sdstop.Date=sdstop.Date.AddMinutes(1);
m.StartDate=sdstart.DBValue;
m.StopDate=sdstop.DBValue;
//case 1968
if (sdstop.Date < dtStart)
m.Completed = true;
//---------------
m.Save();
lImported++;
}
rdr.Close();if(cancel) goto BAIL;
ShowProgress("Imported: "+ lImported.ToString()+" Schedule marker records.","",100, out cancel);
lImported=0;
lTotalRecords=0;
//END
//************************************************************************
#endregion
#region Import Tasks
//*********************************************************
// Tasks
ShowProgress("","Importing Tasks...",0, out cancel);
cmd.CommandText="SELECT Count(tasks.id) AS TotalRecords FROM tasks;";
rdr=cmd.ExecuteReader();
rdr.Read();
lTotalRecords=rdr.GetInt32(0);
rdr.Close();if(cancel) goto BAIL;
cmd.CommandText="SELECT tasks.id, tasks.description, tasks.details, " +
"tasks.minutes, tasks.active FROM tasks;";
rdr=cmd.ExecuteReader();
while(rdr.Read() && !cancel)
{
ShowProgress("","",(int)((lImported/lTotalRecords)*100),out cancel );
sLastOp=rdr.GetInt32(0).ToString();
Tasks ts=Tasks.GetItems();
Task t = ts.Add();
//------------------------
t.Active=rdr.GetBoolean(4);
string s=GetString(rdr,1) + " " + GetString(rdr,2);
if(s.Length>255)
t.Name=s.Substring(0,255);
else
t.Name=s;
//-------------------------
ts.Save();
lImported++;
}
rdr.Close();if(cancel) goto BAIL;
//END Tasks
ShowProgress("Imported: "+ lImported.ToString()+" Tasks.","",100, out cancel);
lImported=0;
lTotalRecords=0;
//************************************************************************
#endregion
#region Import Unit model categories
//*********************************************************
// Unit model categories
ShowProgress("","Importing Unit model categories...",0, out cancel);
cmd.CommandText="SELECT Count(unitmodelcats.id) AS TotalRecords FROM unitmodelcats;";
rdr=cmd.ExecuteReader();
rdr.Read();
lTotalRecords=rdr.GetInt32(0);
rdr.Close();if(cancel) goto BAIL;
Hashtable htUnitModelCategories=new Hashtable(lTotalRecords);
UnitModelCategories uc=UnitModelCategories.GetItems();
//ShowProgress("\r\nUnit model categories\r\n******************");
cmd.CommandText="SELECT unitmodelcats.id, unitmodelcats.notes, unitmodelcats.name FROM unitmodelcats;";
rdr=cmd.ExecuteReader();
while(rdr.Read() && !cancel)
{
ShowProgress("","",(int)((lImported/lTotalRecords)*100),out cancel );
sLastOp=rdr.GetInt32(0).ToString();
UnitModelCategory u = uc.Add();
htUnitModelCategories.Add(rdr.GetInt32(0),u.ID);
//------------------------
u.Active=true;
u.Name=GetString(rdr,2);
u.Description=GetString(rdr,1,255);
//-------------------------
uc.Save();
lImported++;
}
rdr.Close();if(cancel) goto BAIL;
//END Unit model categories
ShowProgress("Imported: "+ lImported.ToString()+" Unit model categories.","",100, out cancel);
lImported=0;
lTotalRecords=0;
uc=null;
//************************************************************************
#endregion
#region Import Unit models
//*********************************************************
// Unit model categories
ShowProgress("","Importing Unit models...",0, out cancel);
cmd.CommandText="SELECT Count(unitmodels.id) AS TotalRecords FROM unitmodels;";
rdr=cmd.ExecuteReader();
rdr.Read();
lTotalRecords=rdr.GetInt32(0);
rdr.Close();if(cancel) goto BAIL;
Hashtable htUnitModels=new Hashtable(lTotalRecords);
//ShowProgress("\r\nUnit model categories\r\n******************");
cmd.CommandText="SELECT unitmodels.id, unitmodels.model, unitmodels.description, " +
" unitmodels.lifetimewarranty, unitmodels.warranty, " +
" unitmodels.warrantyterms, unitmodels.discontinued, " +
" unitmodels.discodate, unitmodels.introduced, " +
" unitmodels.active, unitmodels.notes, unitmodels.category, unitmodels.manufacturer " +
"FROM unitmodels;";
rdr=cmd.ExecuteReader();
while(rdr.Read() && !cancel)
{
ShowProgress("","",(int)((lImported/lTotalRecords)*100),out cancel );
sLastOp=rdr.GetInt32(0).ToString();
UnitModel u = UnitModel.NewItem();
htUnitModels.Add(rdr.GetInt32(0),u.ID);
//------------------------
u.Active=rdr.GetBoolean(9);
u.Discontinued=rdr.GetBoolean(6);
u.DiscontinuedDate=GetSmartDate(rdr,7).DBValue;
u.IntroducedDate=GetSmartDate(rdr,8).DBValue;
u.LifeTimeWarranty=rdr.GetBoolean(3);
u.ModelNumber=GetString(rdr,1);
u.Name=GetString(rdr,2);
if(u.ModelNumber=="")
{
if(u.ModelNumber=="" && u.Name!="")
u.ModelNumber=u.Name;
else
u.ModelNumber="IMPORTMISSING CE_DB_ID:" + rdr.GetInt32(0).ToString();
}
u.Notes=GetString(rdr,10);
if(htUnitModelCategories.Contains(rdr.GetInt32(11)))
u.UnitModelCategoryID=(Guid)htUnitModelCategories[rdr.GetInt32(11)];
if(htVendors.Contains(rdr.GetInt32(12)))
u.VendorID=(Guid)htVendors[rdr.GetInt32(12)];
u.WarrantyLength=rdr.GetInt32(4);
u.WarrantyTerms=GetString(rdr,5);
//-------------------------
u.Save();
lImported++;
}
rdr.Close();if(cancel) goto BAIL;
//END Unit model categories
ShowProgress("Imported: "+ lImported.ToString()+" Unit model.","",100, out cancel);
lImported=0;
lTotalRecords=0;
//************************************************************************
#endregion
#region Import Units
//*********************************************************
// Units
ShowProgress("","Importing units...",0, out cancel);
cmd.CommandText="SELECT Count(units.id) AS TotalRecords FROM units;";
rdr=cmd.ExecuteReader();
rdr.Read();
lTotalRecords=rdr.GetInt32(0);
rdr.Close();if(cancel) goto BAIL;
Hashtable htUnits=new Hashtable(lTotalRecords);
Hashtable htLoanItemsUnits=new Hashtable();
//See if there are any units marked as loaner, if so then
//we need to create a client record to import them under
//because the concept of loaner in CE included self owned units
//where in Bamboo it's can be either loaner items or self owned units under
//a self client record so to be safe we'll import them as both and the
//user can delete them afterwards if they are not required
cmd.CommandText="SELECT Count(units.id) AS LOANERCOUNT FROM units WHERE (((units.loaner)=True));";
rdr=cmd.ExecuteReader();
rdr.Read();
Client cCompany=null;
if(rdr.GetInt32(0) > 0)
{
cCompany=Client.NewItem();
cCompany.Name="AyaNova CE Loaner unit owner";
cCompany.Notes=
"This client was created to be the owner for imported loaner units\r\n" +
"from AyaNova CE. The CE loaner units were also imported as Loan items\r\n" +
"If you do not want to track service for your own units then you can delete the " +
"units that were imported and then delete this client record.\r\n\r\n" +
"If you do want to track service on your own units you can simply rename this client\r\n" +
"to a more meaningful name like your own company name.";
cCompany.Active=true;
cCompany.Save();
//Keep track of the rental unit company client
//so it can be re-used in PM for units later
htClients.Add(0,cCompany.ID);
}
rdr.Close();if(cancel) goto BAIL;
//ShowProgress("\r\nUnits\r\n******************");
cmd.CommandText="SELECT "+
"units.id, units.model, units.sn, units.id1, " +
"units.id2, units.id3, units.boughthere, units.purchasedfrom, " +
"units.receipt, units.purchasedate, units.client, " +
"units.specialwarranty, units.notes, units.pmreport, " +
"units.description, units.loaner, units.lastmeter " +
"FROM units;";
rdr=cmd.ExecuteReader();
while(rdr.Read() && !cancel)
{
ShowProgress("","",(int)((lImported/lTotalRecords)*100),out cancel );
sLastOp=rdr.GetInt32(0).ToString();
Unit u = Unit.NewItem();
htUnits.Add(rdr.GetInt32(0),u.ID);
//------------------------
u.Active=true;
u.BoughtHere=rdr.GetBoolean(6);
//loaner?
if(rdr.GetBoolean(15)==true)
u.ClientID=cCompany.ID;
else
{
if(htClients.Contains(rdr.GetInt32(10)))
u.ClientID=(Guid)htClients[rdr.GetInt32(10)];
}
u.Custom0=GetString(rdr,3);
u.Custom1=GetString(rdr,4);
u.Custom2=GetString(rdr,5);
u.Description=GetString(rdr,14);
u.Notes=GetString(rdr,12);
u.PurchasedDate=GetSmartDate(rdr,9).DBValue;
u.WarrantyTerms=GetString(rdr,11);
//default is false
u.OverrideModelWarranty=false;
if(u.WarrantyTerms.Length>0)
{
u.OverrideModelWarranty=true;
//Don't know what to do with this
//u.WarrantyLength
}
//purchased from?
//Give precedence to wholesaler record if present
//else check vendors
if(htWholesalers.Contains(rdr.GetInt32(7)))
u.PurchasedFromID=(Guid)htWholesalers[rdr.GetInt32(7)];
else if(htVendors.Contains(rdr.GetInt32(7)))
u.PurchasedFromID=(Guid)htVendors[rdr.GetInt32(7)];
else
u.PurchasedFromID=Guid.Empty;
u.Receipt=GetString(rdr,8);
u.ReplacedByUnitID=Guid.Empty;
u.Serial=GetString(rdr,2);
u.UnitHasOwnAddress=false;
//Model number?
if(htUnitModels.Contains(rdr.GetInt32(1)))
{
u.UnitModelID=(Guid)htUnitModels[rdr.GetInt32(1)];
}
else
u.UnitModelID=Guid.Empty;
//-------------------------
#if(DEBUG)
//if (sLastOp == "164")
// System.Diagnostics.Debugger.Break();
#endif
u.Save();
//If it was a loaner then
//create a loan item record as well
if(cCompany!=null && u.ClientID==cCompany.ID)
{
LoanItem li=LoanItem.NewItem();
htLoanItemsUnits.Add(rdr.GetInt32(0),li.ID);
li.Active=true;
li.Serial=u.Serial;
li.Name=UnitNameFetcher.GetUnitNameFromUnitID(u.ID) + " " + u.Description;
li.Notes=u.Notes;
li.Custom0=u.Description;
li.Save();
}
lImported++;
}
rdr.Close();if(cancel) goto BAIL;
//END Units
ShowProgress("Imported: "+ lImported.ToString()+" Units.","",100, out cancel);
lImported=0;
lTotalRecords=0;
//************************************************************************
#endregion
#region SubUnits
//*********************************************************
// MasterUnits
ShowProgress("","Importing subunits...",0, out cancel);
cmd.CommandText="SELECT Count(subunits.unitid) AS CountOfunitid FROM " +
"subunits WHERE (((subunits.masterunitid)<>0)) HAVING " +
"(((Count(subunits.unitid))<>0));";
rdr=cmd.ExecuteReader();
//todo: echo this for each routine, there
//is no guarantee that rdr.Read will be true
//and the subsequent get will fail if there is no data and
//throw and exeception that will stop the whole import
if(rdr.Read())
lTotalRecords=rdr.GetInt32(0);
else
lTotalRecords=0;
rdr.Close();if(cancel) goto BAIL;
cmd.CommandText="SELECT subunits.unitid, subunits.masterunitid FROM " +
"subunits WHERE (((subunits.unitid)<>0) AND ((subunits.masterunitid)<>0)) " +
"ORDER BY subunits.unitid;";
rdr=cmd.ExecuteReader();
while(rdr.Read() && !cancel)
{
ShowProgress("","",(int)((lImported/lTotalRecords)*100),out cancel );
sLastOp=rdr.GetInt32(0).ToString();
//Make sure the unit and parent unit both exist...
if(!htUnits.Contains(rdr.GetInt32(0)) || !htUnits.Contains(rdr.GetInt32(1)) ) continue;
Unit u = Unit.GetItem( (Guid)htUnits[rdr.GetInt32(0)]) ;
u.ParentID=(Guid)htUnits[rdr.GetInt32(1)];
//-------------------------
u.Save();
lImported++;
}
rdr.Close();if(cancel) goto BAIL;
//END
ShowProgress("Imported: "+ lImported.ToString()+" SubUnits.","",100, out cancel);
lImported=0;
lTotalRecords=0;
//************************************************************************
#endregion
#region Workorders
//*********************************************************
// workorders
ShowProgress("","Importing Work orders...",0, out cancel);
cmd.CommandText="SELECT Count(wo.id) AS TotalRecords FROM wo "+
"LEFT JOIN clients ON wo.client = clients.id WHERE (((clients.isheadoffice)=False));";
rdr=cmd.ExecuteReader();
rdr.Read();
lTotalRecords=rdr.GetInt32(0);
rdr.Close();if(cancel) goto BAIL;
Hashtable htWorkorders=new Hashtable(lTotalRecords);
cmd.CommandText="SELECT "+
"wo.id, wo.project, wo.client, wo.type, wo.closed, " +
"wo.notes, wo.onsite, wo.invoice, wo.created," +
"wo.clientrefnum, wo.clientcontact, wo.status, wo.ourref, " +
"wo.prob_reported, wo.prob_found, wo.action_taken FROM wo " +
"LEFT JOIN clients ON wo.client = clients.id "+
//"WHERE (((clients.isheadoffice)=False)) ORDER BY wo.id;";
"WHERE ( ((clients.isheadoffice)=False)) ORDER BY wo.id;";
//"wo.id, wo.project, wo.client, wo.type, wo.closed, " +
//"wo.notes, wo.onsite, wo.anytime, wo.starttime, " +
//"wo.stoptime, wo.assigntech, wo.quick, wo.invoice, " +
//"wo.creator, wo.modifier, wo.created, wo.modified, " +
//"wo.clientrefnum, wo.clientcontact, wo.status, wo.ourref " +
//"wo.esthours, wo.estrate, wo.indexed, wo.prob_reported, " +
//"wo.prob_found, wo.action_taken, wo.starttime2, " +
//"wo.stoptime2, wo.assigntech2, wo.starttime3, " +
//"wo.stoptime3, wo.assigntech3, wo.starttime4, " +
//"wo.stoptime4, wo.assigntech4, wo.pmid FROM wo "+
//"LEFT JOIN clients ON wo.client = clients.id "+
//"WHERE (((clients.isheadoffice)=False));";
rdr=cmd.ExecuteReader();
while(rdr.Read() && !cancel)
{
ShowProgress("","",(int)((lImported/lTotalRecords)*100),out cancel );
sLastOp=rdr.GetInt32(0).ToString();
Workorder w = Workorder.NewItem(WorkorderTypes.Service);
//------------------------------
//Case 1134
w.CustomerContactName = ".";
w.ClientID=(Guid)htClients[rdr.GetInt32(2)];
int CEWONumber=rdr.GetInt32(0);
htWorkorders.Add(CEWONumber,w.ID);
w.CustomerContactName=GetString(rdr,10);
w.CustomerReferenceNumber=GetString(rdr,9);
w.InternalReferenceNumber=GetString(rdr,12);
w.Onsite=rdr.GetBoolean(6);
//project (can be empty)
if(htProjects.Contains(rdr.GetInt32(1)))
w.ProjectID=(Guid)htProjects[rdr.GetInt32(1)];
//w.RegionID=new Guid("8236E8D1-CAB1-4797-9C34-93861954AE6A");//Default region
w.Summary=GetString(rdr,5);
//Workorder Category (can be empty)
if(htCategories.Contains(rdr.GetInt32(3)))
w.WorkorderCategoryID=(Guid)htCategories[rdr.GetInt32(3)];
//Children
w.WorkorderService.InvoiceNumber=GetString(rdr,7);
w.WorkorderService.WorkorderPreventiveMaintenanceWorkorderID=Guid.Empty;
w.WorkorderService.ServiceDate=GetSmartDate(rdr,8).DBValue;
//w.WorkorderService.ServiceNumber=rdr.GetInt32(0);
//Status (can be empty)
if (htWOStatus.Contains(rdr.GetInt32(11)))
{
w.WorkorderService.WorkorderStatusID = (Guid)htWOStatus[rdr.GetInt32(11)];
}
#region WorkorderItems
//***************************************
// //Open a new reader from a new connection
// System.Data.OleDb.OleDbConnection cnSub = new System.Data.OleDb.OleDbConnection();
// cnSub.ConnectionString = conn.ConnectionString;
// cnSub.Open();
// OleDbCommand cmSub = new OleDbCommand();
// cmSub.Connection=cnSub;
// cmSub.CommandType=System.Data.CommandType.Text;
// OleDbDataReader drSub;
// //****************************************
cmSub.CommandText="SELECT "+
"probs.wolink, probs.id, probs.brief, probs.notes, " +
"probs.unit, probs.meter, probs.status, probs.pmscheduleid, " +
"probs.taskid, probs.creator, probs.modifier, " +
"probs.created, probs.modified FROM (probs LEFT JOIN wo ON probs.wolink = wo.id) LEFT JOIN clients ON wo.client = clients.id " +
"WHERE (((probs.wolink)=" + CEWONumber.ToString()+") AND ((clients.isheadoffice)=False))" +
"ORDER BY probs.wolink, probs.id;";
drSub=cmSub.ExecuteReader();
//Keep track if first run through loop so we know whether
//to add a woitem or use the initial first one or not
bool bItemsAdded=false;
WorkorderItem wi=null;
while(drSub.Read() && !cancel)
{
if(!bItemsAdded)
{
//It's a workorder that has not yet had any
//workorderitems imported, so it has a default
//blank workorder item already that we will work with
wi=w.WorkorderItems[0];
bItemsAdded=true;
}
else
{
//It's a workorder that has already had a workorder item imported
//so we will need to add a new one
wi=w.WorkorderItems.Add(w);
}
sLastOp="Prob:" + drSub.GetInt32(1).ToString();
int CEProbNumber=drSub.GetInt32(1);
//------------------------
//preserve old ID value
//htWorkorderItems.Add(drSub.GetInt32(1),wi.ID);
wi.Summary=GetString(drSub,2);
wi.TechNotes=GetString(drSub,3);
//New object, just set to unselected
wi.TypeID=Guid.Empty;
//Unit (can be empty)
if(htUnits.Contains(drSub.GetInt32(4)))
wi.UnitID=(Guid)htUnits[drSub.GetInt32(4)];
wi.WarrantyService=false;
//wi.WorkorderItemUnitServiceTypeID=DefaultUnitServiceType.ID;
//Status (can be empty)
if(htWOStatus.Contains(drSub.GetInt32(6)))
wi.WorkorderStatusID=(Guid)htWOStatus[drSub.GetInt32(6)];
sLastOp="Starting Workorder item child items...";
#region Workorder item children
//***************************************
// //Open a new reader from a new connection
// System.Data.OleDb.OleDbConnection cnSub2 = new System.Data.OleDb.OleDbConnection();
// cnSub2.ConnectionString = conn.ConnectionString;
// cnSub2.Open();
// OleDbCommand cmSub2 = new OleDbCommand();
// cmSub2.Connection=cnSub2;
// cmSub2.CommandType=System.Data.CommandType.Text;
// OleDbDataReader drSub2;
// //****************************************
#region Import Scheduled techs
//*********************************************************
sLastOp="Starting scheduled techs...";
cmSub2.CommandText="SELECT wo.id, "+
"wo.starttime, wo.stoptime, wo.assigntech, " +
"wo.starttime2, wo.stoptime2, wo.assigntech2, " +
"wo.starttime3, wo.stoptime3, wo.assigntech3, "+
"wo.starttime4, wo.stoptime4, wo.assigntech4 "+
"FROM wo LEFT JOIN " +
"clients ON wo.client = clients.id WHERE (((wo.id)=" + CEWONumber.ToString()+") AND ((wo.quick)=False) " +
"AND ((clients.isheadoffice)=False)) "+
"ORDER BY wo.id;";
drSub2=cmSub2.ExecuteReader();
while(drSub2.Read() && !cancel)
{
sLastOp="WOSchedTech Wo#:" + drSub2.GetInt32(0).ToString();
int nTechID=0;
//------------------------
//techs 1 thru 4
for(int x=1;x<5;x++)
{
nTechID=drSub2.GetInt32(x*3);
//change here for v3.0.2
//not allowing import of old sched techs where the techid is selected
//but either date is null
if(nTechID!=-1 &&
!drSub2.IsDBNull((x*3)-2) &&//stop date
!drSub2.IsDBNull((x*3)-1))//start date
{
WorkorderItemScheduledUser s = wi.ScheduledUsers.Add(wi);
if(nTechID==0 || !htUsers.Contains(nTechID))//Scheduled but no selected user
s.UserID=Guid.Empty;
else
{
s.UserID=(Guid)htUsers[nTechID];
}
//---------- DATES ---------------------------
//Fixup start and stop times so in correct order
//old AyaNova allowed start to be after stop etc
SmartDate sdstart=GetSmartDate(drSub2,(x*3)-2);
SmartDate sdstop=GetSmartDate(drSub2,(x*3)-1);
if(sdstart.Date > sdstop.Date)
{
//then flip them and retrieve stop in start position
//and vice versa
sdstart=GetSmartDate(drSub2,(x*3)-1);
sdstop=GetSmartDate(drSub2,(x*3)-2);
}
//Add a minute to the stop time if they are equal
//because the Businessrule for this doesn't allow
//equal start and stop times
if(DBUtil.DatesAreEqualish(sdstart.Date,sdstop.Date))
sdstop.Date=sdstop.Date.AddMinutes(1);
s.StartDate=sdstart.DBValue;
s.StopDate=sdstop.DBValue;
//-----------------------------------------------
}
}
//-------------------------
}//end of sched techs loop
drSub2.Close();if(cancel) goto BAIL;
//END Scheduled techs
sLastOp="Done scheduled techs, starting labor";
//************************************************************************
#endregion
#region Import Labor
//*********************************************************
// labor
cmSub2.CommandText=
"SELECT probs.wolink AS WOID, probs.id AS WOITEMID, " +
"labor.tech, labor.hours, labor.nchours, labor.travhours, " +
"labor.rate, labor.travrate, labor.start, labor.stop, " +
"labor.details, labor.distance, labor.id FROM ((labor " +
"LEFT JOIN probs ON labor.link = probs.id) LEFT JOIN " +
"wo ON probs.wolink = wo.id) LEFT JOIN clients ON " +
"wo.client = clients.id WHERE ( "+
"((probs.id)=" + CEProbNumber.ToString()+") AND " +
"((labor.tech) Is Not Null) AND " +
"((labor.rate) Is Not Null) AND " +
"((clients.isheadoffice)=False)) "+
"ORDER BY probs.wolink;";
drSub2=cmSub2.ExecuteReader();
while(drSub2.Read() && !cancel)
{
ShowProgress("","",(int)((lImported/lTotalRecords)*100),out cancel );
sLastOp="Labor:" + drSub2.GetInt32(12).ToString();
//only import if there are actual dates
//and not null values
if(!drSub2.IsDBNull(9) &&//stop date
!drSub2.IsDBNull(8))//start date)
{
//IMPORT LABOR (SERVICE) HOURS AND DETAILS
WorkorderItemLabor wil=wi.Labors.Add(wi);
wil.NoChargeQuantity=(decimal)drSub2.GetFloat(4);
wil.ServiceDetails=GetString(drSub2,10);
//regular rate
if(htRates.Contains(drSub2.GetInt32(6)))
wil.ServiceRateID=(Guid)htRates[drSub2.GetInt32(6)];
wil.ServiceRateQuantity=(decimal)drSub2.GetFloat(3);
//---------- DATES ---------------------------
//Fixup start and stop times so in correct order
//old AyaNova allowed start to be after stop etc
SmartDate sdstart=GetSmartDate(drSub2,8);
SmartDate sdstop=GetSmartDate(drSub2,9);
if(sdstart.Date > sdstop.Date)
{
//then flip them and retrieve stop in start position
//and vice versa
sdstart=GetSmartDate(drSub2,9);
sdstop=GetSmartDate(drSub2,8);
}
//Add a minute to the stop time if they are equal
//because the Businessrule for this doesn't allow
//equal start and stop times
if(DBUtil.DatesAreEqualish(sdstart.Date,sdstop.Date))
sdstop.Date=sdstop.Date.AddMinutes(1);
wil.ServiceStartDate=sdstart.DBValue;
wil.ServiceStopDate=sdstop.DBValue;
//-----------------------------------------------
if(htUsers.Contains(drSub2.GetInt32(2)))
wil.UserID=(Guid)htUsers[drSub2.GetInt32(2)];
//IMPORT TRAVEL HOURS AND RELATED ETC
//are there any travel hours or distance entered?
if((decimal)drSub2.GetFloat(5)!=0 || (decimal)drSub2.GetFloat(11)!=0)
{
//yes, more than or less than zero travel hours or there is a distance value entered
WorkorderItemTravel wit=wi.Travels.Add(wi);
wit.Distance=(decimal)drSub2.GetFloat(11);
if(htRates.Contains(drSub2.GetInt32(7)))
wit.TravelRateID=(Guid)htRates[drSub2.GetInt32(7)];
wit.TravelRateQuantity=(decimal)drSub2.GetFloat(5);
//There is no separate travel stop and start in AyaNova CE
//but this will barf if they are not set so defaulting
//to the labor start and stop dates which is inherently wrong
//but "more than adequate" (tm) ;)
wit.TravelStartDate=wil.ServiceStartDate;
wit.TravelStopDate=wil.ServiceStopDate;
wit.UserID=wil.UserID;
}
//-------------------------
}//end of if dates valid
}//End labour loop
drSub2.Close();if(cancel) goto BAIL;
sLastOp="Done scheduled labor, starting parts";
//************************************************************************
#endregion
#region WoParts
//*********************************************************
// Part
cmSub2.CommandText=
"SELECT probs.wolink AS WOID, woparts.link AS WOITEMID, " +
"woparts.partnum, woparts.misc, woparts.quantity, " +
"woparts.price, woparts.usedby, woparts.sn, woparts.cost, woparts.id " +
"FROM ((woparts " +
"LEFT JOIN probs ON woparts.link = probs.id) LEFT " +
"JOIN wo ON probs.wolink = wo.id) LEFT JOIN clients " +
"ON wo.client = clients.id WHERE ( " +
"((probs.id)=" + CEProbNumber.ToString()+") AND " +
"((clients.isheadoffice)=False)) "+
"ORDER BY probs.wolink;";
drSub2=cmSub2.ExecuteReader();
//IF a part is found to be missing then
//a placeholder one will be created and this
//guid will contain it's id
Guid gMissingPartID=Guid.Empty;
while(drSub2.Read() && !cancel)
{
ShowProgress("","",(int)((lImported/lTotalRecords)*100),out cancel );
sLastOp="WOPart:" + drSub2.GetInt32(9).ToString();
//IMPORT Part
//see if it's a misc or a regular part first...
if(drSub2.GetInt32(2)==0)//partnum field (which is actually the parts.id field link) is zero
{
//it's misc part...
WorkorderItemMiscExpense me=wi.Expenses.Add(wi);
me.ChargeAmount=GetDecimal(drSub2,5)*(decimal)drSub2.GetFloat(4);//charge * quantity since new ayanova has no quantity for m.e.
me.Description=((decimal)drSub2.GetFloat(4)).ToString() + " @ " + GetDecimal(drSub2,5).ToString("C");
me.ChargeToClient=true;
me.Name=GetString(drSub2,3);
me.ReimburseUser=false;
me.TaxPaid=0;
me.TotalCost=me.ChargeAmount;
if(htUsers.Contains(drSub2.GetInt32(6)))
me.UserID=(Guid)htUsers[drSub2.GetInt32(6)];
}
else
{
//it's an "inventory" part...
WorkorderItemPart wp=wi.Parts.Add(wi);
wp.Cost=GetDecimal(drSub2,8);
if(htParts.Contains(drSub2.GetInt32(2)))
wp.PartID=(Guid)htParts[drSub2.GetInt32(2)];
else
{
//A part is missing, this should not be happening
//and wouldn't with referential integrity,
//unfortunately... :(
if(gMissingPartID==Guid.Empty)
{
Part p = Part.NewItem();
p.Name="IMPORT PLACEHOLDER FOR MISSING PART";
p.Notes="During import a workorder had a part set that doesn't actually exist\r\n" +
"in the parts table. This placehoder was created and used instead\r\n" +
"so that the workorder could be imported.\r\n";
p.PartNumber="MISSING";
p.Retail=0m;
p.Save();
gMissingPartID=p.ID;
}
wp.PartID=gMissingPartID;
}
wp.PartWarehouseID=PartWarehouse.DefaultWarehouseID;
wp.Price=GetDecimal(drSub2,5);
//wp.PurchaseOrderID=Guid.Empty;
wp.Quantity=(decimal)drSub2.GetFloat(4);
wp.Description=GetString(drSub2,7);
}
}//end part loop
drSub2.Close();if(cancel) goto BAIL;
sLastOp="Done parts, starting subrepair...";
//END Part
//************************************************************************
#endregion workorder parts
#region Subrepair
//*********************************************************
// Subrepair
cmSub2.CommandText=
"SELECT probs.wolink, subrepair.where, subrepair.sent, " +
"subrepair.isback, subrepair.eta, subrepair.received, " +
"subrepair.sentvia, subrepair.waybill, subrepair.rma, " +
"subrepair.cost, subrepair.charge, subrepair.notes, subrepair.link, subrepair.id " +
"FROM ((subrepair " +
"LEFT JOIN probs ON subrepair.link = probs.id) " +
"LEFT JOIN wo ON probs.wolink = wo.id) LEFT JOIN " +
"clients ON wo.client = clients.id WHERE ( " +
"((probs.id)=" + CEProbNumber.ToString()+") AND " +
"((clients.isheadoffice)=False));";
drSub2=cmSub2.ExecuteReader();
while(drSub2.Read() && !cancel)
{
sLastOp="Subrepair:" + drSub2.GetInt32(13).ToString();
wi.OutsideService.DateETA=GetSmartDate(drSub2,4).DBValue;
CSLA.SmartDate sdValue=GetSmartDate(drSub2,5);//drSub2.GetDateTime(5);
if(sdValue.IsEmpty || sdValue.Date.Year<1969)
wi.OutsideService.DateReturned=new CSLA.SmartDate().DBValue;
else
wi.OutsideService.DateReturned=sdValue.DBValue;
wi.OutsideService.DateSent=GetSmartDate(drSub2,2).DBValue;
wi.OutsideService.Notes=GetString(drSub2,11);
//wi.OutsideService.ReceivedBack=drSub2.GetBoolean(3);
wi.OutsideService.RepairCost=GetDecimal(drSub2,9);
wi.OutsideService.RepairPrice=GetDecimal(drSub2,10);
wi.OutsideService.RMANumber=GetString(drSub2,8);
wi.OutsideService.ShippingCost=0.0M;
wi.OutsideService.ShippingPrice=0.0M;
wi.OutsideService.TrackingNumber=GetString(drSub2,7);
//Vendor sent to...
if(htVendors.Contains(drSub2.GetInt32(1)))
wi.OutsideService.VendorSentToID=(Guid)htVendors[drSub2.GetInt32(1)];
else if(htWholesalers.Contains(drSub2.GetInt32(1)))
wi.OutsideService.VendorSentToID=(Guid)htWholesalers[drSub2.GetInt32(1)];
//Vendor sent via (shipper)...
if(htVendors.Contains(drSub2.GetInt32(6)))
wi.OutsideService.VendorSentViaID=(Guid)htVendors[drSub2.GetInt32(6)];
}//end outside service loop
drSub2.Close();if(cancel) goto BAIL;
sLastOp="Done Subrepair";
//END Subrepair
//************************************************************************
#endregion subrepair / outside service
#endregion workorderitem children
}//Bottom of problem items loop
drSub.Close();if(cancel) goto BAIL;
sLastOp="Done problem items";
//END Probs
//************************************************************************
#endregion problem items / workorder items
//ONE CLIENT USES THE PROBREPORTED, PROBFOUND, ACTIONTAKEN FIELDS
//THEY WERE TOLD THEY
//WOULD NEVER BE ABLE TO UPGRADE IN FUTURE AND I CAN'T SEE A GOOD PLACE
//TO PUT THAT DATA SO IT'S OUT FOR NOW UNTIL THEY ASK AND WE DETERMINE
//WHERE THEY WANT IT TO GO
//------------------------------
//case 1709
//This can fail here because it has too be valid to set service completed so
//rather than just bomb the whole thing for one bad workorder check first and just log it as unsaveable and move on
if (!w.IsValid)
{
ShowProgress("Source workorder " + CEWONumber.ToString()+ " not valid, can't be imported (" + w.BrokenRulesText+")", "", (int)((lImported / lTotalRecords) * 100), out cancel);
continue;
}
sLastOp="Saving workorder" + w.WorkorderService.ServiceNumber.ToString();
//Added 3.0.1
w.ServiceCompleted=rdr.GetDateTime(4).Year!=1968;
w.Closed=w.ServiceCompleted;
//-------------
//Optimization related to avoid needless forced setting of
//db workorder service autonumber field when next wo is one more than
//the last wo imported
if ((nLastImportedWorkorderNumber + 1) != CEWONumber)
{
WorkorderService.SetVisibleIDNumber(CEWONumber);
}
w.WorkorderService.ServiceNumber = 0;
w.Save();
nLastImportedWorkorderNumber = CEWONumber;
lImported++;
}
rdr.Close();if(cancel) goto BAIL;
ShowProgress("Imported: "+ lImported.ToString()+" Work orders.","",100, out cancel);
lImported=0;
lTotalRecords=0;
//END Workorders
//************************************************************************
#endregion
#region Mail
//*********************************************************
// Mails
ShowProgress("","Importing mail messages...",0, out cancel);
//changed v 3.0.2 to only count importable messages
cmd.CommandText="SELECT Count(mailroute.recipient) AS TotalRecords FROM " +
"users INNER JOIN (users AS users_1 INNER JOIN " +
"(mailroute INNER JOIN mail ON mailroute.maillink = " +
"mail.id) ON users_1.id = mail.from) ON users.id = " +
"mailroute.recipient;";
rdr=cmd.ExecuteReader();
rdr.Read();
lTotalRecords=rdr.GetInt32(0);
rdr.Close();if(cancel) goto BAIL;
//changed for v 3.0.2
//mail can exist with no existing recipient or sender
//the query was changed to weed them out
cmd.CommandText=
"SELECT mail.from, mailroute.recipient, mail.date, mailroute.remind, " +
" mail.subject, mail.message, mail.id, " +
" mail.popup FROM users AS users_1 INNER JOIN (users " +
"INNER JOIN (mailroute INNER JOIN mail ON mailroute.maillink " +
"= mail.id) ON users.id = mailroute.recipient) " +
"ON users_1.id = mail.from WHERE (((users.id) " +
"Is Not Null) AND ((users_1.id) Is Not Null));";
rdr=cmd.ExecuteReader();
while(rdr.Read() && !cancel)
{
ShowProgress("","",(int)((lImported/lTotalRecords)*100),out cancel );
sLastOp=rdr.GetInt32(6).ToString();
//Guid gFrom;
//Guid gTo;
Memo m = Memo.NewItem();
//Mail from...
if(htUsers.Contains(rdr.GetInt32(0)))
m.FromID=(Guid)htUsers[rdr.GetInt32(0)];
//Mail to...
if(htUsers.Contains(rdr.GetInt32(1)))
m.ToID=(Guid)htUsers[rdr.GetInt32(1)];
sTemp=GetString(rdr,5);
cryp.Process(ref sTemp,false,40);//Mail uses it's own offset of 40
m.Message=sTemp;
sTemp=GetString(rdr,4);
cryp.Process(ref sTemp,false,40);//Mail uses it's own offset of 40
m.Subject=sTemp;
m.zInternal=GetSmartDate(rdr,2);
//viewed = NOT Popup (popup=true meant unread in CE)
m.Viewed=!rdr.GetBoolean(7);
//-------------------------
m.Save();
lImported++;
}
rdr.Close();if(cancel) goto BAIL;
//END Mails
ShowProgress("Imported: "+ lImported.ToString()+" Mail messages.","",100, out cancel);
lImported=0;
lTotalRecords=0;
//************************************************************************
#endregion
#region Import Rentals 'n loaners
//*********************************************************
// Rentals
ShowProgress("","Importing Rentals...",0, out cancel);
cmd.CommandText=
"SELECT Count(rentals.id) AS CountOfid FROM rentals " +
"WHERE ( ((rentals.clientlink) Is Not Null And (rentals.clientlink)<>0) " +
"AND ( ((rentals.partlink) Is " +
"Not Null And (rentals.partlink)<>0) OR ((rentals.unitlink) " +
"Is Not Null And (rentals.unitlink)<>0) ));";
rdr=cmd.ExecuteReader();
rdr.Read();
lTotalRecords=rdr.GetInt32(0);
rdr.Close();if(cancel) goto BAIL;
cmd.CommandText=
"SELECT rentals.clientlink, rentals.id, rentals.partlink, " +
" rentals.unitlink, rentals.dateout, rentals.datedue, " +
" rentals.datereturn, rentals.charges, rentals.notes, " +
" rentals.ref, rentals.returned " +
"FROM rentals WHERE (((rentals.clientlink) " +
"Is Not Null And (rentals.clientlink)<>0) " +
"AND ((rentals.partlink) Is Not Null And (rentals.partlink)<>0)) " +
"OR (((rentals.clientlink) Is Not " +
"Null And (rentals.clientlink)<>0) AND ((rentals.unitlink) " +
"Is Not Null And (rentals.unitlink)<>0)) " +
"ORDER BY rentals.clientlink, rentals.id;";
rdr=cmd.ExecuteReader();
int nCurrentClientID=0;
int nLastClientID=0;
Workorder wRental=null;
while(rdr.Read() && !cancel)
{
ShowProgress("","",(int)((lImported/lTotalRecords)*100),out cancel );
sLastOp=rdr.GetInt32(1).ToString();
nCurrentClientID=rdr.GetInt32(0);
bool bReturned=rdr.GetBoolean(10);
//---------- DATES ---------------------------
SmartDate sdout=GetSmartDate(rdr,4);
SmartDate sddue=GetSmartDate(rdr,5);
SmartDate sdreturned=GetSmartDate(rdr,6);
//-----------------------------------------------
if(nCurrentClientID!=nLastClientID)
{
nLastClientID=nCurrentClientID;
//See if we can close the last workorder
//if it has no outstanding loaners on it
if(wRental!=null)
{
bool bCloseable=true;
foreach(WorkorderItemLoan wil in wRental.WorkorderItems[0].Loans)
{
if(wil.ReturnDate==null || wil.ReturnDate==System.DBNull.Value)
{
bCloseable=false;
break;
}
}
if(bCloseable)
{
wRental.ServiceCompleted=true;
wRental.Closed=true;
wRental.Save();
}
}
//NEW Workorder...
wRental=Workorder.NewItem(WorkorderTypes.Service);
wRental.ClientID=(Guid)htClients[rdr.GetInt32(0)];
wRental.Onsite=false;
wRental.Summary="AyaNovaCE imported rental items consolidated by client";
wRental.WorkorderItems[0].Summary="Consolidated rental items imported";
}
//set this each time so at the last it's set to the last most current
//rental settings since the query is sorted by rental ID
wRental.CustomerReferenceNumber=GetString(rdr,9);
wRental.WorkorderService.ServiceDate=sdout.DBValue;
WorkorderItemLoan l=wRental.WorkorderItems[0].Loans.Add(wRental.WorkorderItems[0]);
l.Charges=rdr.GetDecimal(7);
l.DueDate=sddue.DBValue;
//Is it a unit or a part?
Guid gLoanItemID=Guid.Empty;
if(rdr.GetInt32(3)!=0)//Unit?
{
gLoanItemID=(Guid)htLoanItemsUnits[rdr.GetInt32(3)];
}
else//It's a part, query above guarantees one or the other
{
gLoanItemID=(Guid)htPartsRentals[rdr.GetInt32(2)];
}
l.LoanItemID=gLoanItemID;
l.Notes=GetString(rdr,9) + "" + GetString(rdr,8);
l.OutDate=sdout.DBValue;
if(bReturned)
l.ReturnDate=sdreturned.DBValue;
//-------------------------
wRental.Save();
lImported++;
}
//See if we can close the last workorder
//if it has no outstanding loaners on it
//REPEATED HERE because it would not get the last one
//inside the loop above otherwise
if(wRental!=null)
{
bool bCloseable=true;
foreach(WorkorderItemLoan wil in wRental.WorkorderItems[0].Loans)
{
if(wil.ReturnDate==null || wil.ReturnDate==System.DBNull.Value)
{
bCloseable=false;
break;
}
}
if(bCloseable)
{
wRental.ServiceCompleted=true;
wRental.Closed=true;
wRental.Save();
}
}
rdr.Close();if(cancel) goto BAIL;
//END Rentals
ShowProgress("Imported: "+ lImported.ToString()+" Rentals/Loaner.","",100, out cancel);
lImported=0;
lTotalRecords=0;
//************************************************************************
#endregion
//keep track of pmHeadID/pmworkorder Guid values
//so parts can be imported into them when all the pm's
//have been imported
Hashtable htPM=new Hashtable();
#region Import Preventive maintenance CLIENT BASED
//*********************************************************
// CLIENT PM
ShowProgress("","Importing Preventive maintenance CLIENT BASED...",0, out cancel);
int nNewWorkorderStatus=0;
cmd.CommandText="SELECT defaults.wonewstat FROM defaults;";
rdr=cmd.ExecuteReader();
if(rdr.Read())
nNewWorkorderStatus=rdr.GetInt32(0);
rdr.Close();
cmd.CommandText="SELECT Count(pmhead.id) AS CountOfid FROM pmhead INNER " +
"JOIN clients ON pmhead.link = clients.id;";
rdr=cmd.ExecuteReader();
rdr.Read();
lTotalRecords=rdr.GetInt32(0);
rdr.Close();if(cancel) goto BAIL;
cmd.CommandText="SELECT "+
"pmhead.id, pmhead.active, pmhead.description, " +
"pmhead.notes, pmhead.link, pmhead.woconvert, pmhead.nextsrvdate, " +
"pmhead.repeatevery AS MONTHS, pmhead.rptweeks, " +
"pmhead.rptdays, pmhead.dow, pmhead.tech, " +
"pmhead.wotype, pmhead.woproject, pmhead.woonsite, " +
"pmhead.starttime, pmhead.endtime FROM pmhead " +
"INNER JOIN clients ON pmhead.link = clients.id WHERE " +
"(((pmhead.isclient)=True) AND ((pmhead.autowo)=True));";
rdr=cmd.ExecuteReader();
while(rdr.Read() && !cancel)
{
ShowProgress("","",(int)((lImported/lTotalRecords)*100),out cancel );
sLastOp=rdr.GetInt32(0).ToString();
Workorder w = Workorder.NewItem(WorkorderTypes.PreventiveMaintenance);
//------------------------
w.ClientID=(Guid)htClients[rdr.GetInt32(4)];
htPM.Add(rdr.GetInt32(0),w.ID);
w.Onsite=rdr.GetBoolean(14);
//Project
if(htProjects.Contains(rdr.GetInt32(13)))
w.ProjectID=(Guid)htProjects[rdr.GetInt32(13)];
//w.RegionID=new Guid("8236E8D1-CAB1-4797-9C34-93861954AE6A");//Default region
w.Summary=GetString(rdr,2);
//Category (type)
if(htCategories.Contains(rdr.GetInt32(12)))
w.WorkorderCategoryID=(Guid)htCategories[rdr.GetInt32(12)];
WorkorderItem wi=w.WorkorderItems[0];
wi.Summary=w.Summary;
wi.TechNotes=GetString(rdr,3);
wi.TypeID=Guid.Empty;
w.WorkorderPreventiveMaintenance.Active=rdr.GetBoolean(1);
WorkorderItemScheduledUser wisu=wi.ScheduledUsers.Add(wi);
if(htUsers.Contains(rdr.GetInt32(11)))
wisu.UserID=(Guid)htUsers[rdr.GetInt32(11)];
//Get the start date from next service date
//get the start time from startime and end time from endtime
//munge together, add a little salt and wala!
//START
System.DateTime nsd=GetSmartDate(rdr,6).Date;
System.DateTime nst=GetSmartDate(rdr,15).Date;
System.DateTime nsdstart=new DateTime(nsd.Year,nsd.Month,nsd.Day,nst.Hour,nst.Minute,0);
wisu.StartDate=new SmartDate(nsdstart).DBValue;
//STOP
System.DateTime nststop=GetSmartDate(rdr,16).Date;
System.DateTime nsdstop=new DateTime(nsd.Year,nsd.Month,nsd.Day,nststop.Hour,nststop.Minute+1,0);
wisu.StopDate=new SmartDate(nsdstop).DBValue;
int nID=rdr.GetInt32(10);
switch(nID)
{
case 0://ANY DAY
w.WorkorderPreventiveMaintenance.DayOfTheWeek=AyaDayOfWeek.AnyDayOfWeek;
break;
case 1://MONDAY
w.WorkorderPreventiveMaintenance.DayOfTheWeek=AyaDayOfWeek.Monday;
break;
case 2://TUESDAY
w.WorkorderPreventiveMaintenance.DayOfTheWeek=AyaDayOfWeek.Tuesday;
break;
case 31://WEDNESDAY
w.WorkorderPreventiveMaintenance.DayOfTheWeek=AyaDayOfWeek.Wednesday;
break;
case 4://THURSDAY
w.WorkorderPreventiveMaintenance.DayOfTheWeek=AyaDayOfWeek.Thursday;
break;
case 5://FRIDAY
w.WorkorderPreventiveMaintenance.DayOfTheWeek=AyaDayOfWeek.Friday;
break;
case 6://SATURDAY
w.WorkorderPreventiveMaintenance.DayOfTheWeek=AyaDayOfWeek.Saturday;
break;
case 7://SUNDAY
w.WorkorderPreventiveMaintenance.DayOfTheWeek=AyaDayOfWeek.Sunday;
break;
}
//calculate time span
//if there are any days then it's all in days
//if there are no days but weeks then it's all in days
//if there are no week or days then it's all in months
//In the new AyaNova only hours days months or years are valid timespans
if(rdr.GetInt32(9)!=0)//Days
{
//Set to days plus months *29.5 + weeks * 7 converted to int32
w.WorkorderPreventiveMaintenance.GenerateSpan=System.Convert.ToInt32(rdr.GetInt32(9)+(rdr.GetInt32(7)*29.5)+(rdr.GetInt32(8)*7));//whole days only so convert to int
w.WorkorderPreventiveMaintenance.GenerateSpanUnit=AyaUnitsOfTime.Days;
}
else if(rdr.GetInt32(8)!=0)//Weeks
{
//Convert the weeks and months to days
//An average month is 29.5 days long, but we can only handle ints
//so multiply month by 29.5 and convert to int32
w.WorkorderPreventiveMaintenance.GenerateSpan=System.Convert.ToInt32((rdr.GetInt32(7)*29.5)+(rdr.GetInt32(8)*7));
w.WorkorderPreventiveMaintenance.GenerateSpanUnit=AyaUnitsOfTime.Days;
}
else if(rdr.GetInt32(7)!=0)//Months
{
if(rdr.GetInt32(7)==12)
{
w.WorkorderPreventiveMaintenance.GenerateSpanUnit=AyaUnitsOfTime.Years;
w.WorkorderPreventiveMaintenance.GenerateSpan=1;
}
else
{
w.WorkorderPreventiveMaintenance.GenerateSpanUnit=AyaUnitsOfTime.Months;
w.WorkorderPreventiveMaintenance.GenerateSpan=rdr.GetInt32(7);
}
}
w.WorkorderPreventiveMaintenance.ThresholdSpan=System.Convert.ToInt32(rdr.GetInt32(5));
w.WorkorderPreventiveMaintenance.ThresholdSpanUnit=AyaUnitsOfTime.Days;
if(htWOStatus.Contains(nNewWorkorderStatus))
w.WorkorderPreventiveMaintenance.WorkorderStatusID=(Guid)htWOStatus[nNewWorkorderStatus];
w.WorkorderPreventiveMaintenance.NextServiceDate=GetSmartDate(rdr,6).DBValue;
//-------------------------
w.Save();
lImported++;
}
rdr.Close();if(cancel) goto BAIL;
//END Tasks
ShowProgress("Imported: "+ lImported.ToString()+" Preventive Maintenance records for CLIENT (TIME BASED) records.","",100, out cancel);
lImported=0;
lTotalRecords=0;
//************************************************************************
#endregion
#region Import Preventive maintenance UNITS (TIME / AGE BASED)
//*********************************************************
// UNIT TIME/AGE PM'S
//PMHEAD.TYPE<>1
ShowProgress("","Importing Preventive maintenance UNITS (TIME / AGE BASED)...",0, out cancel);
cmd.CommandText="SELECT Count(pmhead.id) AS CountOfid FROM pmhead INNER " +
"JOIN units ON pmhead.link = units.id WHERE (((pmhead.isclient)=False) AND ((pmhead.ismodel)=False) " +
"AND ((pmhead.autowo)=True) " +
"AND ((pmhead.type)<>1));";
rdr=cmd.ExecuteReader();
rdr.Read();
lTotalRecords=rdr.GetInt32(0);
rdr.Close();if(cancel) goto BAIL;
cmd.CommandText="SELECT "+
"pmhead.id, pmhead.active, pmhead.description, " +
"pmhead.notes, pmhead.link, pmhead.woconvert, pmhead.nextsrvdate, " +
"pmhead.repeatevery AS MONTHS, pmhead.rptweeks, " +
"pmhead.rptdays, pmhead.dow, pmhead.tech, " +
"pmhead.wotype, pmhead.woproject, pmhead.woonsite, " +
"pmhead.starttime, pmhead.endtime, units.client, pmhead.agemonths, pmhead.ageyears FROM pmhead " +
"INNER JOIN units ON pmhead.link = units.id WHERE " +
"(((pmhead.isclient)=False) AND ((pmhead.autowo)=True) AND ((pmhead.type)<>1) AND ((pmhead.ismodel)=False));";
rdr=cmd.ExecuteReader();
while(rdr.Read() && !cancel)
{
ShowProgress("","",(int)((lImported/lTotalRecords)*100),out cancel );
sLastOp=rdr.GetInt32(0).ToString();
Workorder w = Workorder.NewItem(WorkorderTypes.PreventiveMaintenance);
//Keep track if this is an age based pm
int nAgeMonths=rdr.GetInt32(18);
int nAgeYears=rdr.GetInt32(19);
bool bAged=false;
if( nAgeMonths!=0 || nAgeYears!=0)
bAged=true;
//------------------------
//If it's a rental unit that's ok because in
//units block a client would have been added with id 0 for self owned units
//rental units will return client id 0 which will match the special
//client in the hashtable htClients that was added during unit import
w.ClientID=(Guid)htClients[rdr.GetInt32(17)];
htPM.Add(rdr.GetInt32(0),w.ID);
w.Onsite=rdr.GetBoolean(14);
//Project
if(htProjects.Contains(rdr.GetInt32(13)))
w.ProjectID=(Guid)htProjects[rdr.GetInt32(13)];
//w.RegionID=new Guid("8236E8D1-CAB1-4797-9C34-93861954AE6A");//Default region
w.Summary=GetString(rdr,2);
if(bAged)
{
w.Summary="*Imported inactive (was unit age pm)* " + w.Summary;
}
//Category (type)
if(htCategories.Contains(rdr.GetInt32(12)))
w.WorkorderCategoryID=(Guid)htCategories[rdr.GetInt32(12)];
WorkorderItem wi=w.WorkorderItems[0];
wi.Summary=w.Summary;
wi.TechNotes=GetString(rdr,3);
wi.TypeID=Guid.Empty;
w.WorkorderPreventiveMaintenance.Active=rdr.GetBoolean(1);
//however..if it's age based then it's inactive by default
if(bAged)
w.WorkorderPreventiveMaintenance.Active=false;
WorkorderItemScheduledUser wisu=wi.ScheduledUsers.Add(wi);
if(htUsers.Contains(rdr.GetInt32(11)))
wisu.UserID=(Guid)htUsers[rdr.GetInt32(11)];
//Get the start date from next service date
//get the start time from startime and end time from endtime
//munge together, add a little salt and wala!
//START
System.DateTime nsd=GetSmartDate(rdr,6).Date;
System.DateTime nst=GetSmartDate(rdr,15).Date;
System.DateTime nsdstart=new DateTime(nsd.Year,nsd.Month,nsd.Day,nst.Hour,nst.Minute,0);
wisu.StartDate=new SmartDate(nsdstart).DBValue;
//STOP
System.DateTime nststop=GetSmartDate(rdr,16).Date;
System.DateTime nsdstop=new DateTime(nsd.Year,nsd.Month,nsd.Day,nststop.Hour,nststop.Minute+1,0);
wisu.StopDate=new SmartDate(nsdstop).DBValue;
int nID=rdr.GetInt32(10);
switch(nID)
{
case 0://ANY DAY
w.WorkorderPreventiveMaintenance.DayOfTheWeek=AyaDayOfWeek.AnyDayOfWeek;
break;
case 1://MONDAY
w.WorkorderPreventiveMaintenance.DayOfTheWeek=AyaDayOfWeek.Monday;
break;
case 2://TUESDAY
w.WorkorderPreventiveMaintenance.DayOfTheWeek=AyaDayOfWeek.Tuesday;
break;
case 31://WEDNESDAY
w.WorkorderPreventiveMaintenance.DayOfTheWeek=AyaDayOfWeek.Wednesday;
break;
case 4://THURSDAY
w.WorkorderPreventiveMaintenance.DayOfTheWeek=AyaDayOfWeek.Thursday;
break;
case 5://FRIDAY
w.WorkorderPreventiveMaintenance.DayOfTheWeek=AyaDayOfWeek.Friday;
break;
case 6://SATURDAY
w.WorkorderPreventiveMaintenance.DayOfTheWeek=AyaDayOfWeek.Saturday;
break;
case 7://SUNDAY
w.WorkorderPreventiveMaintenance.DayOfTheWeek=AyaDayOfWeek.Sunday;
break;
}
//**** ASSUMPTION HERE: in an age based pm there may or may not be any values enterd
//for the repeating factor, so the code below *should* end up in a default value
//set in pm anyway
//calculate time span
//if there are any days then it's all in days
//if there are no days but weeks then it's all in days
//if there are no week or days then it's all in months
//In the new AyaNova only hours days months or years are valid timespans
if(rdr.GetInt32(9)!=0)//Days
{
//Set to days plus months *29.5 + weeks * 7 converted to int32
w.WorkorderPreventiveMaintenance.GenerateSpan=System.Convert.ToInt32(rdr.GetInt32(9)+(rdr.GetInt32(7)*29.5)+(rdr.GetInt32(8)*7));//whole days only so convert to int
w.WorkorderPreventiveMaintenance.GenerateSpanUnit=AyaUnitsOfTime.Days;
}
else if(rdr.GetInt32(8)!=0)//Weeks
{
//Convert the weeks and months to days
//An average month is 29.5 days long, but we can only handle ints
//so multiply month by 29.5 and convert to int32
w.WorkorderPreventiveMaintenance.GenerateSpan=System.Convert.ToInt32((rdr.GetInt32(7)*29.5)+(rdr.GetInt32(8)*7));
w.WorkorderPreventiveMaintenance.GenerateSpanUnit=AyaUnitsOfTime.Days;
}
else if(rdr.GetInt32(7)!=0)//Months
{
if(rdr.GetInt32(7)==12)
{
w.WorkorderPreventiveMaintenance.GenerateSpanUnit=AyaUnitsOfTime.Years;
w.WorkorderPreventiveMaintenance.GenerateSpan=1;
}
else
{
w.WorkorderPreventiveMaintenance.GenerateSpanUnit=AyaUnitsOfTime.Months;
w.WorkorderPreventiveMaintenance.GenerateSpan=rdr.GetInt32(7);
}
}
else
{
//apparently no time frame was set, it's likely age based with no repeat factor so
//set it to inactive to be on the safe side
w.WorkorderPreventiveMaintenance.Active=false;
}
w.WorkorderPreventiveMaintenance.ThresholdSpan=System.Convert.ToInt32(rdr.GetInt32(5));
w.WorkorderPreventiveMaintenance.ThresholdSpanUnit=AyaUnitsOfTime.Days;
if(htWOStatus.Contains(nNewWorkorderStatus))
w.WorkorderPreventiveMaintenance.WorkorderStatusID=(Guid)htWOStatus[nNewWorkorderStatus];
w.WorkorderPreventiveMaintenance.NextServiceDate=GetSmartDate(rdr,6).DBValue;
//UNIT
if(htUnits.Contains(rdr.GetInt32(4)))
wi.UnitID=(Guid)htUnits[rdr.GetInt32(4)];
//-------------------------
w.Save();
lImported++;
}
rdr.Close();if(cancel) goto BAIL;
//END Tasks
ShowProgress("Imported: "+ lImported.ToString()+" Preventive Maintenance records for UNIT (TIME / AGE BASED) records.","",100, out cancel);
lImported=0;
lTotalRecords=0;
//************************************************************************
#endregion
#region Import Preventive maintenance UNITS (METER BASED)
//PMHEAD.TYPE=1
//*********************************************************
ShowProgress("","Importing Preventive maintenance UNITS (METER BASED)...",0, out cancel);
cmd.CommandText="SELECT Count(pmhead.id) AS CountOfid FROM pmhead INNER " +
"JOIN units ON pmhead.link = units.id WHERE (((pmhead.isclient)=False) AND ((pmhead.ismodel)=False) " +
"AND ((pmhead.autowo)=True) " +
"AND ((pmhead.type)=1));";
rdr=cmd.ExecuteReader();
rdr.Read();
lTotalRecords=rdr.GetInt32(0);
rdr.Close();if(cancel) goto BAIL;
cmd.CommandText="SELECT "+
"pmhead.id, pmhead.active, pmhead.description, " +
"pmhead.notes, pmhead.link, pmhead.woconvert, pmhead.nextsrvmeter, " +
"pmhead.repeatevery AS METERCOUNTS, pmhead.rptweeks, " +
"pmhead.rptdays, pmhead.dow, pmhead.tech, " +
"pmhead.wotype, pmhead.woproject, pmhead.woonsite, " +
"pmhead.starttime, pmhead.endtime, units.client FROM pmhead " +
"INNER JOIN units ON pmhead.link = units.id WHERE " +
"(((pmhead.isclient)=False) AND ((pmhead.autowo)=True) AND ((pmhead.type)=1) AND ((pmhead.ismodel)=False));";
rdr=cmd.ExecuteReader();
while(rdr.Read() && !cancel)
{
ShowProgress("","",(int)((lImported/lTotalRecords)*100),out cancel );
sLastOp=rdr.GetInt32(0).ToString();
Workorder w = Workorder.NewItem(WorkorderTypes.PreventiveMaintenance);
//------------------------
//If it's a rental unit that's ok because in
//units block a client would have been added with id 0 for self owned units
//rental units will return client id 0 which will match the special
//client in the hashtable htClients that was added during unit import
w.ClientID=(Guid)htClients[rdr.GetInt32(17)];
htPM.Add(rdr.GetInt32(0),w.ID);
w.Onsite=rdr.GetBoolean(14);
//Project
if(htProjects.Contains(rdr.GetInt32(13)))
w.ProjectID=(Guid)htProjects[rdr.GetInt32(13)];
//w.RegionID=new Guid("8236E8D1-CAB1-4797-9C34-93861954AE6A");//Default region
w.Summary="*Imported inactive (was unit meter pm)* " + GetString(rdr,2);
//Category (type)
if(htCategories.Contains(rdr.GetInt32(12)))
w.WorkorderCategoryID=(Guid)htCategories[rdr.GetInt32(12)];
WorkorderItem wi=w.WorkorderItems[0];
wi.Summary=w.Summary;
wi.TechNotes=GetString(rdr,3);
wi.TypeID=Guid.Empty;
//meter based are always inactive
w.WorkorderPreventiveMaintenance.Active=false;
WorkorderItemScheduledUser wisu=wi.ScheduledUsers.Add(wi);
if(htUsers.Contains(rdr.GetInt32(11)))
wisu.UserID=(Guid)htUsers[rdr.GetInt32(11)];
//Get the start date from next service date
//get the start time from startime and end time from endtime
//munge together, add a little salt and wala!
//START
// System.DateTime nsd=DateTime.Today;
// System.DateTime nst=GetSmartDate(rdr,15).Date;
// System.DateTime nsdstart=new DateTime(nsd.Year,nsd.Month,nsd.Day,nst.Hour,nst.Minute,0);
wisu.StartDate=new SmartDate(DateTime.Now).DBValue;
//STOP
//System.DateTime nststop=DateTime.Today;
//System.DateTime nsdstop=new DateTime(nsd.Year,nsd.Month,nsd.Day,nststop.Hour,nststop.Minute+1,0);
wisu.StopDate=new SmartDate(DateTime.Now.AddHours(1)).DBValue;
int nID=rdr.GetInt32(10);
switch(nID)
{
case 0://ANY DAY
w.WorkorderPreventiveMaintenance.DayOfTheWeek=AyaDayOfWeek.AnyDayOfWeek;
break;
case 1://MONDAY
w.WorkorderPreventiveMaintenance.DayOfTheWeek=AyaDayOfWeek.Monday;
break;
case 2://TUESDAY
w.WorkorderPreventiveMaintenance.DayOfTheWeek=AyaDayOfWeek.Tuesday;
break;
case 31://WEDNESDAY
w.WorkorderPreventiveMaintenance.DayOfTheWeek=AyaDayOfWeek.Wednesday;
break;
case 4://THURSDAY
w.WorkorderPreventiveMaintenance.DayOfTheWeek=AyaDayOfWeek.Thursday;
break;
case 5://FRIDAY
w.WorkorderPreventiveMaintenance.DayOfTheWeek=AyaDayOfWeek.Friday;
break;
case 6://SATURDAY
w.WorkorderPreventiveMaintenance.DayOfTheWeek=AyaDayOfWeek.Saturday;
break;
case 7://SUNDAY
w.WorkorderPreventiveMaintenance.DayOfTheWeek=AyaDayOfWeek.Sunday;
break;
}
//**** ASSUMPTION HERE: in an age based pm there may or may not be any values enterd
//for the repeating factor, so the code below *should* end up in a default value
//set in pm anyway
//calculate time span
//if there are any days then it's all in days
//if there are no days but weeks then it's all in days
//if there are no week or days then it's all in months
//In the new AyaNova only hours days months or years are valid timespans
//
// if(rdr.GetInt32(9)!=0)//Days
// {
// //Set to days plus months *29.5 + weeks * 7 converted to int32
// w.WorkorderPreventiveMaintenance.GenerateSpan=System.Convert.ToInt32(rdr.GetInt32(9)+(rdr.GetInt32(7)*29.5)+(rdr.GetInt32(8)*7));//whole days only so convert to int
// w.WorkorderPreventiveMaintenance.GenerateSpanUnit=AyaUnitsOfTime.Days;
// }
// else if(rdr.GetInt32(8)!=0)//Weeks
// {
// //Convert the weeks and months to days
// //An average month is 29.5 days long, but we can only handle ints
// //so multiply month by 29.5 and convert to int32
// w.WorkorderPreventiveMaintenance.GenerateSpan=System.Convert.ToInt32((rdr.GetInt32(7)*29.5)+(rdr.GetInt32(8)*7));
// w.WorkorderPreventiveMaintenance.GenerateSpanUnit=AyaUnitsOfTime.Days;
// }
// else if(rdr.GetInt32(7)!=0)//Months
// {
// if(rdr.GetInt32(7)==12)
// {
// w.WorkorderPreventiveMaintenance.GenerateSpanUnit=AyaUnitsOfTime.Years;
// w.WorkorderPreventiveMaintenance.GenerateSpan=1;
// }
// else
// {
// w.WorkorderPreventiveMaintenance.GenerateSpanUnit=AyaUnitsOfTime.Months;
// w.WorkorderPreventiveMaintenance.GenerateSpan=rdr.GetInt32(7);
// }
//
// }
// else
// {
// //apparently no time frame was set, it's likely age based with no repeat factor so
// //set it to inactive to be on the safe side
// w.WorkorderPreventiveMaintenance.Active=false;
// }
//
//
//
// w.WorkorderPreventiveMaintenance.ThresholdSpan=System.Convert.ToInt32(rdr.GetInt32(5));
// w.WorkorderPreventiveMaintenance.ThresholdSpanUnit=AyaUnitsOfTime.Days;
//
//
// if(htWOStatus.Contains(nNewWorkorderStatus))
// w.WorkorderPreventiveMaintenance.WorkorderStatusID=(Guid)htWOStatus[nNewWorkorderStatus];
//
// w.WorkorderPreventiveMaintenance.NextServiceDate=GetSmartDate(rdr,6).DBValue;
//
//UNIT
if(htUnits.Contains(rdr.GetInt32(4)))
wi.UnitID=(Guid)htUnits[rdr.GetInt32(4)];
//-------------------------
//w.WorkorderPreventiveMaintenance.NextServiceDate=System.DateTime.Now;
w.Save();
lImported++;
}
rdr.Close();if(cancel) goto BAIL;
//END Tasks
ShowProgress("Imported: "+ lImported.ToString()+" Preventive Maintenance records for UNIT (METER BASED) records.","",100, out cancel);
lImported=0;
lTotalRecords=0;
//************************************************************************
#endregion
#region PM Parts
//*********************************************************
// Mails
ShowProgress("","Importing PM part selections...",0, out cancel);
cmd.CommandText="SELECT Count(pmparts.pmlink) AS CountOfpmlink FROM pmparts;";
rdr=cmd.ExecuteReader();
rdr.Read();
lTotalRecords=rdr.GetInt32(0);
rdr.Close();if(cancel) goto BAIL;
cmd.CommandText="SELECT pmparts.pmlink, pmparts.partnum, pmparts.quantity FROM pmparts ORDER BY pmparts.pmlink;";
rdr=cmd.ExecuteReader();
while(rdr.Read() && !cancel)
{
ShowProgress("","",(int)((lImported/lTotalRecords)*100),out cancel );
sLastOp=rdr.GetInt32(0).ToString();
//If there is a workorder and part matching that was already
//imported then add the parts to the workorder
if(htPM.Contains(rdr.GetInt32(0)) && htParts.Contains(rdr.GetInt32(1)))
{
Workorder w=Workorder.GetItem((Guid)htPM[rdr.GetInt32(0)]);
WorkorderItem wi=w.WorkorderItems[0];
WorkorderItemPart p=wi.Parts.Add(wi);
p.PartID=(Guid)htParts[rdr.GetInt32(1)];
p.Quantity=(decimal)rdr.GetFloat(2);
w.Save();
}
lImported++;
}
rdr.Close();if(cancel) goto BAIL;
//END Mails
ShowProgress("Imported: "+ lImported.ToString()+" PM part selections.","",100, out cancel);
lImported=0;
lTotalRecords=0;
//************************************************************************
#endregion
TimeSpan span = System.DateTime.Now.Subtract(dtStart);
ShowProgress("","Import complete ("+ span.TotalMinutes.ToString("F") + " minutes)",100, out cancel);
ShowProgress("\r\n-IMPORT COMPLETED\r\n************************************\r\n","",100, out cancel);
return;
BAIL:
ShowProgress("\r\n-IMPORT CANCELLED!!\r\n****************************************************\r\n","",-1, out cancel);
}
catch(Exception ex)
{
if(ex.InnerException==null)
ShowProgress("\r\n************************\r\n-IMPORT FAILED:\r\nLastOp: " + sLastOp + "\r\n" + ex.Message+"\r\n"+ex.StackTrace,"",-1, out cancel);
else
ShowProgress(
"\r\n************************\r\n" +
"-IMPORT FAILED:\r\n" +
"LastOp: " + sLastOp + "\r\n" +
ex.Message+"\r\n"+
ex.StackTrace + "\r\n\r\n" +
ex.InnerException.Message +"\r\n" +
ex.InnerException.StackTrace,
"",-1, out cancel);
}
finally
{
conn.Close();
}
//*************************
}
/// <summary>
/// Set AyaNova right
/// </summary>
/// <param name="nRight">Old right</param>
/// <returns></returns>
public void SetRight(int nRight, string sRightName, SecurityGroup s)
{
//Old rights were:
//0=not allowed , 1=full, 2=read only
//New rights are:
//NoAccess = 1, ReadOnly = 2, ReadWrite = 3, ReadWriteDelete = 4
UserRight ur=s.Rights[sRightName];
switch(nRight)
{
case 0:
ur.SecurityLevel= SecurityLevelTypes.NoAccess;
break;
case 1:
ur.SecurityLevel= SecurityLevelTypes.ReadWriteDelete;
break;
case 2:
ur.SecurityLevel= SecurityLevelTypes.ReadOnly;
break;
default:
ur.SecurityLevel= SecurityLevelTypes.NoAccess;
break;
}
}
delegate void ShowProgressDelegate(string sStatusString, string sCurrentString, int nProgress, out bool cancel);
/// <summary>
/// Feedback to user through UI thread
/// </summary>
/// <param name="sStatusString"></param>
/// <param name="sCurrentString"></param>
/// <param name="nProgress"></param>
void ShowProgress(string sStatusString, string sCurrentString, int nProgress, out bool cancel)
{
// Make sure we're on the right thread
if( edStatus.InvokeRequired == false )
{
if(sStatusString!="")
{
sStatusString=sStatusString+"\r\n";
edStatus.AppendText(sStatusString);
}
if(sStatusString.LastIndexOf("-IMPORT ")!=-1)
{
//Import has completed,disable import cancel button
btnStopSearch.Visible=false;
}
if(nProgress!=-1)
pBar.Value=nProgress;
if(sCurrentString!="")
lblCurrentOp.Text=sCurrentString;
// Check for Cancel
cancel = (_state == OpState.Canceled);
// Check for completion
if( cancel )
{
_state = OpState.Pending;
this.btnStopSearch.Visible=false;
}
}
else
{
// Show progress asynchronously
// ShowProgressDelegate showProgress =
// new ShowProgressDelegate(ShowProgress);
// BeginInvoke(showProgress,
// new object[] { sStatusString, sCurrentString, nProgress});
ShowProgressDelegate showProgress = new ShowProgressDelegate(ShowProgress);
object inoutCancel = false; // Avoid boxing and losing our return value
// Show progress synchronously (so we can check for cancel)
Invoke(showProgress, new object[] { sStatusString, sCurrentString, nProgress, inoutCancel});
cancel = (bool)inoutCancel;
}
}
// private void Status(string sStringToAdd)
// {
// sStringToAdd=sStringToAdd+"\r\n";
// edStatus.AppendText(sStringToAdd);
//
// )
//
//}
/// <summary>
/// provides a way to get a string while handling null values
/// </summary>
/// <param name="rdr"></param>
/// <param name="nColumn"></param>
/// <returns></returns>
private string GetString(OleDbDataReader rdr,int nColumn)
{
if (rdr.IsDBNull(nColumn))
return "";
else//Important, some noobs have imported lot's of data with spaces in field names or from
//sources with fixed length fields where there is a lot of padding, the Trim will
//ensure that they don't get imported unnecessarily
return rdr.GetString(nColumn).Trim();
}
/// <summary>
/// provides a way to get a string while handling null values
/// with max chars returned
/// </summary>
/// <param name="rdr"></param>
/// <param name="nColumn"></param>
/// <returns></returns>
private string GetString(OleDbDataReader rdr,int nColumn,int maxChars)
{
if(rdr.IsDBNull(nColumn))
return "";
else
{
string s= rdr.GetString(nColumn).Trim();//while working on case 1209 noticed trim missing here as in above
if(s.Length>maxChars) return s.Substring(0,maxChars);
return s;
}
}
/// <summary>
/// provides a way to get a Smart Date while handling null values
/// </summary>
/// <param name="rdr"></param>
/// <param name="nColumn"></param>
/// <returns></returns>
private CSLA.SmartDate GetSmartDate(OleDbDataReader rdr,int nColumn)
{
if(rdr.IsDBNull(nColumn))
return new CSLA.SmartDate();
else
{
CSLA.SmartDate sd= new CSLA.SmartDate(rdr.GetDateTime(nColumn));
//date sanity check
//If the date is out of whack make a set date to use instead
//this ensures sql server won't bomb with:
//SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM.
if(sd.Date.Year<1900 || sd.Date.Year>3000)
{
return new CSLA.SmartDate(new System.DateTime(1988,8,8,8,8,8));
}
else
return sd;
}
}
/// <summary>
/// provides a way to get a decimal (currency) while handling null values
/// </summary>
/// <param name="rdr"></param>
/// <param name="nColumn"></param>
/// <returns></returns>
private decimal GetDecimal(OleDbDataReader rdr,int nColumn)
{
if(rdr.IsDBNull(nColumn))
return 0;
else
return rdr.GetDecimal(nColumn);
}
/// <summary>
/// provides a way to get an INT while handling null values
/// </summary>
/// <param name="rdr"></param>
/// <param name="nColumn"></param>
/// <returns></returns>
private int SafeGetInt32(OleDbDataReader rdr,int nColumn)
{
if(rdr.IsDBNull(nColumn))
return 0;
else
return rdr.GetInt32(nColumn);
}
#endregion
#region Authentication
private bool DoLogin()
{
Login dlg = new Login();
dlg.ShowDialog(this);
if(dlg.LoggingIn)
{
if(DoNewLogin(dlg.Username,dlg.Password))
{
if(DoOldLogin(dlg.OldUsername,dlg.OldPassword))
{
return true;
}
else
{
MessageBox.Show("The old AyaNova CE username or password are not valid","",MessageBoxButtons.OK,MessageBoxIcon.Exclamation);
}
}
else
{
MessageBox.Show("The new AyaNova username or password are not valid","",MessageBoxButtons.OK,MessageBoxIcon.Exclamation);
}
}
DoLogout();
return false;
}
/// <summary>
/// Login to old AyaNova CE database
/// </summary>
/// <param name="User"></param>
/// <param name="Password"></param>
/// <returns></returns>
private bool DoOldLogin(string User, string Password)
{
bool bLoginResult=false;
string userhashed="";
string passwordhashed="";
//Get hash of user
userhashed=GZHash(User).ToString();
if(Password=="")
Password="@" + userhashed + "gz";
else
passwordhashed=GZHash(Password).ToString();
System.Data.OleDb.OleDbConnection conn = new
System.Data.OleDb.OleDbConnection();
conn.ConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;" +
@"Data source= " +strOldDBPath;
try
{
//****************************
string q = string.Format("SELECT users.c FROM users WHERE (((users.login)='{0}') AND ((users.pass)='{1}'));",
userhashed,passwordhashed);
conn.Open();
OleDbCommand cmd = new OleDbCommand(q,conn);
OleDbDataReader rdr;
rdr = cmd.ExecuteReader();
if(rdr.Read())
{
if(rdr.GetInt32(0)!=1)
{
MessageBox.Show("Only users who are memebers of the <MANAGERS> security group can import from AyaNova CE.\r\nYou must log on with the manager or equivalent account.");
bLoginResult=false;
}
else
bLoginResult=true;
}
rdr.Close();
//****************************
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return false;
}
finally
{
conn.Close();
}
//************************************
return bLoginResult;
}
/// <summary>
/// Calculate AyaNova CE style hash
///
/// </summary>
/// <param name="src"></param>
/// <returns></returns>
private uint GZHash(string src)
{
// Convert the string into a unicode byte[].
Encoding unicode = Encoding.Unicode;
byte[] unicodeBytes = unicode.GetBytes(src);
//Calculate the hash
uint hash=5381;
byte c;
//AyaNova CE knew nothing about Unicode so throw out every second byte in the array
//gives the equivalent of the original char* pointer based function
for(int x=0;x<unicodeBytes.Length;x+=2)
{
c=unicodeBytes[x];
hash=((hash<<5)+hash)+c;
}
return hash;
}
/// <summary>
/// Login to new AyaNova database
/// </summary>
/// <param name="User"></param>
/// <param name="Password"></param>
/// <returns></returns>
private bool DoNewLogin(string Login, string Password)
{
if(Thread.CurrentPrincipal.Identity==null || !Thread.CurrentPrincipal.Identity.IsAuthenticated)
AyaBizUtils.Login(Login, Password);
if(Thread.CurrentPrincipal.Identity.IsAuthenticated)
{
//To prevent potential freeze during import when
//global is fetched during a save of an object being imported
//to break it's text global must be pre-initialized this way
GZTW.AyaNova.BLL.AyaBizUtils.mGlobalSettings=Global.GetItem();
if(!User.IsAdmin)
{
MessageBox.Show("Only the new AyaNova Admin account can import from AyaNova CE.\r\nYou must log on with the admin account to the new AyaNova.");
DoLogout();
return false;
}
//Proceed with import
return true;
}
else
{
DoLogout();
return false;
}
}
private void DoLogout()
{
Thread.CurrentPrincipal = null;
}
#endregion
}//End of class
#region Helper classes
public class AyaNovaDBItem
{
private string path;
private string regto;
private System.DateTime databaseLastModified;
private System.DateTime workorderLastCreated;
private long highestWorkorderNumber;
//if bControlItem then path contains
//the command to run, not the path of the db
private bool bControlItem;
public AyaNovaDBItem(string strpath,string strregto,
System.DateTime dtDatabaseLastModified, System.DateTime dtWorkorderLastCreated,
long lHighestWorkorderNumber)
{
this.path=strpath;
this.regto=strregto;
this.databaseLastModified=dtDatabaseLastModified;
this.workorderLastCreated=dtWorkorderLastCreated;
this.highestWorkorderNumber=lHighestWorkorderNumber;
this.bControlItem=false;
}
public AyaNovaDBItem(string strpath)
{
this.path=strpath;
this.bControlItem=true;
}
public string Path
{
get
{
return path;
}
}
public string RegTo
{
get
{
return regto;
}
}
public string DatabaseLastModified
{
get
{
return databaseLastModified.ToString();
}
}
public string WorkorderLastCreated
{
get
{
return workorderLastCreated.ToString();
}
}
public string HighestWorkorderNumber
{
get
{
return highestWorkorderNumber.ToString();
}
}
public bool ControlItem
{
get
{
return bControlItem;
}
}
}
#endregion
}