using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using VEPROMS.CSLA.Library;
using Volian.Base.Library;
using System.Xml;
using System.IO;
using Ionic.Zip;
using System.Text.RegularExpressions;

namespace VEPROMS
{
	public partial class dlgExportImport : Form
{
	#region Log4Net
	private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
	#endregion
	frmVEPROMS _MyFrmVEPROMS = null;// Save frmVEPROMS for Import to shutoff SessionPing
	public frmVEPROMS MyFrmVEPROMS
	{
		get { return _MyFrmVEPROMS; }
		set { _MyFrmVEPROMS = value; }
	}
	private bool _ConvertROsToTextDuringImport = false;
		private bool _ConvertROsAndTransitionsToText = false; // set to true when Approval creates an Export file

		// B2016-225 notify user when Transitions and/or ROs are converted to text
		private bool _DidConvertTransitionsToText = false;
		private bool _DidConvertROsToText = false;

		private ItemInfo _ExternalTransitionItem = null;
		public ItemInfo ExternalTransitionItem
		{
			get { return _ExternalTransitionItem; }
			set { _ExternalTransitionItem = value; }
		}
    private Dictionary<int, int> floatFoldout;
    private Dictionary<int, string> oldFormat;
    private Dictionary<string, int> newFormat;
    private int oldRODbID;
    private int newRODbID;
    private FolderInfo _MyNewFolder;
    public FolderInfo MyNewFolder
    {
      get { return _MyNewFolder; }
    }
    private ProcedureInfo _MyNewProcedure;
    public ProcedureInfo MyNewProcedure
    {
      get { return _MyNewProcedure; }
			set { _MyNewProcedure = value; }
    }
    private string PEIPath;
		private string _MyMode;
		private FolderInfo MyFolder = null;
    private DocVersionInfo MyDocVersion = null;
    private ProcedureInfo MyProcedure = null;
    private XmlAttribute AddAttribute(XmlDocument xd, string name, string value)
		{
			XmlAttribute xa = xd.CreateAttribute(name);
			xa.InnerText = value;
			return xa;
		}
		public dlgExportImport(string mode, FolderInfo folderInfo, frmVEPROMS myFrmVEPROMS)
		{
			MyFrmVEPROMS = myFrmVEPROMS;// Save frmVEPROMS for Import to shutoff SessionPing
			_MyMode = mode;
			MyFolder = folderInfo;
			InitializeComponent();
			this.Text = mode + " Dialog for " + folderInfo.Name;
		}
		public dlgExportImport(string mode, DocVersionInfo docVersionInfo, frmVEPROMS myFrmVEPROMS)
		{
			MyFrmVEPROMS = myFrmVEPROMS;// Save frmVEPROMS for Import to shutoff SessionPing
      _MyMode = mode;
      MyDocVersion = docVersionInfo;
      InitializeComponent();
      this.Text = mode + " Dialog for " + docVersionInfo.Name + " of " + docVersionInfo.MyFolder.Name;
    }
		public dlgExportImport(string mode, ProcedureInfo procedureInfo, frmVEPROMS myFrmVEPROMS)
		{
			MyFrmVEPROMS = myFrmVEPROMS;// Save frmVEPROMS for Import to shutoff SessionPing
      _MyMode = mode;
      MyProcedure = procedureInfo;
      InitializeComponent();
      this.Text = mode + " Dialog for " + procedureInfo.DisplayNumber;
    }
    private void dlgExportImport_Load(object sender, EventArgs e)
		{
      PEIPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + @"\VEPROMS\PEI_" + Database.VEPROMS_SqlConnection.Database;
      if (!Directory.Exists(PEIPath))
        Directory.CreateDirectory(PEIPath);
      if (_MyMode == "Import")
      {
				//If you try to import a procedure into an empty PROMS folder, the code was deleting the File System Folder including the import file.  This happened during D.C. Cook training (12/3/2015).
				//if (MyFolder != null && MyFolder.ChildFolderCount == 0 )
				//{
				//	Directory.Delete(PEIPath, true);
				//	Directory.CreateDirectory(PEIPath);
				//}
      }
      pnlExport.Dock = DockStyle.Fill;
			pnlImport.Dock = DockStyle.Fill;
      if (_MyMode.ToLower() == "export")
      {
        sfd.InitialDirectory = PEIPath;
        pnlExport.BringToFront();
      }
      else
      {
        ofd.InitialDirectory = PEIPath;
        pnlImport.BringToFront();
      }
			this.Height = this.Height / 2;
		}
		private void btnExport_Click(object sender, EventArgs e)
		{
      if (MyFolder != null)
      {
        //Database.SelectedDatabase
        //sfd.FileName = string.Format("{0}.expx", MyFolder.Name);
        sfd.FileName = string.Format("{0}-{1}.expx",Database.ActiveDatabase, MyFolder.Name);
        if (sfd.ShowDialog(this) == DialogResult.OK)
        {
          if (sfd.FileName != string.Empty)
          {
            txtExport.Text = sfd.FileName;
            if (File.Exists(txtExport.Text))
              File.Delete(txtExport.Text);
            MyExpxZipFile = new ZipFile(txtExport.Text, Encoding.UTF8);
            MyExpxZipFile.Save();
          }
        }
      }
      else if (MyProcedure != null)
      {
				txtExport.Text = string.Format(@"{0}\{1}.pxml", PEIPath, MyProcedure.DisplayNumber.Replace("/", "_").Replace("\\","_"));
      }
		}
		private void txtExport_TextChanged(object sender, EventArgs e)
		{
			btnDoExport.Enabled = txtExport.TextLength > 0;
			if (btnDoExport.Enabled)
				lblExportStatus.Text = "Ready To Perform Export";
			else
				lblExportStatus.Text = "Awaiting Export File Name:";
		}
		private XmlWriter MyWriter = null;
    private ZipFile MyExpxZipFile = null;
    private ZipFile MyImpxZipFile = null;
    private DateTime MyStart;
		private bool successfullExport = true;
    private void btnDoExport_Click(object sender, EventArgs e)
		{
      btnExport.Enabled = false;
			string msg = "Finished Exporting:\n\n";
      if (MyFolder != null)
      {
        this.Cursor = Cursors.WaitCursor;
        MyStart = DateTime.Now;
        btnDoExport.Enabled = false;
        lblExportStatus.Text = "Performing Export";
        SaveExportData();
        //SaveExportDataWriter();

        TimeSpan elapsed = DateTime.Now.Subtract(MyStart);
        lblExportStatus.Text = "Export Completed in " + elapsed.ToString();
        this.Cursor = Cursors.Default;
				msg += MyFolder.Name;
      }
      else if (MyProcedure != null)
      {
        this.Cursor = Cursors.WaitCursor;
        MyStart = DateTime.Now;
        btnDoExport.Enabled = false;
        lblExportStatus.Text = "Performing Export";
        pbExportProcedure.Maximum = 1;
        XmlDocument xd = new XmlDocument();
        ExportItem(xd, MyProcedure, "procedure");
        xd.Save(txtExport.Text);
        TimeSpan elapsed = DateTime.Now.Subtract(MyStart);
        lblExportStatus.Text = "Export Completed in " + elapsed.ToString();
        this.Cursor = Cursors.Default;
      }
			// added message to user when export of a procedure or procedure set has completed
			if (successfullExport)
				msg += MyProcedure;
			else
				msg = "Could not complete export";
			MessageBox.Show(msg, "Export", MessageBoxButtons.OK, MessageBoxIcon.Information);
			btnCloseExport.Enabled = true;
    }
    private void SaveExportData()
    {
      XmlDocument xd = new XmlDocument();
      ExportFolder(xd, MyFolder, "folder");
    }

		// appears to not be used -jsj 4-29-2016
		//private void SaveExportDataWriter()
		//{
		//	XmlWriterSettings ws = new XmlWriterSettings();
		//	ws.Indent = true;
		//	ws.NewLineHandling = NewLineHandling.Entitize;
		//	ws.CheckCharacters = false;
		//	MyWriter = XmlWriter.Create(txtExport.Text, ws);
		//	ExportFolder(MyFolder, "folder");
		//	MyWriter.Close();
		//}

		private void btnDoImport_Click(object sender, EventArgs e)
		{
			bool isImported = false;
			bool canceledPressed = false;
			btnImport.Enabled = false;
			this.Cursor = Cursors.WaitCursor;
			MyStart = DateTime.Now;
			btnDoImport.Enabled = false;
			lblImportStatus.Text = "Performing Import";
			_DidConvertTransitionsToText = false;
			_DidConvertROsToText = false;
			//LoadImportDataReader();
			if (MyFolder != null)  // import a folder - a .expx file
			{
				TurnChangeManagerOff.Execute();
				MyFrmVEPROMS.DisablePing = true;// Turn-off SessionPing
				TryToLoadImportDataDocument();// Added Try Catch Error Handling to assure that the Change Manager is tuned-on
				MyDocVersion = null;
				isImported = true;
				MyFrmVEPROMS.DisablePing = false;// Turn-on SessionPing
				TurnChangeManagerOn.Execute();
			}
			if (MyDocVersion != null) // import a procedure - a .pxml file
			{
				// compare the ROPath of MyDocVerion
				// if no path set, display Pick RO Folder dialog
				// if MyDocVersion ROPath is different than the import file ROPath, then ask user:
				//  - use MyDocVersion ROPath (warn resulting RO values may be be correct)
				//    * set oldRODbID to id in import file
				//    * set newRODbid to MyDocVersion rodbid
				//  - or convert ROs to text
				TurnChangeManagerOff.Execute();
				// Added Try Catch Error Handling to assure that the Change Manager is tuned-off
				MyFrmVEPROMS.DisablePing = true;// Turn-off SessionPing B2017-157
				bool result = TryToImportProcedure(ref isImported, ref canceledPressed);
				MyFrmVEPROMS.DisablePing = false;// Turn-on SessionPing
				TurnChangeManagerOn.Execute();
				if (!result) return;
				if (isImported)
				{
					TimeSpan elapsed = DateTime.Now.Subtract(MyStart);
					lblImportStatus.Text = "Import Completed in " + elapsed.ToString();
				}
				else
				{
					btnImport.Enabled = true;
					btnDoImport.Enabled = true;
				}
			}
			this.Cursor = Cursors.Default;
			btnCloseImport.Enabled = true;
			if (isImported)
			{
				string msg = string.Format("Finished Importing:\n\n{0}", txtImport.Text.Substring(txtImport.Text.LastIndexOf("\\") + 1));
				if (_DidConvertTransitionsToText || _DidConvertROsToText)
				{
					string msg1 = (_DidConvertTransitionsToText && _DidConvertROsToText)?"Transitions and Referenced Objects":(_DidConvertTransitionsToText)?"Transitions":"Referenced Objects";
					msg += string.Format("\n\n{0} converted to text.\n\nThe locations can be found by doing a Global Search for the \"Link Converted To Text\" annotation type",msg1);
				}
				// B2016-225 added more information to the finish import message to tell the user when ROs or Transitions are converted to text.
				MessageBox.Show(msg, "Import", MessageBoxButtons.OK, MessageBoxIcon.Information);
				//MessageBox.Show(string.Format("Finished Importing:\n\n{0}", txtImport.Text.Substring(txtImport.Text.LastIndexOf("\\") + 1)), "Import", MessageBoxButtons.OK, MessageBoxIcon.Information);
			}
			if (canceledPressed)
			{
				MessageBox.Show(string.Format("Canceling the import of:\n\n{0}",txtImport.Text.Substring(txtImport.Text.LastIndexOf("\\")+1)),"Import",MessageBoxButtons.OK,MessageBoxIcon.Information);
				btnCloseImport.PerformClick();
			}
		}
		private bool TryToImportProcedure(ref bool isImported, ref bool canceledPressed)
		{
			try
			{
				return ImportProcedure(ref isImported, ref canceledPressed);
			}
			catch (Exception ex)
			{
				MessageBox.Show(ex.StackTrace, ex.Message, MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
				_MyLog.Warn("Failed during Procedure Import", ex);
				this.Close();
				return false;
			}
		}
		private bool ImportProcedure(ref bool isImported, ref bool canceledPressed)
		{
			XmlDocument xd = new XmlDocument();
			xd.Load(txtImport.Text);
			pbImportProcedure.Maximum = 1;
			string rofolderpath = xd.DocumentElement.Attributes.GetNamedItem("rofolderpath").InnerText;
			int rodbid = int.Parse(xd.DocumentElement.Attributes.GetNamedItem("rodbid").InnerText);
			int rofstid = int.Parse(xd.DocumentElement.Attributes.GetNamedItem("rofstid").InnerText);
			if (MyDocVersion.DocVersionAssociationCount > 0)
			{
				// use current ROPath
				MyRODb = RODb.GetJustRoDb(MyDocVersion.DocVersionAssociations[0].MyROFst.MyRODb.RODbID);
				// if the current RO Path and the import file RO Path are not the same
				//  then ask if we should import using the current workingdraft RO Path, convert the ROs to text, or cancel the import
				if (MyRODb.FolderPath != rofolderpath)
				{
					dlgImpHowToHandleROs dlg = new dlgImpHowToHandleROs();
					dlg.ImportedROFolder = rofolderpath;
					dlg.WorkingDraftROFolder = MyRODb.FolderPath;
					dlg.ShowDialog(this);
					if (dlg.CancelImport)
					{
						this.Cursor = Cursors.Default;
						this.btnImport.Enabled = true; // allow user to select a different export file to import
						this.btnDoImport.Enabled = true; // allow user to change mind and perform the import
						return false; // Return False to Indicate that the Import did not succeed
					}
					_ConvertROsToTextDuringImport = dlg.ConvertROsToText;
				}
				// this saves the old RO database ID and the current RO database ID so that we can change the RODBIDs in the RO links
				newRODbID = MyRODb.RODbID;
				oldRODbID = rodbid;
			}
			else
			{
				#region NeedToSelectROPath
				// MyDocVersion does not have an RO database (ro folder path) assigned to it so we need to select an RO Path
				List<string> localROPaths = new List<string>();
				RODbInfoList rolist = RODbInfoList.Get();
				foreach (RODbInfo dbi in rolist)
				{
					if (dbi.FolderPath == rofolderpath && dbi.RODbID == rodbid)
					{
						MyRODb = RODb.GetJustRoDb(rodbid);
						oldRODbID = newRODbID = rodbid;
						break;
					}
					// B2016-175 have the correct (matching) RO Path but the rodbid is different (procedure came from a different SQL database)
					// We can use the RO Path but we need to change the rodbid in the RO links of the procedure we are importing
					else if (dbi.FolderPath == rofolderpath && dbi.RODbID != rodbid)
					{
						MyRODb = RODb.GetByFolderPath(rofolderpath);
						newRODbID = MyRODb.RODbID;
						oldRODbID = rodbid;
						break;
					}
					else
					{
						DirectoryInfo di = new DirectoryInfo(dbi.FolderPath);
						if (di.Exists)
							localROPaths.Add(dbi.FolderPath);
					}
				}
				if (MyRODb == null)
				{
					if (localROPaths.Count == 0)
					{
						MessageBox.Show("There has been no RO folder defined for this database.\r\n\r\nIn order to import a procedure, you need to assign a RO folder path.\r\n\r\nImport process will terminate.");
						this.Cursor = Cursors.Default;
						return false;// Return False to Indicate that the Import did not succeed
					}
					else
					{
						this.Cursor = Cursors.Default;
						dlgPickROFolder dlg = new dlgPickROFolder();
						dlg.ImportedROFolder = rofolderpath;
						dlg.LocalROFolders = localROPaths;
						dlg.ShowDialog(this);
						if ((dlg.SelectedROFolder ?? string.Empty) != string.Empty) // B2015-216 If the return value is null treat it like an empty string
						{
							MyRODb = RODb.GetByFolderPath(dlg.SelectedROFolder);
							RODbInfo myRODBInfo = RODbInfo.Get(MyRODb.RODbID);
							oldRODbID = newRODbID = MyRODb.RODbID;
							ROFstInfo fstInfo = null;
							foreach (ROFstInfo tmp in myRODBInfo.RODbROFsts)
								if (fstInfo == null || tmp.ROFstID > fstInfo.ROFstID)
									fstInfo = tmp;
							using (DocVersion dv = MyDocVersion.Get())
							{
								using (ROFst fst = fstInfo.Get())
								{
									dv.DocVersionAssociations.Add(fst);
									dv.Save();
								}
								dv.Reset_DocVersionAssociations();
								MyDocVersion.RefreshDocVersionAssociations();
							}
						}
						else
						{
							MessageBox.Show("Since you did not pick an existing RO folder defined for this database, the import process will terminate.");
							this.Close();// Close the Import Window
							return false;// Return False to Indicate that the Import did not succeed
						}
					}
				}
				#endregion
			} // end - need to select RO Path

			// use resolvedProcNum to determine if procedure is 'unique', i.e. if the procedure number exists
			// and user does not overwrite or copy, then the procedure should NOT be imported. Fix for B2016-045
			bool resolvedProcNum = true;
			foreach (ProcedureInfo pi in MyDocVersion.Procedures)
			{
				// procedure numbers that contain a hyphen may have the hyphen represented as the unicode character
				// '\u8209?' or the '-' character.  If proc number is same except for hyphen representation, they
				//  should be considered the same procedure (fix for B2016-084)
				string hyphenNum = pi.MyContent.Number == null ? "" : pi.MyContent.Number.Replace(@"\u8209?", "-").Replace("\u2011", "-").Replace(@"\u9586?", @"\").Replace("\u2572", @"\");
				string hyphenImpNum = xd.SelectSingleNode("procedure/content/@number").InnerText;
				// bug fix C2015-044 - jsj
				// - the cancel button would ignor the user's wishes and proceed with the import (overwriting the existing procedure)
				// - also found that the message about overwriting or making a copy wasn't appearing because we where not converting the import procedure number
				// - our standard unicode dash (\u8209?) before conparing the existing and imported
				// - also found the Overrite and make a copy of messages looked too similar - fixed that as well.
				//hyphenImpNum = hyphenImpNum == null ? "" : hyphenImpNum.Replace("\u8030?", "-"); -did not find any reason to have this \u8030? - note retested sourcesafe doc for B2016-084 without this logic and it was fine
				hyphenImpNum = hyphenImpNum == null ? "" : hyphenImpNum.Replace(@"\u8209?", "-").Replace("\u2011", "-").Replace(@"\u9586?", @"\").Replace("\u2572", @"\");

				if (hyphenNum == hyphenImpNum)
				{
					string msg = string.Format("The procedure you are importing{0}already exists in this procedure set.\n\nDo you want to OVERWRITE the existing procedure?", !hyphenImpNum.Equals("") ? string.Format(" ({0}) ", hyphenImpNum) : " ");
					DialogResult dr = MessageBox.Show(this, msg, "Overwrite Existing Procedure", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Stop);
					if (dr == DialogResult.Yes)
					{
						ImportProcedureOverwrite(xd, pi);
						isImported = true;
						break;
					}
					if (dr == DialogResult.No)
					{
						msg = string.Format("Do you want to import {0} as a COPY of the existing procedure?\n\nThis will prefix the procedure number with \"Copy of\"", !hyphenImpNum.Equals("") ? string.Format("({0})", hyphenImpNum) : "the procedure");
						dr = MessageBox.Show(this, msg, "Create Copy Of Existing Procedure", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Stop);
						if (dr == DialogResult.Yes)
						{
							ImportProcedureCopy(xd);
							isImported = true;
							break;
						}
						else
							resolvedProcNum = false;
					}
					if (dr == System.Windows.Forms.DialogResult.Cancel)
					{
						canceledPressed = true;
						resolvedProcNum = false;
					}
					break; // user selected No or Cancel so break out of the foreach loop
				}
			}
			if (!canceledPressed && !isImported && resolvedProcNum)
			{
				ImportProcedureNew(xd);
				isImported = true;
			}
			return true;// Import Suceeded
		}
		// Added Error Handling to assure that Change Manager is turned-on regardless of success or failure of the import
		private void TryToLoadImportDataDocument()
		{
			try
			{
				LoadImportDataDocument();
			}
			catch (Exception ex)
			{
				_MyLog.Warn("Failure During Import", ex);
			}
		}
    private void ImportProcedureNew(XmlDocument xd)
    {
      //add imported procedure
			floatFoldout = new Dictionary<int, int>();
			oldFormat = new Dictionary<int, string>();
      newFormat = new Dictionary<string, int>();
      FormatInfoList fil = FormatInfoList.Get();
      foreach (FormatInfo fi in fil)
      {
        oldFormat.Add(fi.FormatID, fi.Name);
        newFormat.Add(fi.Name, fi.FormatID);
      }
      Old2NewItem = new Dictionary<int, int>();
      Old2NewContent = new Dictionary<int, int>();
      Old2NewLibDoc = new Dictionary<int, int>();
      PendingTransitions = new XmlDocument();
      XmlElement xe = PendingTransitions.CreateElement("transitions");
      PendingTransitions.AppendChild(xe);
      string fn = PEIPath + @"\transitions.xml";
      PendingTransitions.Save(fn);
      ProcedureInfo lastProcedure = null;
      foreach (ProcedureInfo pi in MyDocVersion.Procedures)
        lastProcedure = pi;
      _MyNewProcedure = AddProcedure(xd.DocumentElement, MyDocVersion, lastProcedure);
      //update transitions
      AddTransitions(PendingTransitions);
			PendingTransitions.Save(fn);
			FixFloatingFoldouts();
			//File.Delete(fn);
    }
    private void ImportProcedureCopy(XmlDocument xd)
    {
			floatFoldout = new Dictionary<int, int>();
			oldFormat = new Dictionary<int, string>();
      newFormat = new Dictionary<string, int>();
      FormatInfoList fil = FormatInfoList.Get();
      foreach (FormatInfo fi in fil)
      {
        oldFormat.Add(fi.FormatID, fi.Name);
        newFormat.Add(fi.Name, fi.FormatID);
      }
      Old2NewItem = new Dictionary<int, int>();
      Old2NewContent = new Dictionary<int, int>();
      Old2NewLibDoc = new Dictionary<int, int>();
      PendingTransitions = new XmlDocument();
      XmlElement xe = PendingTransitions.CreateElement("transitions");
      PendingTransitions.AppendChild(xe);
      string fn = PEIPath + @"\transitions.xml";
      PendingTransitions.Save(fn);
      ProcedureInfo lastProcedure = null;
      //determine count of existing procedures with same number
      string number = xd.SelectSingleNode("procedure/content/@number").InnerText;

			// kbr - could replace '-' with unicode in number, here.
      int count = 0;
      foreach (ProcedureInfo pi in MyDocVersion.Procedures)
      {
        lastProcedure = pi;
        if (pi.MyContent.Number.EndsWith(number))
          count++;
      }
      xd.SelectSingleNode("procedure/content/@number").InnerText = string.Format("Copy({0}) of {1}", count.ToString(), number);
      //add imported procedure and copy count
      _MyNewProcedure = AddProcedure(xd.DocumentElement, MyDocVersion, lastProcedure);
      //update transitions
      AddTransitions(PendingTransitions);
			FixFloatingFoldouts();
      File.Delete(fn);
    }
    private void ImportProcedureOverwrite(XmlDocument xd, ProcedureInfo pi)
    {
			floatFoldout = new Dictionary<int, int>();
			oldFormat = new Dictionary<int, string>();
      newFormat = new Dictionary<string, int>();
      FormatInfoList fil = FormatInfoList.Get();
      foreach (FormatInfo fi in fil)
      {
        oldFormat.Add(fi.FormatID, fi.Name);
        newFormat.Add(fi.Name, fi.FormatID);
      }
      Old2NewItem = new Dictionary<int, int>();
      Old2NewContent = new Dictionary<int, int>();
      Old2NewLibDoc = new Dictionary<int, int>();
      PendingTransitions = new XmlDocument();
      XmlElement xe = PendingTransitions.CreateElement("transitions");
      PendingTransitions.AppendChild(xe);
      string fn = PEIPath + @"\transitions.xml";
      PendingTransitions.Save(fn);
      ProcedureInfo lastProcedure = null;
      //delete old procedure
      foreach (ProcedureInfo lp in MyDocVersion.Procedures)
        lastProcedure = lp;
      //delete opi
			try
			{
				TurnChangeManagerOn.Execute(); // Import Turns off the Change Manager - Delete needs to have it on
				Item.DeleteItemAndChildren(pi);
				TurnChangeManagerOff.Execute(); // Assure that the Change Manager is off
			}
			catch(Exception ex)
			{
				ExternalTransitionItem = pi.HandleSqlExceptionOnDelete(ex);
				File.Delete(fn);
				TurnChangeManagerOff.Execute(); // Assure that the Change Manager is off
				return;
			}
      //add imported procedure
      _MyNewProcedure = AddProcedure(xd.DocumentElement, MyDocVersion, lastProcedure);
      //update transitions
      AddTransitions(PendingTransitions);
			FixFloatingFoldouts();
    }
		private void LoadImportDataDocument()
		{
      floatFoldout = new Dictionary<int, int>();
      ZipEntry ze = MyExpxZipFile[0];
      string fn = PEIPath + @"\" + ze.FileName;
      ze.Extract(PEIPath, ExtractExistingFileAction.OverwriteSilently);
			XmlDocument xd = new XmlDocument();
			xd.Load(fn);
      LoadFormats(xd);
      Folder ff = AddFolder(Folder.Get(MyFolder.FolderID), xd);
      if (ff == null)
      {
        MessageBox.Show("You can not import the same procedure set more than once", "Duplicate Import Error");
        return;
      }
      _MyNewFolder = FolderInfo.Get(ff.FolderID);
      AddAnnotationTypes(xd);
			DocVersionInfo dvi = AddDocVersion(ff, xd);
			MyDocVersion = dvi;
      xd = null;
      lblImportStatus.Text = "Creating Procedures...";
      Application.DoEvents();
      ProcedureInfo pi = null;
      pbImportProcedure.Value = 0;
      pbImportProcedure.Maximum = MyExpxZipFile.Entries.Count - 1;
      for (int i = 1; i < MyExpxZipFile.Entries.Count; i++)
      {
        ze = MyExpxZipFile[i];
        fn = PEIPath + @"\" + ze.FileName;
        ze.Extract(PEIPath, ExtractExistingFileAction.OverwriteSilently);
        xd = new XmlDocument();
        xd.Load(fn);
        pi = AddProcedure(xd.DocumentElement, dvi, pi);
				GC.Collect(); // need to cleanup memory after importing each procedure due to use of Regular Expressions in processing RO and Transition links
      }
      DirectoryInfo di = new DirectoryInfo(PEIPath);
      DirectoryInfo[] dis = di.GetDirectories();
      for (int d = 0; d < dis.Length; d++)
        dis[d].Delete(true);
			lblImportStatus.Text = "Updating Transitions";
			AddTransitions();
      FixFloatingFoldouts();
			SaveTransitionAndItemContentIDs();
		}
		private void FixSectionStart(ProcedureInfo pi)
		{
			Content c = Content.Get(pi.MyContent.ContentID);
			XmlDocument xd = new XmlDocument();
			// If the config field is empty, add an empty xml node.
			if (c.Config == "") c.Config = "<Config/>";
			xd.LoadXml(c.Config);
			XmlNode xn = xd.SelectSingleNode("Config/Procedure/@SectionStart");
			if (xn != null)
			{
			int iid = int.Parse(xn.InnerText);
			if (Old2NewItem.ContainsKey(iid))
				iid = Old2NewItem[iid];
			else
			{
				int oldid = iid;
				iid = pi.ItemID;
				XmlAttribute xa = xd.CreateAttribute("ErrorSectionStart");
				xa.InnerText = oldid.ToString();
				XmlNode xp = xd.SelectSingleNode("Config/Procedure");
				xp.Attributes.SetNamedItem(xa);
			}
			xn.InnerText = iid.ToString();
			c.Config = xd.OuterXml;
			c.Save();
			}
		}
    private void FixFloatingFoldouts()
    {
      foreach (int key in floatFoldout.Keys)
      {
        lblImportStatus.Text = "Updating Floating Foldouts";
        int cid = Old2NewContent[key];
        int iid = Old2NewItem[floatFoldout[key]];
        Content c = Content.Get(cid);
        XmlDocument xd = new XmlDocument();
        xd.LoadXml(c.Config);
        XmlNode xn = xd.SelectSingleNode("Config/Step/@FloatingFoldout");
        xn.InnerText = iid.ToString();
        c.Config = xd.OuterXml;
        c.Save();
      }
    }

		// note that his is only used when importing a folder
    private void LoadFormats(XmlDocument xd)
    {
      oldFormat = new Dictionary<int, string>();
      XmlNodeList nl = xd.SelectNodes("folder/formats/format");
      foreach (XmlNode nd in nl)
      {
        int formatid = int.Parse(nd.Attributes.GetNamedItem("formatid").InnerText);
        string name = nd.Attributes.GetNamedItem("name").InnerText;
        oldFormat.Add(formatid, name);
      }
      newFormat = new Dictionary<string, int>();
      FormatInfoList fil = FormatInfoList.Get();
      foreach (FormatInfo fi in fil)
        newFormat.Add(fi.Name, fi.FormatID);
    }

		//jsj 4-29-2016 appears to not be used
		//Dictionary<int, ItemInfo> dicParentItem = null;
		//private void UpdateParentItem(int depth, ItemInfo ii)
		//{
		//	if (dicParentItem == null) dicParentItem = new Dictionary<int, ItemInfo>();
		//	if (!dicParentItem.ContainsKey(depth)) dicParentItem.Add(depth, null);
		//	dicParentItem[depth] = ii;
		//}

		//jsj 4-29-2016 appears to not be used
		//Dictionary<int, ItemInfo> dicPreviousItem = null;
		//private void UpdatePreviousItem(int depth, ItemInfo ii)
		//{
		//	if (dicPreviousItem == null) dicPreviousItem = new Dictionary<int, ItemInfo>();
		//	if (!dicPreviousItem.ContainsKey(depth)) dicPreviousItem.Add(depth, null);
		//	dicPreviousItem[depth] = ii;
		//}

		Dictionary<int, int> dicItemDepth = null;

		// jsj 4-29-2016 appears to not be used
		//private void UpdateItemDepth(int depth, int id)
		//{
		//	if (dicItemDepth == null) dicItemDepth = new Dictionary<int, int>();
		//	if (!dicItemDepth.ContainsKey(depth)) dicItemDepth.Add(depth, 0);
		//	dicItemDepth[depth] = id;
		//}
		// jsj 2016Feb17 - this appears to not be used
		//private void LoadImportDataReader()
		//{
		//	int pCount = 0;
		//	int sCount = 0;
		//	Folder folder = null;
		//	DocVersion docversion = null;
		//	Dictionary<string, string> dicRofst = null;
		//	Dictionary<string, string> dicEntry = null;
		//	ROFst rofst = null;
		//	GetImportDataCounts();
		//	pbImportProcedure.Maximum = MyCounts.Count;
		//	pbImportProcedure.Value = 0;
		//	Application.DoEvents();
		//	FileStream fs = File.OpenRead(txtImport.Text);
		//	XmlReaderSettings rs = new XmlReaderSettings();
		//	rs.CheckCharacters = false;
		//	XmlReader xr = XmlReader.Create(fs, rs);
		//	while (xr.Read())
		//	{
		//		if (xr.IsStartElement())
		//		{
		//			switch (xr.Name)
		//			{
		//				case "annotation":
		//					AddAnnotation(xr);
		//					break;
		//				//case "association":
		//				//  break;
		//				case "content":
		//					{
		//						if (xr.Depth == 3)	//content for procedure
		//						{
		//							ItemInfo ii = AddProcedure(xr, docversion, dicPreviousItem[xr.Depth], dicItemDepth[xr.Depth]);
		//							UpdatePreviousItem(xr.Depth, ii);
		//							UpdateParentItem(xr.Depth, ii);
		//						}
		//						else
		//						{

		//							int fromtype = dicItemDepth.ContainsKey(xr.Depth - 2) ? dicItemDepth[xr.Depth - 2] : 0;
		//							switch (fromtype)
		//							{
		//								case 2:
		//									{	//sections
		//										ItemInfo ii = AddSection(xr, dicParentItem[xr.Depth], dicPreviousItem[xr.Depth], dicItemDepth[xr.Depth]);
		//										UpdatePreviousItem(xr.Depth, ii);
		//										UpdateParentItem(xr.Depth, ii);
		//										break;
		//									}
		//								case 3:
		//									{	//cautions
		//										ItemInfo ii = AddCaution(xr, dicParentItem[xr.Depth], dicPreviousItem[xr.Depth], dicItemDepth[xr.Depth]);
		//										UpdatePreviousItem(xr.Depth, ii);
		//										UpdateParentItem(xr.Depth, ii);
		//										break;
		//									}
		//								case 4:
		//									{	//notes
		//										ItemInfo ii = AddNote(xr, dicParentItem[xr.Depth], dicPreviousItem[xr.Depth], dicItemDepth[xr.Depth]);
		//										UpdatePreviousItem(xr.Depth, ii);
		//										UpdateParentItem(xr.Depth, ii);
		//										break;
		//									}
		//								case 5:
		//									{	//rnos
		//										ItemInfo ii = AddRNO(xr, dicParentItem[xr.Depth], dicPreviousItem[xr.Depth], dicItemDepth[xr.Depth]);
		//										UpdatePreviousItem(xr.Depth, ii);
		//										UpdateParentItem(xr.Depth, ii);
		//										break;
		//									}
		//								case 6:
		//									{	//steps
		//										ItemInfo ii = AddStep(xr, dicParentItem[xr.Depth], dicPreviousItem[xr.Depth], dicItemDepth[xr.Depth]);
		//										UpdatePreviousItem(xr.Depth, ii);
		//										UpdateParentItem(xr.Depth, ii);
		//										break;
		//									}
		//								case 7:
		//									{	//tables
		//										ItemInfo ii = AddTable(xr, dicParentItem[xr.Depth], dicPreviousItem[xr.Depth], dicItemDepth[xr.Depth]);
		//										UpdatePreviousItem(xr.Depth, ii);
		//										UpdateParentItem(xr.Depth, ii);
		//										break;
		//									}
		//								default:
		//									break;
		//							}
		//						}
		//						break;
		//					}
		//				case "document":
		//					AddDocument(xr, dicEntry);
		//					break;
		//				case "docversion":
		//					{
		//						docversion = AddDocVersion(folder, xr);
		//						UpdatePreviousItem(xr.Depth + 2, null);
		//						break;
		//					}
		//				case "entry":
		//					dicEntry = AddEntry(xr);
		//					break;
		//				case "folder":
		//					folder = AddFolder(Folder.Get(MyFolder.FolderID), xr);
		//					break;
		//				case "grid":
		//					AddGrid(xr);
		//					break;
		//				case "procedure":
		//					{
		//						UpdateItemDepth(xr.Depth + 1, int.Parse(xr.GetAttribute("itemid")));
		//						pbImportProcedure.PerformStep();
		//						lblImportProcedure.Text = string.Format("{0} of {1} Procedures", pbImportProcedure.Value.ToString(), pbImportProcedure.Maximum.ToString());
		//						pCount++;
		//						pbImportSection.Maximum = MyCounts[pCount].Count;
		//						pbImportSection.Value = 0;
		//						sCount = 0;
		//						Application.DoEvents();
		//						break;
		//					}
		//				case "section":
		//					{
		//						UpdateItemDepth(xr.Depth + 1, int.Parse(xr.GetAttribute("itemid")));
		//						pbImportSection.PerformStep();
		//						lblImportSection.Text = string.Format("{0} of {1} Sections", pbImportSection.Value.ToString(), pbImportSection.Maximum.ToString());
		//						sCount++;
		//						pbImportStep.Maximum = MyCounts[pCount][sCount];
		//						pbImportStep.Value = 0;
		//						Application.DoEvents();
		//						break;
		//					}
		//				case "step":
		//					{
		//						UpdateItemDepth(xr.Depth + 1, int.Parse(xr.GetAttribute("itemid")));
		//						if (xr.Depth == 8)
		//						{
		//							pbImportStep.PerformStep();
		//							lblImportStep.Text = string.Format("{0} of {1} Steps", pbImportStep.Value.ToString(), pbImportStep.Maximum.ToString());
		//							Application.DoEvents();
		//						}
		//						break;
		//					}
		//				case "caution":
		//				case "note":
		//				case "rno":
		//				case "table":
		//					UpdateItemDepth(xr.Depth + 1, int.Parse(xr.GetAttribute("itemid")));
		//					break;
		//				case "cautions":
		//				case "notes":
		//				case "rnos":
		//				case "sections":
		//				case "steps":
		//				case "tables":
		//					{
		//						UpdateItemDepth(xr.Depth, int.Parse(xr.GetAttribute("fromtype")));
		//						UpdatePreviousItem(xr.Depth + 2, null);
		//						UpdateParentItem(xr.Depth + 2, dicParentItem[xr.Depth - 1]);
		//						break;
		//					}
		//				case "rodb":
		//					{
		//						MyRODb = AddRODb(xr);
		//						rofst = AddROFst(dicRofst);
		//						docversion.DocVersionAssociations.Add(rofst);
		//						docversion.Save();
		//						break;
		//					}
		//				case "rofst":
		//					dicRofst = GetROFstData(xr);
		//					break;
		//				case "rousage":
		//					AddROUsage(xr);
		//					break;
		//				//case "transition":
		//				//  break;
		//				default:
		//					break;
		//			}
		//			Console.WriteLine("{0} - {1}", xr.Name, xr.Depth.ToString());
		//		}
		//	}
		//	pbImportProcedure.PerformStep();
		//	Application.DoEvents();
		//	fs.Close();
		//	FixImportDataTransitions();
		//	StoreItemContentIDs();
		//	ResolveExternalTransitions(folder);
		//}

		// This is called only when we are importing an entire folder.
		// if there is a .impx file (a zip file generated from the last folder export file and based on location -folder name- of the export file you are importing), then it updates it with new values, 
		// else it will create a .impx file, and saves the id information listed below.
		// This will create and save the ItemIDs (old and new), ContentIDs (old andnew), library document IDs (old and new), and pending transitions each in their own xml file
		// the xml files are then added (or replaced) in the .impx file.
		private void SaveTransitionAndItemContentIDs()
    {
      XmlDocument xd = new XmlDocument();
      XmlElement xe = xd.CreateElement("items");
      xd.AppendChild(xe);
      string fn = PEIPath + @"\items.xml";
      foreach (int key in Old2NewItem.Keys)
      {
        xe = xd.CreateElement("item");
        xe.Attributes.SetNamedItem(AddAttribute(xd, "old", key.ToString()));
        xe.Attributes.SetNamedItem(AddAttribute(xd, "new", Old2NewItem[key].ToString()));
        xd.DocumentElement.AppendChild(xe);
      }
      xd.Save(fn);
      ZipEntry ze = MyImpxZipFile["items.xml"];
      MyImpxZipFile.RemoveEntry(ze);
      MyImpxZipFile.Save();
      MyImpxZipFile.AddFile(fn, "");
      MyImpxZipFile.Save();
      File.Delete(fn);
      xd = new XmlDocument();
      xe = xd.CreateElement("contents");
      xd.AppendChild(xe);
      fn = PEIPath + @"\contents.xml";
      foreach (int key in Old2NewContent.Keys)
      {
        xe = xd.CreateElement("content");
        xe.Attributes.SetNamedItem(AddAttribute(xd, "old", key.ToString()));
        xe.Attributes.SetNamedItem(AddAttribute(xd, "new", Old2NewContent[key].ToString()));
        xd.DocumentElement.AppendChild(xe);
      }
      xd.Save(fn);
      ze = MyImpxZipFile["contents.xml"];
      MyImpxZipFile.RemoveEntry(ze);
      MyImpxZipFile.Save();
      MyImpxZipFile.AddFile(fn, "");
      MyImpxZipFile.Save();
      File.Delete(fn);
      xd = new XmlDocument();
      xe = xd.CreateElement("transitions");
      xd.AppendChild(xe);
      fn = PEIPath + @"\transitions.xml";
      if (PendingTransitions != null && PendingTransitions.DocumentElement.HasChildNodes)
      {
        foreach (XmlNode nd in PendingTransitions.DocumentElement.ChildNodes)
        {
          if(nd.InnerText == "")
            xd.DocumentElement.AppendChild(xd.ImportNode(nd, true));
        }
      }
      xd.Save(fn);
      ze = MyImpxZipFile["transitions.xml"];
      MyImpxZipFile.RemoveEntry(ze);
      MyImpxZipFile.Save();
      MyImpxZipFile.AddFile(fn, "");
      MyImpxZipFile.Save();
      File.Delete(fn);
    }
		// appears to not be used - jsj 4-28-2016
		//private void StoreItemContentIDs()
		//{
		//	XmlDocument xd = new XmlDocument();
		//	string fn = PEIPath + @"\ExternalTransitions.xml";
		//	xd.Load(fn);
		//	XmlElement xe = (XmlElement)xd.SelectSingleNode("externaltransitions/oldtonewitem");
		//	foreach (int key in Old2NewItem.Keys)
		//	{
		//		XmlElement xee = xd.CreateElement("item");
		//		XmlAttribute xa = AddAttribute(xd, "old", key.ToString());
		//		xee.Attributes.SetNamedItem(xa);
		//		xa = AddAttribute(xd, "new", Old2NewItem[key].ToString());
		//		xee.Attributes.SetNamedItem(xa);
		//		xe.AppendChild(xee);
		//	}
		//	xd.Save(fn);
		//	xe = (XmlElement)xd.SelectSingleNode("externaltransitions/oldtonewcontent");
		//	foreach (int key in Old2NewContent.Keys)
		//	{
		//		XmlElement xee = xd.CreateElement("content");
		//		XmlAttribute xa = AddAttribute(xd, "old", key.ToString());
		//		xee.Attributes.SetNamedItem(xa);
		//		xa = AddAttribute(xd, "new", Old2NewContent[key].ToString());
		//		xee.Attributes.SetNamedItem(xa);
		//		xe.AppendChild(xee);
		//	}
		//	xd.Save(fn);
		//}
		//private void ResolveExternalTransitions(Folder folder)
		//{
		//	XmlDocument xd = new XmlDocument();
		//	string fn = PEIPath + @"\ExternalTransitions.xml";
		//	xd.Load(fn);
		//	AddStoredItemContentIDs(xd);
		//	XmlNodeList nl = xd.SelectNodes("//transition[@folder!='']");
		//	foreach (XmlNode nd in nl)
		//	{
		//		int transitionid = int.Parse(nd.Attributes.GetNamedItem("transitionid").InnerText);
		//		int fromid = int.Parse(nd.Attributes.GetNamedItem("fromid").InnerText);
		//		int toid = int.Parse(nd.Attributes.GetNamedItem("toid").InnerText);
		//		int rangeid = int.Parse(nd.Attributes.GetNamedItem("rangeid").InnerText);
		//		if (Old2NewContent.ContainsKey(fromid) && Old2NewItem.ContainsKey(toid) && Old2NewItem.ContainsKey(rangeid))
		//		{
		//			int isrange = int.Parse(nd.Attributes.GetNamedItem("isrange").InnerText);
		//			int trantype = int.Parse(nd.Attributes.GetNamedItem("trantype").InnerText);
		//			string config = nd.Attributes.GetNamedItem("config").InnerText;
		//			string userid = nd.Attributes.GetNamedItem("userid").InnerText;
		//			DateTime dts = DateTime.Parse(nd.Attributes.GetNamedItem("dts").InnerText);
		//			string lookfor;
		//			if (isrange == 0)
		//				lookfor = string.Format("#Link:Transition:{0} {1} {2}", trantype, transitionid, toid);
		//			else
		//				lookfor = string.Format("#Link:TransitionRange:{0} {1} {2} {3}", trantype, transitionid, toid, rangeid);
		//			fromid = Old2NewContent[fromid];
		//			toid = Old2NewItem[toid];
		//			rangeid = Old2NewItem[rangeid];
		//			Content cc = Content.Get(fromid);
		//			Transition tt = Transition.MakeTransition(cc, Item.Get(toid), Item.Get(rangeid), isrange, trantype, config, dts, userid);
		//			transitionid = tt.TransitionID;
		//			string replacewith;
		//			if (isrange == 0)
		//				replacewith = string.Format("#Link:Transition:{0} {1} {2}", trantype, transitionid, toid);
		//			else
		//				replacewith = string.Format("#Link:TransitionRange:{0} {1} {2} {3}", trantype, transitionid, toid, rangeid);
		//			cc.Text = cc.Text.Replace(lookfor, replacewith);
		//			cc.Save();
		//			nd.Attributes.GetNamedItem("folder").InnerText = "";
		//		}
		//	}
		//	xd.Save(fn);
		//}

		// This is called only when we are importing an entire folder and there is a .impx file (a zip file)
		// the name of the .impx file is based on the folder name containing the export file being imported
		// This will read in the saved ItemIDs (old and new), ContentIDs (old andnew), library document IDs (old and new), and pending transitions
    private void ReadTransitionAndItemContentIDs()
    {
      ZipEntry ze = MyImpxZipFile["items.xml"];
      ze.Extract(PEIPath, ExtractExistingFileAction.OverwriteSilently);
      string fn = PEIPath + @"\items.xml";
      XmlDocument xd = new XmlDocument();
      xd.Load(fn);
			// B2016-176, B2016-197  Transitions were no always properly resolved - don't load in the old item ids
			//XmlNodeList nl = xd.SelectNodes("//item");
			//foreach (XmlNode nd in nl)
			//{
			//	int oldid = int.Parse(nd.Attributes.GetNamedItem("old").InnerText);
			//	int newid = int.Parse(nd.Attributes.GetNamedItem("new").InnerText);
			//	//if (!Old2NewItem.ContainsKey(oldid))
			//		Old2NewItem.Add(oldid, newid);
			//}
      File.Delete(fn);
      ze = MyImpxZipFile["contents.xml"];
      ze.Extract(PEIPath, ExtractExistingFileAction.OverwriteSilently);
      fn = PEIPath + @"\contents.xml";
      xd = new XmlDocument();
      xd.Load(fn);
			// B2016-176, B2016-197  Transitions were no always properly resolved - don't load in the old content ids
			//nl = xd.SelectNodes("//content");
			//foreach (XmlNode nd in nl)
			//{
			//	int oldid = int.Parse(nd.Attributes.GetNamedItem("old").InnerText);
			//	int newid = int.Parse(nd.Attributes.GetNamedItem("new").InnerText);
			//	//if (!Old2NewContent.ContainsKey(oldid))
			//		Old2NewContent.Add(oldid, newid);
			//}
      File.Delete(fn);
      ze = MyImpxZipFile["libdocs.xml"];
      ze.Extract(PEIPath, ExtractExistingFileAction.OverwriteSilently);
      fn = PEIPath + @"\libdocs.xml";
      xd = new XmlDocument();
      xd.Load(fn);
			XmlNodeList nl = xd.SelectNodes("//libdoc");
			//nl = xd.SelectNodes("//libdoc");
			foreach (XmlNode nd in nl)
			{
				int oldid = int.Parse(nd.Attributes.GetNamedItem("old").InnerText);
				int newid = int.Parse(nd.Attributes.GetNamedItem("new").InnerText);
				//if (!Old2NewContent.ContainsKey(oldid))
				Old2NewLibDoc.Add(oldid, newid);
			}
      File.Delete(fn);
      ze = MyImpxZipFile["transitions.xml"];
      ze.Extract(PEIPath, ExtractExistingFileAction.OverwriteSilently);
      fn = PEIPath + @"\transitions.xml";
      PendingTransitions.Load(fn);
      File.Delete(fn);
    }
		// appears not to be used - jsj  4-28-2016
		//private void AddStoredItemContentIDs(XmlDocument xd)
		//{
		//	XmlNodeList nl = xd.SelectNodes("//item");
		//	foreach (XmlNode nd in nl)
		//	{
		//		int oldid = int.Parse(nd.Attributes.GetNamedItem("old").InnerText);
		//		int newid = int.Parse(nd.Attributes.GetNamedItem("new").InnerText);
		//		if (!Old2NewItem.ContainsKey(oldid))
		//			Old2NewItem.Add(oldid, newid);
		//	}
		//	nl = xd.SelectNodes("//content");
		//	foreach (XmlNode nd in nl)
		//	{
		//		int oldid = int.Parse(nd.Attributes.GetNamedItem("old").InnerText);
		//		int newid = int.Parse(nd.Attributes.GetNamedItem("new").InnerText);
		//		if (!Old2NewContent.ContainsKey(oldid))
		//			Old2NewContent.Add(oldid, newid);
		//	}
		//}

		// appears not to be used - jsj  4-28-2016
		//private void FixImportDataTransitions()
		//{
		//	XmlDocument xd = new XmlDocument();
		//	string fn = PEIPath + @"\ExternalTransitions.xml";
		//	if (!File.Exists(fn))
		//	{
		//		XmlElement xe = xd.CreateElement("externaltransitions");
		//		XmlElement xee = xd.CreateElement("oldtonewitem");
		//		xe.AppendChild(xee);
		//		xee = xd.CreateElement("oldtonewcontent");
		//		xe.AppendChild(xee);
		//		xee = xd.CreateElement("transitions");
		//		xe.AppendChild(xee);
		//		xd.AppendChild(xe);
		//		xd.Save(fn);
		//	}
		//	else
		//	{
		//		xd.Load(fn);
		//	}
		//	FileStream fs = File.OpenRead(txtImport.Text);
		//	XmlReaderSettings rs = new XmlReaderSettings();
		//	rs.CheckCharacters = false;
		//	XmlReader xr = XmlReader.Create(fs, rs);
		//	while (xr.Read())
		//	{
		//		if (xr.IsStartElement())
		//		{
		//			switch (xr.Name)
		//			{
		//				case "transition":
		//					AddTransitions(xr);
		//					break;
		//				case "externaltransition":
		//					{
		//						AddExternalTransition(xr, xd);
		//						break;
		//					}
		//				default:
		//					break;
		//			}
		//		}
		//	}
		//	fs.Close();
		//	xd.Save(fn);
		//}

		// jsj 4-29-2016 appears to not be used
		//private Dictionary<int, Dictionary<int, int>> MyCounts = null;
		//private Dictionary<int, int> MySubCounts = null;
	//private void GetImportDataCounts()
		//{
		//	int pCount = 0;
		//	int sCount = 0;
		//	int tCount = 0;
		//	MyCounts = new Dictionary<int, Dictionary<int, int>>();
		//	MySubCounts = new Dictionary<int, int>();
		//	FileStream fs = File.OpenRead(txtImport.Text);
		//	XmlReaderSettings rs = new XmlReaderSettings();
		//	rs.CheckCharacters = false;
		//	XmlReader xr = XmlReader.Create(fs, rs);
		//	while (xr.Read())
		//	{
		//		if (xr.IsStartElement())
		//		{
		//			switch (xr.Name)
		//			{
		//				case "procedure":
		//					{
		//						if (pCount > 0)
		//						{
		//							MySubCounts.Add(sCount, tCount);
		//							MyCounts.Add(pCount, MySubCounts);
		//							sCount = 0;
		//							tCount = 0;
		//							MySubCounts = new Dictionary<int, int>();
		//						}
		//						pCount++;
		//						break;
		//					}
		//				case "section":
		//					{
		//						if (sCount > 0)
		//						{
		//							MySubCounts.Add(sCount, tCount);
		//							tCount = 0;
		//						}
		//						sCount++;
		//						break;
		//					}
		//				case "step":
		//					{
		//						if (xr.Depth == 8)
		//							tCount++;
		//						break;
		//					}
		//				default:
		//					break;
		//			}
		//		}
		//	}
		//	MySubCounts.Add(sCount, tCount);
		//	MyCounts.Add(pCount, MySubCounts);
		//	fs.Close();
		//}

		private void btnImport_Click(object sender, EventArgs e)
		{
      if (MyFolder != null)
      {
        if (ofd.ShowDialog(this) == DialogResult.OK)
        {
          if (ofd.FileName != string.Empty)
          {
            Old2NewItem = new Dictionary<int, int>();
            Old2NewContent = new Dictionary<int, int>();
            Old2NewLibDoc = new Dictionary<int, int>();
            PendingTransitions = new XmlDocument();
            FileInfo fi = new FileInfo(ofd.FileName);
            string dn;
						if (fi.Name.IndexOf("-") > 0)
							dn = fi.Name.Substring(0, fi.Name.IndexOf("-"));
						else
							dn = fi.Name.Substring(0,fi.Name.IndexOf("."));
            txtImport.Text = ofd.FileName;
            ReadOptions ro = new ReadOptions();
            ro.Encoding = Encoding.UTF8;
            MyExpxZipFile = ZipFile.Read(txtImport.Text, ro);
            string fn = string.Format(@"{0}\{1}.impx", PEIPath, dn);
            if (File.Exists(fn))
            {
							MyImpxZipFile = ZipFile.Read(fn, ro);
							ReadTransitionAndItemContentIDs();
            }
            else
            {
              MyImpxZipFile = new ZipFile(fn, Encoding.UTF8);
              //transitions
              XmlElement xe = PendingTransitions.CreateElement("transitions");
              PendingTransitions.AppendChild(xe);
              fn = PEIPath + @"\transitions.xml";
              PendingTransitions.Save(fn);
              MyImpxZipFile.AddFile(fn, "");
              MyImpxZipFile.Save();
              File.Delete(fn);
              //itemids
              XmlDocument xd = new XmlDocument();
              xe = xd.CreateElement("items");
              xd.AppendChild(xe);
              fn = PEIPath + @"\items.xml";
              xd.Save(fn);
              MyImpxZipFile.AddFile(fn, "");
              MyImpxZipFile.Save();
              File.Delete(fn);
              //contentids
              xd = new XmlDocument();
              xe = xd.CreateElement("contents");
              xd.AppendChild(xe);
              fn = PEIPath + @"\contents.xml";
              xd.Save(fn);
              MyImpxZipFile.AddFile(fn, "");
              MyImpxZipFile.Save();
              File.Delete(fn);
              //libdocids
              xd = new XmlDocument();
              xe = xd.CreateElement("libdocs");
              xd.AppendChild(xe);
              fn = PEIPath + @"\libdocs.xml";
              xd.Save(fn);
              MyImpxZipFile.AddFile(fn, "");
              MyImpxZipFile.Save();
              File.Delete(fn);
            }
          }
        }
      }
      if (MyDocVersion != null)
      {
        ofd.Filter = "PROMS Procedure Export Files|*.pxml";
        if (ofd.ShowDialog(this) == DialogResult.OK)
          txtImport.Text = ofd.FileName;
      }
		}
		private void txtImport_TextChanged(object sender, EventArgs e)
		{
			btnDoImport.Enabled = txtImport.TextLength > 0;
			if (btnDoImport.Enabled)
				lblImportStatus.Text = "Ready To Perform Import";
			else
				lblImportStatus.Text = "Awaiting Import File Name:";
		}
		#region Export for Merge
    private string FromFolderName = string.Empty;
    private void ExportFolder(XmlDocument xd, FolderInfo fi, string nodename)
    {
      /*
      FolderID
      ParentID
      DBID
      Name
      Title
      ShortName
      FormatID
      ManualOrder
      Config
      DTS
      UsrID
      */
      lblExportStatus.Text = "Exporting Folder...";
      Application.DoEvents();
			string formatFileName = (fi.MyFormat != null)? fi.MyFormat.Name:"";
      FromFolderName = fi.Name;
      XmlElement xe = xd.CreateElement(nodename);
      xe.Attributes.SetNamedItem(AddAttribute(xd, "folderid", fi.FolderID.ToString()));
      xe.Attributes.SetNamedItem(AddAttribute(xd, "parentid", fi.ParentID.ToString()));
      xe.Attributes.SetNamedItem(AddAttribute(xd, "dbid", fi.DBID.ToString()));
      xe.Attributes.SetNamedItem(AddAttribute(xd, "name", fi.Name));
      xe.Attributes.SetNamedItem(AddAttribute(xd, "title", fi.Title));
      xe.Attributes.SetNamedItem(AddAttribute(xd, "shortname", fi.ShortName));
      xe.Attributes.SetNamedItem(AddAttribute(xd, "formatid", fi.FormatID.ToString()));
      xe.Attributes.SetNamedItem(AddAttribute(xd, "manualorder", fi.ManualOrder.ToString()));
      xe.Attributes.SetNamedItem(AddAttribute(xd, "config", fi.Config));
      xe.Attributes.SetNamedItem(AddAttribute(xd, "dts", fi.DTS.ToString("MM/dd/yyyy HH:mm:ss.fff")));
      xe.Attributes.SetNamedItem(AddAttribute(xd, "usrid", fi.UsrID.ToString()));
			xe.Attributes.SetNamedItem(AddAttribute(xd, "formatfilename",formatFileName));
      xd.AppendChild(xe);
      ExportAnnotationTypes(xe, "annotationtypes");
      ExportFormats(xe, "formats");
      if (fi.FolderDocVersionCount > 0)
        foreach (DocVersionInfo dvi in fi.FolderDocVersions)
          ExportDocVersion(xe, dvi, "docversion");
    }
    private void ExportFormats(XmlElement xn, string nodename)
    {
      XmlElement xe = xn.OwnerDocument.CreateElement(nodename);
      FormatInfoList fil = FormatInfoList.Get();
      foreach (FormatInfo fi in fil)
        ExportFormat(xe, fi, "format");
      xn.AppendChild(xe);
    }
    private void ExportFormat(XmlElement xn, FormatInfo fi, string nodename)
    {
      XmlElement xe = xn.OwnerDocument.CreateElement(nodename);
      xe.Attributes.SetNamedItem(AddAttribute(xe.OwnerDocument, "formatid", fi.FormatID.ToString()));
      xe.Attributes.SetNamedItem(AddAttribute(xe.OwnerDocument, "name", fi.Name));
      xn.AppendChild(xe);
    }
    private void ExportAnnotationTypes(XmlElement xn, string nodename)
    {
      XmlElement xe = xn.OwnerDocument.CreateElement(nodename);
      AnnotationTypeInfoList atl = AnnotationTypeInfoList.Get();
      foreach (AnnotationTypeInfo ati in atl)
          ExportAnnotationType(xe, ati, "annotationtype");
      xn.AppendChild(xe);
    }
    private void ExportAnnotationType(XmlElement xn, AnnotationTypeInfo ati, string nodename)
    {
      /*
      TypeID
      Name
      Config
      DTS
      UserID
      */
      XmlElement xe = xn.OwnerDocument.CreateElement(nodename);
      xe.Attributes.SetNamedItem(AddAttribute(xe.OwnerDocument, "typeid", ati.TypeID.ToString()));
      xe.Attributes.SetNamedItem(AddAttribute(xe.OwnerDocument, "name", ati.Name));
      xe.Attributes.SetNamedItem(AddAttribute(xe.OwnerDocument, "config", ati.Config));
      xe.Attributes.SetNamedItem(AddAttribute(xe.OwnerDocument, "dts", ati.DTS.ToString("MM/dd/yyyy HH:mm:ss.fff")));
      xe.Attributes.SetNamedItem(AddAttribute(xe.OwnerDocument, "userid", ati.UserID.ToString()));
      xn.AppendChild(xe);
    }

		// jsj 4-29-2016  appears to not be used
		//private void ExportFolder(FolderInfo fi, string nodename)
		//{
		//	/*
		//	FolderID
		//	ParentID
		//	DBID
		//	Name
		//	Title
		//	ShortName
		//	FormatID
		//	ManualOrder
		//	Config
		//	DTS
		//	UsrID
		//	*/
		//	string formatFileName = (fi.MyFormat != null) ? fi.MyFormat.Name : "";
		//	FromFolderName = fi.Name;
		//	MyWriter.WriteStartDocument();
		//	MyWriter.WriteStartElement(nodename);
		//	MyWriter.WriteAttributeString("folderid", fi.FolderID.ToString());
		//	MyWriter.WriteAttributeString("parentid", fi.ParentID.ToString());
		//	MyWriter.WriteAttributeString("dbid", fi.DBID.ToString());
		//	MyWriter.WriteAttributeString("name", fi.Name);
		//	MyWriter.WriteAttributeString("title", fi.Title);
		//	MyWriter.WriteAttributeString("shortname", fi.ShortName);
		//	MyWriter.WriteAttributeString("formatid", fi.FormatID.ToString());
		//	MyWriter.WriteAttributeString("manualorder", fi.ManualOrder.ToString());
		//	MyWriter.WriteAttributeString("config", fi.Config);
		//	MyWriter.WriteAttributeString("dts", fi.DTS.ToString("MM/dd/yyyy HH:mm:ss.fff"));
		//	MyWriter.WriteAttributeString("usrid", fi.UsrID.ToString());
		//	MyWriter.WriteAttributeString("formatfilename", formatFileName);
      
		//	if (fi.FolderDocVersionCount > 0)
		//		foreach (DocVersionInfo dvi in fi.FolderDocVersions)
		//			ExportDocVersion(dvi, "docversion");
		//	MyWriter.WriteEndElement();
		//	MyWriter.WriteEndDocument();
		//}

		// bug fix:  B2017-082 don't export if no RO Path - display an message to the user to assign a RO Path
		private bool ValidDocVersionAssociation(DocVersionInfo dvi)
		{
			if (dvi.DocVersionAssociationCount <= 0)
			{
				MessageBox.Show("Assign a Referenced Object path to the Working Draft tree node before exporting.", "RO Path not assigned");
				successfullExport = false;
				return false;
			}
			return true;
		}
		private void ExportDocVersion(XmlElement xn, DocVersionInfo dvi, string nodename)
		{
			/*
			VersionID
			FolderID
			VersionType
			Name
			Title
			ItemID
			FormatID
			Config
			DTS
			UserID
			*/
			lblExportStatus.Text = "Exporting DocVersion...";
			Application.DoEvents();
			string formatFileName = (dvi.MyFormat != null) ? dvi.MyFormat.Name : "";
			XmlElement xe = xn.OwnerDocument.CreateElement(nodename);
			xe.Attributes.SetNamedItem(AddAttribute(xe.OwnerDocument, "versionid", dvi.VersionID.ToString()));
			xe.Attributes.SetNamedItem(AddAttribute(xe.OwnerDocument, "folderid", dvi.FolderID.ToString()));
			xe.Attributes.SetNamedItem(AddAttribute(xe.OwnerDocument, "versiontype", dvi.VersionType.ToString()));
			xe.Attributes.SetNamedItem(AddAttribute(xe.OwnerDocument, "name", dvi.Name));
			xe.Attributes.SetNamedItem(AddAttribute(xe.OwnerDocument, "title", dvi.Title));
			xe.Attributes.SetNamedItem(AddAttribute(xe.OwnerDocument, "itemid", dvi.ItemID.ToString()));
			xe.Attributes.SetNamedItem(AddAttribute(xe.OwnerDocument, "formatid", dvi.FormatID.ToString()));
			xe.Attributes.SetNamedItem(AddAttribute(xe.OwnerDocument, "config", dvi.Config));
			xe.Attributes.SetNamedItem(AddAttribute(xe.OwnerDocument, "dts", dvi.DTS.ToString("MM/dd/yyyy HH:mm:ss.fff")));
			xe.Attributes.SetNamedItem(AddAttribute(xe.OwnerDocument, "userid", dvi.UserID.ToString()));
			xe.Attributes.SetNamedItem(AddAttribute(xe.OwnerDocument, "formatfilename", formatFileName));
			xn.AppendChild(xe);
			if (!ValidDocVersionAssociation(dvi)) return;  // bug fix:  B2017-082 don't export if no RO Path
			if (dvi.DocVersionAssociationCount > 0)
				foreach (AssociationInfo ai in dvi.DocVersionAssociations)
					ExportAssociation(xe, ai, "association");
			string fn = PEIPath + @"\folder.xml";
			xn.OwnerDocument.Save(fn);
			MyExpxZipFile.AddFile(fn, "folder");
			MyExpxZipFile.Save();
			File.Delete(fn);
			//here
			lblExportStatus.Text = "Exporting Procedures...";
			Application.DoEvents();
			if (dvi.Procedures.Count > 0)
			{
				pbExportProcedure.Value = 0;
				pbExportProcedure.Maximum = dvi.Procedures.Count;
				lblExportProcedure.Text = pbExportProcedure.Maximum.ToString() + " Procedures";
				foreach (ItemInfo ii in dvi.Procedures)
				{
					XmlDocument xd = new XmlDocument();
					ExportItem(xd, ii, "procedure");
					fn = string.Format(@"{0}\proc{1}.xml", PEIPath, pbExportProcedure.Value.ToString().PadLeft(4, '0'));
					xd.Save(fn);
					MyExpxZipFile.AddFile(fn, "procedures");
					MyExpxZipFile.Save();
					File.Delete(fn);
					xd = null;
				}
			}
		}
    private void ExportDocVersion(DocVersionInfo dvi, string nodename)
		{
			/*
			VersionID
			FolderID
			VersionType
			Name
			Title
			ItemID
			FormatID
			Config
			DTS
			UserID
			*/
			string formatFileName = (dvi.MyFormat != null) ? dvi.MyFormat.Name : "";
			MyWriter.WriteStartElement(nodename);
			MyWriter.WriteAttributeString("versionid", dvi.VersionID.ToString());
			MyWriter.WriteAttributeString("folderid", dvi.FolderID.ToString());
			MyWriter.WriteAttributeString("versiontype", dvi.VersionType.ToString());
			MyWriter.WriteAttributeString("name", dvi.Name);
			MyWriter.WriteAttributeString("title", dvi.Title);
			MyWriter.WriteAttributeString("itemid", dvi.ItemID.ToString());
			MyWriter.WriteAttributeString("formatid", dvi.FormatID.ToString());
			MyWriter.WriteAttributeString("config", dvi.Config);
			MyWriter.WriteAttributeString("dts", dvi.DTS.ToString("MM/dd/yyyy HH:mm:ss.fff"));
			MyWriter.WriteAttributeString("userid", dvi.UserID.ToString());
			MyWriter.WriteAttributeString("formatfilename", formatFileName);
      if (dvi.DocVersionAssociationCount > 0)
        foreach (AssociationInfo ai in dvi.DocVersionAssociations)
          ExportAssociation(ai, "association");
			if (dvi.Procedures.Count > 0)
			{
				pbExportProcedure.Value = 0;
				pbExportProcedure.Maximum = dvi.Procedures.Count;
				lblExportProcedure.Text = pbExportProcedure.Maximum.ToString() + " Procedures";
				foreach (ItemInfo ii in dvi.Procedures)
				{
					ExportItem(ii, "procedure");
				}
			}
			MyWriter.WriteEndElement();
		}
    private void ExportAssociation(XmlElement xn, AssociationInfo ai, string nodename)
    {
      /*
      AssociationID
      VersionID
      ROFstID
      Config
      DTS
      UserID
      */
      lblExportStatus.Text = "Exporting Association...";
      Application.DoEvents();
      XmlElement xe = xn.OwnerDocument.CreateElement(nodename);
      xe.Attributes.SetNamedItem(AddAttribute(xe.OwnerDocument, "associationid", ai.AssociationID.ToString()));
      xe.Attributes.SetNamedItem(AddAttribute(xe.OwnerDocument, "versionid", ai.VersionID.ToString()));
      xe.Attributes.SetNamedItem(AddAttribute(xe.OwnerDocument, "rofstid", ai.ROFstID.ToString()));
      xe.Attributes.SetNamedItem(AddAttribute(xe.OwnerDocument, "config", ai.Config));
      xe.Attributes.SetNamedItem(AddAttribute(xe.OwnerDocument, "dts", ai.DTS.ToString("MM/dd/yyyy HH:mm:ss.fff")));
      xe.Attributes.SetNamedItem(AddAttribute(xe.OwnerDocument, "userid", ai.UserID.ToString()));
      xn.AppendChild(xe);
      ExportROFst(xe, ai.MyROFst, "rofst");
    }
    private void ExportAssociation(AssociationInfo ai, string nodename)
		{
			/*
			AssociationID
			VersionID
			ROFstID
			Config
			DTS
			UserID
			*/
			MyWriter.WriteStartElement(nodename);
			MyWriter.WriteAttributeString("associationid", ai.AssociationID.ToString());
			MyWriter.WriteAttributeString("versionid", ai.VersionID.ToString());
			MyWriter.WriteAttributeString("rofstid", ai.ROFstID.ToString());
			MyWriter.WriteAttributeString("config", ai.Config);
			MyWriter.WriteAttributeString("dts", ai.DTS.ToString("MM/dd/yyyy HH:mm:ss.fff"));
			MyWriter.WriteAttributeString("userid", ai.UserID.ToString());
			ExportROFst(ai.MyROFst, "rofst");
			MyWriter.WriteEndElement();
		}
    private void ExportROFst(XmlElement xn, ROFstInfo fst, string nodename)
    {
      /*
      ROFstID
      RODbID
      ROLookup
      Config
      DTS
      UserID
      */
      lblExportStatus.Text = "Exporting ROFst...";
      Application.DoEvents();
      XmlElement xe = xn.OwnerDocument.CreateElement(nodename);
      xe.Attributes.SetNamedItem(AddAttribute(xe.OwnerDocument, "rofstid", fst.ROFstID.ToString()));
      xe.Attributes.SetNamedItem(AddAttribute(xe.OwnerDocument, "rodbid", fst.RODbID.ToString()));
      xe.Attributes.SetNamedItem(AddAttribute(xe.OwnerDocument, "rolookup", Convert.ToBase64String(fst.ROLookup)));
      xe.Attributes.SetNamedItem(AddAttribute(xe.OwnerDocument, "config", fst.Config));
      xe.Attributes.SetNamedItem(AddAttribute(xe.OwnerDocument, "dts", fst.DTS.ToString("MM/dd/yyyy HH:mm:ss.fff")));
      xe.Attributes.SetNamedItem(AddAttribute(xe.OwnerDocument, "userid", fst.UserID.ToString()));
      xn.AppendChild(xe);
			ExportFigures(xe, fst);
      ExportRODb(xe, fst.MyRODb, "rodb");
    }
    private void ExportROFst(ROFstInfo fst, string nodename)
		{
			/*
			ROFstID
			RODbID
			ROLookup
			Config
			DTS
			UserID
			*/
			MyWriter.WriteStartElement(nodename);
			MyWriter.WriteAttributeString("rofstid", fst.ROFstID.ToString());
			MyWriter.WriteAttributeString("rodbid", fst.RODbID.ToString());
			MyWriter.WriteAttributeString("rolookup", Convert.ToBase64String(fst.ROLookup));
			MyWriter.WriteAttributeString("config", fst.Config);
			MyWriter.WriteAttributeString("dts", fst.DTS.ToString("MM/dd/yyyy HH:mm:ss.fff"));
			MyWriter.WriteAttributeString("userid", fst.UserID.ToString());
			ExportRODb(fst.MyRODb, "rodb");
			MyWriter.WriteEndElement();
		}
		private void ExportFigures(XmlElement xn, ROFstInfo fst)
		{
			if (fst.ROFstFigureCount > 0)
			{
				XmlElement xe = xn.OwnerDocument.CreateElement("figures");
				xn.AppendChild(xe);
				foreach (FigureInfo figure in fst.ROFstFigures)
				{
					XmlElement xee = xn.OwnerDocument.CreateElement("figure");
					xee.Attributes.SetNamedItem(AddAttribute(xee.OwnerDocument, "figureid", figure.FigureID.ToString()));
					xee.Attributes.SetNamedItem(AddAttribute(xee.OwnerDocument, "rofstid", figure.ROFstID.ToString()));
					xee.Attributes.SetNamedItem(AddAttribute(xee.OwnerDocument, "imageid", figure.ImageID.ToString()));
					xee.Attributes.SetNamedItem(AddAttribute(xee.OwnerDocument, "config", figure.Config));
					xee.Attributes.SetNamedItem(AddAttribute(xee.OwnerDocument, "dts", figure.DTS.ToString("MM/dd/yyyy HH:mm:ss.fff")));
					xee.Attributes.SetNamedItem(AddAttribute(xee.OwnerDocument, "userid", figure.UserID));
					xe.AppendChild(xee);
					ExportROImage(xee, figure.MyROImage);
				}
			}
		}
		private void ExportROImage(XmlElement xn, ROImageInfo image)
		{
			XmlElement xe = xn.OwnerDocument.CreateElement("image");
			xe.Attributes.SetNamedItem(AddAttribute(xe.OwnerDocument, "imageid", image.ImageID.ToString()));
			xe.Attributes.SetNamedItem(AddAttribute(xe.OwnerDocument, "rodbid", image.RODbID.ToString()));
			xe.Attributes.SetNamedItem(AddAttribute(xe.OwnerDocument, "filename", image.FileName));
			xe.Attributes.SetNamedItem(AddAttribute(xe.OwnerDocument, "content", Convert.ToBase64String(image.Content)));
			xe.Attributes.SetNamedItem(AddAttribute(xe.OwnerDocument, "config", image.Config));
			xe.Attributes.SetNamedItem(AddAttribute(xe.OwnerDocument, "dts", image.DTS.ToString("MM/dd/yyyy HH:mm:ss.fff")));
			xe.Attributes.SetNamedItem(AddAttribute(xe.OwnerDocument, "userid", image.UserID));
			xn.AppendChild(xe);
		}
    private void ExportRODb(XmlElement xn, RODbInfo db, string nodename)
    {
      /*
      RODbID
      ROName
      FolderPath
      DBConnectionString
      Config
      DTS
      UserID
      */
      lblExportStatus.Text = "Exporting RODb...";
      Application.DoEvents();
      XmlElement xe = xn.OwnerDocument.CreateElement(nodename);
      xe.Attributes.SetNamedItem(AddAttribute(xe.OwnerDocument, "rodbid", db.RODbID.ToString()));
      xe.Attributes.SetNamedItem(AddAttribute(xe.OwnerDocument, "roname", db.ROName));
      xe.Attributes.SetNamedItem(AddAttribute(xe.OwnerDocument, "folderpath", db.FolderPath));
      xe.Attributes.SetNamedItem(AddAttribute(xe.OwnerDocument, "dbconnectionstring", db.DBConnectionString));
      xe.Attributes.SetNamedItem(AddAttribute(xe.OwnerDocument, "config", db.Config));
      xe.Attributes.SetNamedItem(AddAttribute(xe.OwnerDocument, "dts", db.DTS.ToString("MM/dd/yyyy HH:mm:ss.fff")));
      xe.Attributes.SetNamedItem(AddAttribute(xe.OwnerDocument, "userid", db.UserID.ToString()));
      xn.AppendChild(xe);
    }
    private void ExportRODb(RODbInfo db, string nodename)
		{
			/*
			RODbID
			ROName
			FolderPath
			DBConnectionString
			Config
			DTS
			UserID
			*/
			MyWriter.WriteStartElement(nodename);
			MyWriter.WriteAttributeString("rodbid", db.RODbID.ToString());
			MyWriter.WriteAttributeString("roname", db.ROName);
			MyWriter.WriteAttributeString("folderpath", db.FolderPath);
			MyWriter.WriteAttributeString("dbconnectionstring", db.DBConnectionString);
			MyWriter.WriteAttributeString("config", db.Config);
			MyWriter.WriteAttributeString("dts", db.DTS.ToString("MM/dd/yyyy HH:mm:ss.fff"));
			MyWriter.WriteAttributeString("userid", db.UserID.ToString());
			MyWriter.WriteEndElement();
		}

    public void ExportItem(XmlDocument xd, ItemInfo ii, string nodename)
    {
      XmlElement xe = xd.CreateElement(nodename);
			if (ii.IsProcedure)
			{
				xe.Attributes.SetNamedItem(AddAttribute(xe.OwnerDocument, "rodbid", ii.MyDocVersion.DocVersionAssociations[0].MyROFst.MyRODb.RODbID.ToString()));
				xe.Attributes.SetNamedItem(AddAttribute(xe.OwnerDocument, "rofolderpath", ii.MyDocVersion.DocVersionAssociations[0].MyROFst.MyRODb.FolderPath));
				xe.Attributes.SetNamedItem(AddAttribute(xe.OwnerDocument, "rofstid", ii.MyDocVersion.DocVersionAssociations[0].MyROFst.ROFstID.ToString()));
				xe.Attributes.SetNamedItem(AddAttribute(xe.OwnerDocument, "rofstdts", ii.MyDocVersion.DocVersionAssociations[0].MyROFst.DTS.ToString("MM/dd/yyyy HH:mm:ss.fff")));
			}
      xd.AppendChild(xe);
      ExportItem(xe, ii, nodename);
    }
    private void ExportItem(XmlElement xn, ItemInfo ii, string nodename)
    {
      /*
      ItemID
      PreviousID
      ContentID
      DTS
      */
      XmlElement xe = null;
      if (xn.Name == "procedure")
        xe = xn;
      else
      {
        xe = xn.OwnerDocument.CreateElement(nodename);
        xn.AppendChild(xe);
      }
      if (ii.IsProcedure)
      {
        pbExportProcedure.PerformStep();
        lblExportProcedure.Text = string.Format("{0} of {1} Procedures", pbExportProcedure.Value.ToString(), pbExportProcedure.Maximum.ToString());
        TimeSpan elapsed = DateTime.Now.Subtract(MyStart);
        lblExportTime.Text = "Elapsed Time: " + elapsed.ToString();
        Application.DoEvents();
        pbExportSection.Value = 0;
        pbExportSection.Maximum = pbExportSection.Value;
        pbExportStep.Value = 0;
        pbExportStep.Maximum = pbExportStep.Value;
        if(ii.Sections != null)
          pbExportSection.Maximum = ii.Sections.Count;
				else
				{
					pbExportSection.Maximum = 1;
					pbExportSection.PerformStep();
					pbExportStep.Maximum = 1;
					pbExportStep.PerformStep();
					lblExportSection.Text = "Sections";
					lblExportStep.Text = "Steps";
					Application.DoEvents();
				}
			}
      if (ii.IsSection && ii.ActiveParent.IsProcedure)
      {
        pbExportSection.PerformStep();
        lblExportSection.Text = string.Format("{0} of {1} Sections", pbExportSection.Value.ToString(), pbExportSection.Maximum.ToString());
        Application.DoEvents();
        pbExportStep.Value = 0;
        pbExportStep.Maximum = pbExportStep.Value;
				if (ii.Steps != null)
					pbExportStep.Maximum = ii.Steps.Count;
				else
				{
					pbExportStep.Maximum = 1;
					pbExportStep.PerformStep();
					lblExportStep.Text = "Word Section Data";
					Application.DoEvents();
				}
      }
      if (ii.IsStep && ii.ActiveParent.IsSection && ii.ActiveParent.ActiveParent.IsProcedure)
      {
        pbExportStep.PerformStep();
        lblExportStep.Text = string.Format("{0} of {1} Steps", pbExportStep.Value.ToString(), pbExportStep.Maximum.ToString());
				Application.DoEvents();
      }
      xe.Attributes.SetNamedItem(AddAttribute(xe.OwnerDocument, "itemid", ii.ItemID.ToString()));
      xe.Attributes.SetNamedItem(AddAttribute(xe.OwnerDocument, "previousid", ii.PreviousID.ToString()));
      xe.Attributes.SetNamedItem(AddAttribute(xe.OwnerDocument, "contentid", ii.ContentID.ToString()));
      xe.Attributes.SetNamedItem(AddAttribute(xe.OwnerDocument, "dts", ii.DTS.ToString("MM/dd/yyyy HH:mm:ss.fff")));
      //item audits
      ExportItemAudits(xe, ii);
      ExportContent(xe, ii.MyContent, "content");
      if (ii.ItemAnnotationCount > 0)
        foreach (AnnotationInfo ai in ii.ItemAnnotations)
          ExportAnnotation(xe, ai, "annotation");
    }
    private void ExportItemAudits(XmlElement xn, ItemInfo ii)
    {
      if (cbxExportAudits.Checked)
      {
        ItemAuditInfoList audits = ItemAuditInfoList.Get(ii.ItemID);
        if (audits.Count > 0)
        {
          XmlElement xe = xn.OwnerDocument.CreateElement("audits");
          foreach (ItemAuditInfo audit in audits)
          {
            if (audit.DeleteStatus == 0)
            {
              XmlElement xee = xn.OwnerDocument.CreateElement("audit");
              xee.Attributes.SetNamedItem(AddAttribute(xee.OwnerDocument, "auditid", audit.AuditID.ToString()));
              xee.Attributes.SetNamedItem(AddAttribute(xee.OwnerDocument, "contentid", audit.ContentID.ToString()));
              xee.Attributes.SetNamedItem(AddAttribute(xee.OwnerDocument, "deletestatus", audit.DeleteStatus.ToString()));
              xee.Attributes.SetNamedItem(AddAttribute(xee.OwnerDocument, "dts", audit.DTS.ToString("MM/dd/yyyy HH:mm:ss.fff")));
              xee.Attributes.SetNamedItem(AddAttribute(xee.OwnerDocument, "itemid", audit.ItemID.ToString()));
              xee.Attributes.SetNamedItem(AddAttribute(xee.OwnerDocument, "previousid", audit.PreviousID.ToString()));
              xee.Attributes.SetNamedItem(AddAttribute(xee.OwnerDocument, "userid", audit.UserID));
              xe.AppendChild(xee);
            }
          }
          xn.AppendChild(xe);
        }
      }
    }
		// used to save word sections with resolved ROs (export generated from Approve)
		private Dictionary<int, byte[]> _DocReplace;
		public Dictionary<int, byte[]> DocReplace
		{
			get { return _DocReplace; }
			set 
			{
				_DocReplace = value;
				_ConvertROsAndTransitionsToText = (value != null);
			}
		}
    private void ExportItem(ItemInfo ii, string nodename)
		{
			/*
			ItemID
			PreviousID
			ContentID
			DTS
			*/
			if (ii.IsProcedure)
			{
				pbExportProcedure.PerformStep();
				lblExportProcedure.Text = string.Format("{0} of {1} Procedures", pbExportProcedure.Value.ToString(), pbExportProcedure.Maximum.ToString());
				Application.DoEvents();
				pbExportSection.Value = 0;
				pbExportStep.Value = 0;
				pbExportSection.Maximum = ii.Sections.Count;
				if (ii.Sections != null)
					pbExportSection.Maximum = ii.Sections.Count;
				else
				{
					pbExportSection.Maximum = 1;
					pbExportSection.PerformStep();
					pbExportStep.Maximum = 1;
					pbExportStep.PerformStep();
					lblExportSection.Text = "Sections";
					lblExportStep.Text = "Steps";
					Application.DoEvents();
				}
			}
			if (ii.IsSection)
			{
				pbExportSection.PerformStep();
				lblExportSection.Text = string.Format("{0} of {1} Sections", pbExportSection.Value.ToString(), pbExportSection.Maximum.ToString());
				Application.DoEvents();
				pbExportStep.Value = 0;
				if (ii.Steps != null)
					pbExportStep.Maximum = ii.Steps.Count;
				else
				{
					pbExportStep.Maximum = 1;
					pbExportStep.PerformStep();
					lblExportStep.Text = "Word Section Data";
					Application.DoEvents();
				}
			}
			if (ii.IsStep)
			{
				pbExportStep.PerformStep();
				lblExportStep.Text = string.Format("{0} of {1} Steps", pbExportStep.Value.ToString(), pbExportStep.Maximum.ToString());
				Application.DoEvents();
			}
			MyWriter.WriteStartElement(nodename);
			MyWriter.WriteAttributeString("itemid", ii.ItemID.ToString());
			MyWriter.WriteAttributeString("previousid", ii.PreviousID.ToString());
			MyWriter.WriteAttributeString("contentid", ii.ContentID.ToString());
			MyWriter.WriteAttributeString("dts", ii.DTS.ToString("MM/dd/yyyy HH:mm:ss.fff"));
			ExportContent(ii.MyContent, "content");
			if (ii.ItemAnnotationCount > 0)
				foreach (AnnotationInfo ai in ii.ItemAnnotations)
					ExportAnnotation(ai, "annotation");
			MyWriter.WriteEndElement();
		}
    private void ExportContent(XmlElement xn, ContentInfo ci, string nodename)
    {
      /*
      ContentID
      Number
      Text
      Type
      FormatID
      Config
      DTS
      UserID
      */
      XmlElement xe = xn.OwnerDocument.CreateElement(nodename);
			// strip the link information if we are convertingthe RO and Transitions to text
			string ciText = (_ConvertROsAndTransitionsToText)?ItemInfo.StripLinks(ci.Text):ci.Text;
			string formatFileName = (ci.MyFormat != null) ? ci.MyFormat.Name : "";
      xe.Attributes.SetNamedItem(AddAttribute(xe.OwnerDocument, "contentid", ci.ContentID.ToString()));
      xe.Attributes.SetNamedItem(AddAttribute(xe.OwnerDocument, "number", ci.Number));
      xe.Attributes.SetNamedItem(AddAttribute(xe.OwnerDocument, "text", ciText));
      xe.Attributes.SetNamedItem(AddAttribute(xe.OwnerDocument, "type", ci.Type.ToString()));
      xe.Attributes.SetNamedItem(AddAttribute(xe.OwnerDocument, "formatid", ci.FormatID.ToString()));
      xe.Attributes.SetNamedItem(AddAttribute(xe.OwnerDocument, "config", ci.Config));
      xe.Attributes.SetNamedItem(AddAttribute(xe.OwnerDocument, "dts", ci.DTS.ToString("MM/dd/yyyy HH:mm:ss.fff")));
      xe.Attributes.SetNamedItem(AddAttribute(xe.OwnerDocument, "userid", ci.UserID.ToString()));
      xe.Attributes.SetNamedItem(AddAttribute(xe.OwnerDocument, "formatfilename", formatFileName));
      //content audits
      ExportContentAudits(xe, ci);
      xn.AppendChild(xe);
      if (ci.ContentTransitionCount > 0)
        foreach (TransitionInfo ti in ci.ContentTransitions)
          ExportTransition(xe, ti, "transition");
      if (ci.ContentRoUsageCount > 0)
        foreach (RoUsageInfo ri in ci.ContentRoUsages)
          ExportROUsage(xe, ri, "rousage");
      if (ci.ContentEntryCount > 0)
        ExportEntry(xe, ci.MyEntry, "entry");
      if (ci.ContentGridCount > 0)
        ExportGrid(xe, ci.MyGrid, "grid");
			if (ci.ContentImageCount > 0)
				ExportImage(xe, ci.MyImage, "image");
      if (ci.ContentPartCount > 0)
        foreach (PartInfo pi in ci.ContentParts)
          ExportPart(xe, pi, ((E_FromTypes)pi.FromType).ToString().ToLower());
    }
    private void ExportContentAudits(XmlElement xn, ContentInfo ci)
    {
      if (cbxExportAudits.Checked)
      {
        ContentAuditInfoList audits = ContentAuditInfoList.Get(ci.ContentID);
        if (audits.Count > 0)
        {
          XmlElement xe = xn.OwnerDocument.CreateElement("audits");
          foreach (ContentAuditInfo audit in audits)
          {
            if (audit.DeleteStatus == 0)
            {
              XmlElement xee = xn.OwnerDocument.CreateElement("audit");
              xee.Attributes.SetNamedItem(AddAttribute(xee.OwnerDocument, "auditid", audit.AuditID.ToString()));
              xee.Attributes.SetNamedItem(AddAttribute(xee.OwnerDocument, "contentid", audit.ContentID.ToString()));
              xee.Attributes.SetNamedItem(AddAttribute(xee.OwnerDocument, "number", audit.Number));
              xee.Attributes.SetNamedItem(AddAttribute(xee.OwnerDocument, "text", audit.Text));
              xee.Attributes.SetNamedItem(AddAttribute(xee.OwnerDocument, "type", audit.Type.ToString()));
              xee.Attributes.SetNamedItem(AddAttribute(xee.OwnerDocument, "formatid", audit.FormatID.ToString()));
              xee.Attributes.SetNamedItem(AddAttribute(xee.OwnerDocument, "config", audit.Config));
              xee.Attributes.SetNamedItem(AddAttribute(xee.OwnerDocument, "dts", audit.DTS.ToString("MM/dd/yyyy HH:mm:ss.fff")));
              xee.Attributes.SetNamedItem(AddAttribute(xee.OwnerDocument, "userid", audit.UserID));
              xee.Attributes.SetNamedItem(AddAttribute(xee.OwnerDocument, "deletestatus", audit.DeleteStatus.ToString()));
              xee.Attributes.SetNamedItem(AddAttribute(xee.OwnerDocument, "actiondts", audit.ActionWhen.ToString("MM/dd/yyyy HH:mm:ss.fff")));
              xe.AppendChild(xee);
            }
          }
        }
      }
    }
    private void ExportContent(ContentInfo ci, string nodename)
		{
			/*
			ContentID
			Number
			Text
			Type
			FormatID
			Config
			DTS
			UserID
			*/
			// strip the link information if we are convertinga the ROs and Transitions to text
			string ciText = (_ConvertROsAndTransitionsToText) ? ItemInfo.StripLinks(ci.Text) : ci.Text;
			string formatFileName = (ci.MyFormat != null) ? ci.MyFormat.Name : "";
			MyWriter.WriteStartElement(nodename);
			MyWriter.WriteAttributeString("contentid", ci.ContentID.ToString());
			MyWriter.WriteAttributeString("number", ci.Number);
			MyWriter.WriteAttributeString("text", ciText);
			MyWriter.WriteAttributeString("type", ci.Type.ToString());
			MyWriter.WriteAttributeString("formatid", ci.FormatID.ToString());
			MyWriter.WriteAttributeString("config", ci.Config);
			MyWriter.WriteAttributeString("dts", ci.DTS.ToString("MM/dd/yyyy HH:mm:ss.fff"));
			MyWriter.WriteAttributeString("userid", ci.UserID.ToString());
			MyWriter.WriteAttributeString("formatfilename", formatFileName);
			if (ci.ContentTransitionCount > 0)
				foreach (TransitionInfo ti in ci.ContentTransitions)
					ExportTransition(ti, "transition");
			if (ci.ContentRoUsageCount > 0)
				foreach (RoUsageInfo ri in ci.ContentRoUsages)
					ExportROUsage(ri, "rousage");
			if (ci.ContentEntryCount > 0)
				ExportEntry(ci.MyEntry, "entry");
			if (ci.ContentGridCount > 0)
				ExportGrid(ci.MyGrid, "grid");
			if (ci.ContentImageCount > 0)
				ExportImage(ci.MyImage, "image");
			if (ci.ContentPartCount > 0)
				foreach (PartInfo pi in ci.ContentParts)
					ExportPart(pi, ((E_FromTypes)pi.FromType).ToString().ToLower());
			MyWriter.WriteEndElement();
		}
    private void ExportGrid(XmlElement xn, GridInfo gi, string nodename)
    {
      /*
      ContentID
      Data
      Config
      DTS
      UserID
      */
			string giData = gi.Data;
			if (_ConvertROsAndTransitionsToText)
			{
				giData = giData.Replace("<IsRoTable>True", "<IsRoTable>False"); // converts a RO table to a unlinked regular table
				giData = ItemInfo.StripLinks(giData); // this converts ROs and transitions to text
			}
      XmlElement xe = xn.OwnerDocument.CreateElement(nodename);
      xe.Attributes.SetNamedItem(AddAttribute(xe.OwnerDocument, "contentid", gi.ContentID.ToString()));
      xe.Attributes.SetNamedItem(AddAttribute(xe.OwnerDocument, "data", giData));
      xe.Attributes.SetNamedItem(AddAttribute(xe.OwnerDocument, "config", gi.Config));
      xe.Attributes.SetNamedItem(AddAttribute(xe.OwnerDocument, "dts", gi.DTS.ToString("MM/dd/yyyy HH:mm:ss.fff")));
      xe.Attributes.SetNamedItem(AddAttribute(xe.OwnerDocument, "userid", gi.UserID.ToString()));
      //grid audits
      ExportGridAudits(xe, gi);
      xn.AppendChild(xe);
    }
    private void ExportGridAudits(XmlElement xn, GridInfo gi)
    {
      if (cbxExportAudits.Checked)
      {
        GridAuditInfoList audits = GridAuditInfoList.Get(gi.ContentID);
        if (audits.Count > 0)
        {
          XmlElement xe = xn.OwnerDocument.CreateElement("audits");
          foreach (GridAuditInfo audit in audits)
          {
            if (audit.DeleteStatus == 0)
            {
              XmlElement xee = xn.OwnerDocument.CreateElement("audit");
              xee.Attributes.SetNamedItem(AddAttribute(xee.OwnerDocument, "auditid", audit.AuditID.ToString()));
              xee.Attributes.SetNamedItem(AddAttribute(xee.OwnerDocument, "contentid", audit.ContentID.ToString()));
              xee.Attributes.SetNamedItem(AddAttribute(xee.OwnerDocument, "data", audit.Data));
              xee.Attributes.SetNamedItem(AddAttribute(xee.OwnerDocument, "config", audit.Config));
              xee.Attributes.SetNamedItem(AddAttribute(xee.OwnerDocument, "dts", audit.DTS.ToString("MM/dd/yyyy HH:mm:ss.fff")));
              xee.Attributes.SetNamedItem(AddAttribute(xee.OwnerDocument, "userid", audit.UserID));
              xee.Attributes.SetNamedItem(AddAttribute(xee.OwnerDocument, "deletestatus", audit.DeleteStatus.ToString()));
              xee.Attributes.SetNamedItem(AddAttribute(xee.OwnerDocument, "contentauditid", audit.ContentAuditID.ToString()));
              xe.AppendChild(xee);

            }
          }
        }
      }
    }
    private void ExportGrid(GridInfo gi, string nodename)
		{
			/*
			ContentID
			Data
			Config
			DTS
			UserID
			*/
			string giData = gi.Data;
			if (_ConvertROsAndTransitionsToText)
			{
				giData = giData.Replace("IsRoTable&gtTrue", "IsRoTable&gt;False"); // converts a RO table to regular table
				giData = ItemInfo.StripLinks(giData); // converts ROs and Transitions to text
			}
			MyWriter.WriteStartElement(nodename);
			MyWriter.WriteAttributeString("contentid", gi.ContentID.ToString());
			MyWriter.WriteAttributeString("data", giData);
			MyWriter.WriteAttributeString("config", gi.Config);
			MyWriter.WriteAttributeString("dts", gi.DTS.ToString("MM/dd/yyyy HH:mm:ss.fff"));
			MyWriter.WriteAttributeString("userid", gi.UserID.ToString());
			MyWriter.WriteEndElement();
		}
		private void ExportEntry(XmlElement xn, EntryInfo ei, string nodename)
		{
			/*
			ContentID
			DocID
			DTS
			UserID
			*/
			XmlElement xe = xn.OwnerDocument.CreateElement(nodename);
			xe.Attributes.SetNamedItem(AddAttribute(xe.OwnerDocument, "contentid", ei.ContentID.ToString()));
			xe.Attributes.SetNamedItem(AddAttribute(xe.OwnerDocument, "docid", ei.DocID.ToString()));
			xe.Attributes.SetNamedItem(AddAttribute(xe.OwnerDocument, "dts", ei.DTS.ToString("MM/dd/yyyy HH:mm:ss.fff")));
			xe.Attributes.SetNamedItem(AddAttribute(xe.OwnerDocument, "userid", ei.UserID.ToString()));
			//entry audits
			ExportEntryAudits(xe, ei);
			xn.AppendChild(xe);
			ExportDocument(xe, ei.MyDocument, "document");
		}
    private void ExportEntryAudits(XmlElement xn, EntryInfo ei)
    {
      if (cbxExportAudits.Checked)
      {
        EntryAuditInfoList audits = EntryAuditInfoList.Get(ei.ContentID);
        if (audits.Count > 0)
        {
          XmlElement xe = xn.OwnerDocument.CreateElement("audits");
          foreach (EntryAuditInfo audit in audits)
          {
            if (audit.DeleteStatus == 0)
            {
              XmlElement xee = xn.OwnerDocument.CreateElement("audit");
              xee.Attributes.SetNamedItem(AddAttribute(xee.OwnerDocument, "auditid", audit.AuditID.ToString()));
              xee.Attributes.SetNamedItem(AddAttribute(xee.OwnerDocument, "contentid", audit.ContentID.ToString()));
              xee.Attributes.SetNamedItem(AddAttribute(xee.OwnerDocument, "docid", audit.DocID.ToString()));
              xee.Attributes.SetNamedItem(AddAttribute(xee.OwnerDocument, "dts", audit.DTS.ToString("MM/dd/yyyy HH:mm:ss.fff")));
              xee.Attributes.SetNamedItem(AddAttribute(xee.OwnerDocument, "userid", audit.UserID));
              xee.Attributes.SetNamedItem(AddAttribute(xee.OwnerDocument, "deletestatus", audit.DeleteStatus.ToString()));
              xe.AppendChild(xee);
            }
          }
        }
      }
    }
    private void ExportEntry(EntryInfo ei, string nodename)
		{
			/*
			ContentID
			DocID
			DTS
			UserID
			*/
			MyWriter.WriteStartElement(nodename);
			MyWriter.WriteAttributeString("contentid", ei.ContentID.ToString());
			MyWriter.WriteAttributeString("docid", ei.DocID.ToString());
			MyWriter.WriteAttributeString("dts", ei.DTS.ToString("MM/dd/yyyy HH:mm:ss.fff"));
			MyWriter.WriteAttributeString("userid", ei.UserID.ToString());
			ExportDocument(ei.MyDocument, "document");
			MyWriter.WriteEndElement();
		}
		private void ExportImage(XmlElement xn, ImageInfo ii, string nodename)
		{
			/*
			ContentID
			ImageType
			FileName
			Data
			Config
			DTS
			UserID
			*/
			XmlElement xe = xn.OwnerDocument.CreateElement(nodename);
			xe.Attributes.SetNamedItem(AddAttribute(xe.OwnerDocument, "contentid", ii.ContentID.ToString()));
			xe.Attributes.SetNamedItem(AddAttribute(xe.OwnerDocument, "imagetype", ii.ImageType.ToString()));
			xe.Attributes.SetNamedItem(AddAttribute(xe.OwnerDocument, "filename", ii.FileName));
			xe.Attributes.SetNamedItem(AddAttribute(xe.OwnerDocument, "data", Convert.ToBase64String(ii.Data)));
			xe.Attributes.SetNamedItem(AddAttribute(xe.OwnerDocument, "config", ii.Config));
			xe.Attributes.SetNamedItem(AddAttribute(xe.OwnerDocument, "dts", ii.DTS.ToString("MM/dd/yyyy HH:mm:ss.fff")));
			xe.Attributes.SetNamedItem(AddAttribute(xe.OwnerDocument, "userid", ii.UserID.ToString()));
			//image audits
			ExportImageAudits(xe, ii);
			xn.AppendChild(xe);
		}
		private void ExportImageAudits(XmlElement xn, ImageInfo ii)
		{
			if (cbxExportAudits.Checked)
			{
				ImageAuditInfoList audits = ImageAuditInfoList.Get(ii.ContentID);
				if (audits.Count > 0)
				{
					XmlElement xe = xn.OwnerDocument.CreateElement("audits");
					foreach (ImageAuditInfo audit in audits)
					{
						if (audit.DeleteStatus == 0)
						{
							XmlElement xee = xn.OwnerDocument.CreateElement("audit");
							xee.Attributes.SetNamedItem(AddAttribute(xee.OwnerDocument, "auditid", audit.AuditID.ToString()));
							xee.Attributes.SetNamedItem(AddAttribute(xee.OwnerDocument, "contentid", audit.ContentID.ToString()));
							xee.Attributes.SetNamedItem(AddAttribute(xee.OwnerDocument, "imagetype", audit.ImageType.ToString()));
							xee.Attributes.SetNamedItem(AddAttribute(xee.OwnerDocument, "filename", audit.FileName));
							xee.Attributes.SetNamedItem(AddAttribute(xee.OwnerDocument, "data", Convert.ToBase64String(audit.Data)));
							xee.Attributes.SetNamedItem(AddAttribute(xee.OwnerDocument, "config", audit.Config));
							xee.Attributes.SetNamedItem(AddAttribute(xee.OwnerDocument, "dts", audit.DTS.ToString("MM/dd/yyyy HH:mm:ss.fff")));
							xee.Attributes.SetNamedItem(AddAttribute(xee.OwnerDocument, "userid", audit.UserID));
							xee.Attributes.SetNamedItem(AddAttribute(xee.OwnerDocument, "deletestatus", audit.DeleteStatus.ToString()));
							xe.AppendChild(xee);
						}
					}
				}
			}
		}
		private void ExportImage(ImageInfo ii, string nodename)
		{
			/*
			ContentID
			ImageType
			FileName
			Data
			Config
			DTS
			UserID
			*/
			MyWriter.WriteStartElement(nodename);
			MyWriter.WriteAttributeString("contentid", ii.ContentID.ToString());
			MyWriter.WriteAttributeString("imagetype", ii.ImageType.ToString());
			MyWriter.WriteAttributeString("filename", ii.FileName);
			MyWriter.WriteAttributeString("data", Convert.ToBase64String(ii.Data));
			MyWriter.WriteAttributeString("config", ii.Config);
			MyWriter.WriteAttributeString("dts", ii.DTS.ToString("MM/dd/yyyy HH:mm:ss.fff"));
			MyWriter.WriteAttributeString("userid", ii.UserID.ToString());
			MyWriter.WriteEndElement();
		}
    private void ExportDocument(XmlElement xn, DocumentInfo di, string nodename)
    {
      /*
      DocID
      LibTitle
      DocContent
      DocAscii
      Config
      DTS
      UserID
      FileExtension
      */
			byte[] buf = di.DocContent;
			string libDocTitle = di.LibTitle;
			if (DocReplace != null && DocReplace.ContainsKey(di.DocID) && _ConvertROsAndTransitionsToText)
			{
				buf = DocReplace[di.DocID];
				libDocTitle = null;  // unlink the word section from the library document
			}
      XmlElement xe = xn.OwnerDocument.CreateElement(nodename);
      xe.Attributes.SetNamedItem(AddAttribute(xe.OwnerDocument, "docid", di.DocID.ToString()));
			xe.Attributes.SetNamedItem(AddAttribute(xe.OwnerDocument, "libtitle", libDocTitle)); // di.LibTitle));
			xe.Attributes.SetNamedItem(AddAttribute(xe.OwnerDocument, "doccontent", Convert.ToBase64String(buf)));
      xe.Attributes.SetNamedItem(AddAttribute(xe.OwnerDocument, "docascii", di.DocAscii));
      xe.Attributes.SetNamedItem(AddAttribute(xe.OwnerDocument, "config", di.Config));
      xe.Attributes.SetNamedItem(AddAttribute(xe.OwnerDocument, "dts", di.DTS.ToString("MM/dd/yyyy HH:mm:ss.fff")));
      xe.Attributes.SetNamedItem(AddAttribute(xe.OwnerDocument, "userid", di.UserID.ToString()));
      xe.Attributes.SetNamedItem(AddAttribute(xe.OwnerDocument, "fileextension", di.FileExtension));
      //document audits
      ExportDocumentAudits(xe, di);
      xn.AppendChild(xe);
    }
    private void ExportDocumentAudits(XmlElement xn, DocumentInfo di)
    {
      if (cbxExportAudits.Checked)
      {
        DocumentAuditInfoList audits = DocumentAuditInfoList.Get(di.DocID);
        if (audits.Count > 0)
        {
          XmlElement xe = xn.OwnerDocument.CreateElement("audits");
          foreach (DocumentAuditInfo audit in audits)
          {
            if (audit.DeleteStatus == 0)
            {
              XmlElement xee = xn.OwnerDocument.CreateElement("audit");
              xee.Attributes.SetNamedItem(AddAttribute(xee.OwnerDocument, "auditid", audit.AuditID.ToString()));
              xee.Attributes.SetNamedItem(AddAttribute(xee.OwnerDocument, "docid", audit.DocID.ToString()));
              xee.Attributes.SetNamedItem(AddAttribute(xee.OwnerDocument, "libtitle", audit.LibTitle));
              xee.Attributes.SetNamedItem(AddAttribute(xee.OwnerDocument, "doccontent",Convert.ToBase64String(audit.DocContent)));
              xee.Attributes.SetNamedItem(AddAttribute(xee.OwnerDocument, "docascii", audit.DocAscii));
              xee.Attributes.SetNamedItem(AddAttribute(xee.OwnerDocument, "config", audit.Config));
              xee.Attributes.SetNamedItem(AddAttribute(xee.OwnerDocument, "dts", audit.DTS.ToString("MM/dd/yyyy HH:mm:ss.fff")));
              xee.Attributes.SetNamedItem(AddAttribute(xee.OwnerDocument, "userid", audit.UserID));
              xee.Attributes.SetNamedItem(AddAttribute(xee.OwnerDocument, "fileextension", audit.FileExtension));
              xee.Attributes.SetNamedItem(AddAttribute(xee.OwnerDocument, "deletestatus", audit.DeleteStatus.ToString()));
              xe.AppendChild(xee);
            }
          }
        }
      }
    }
    private void ExportDocument(DocumentInfo di, string nodename)
		{
			/*
			DocID
			LibTitle
			DocContent
			DocAscii
			Config
			DTS
			UserID
			FileExtension
			*/
			byte[] buf = di.DocContent;
			string libDocTitle = di.LibTitle;
			if (DocReplace != null && DocReplace.ContainsKey(di.DocID) && _ConvertROsAndTransitionsToText)
			{
				buf = DocReplace[di.DocID];
				libDocTitle = null; // unlink the word section from the library document
			}
			MyWriter.WriteStartElement(nodename);
			MyWriter.WriteAttributeString("docid", di.DocID.ToString());
			MyWriter.WriteAttributeString("libtitle", libDocTitle);// di.LibTitle);
			MyWriter.WriteAttributeString("doccontent", Convert.ToBase64String(buf));
			MyWriter.WriteAttributeString("docascii", di.DocAscii);
			MyWriter.WriteAttributeString("config", di.Config);
			MyWriter.WriteAttributeString("dts", di.DTS.ToString("MM/dd/yyyy HH:mm:ss.fff"));
			MyWriter.WriteAttributeString("userid", di.UserID.ToString());
			MyWriter.WriteAttributeString("fileextension", di.FileExtension);
			MyWriter.WriteEndElement();
		}
    private void ExportROUsage(XmlElement xn, RoUsageInfo ri, string nodename)
    {
      /*
      ROUsageID
      ContentID
      ROID
      Config
      DTS
      UserID
      RODbID
      */
      XmlElement xe = xn.OwnerDocument.CreateElement(nodename);
      xe.Attributes.SetNamedItem(AddAttribute(xe.OwnerDocument, "rousageid", ri.ROUsageID.ToString()));
      xe.Attributes.SetNamedItem(AddAttribute(xe.OwnerDocument, "contentid", ri.ContentID.ToString()));
      xe.Attributes.SetNamedItem(AddAttribute(xe.OwnerDocument, "roid", ri.ROID));
      xe.Attributes.SetNamedItem(AddAttribute(xe.OwnerDocument, "config", ri.Config));
      xe.Attributes.SetNamedItem(AddAttribute(xe.OwnerDocument, "dts", ri.DTS.ToString("MM/dd/yyyy HH:mm:ss.fff")));
      xe.Attributes.SetNamedItem(AddAttribute(xe.OwnerDocument, "userid", ri.UserID.ToString()));
      xe.Attributes.SetNamedItem(AddAttribute(xe.OwnerDocument, "rodbid", ri.RODbID.ToString()));
      //rousage audits
      ExportROUsageAudits(xe, ri);
      xn.AppendChild(xe);
    }
    private void ExportROUsageAudits(XmlElement xe, RoUsageInfo ri)
    {
      if (cbxExportAudits.Checked)
      {
      }
    }
    private void ExportROUsage(RoUsageInfo ri, string nodename)
		{
			/*
			ROUsageID
			ContentID
			ROID
			Config
			DTS
			UserID
			RODbID
			*/
			MyWriter.WriteStartElement(nodename);
			MyWriter.WriteAttributeString("rousageid", ri.ROUsageID.ToString());
			MyWriter.WriteAttributeString("contentid", ri.ContentID.ToString());
			MyWriter.WriteAttributeString("roid", ri.ROID);
			MyWriter.WriteAttributeString("config", ri.Config);
			MyWriter.WriteAttributeString("dts", ri.DTS.ToString("MM/dd/yyyy HH:mm:ss.fff"));
			MyWriter.WriteAttributeString("userid", ri.UserID.ToString());
			MyWriter.WriteAttributeString("rodbid", ri.RODbID.ToString());
			MyWriter.WriteEndElement();
		}
    private void ExportPart(XmlElement xn, PartInfo pi, string nodename)
    {
      /*
      ContentID
      FromType
      ItemID
      DTS
      UserID
      */
      XmlElement xe = xn.OwnerDocument.CreateElement(nodename);
      xe.Attributes.SetNamedItem(AddAttribute(xe.OwnerDocument, "contentid", pi.ContentID.ToString()));
      xe.Attributes.SetNamedItem(AddAttribute(xe.OwnerDocument, "fromtype", pi.FromType.ToString()));
      xe.Attributes.SetNamedItem(AddAttribute(xe.OwnerDocument, "itemid", pi.ItemID.ToString()));
      xe.Attributes.SetNamedItem(AddAttribute(xe.OwnerDocument, "dts", pi.DTS.ToString("MM/dd/yyyy HH:mm:ss.fff")));
      xe.Attributes.SetNamedItem(AddAttribute(xe.OwnerDocument, "userid", pi.UserID.ToString()));
      //part audits
      ExportPartAudits(xe, pi);
      xn.AppendChild(xe);
      foreach (ItemInfo ii in pi.MyItems)
        ExportItem(xe, ii, pi.PartType.ToString().ToLower());
    }
    private void ExportPartAudits(XmlElement xn, PartInfo pi)
    {
      if (cbxExportAudits.Checked)
      {
        PartAuditInfoList audits = PartAuditInfoList.Get(pi.ContentID);
        if (audits.Count > 0)
        {
          XmlElement xe = xn.OwnerDocument.CreateElement("audits");
          foreach (PartAuditInfo audit in audits)
          {
            if (audit.DeleteStatus == 0)
            {
              XmlElement xee = xn.OwnerDocument.CreateElement("audit");
              xee.Attributes.SetNamedItem(AddAttribute(xee.OwnerDocument, "auditid", audit.AuditID.ToString()));
              xee.Attributes.SetNamedItem(AddAttribute(xee.OwnerDocument, "contentid", audit.ContentID.ToString()));
              xee.Attributes.SetNamedItem(AddAttribute(xee.OwnerDocument, "fromtype", audit.FromType.ToString()));
              xee.Attributes.SetNamedItem(AddAttribute(xee.OwnerDocument, "itemid", audit.ItemID.ToString()));
              xee.Attributes.SetNamedItem(AddAttribute(xee.OwnerDocument, "dts", audit.DTS.ToString("MM/dd/yyyy HH:mm:ss.fff")));
              xee.Attributes.SetNamedItem(AddAttribute(xee.OwnerDocument, "userid", audit.UserID));
              xee.Attributes.SetNamedItem(AddAttribute(xee.OwnerDocument, "deletestatus", audit.DeleteStatus.ToString()));
              xe.AppendChild(xee);
            }
          }
        }
      }
    }
    private void ExportPart(PartInfo pi, string nodename)
		{
			/*
			ContentID
			FromType
			ItemID
			DTS
			UserID
			*/
			MyWriter.WriteStartElement(nodename);
			MyWriter.WriteAttributeString("contentid", pi.ContentID.ToString());
			MyWriter.WriteAttributeString("fromtype", pi.FromType.ToString());
			MyWriter.WriteAttributeString("itemid", pi.ItemID.ToString());
			MyWriter.WriteAttributeString("dts", pi.DTS.ToString("MM/dd/yyyy HH:mm:ss.fff"));
			MyWriter.WriteAttributeString("userid", pi.UserID.ToString());
			foreach (ItemInfo ii in pi.MyItems)
				ExportItem(ii, pi.PartType.ToString().ToLower());
			MyWriter.WriteEndElement();
		}
    private void ExportTransition(XmlElement xn, TransitionInfo ti, string nodename)
    {
      /*
      TransitionID
      FromID
      ToID
      RangeID
      IsRange
      TranType
      Config
      DTS
      UserID
      */
      XmlElement xe = xn.OwnerDocument.CreateElement(nodename);
      xe.Attributes.SetNamedItem(AddAttribute(xe.OwnerDocument, "transitionid", ti.TransitionID.ToString()));
      xe.Attributes.SetNamedItem(AddAttribute(xe.OwnerDocument, "fromid", ti.FromID.ToString()));
      xe.Attributes.SetNamedItem(AddAttribute(xe.OwnerDocument, "toid", ti.ToID.ToString()));
      xe.Attributes.SetNamedItem(AddAttribute(xe.OwnerDocument, "rangeid", ti.RangeID.ToString()));
      xe.Attributes.SetNamedItem(AddAttribute(xe.OwnerDocument, "isrange", ti.IsRange.ToString()));
      xe.Attributes.SetNamedItem(AddAttribute(xe.OwnerDocument, "trantype", ti.TranType.ToString()));
      xe.Attributes.SetNamedItem(AddAttribute(xe.OwnerDocument, "config", ti.Config));
      xe.Attributes.SetNamedItem(AddAttribute(xe.OwnerDocument, "dts", ti.DTS.ToString("MM/dd/yyyy HH:mm:ss.fff")));
      xe.Attributes.SetNamedItem(AddAttribute(xe.OwnerDocument, "userid", ti.UserID.ToString()));
      //transition audits
      ExportTransitionAudits(xe, ti);
      xn.AppendChild(xe);
    }
    private void ExportTransitionAudits(XmlElement xe, TransitionInfo ti)
    {
      if (cbxExportAudits.Checked)
      {
      }
    }
    private void ExportTransition(TransitionInfo ti, string nodename)
		{
			/*
			TransitionID
			FromID
			ToID
			RangeID
			IsRange
			TranType
			Config
			DTS
			UserID
			*/
      string folder = string.Empty;
      if (ti.MyItemToID.MyDocVersion != null && ti.MyItemToID.MyDocVersion.MyFolder.Name != MyFolder.Name)
      {
        nodename = "external" + nodename;
        folder = ti.MyItemToID.MyDocVersion.MyFolder.Name;
      }
      else
      {
        nodename = "external" + nodename;
        folder = "UNKNOWN";
      }
      MyWriter.WriteStartElement(nodename);
      if (folder != string.Empty)
        MyWriter.WriteAttributeString("folder", folder);
			MyWriter.WriteAttributeString("transitionid", ti.TransitionID.ToString());
			MyWriter.WriteAttributeString("fromid", ti.FromID.ToString());
			MyWriter.WriteAttributeString("toid", ti.ToID.ToString());
			MyWriter.WriteAttributeString("rangeid", ti.RangeID.ToString());
			MyWriter.WriteAttributeString("isrange", ti.IsRange.ToString());
			MyWriter.WriteAttributeString("trantype", ti.TranType.ToString());
			MyWriter.WriteAttributeString("config", ti.Config);
			MyWriter.WriteAttributeString("dts", ti.DTS.ToString("MM/dd/yyyy HH:mm:ss.fff"));
			MyWriter.WriteAttributeString("userid", ti.UserID.ToString());
			MyWriter.WriteEndElement();
		}
    private void ExportAnnotation(XmlElement xn, AnnotationInfo ai, string nodename)
    {
      /*
      AnnotationID
      ItemID
      TypeID
      RtfText
      SearchText
      Config
      DTS
      UserID
      */
      XmlElement xe = xn.OwnerDocument.CreateElement(nodename);
      xe.Attributes.SetNamedItem(AddAttribute(xe.OwnerDocument, "annotationid", ai.AnnotationID.ToString()));
      xe.Attributes.SetNamedItem(AddAttribute(xe.OwnerDocument, "itemid", ai.ItemID.ToString()));
      xe.Attributes.SetNamedItem(AddAttribute(xe.OwnerDocument, "typeid", ai.TypeID.ToString()));
      //if(ai.TypeID > 6)
        xe.Attributes.SetNamedItem(AddAttribute(xe.OwnerDocument, "typename", ai.MyAnnotationType.Name));
      xe.Attributes.SetNamedItem(AddAttribute(xe.OwnerDocument, "rtftext", ai.RtfText));
      xe.Attributes.SetNamedItem(AddAttribute(xe.OwnerDocument, "searchtext", ai.SearchText));
      xe.Attributes.SetNamedItem(AddAttribute(xe.OwnerDocument, "config", ai.Config));
      xe.Attributes.SetNamedItem(AddAttribute(xe.OwnerDocument, "dts", ai.DTS.ToString("MM/dd/yyyy HH:mm:ss.fff")));
      xe.Attributes.SetNamedItem(AddAttribute(xe.OwnerDocument, "userid", ai.UserID.ToString()));
      //annotation audits
      ExportAnnotationAudits(xe, ai);
      xn.AppendChild(xe);
    }
    private void ExportAnnotationAudits(XmlElement xn, AnnotationInfo ai)
    {
      if (cbxExportAudits.Checked)
      {
        AnnotationAuditInfoList audits = AnnotationAuditInfoList.GetByAnnotationID(ai.AnnotationID);
        if (audits.Count > 0)
        {
          XmlElement xe = xn.OwnerDocument.CreateElement("audits");
          foreach (AnnotationAuditInfo audit in audits)
          {
            if (audit.DeleteStatus == 0)
            {
              XmlElement xee = xn.OwnerDocument.CreateElement("audit");
              xee.Attributes.SetNamedItem(AddAttribute(xee.OwnerDocument, "auditid", audit.AuditID.ToString()));
              xee.Attributes.SetNamedItem(AddAttribute(xee.OwnerDocument, "annotationid", audit.AnnotationID.ToString()));
              xee.Attributes.SetNamedItem(AddAttribute(xee.OwnerDocument, "itemid", audit.ItemID.ToString()));
              xee.Attributes.SetNamedItem(AddAttribute(xee.OwnerDocument, "typeid", audit.TypeID.ToString()));
              xee.Attributes.SetNamedItem(AddAttribute(xee.OwnerDocument, "rtftext", audit.RtfText));
              xee.Attributes.SetNamedItem(AddAttribute(xee.OwnerDocument, "searchtext", audit.SearchText));
              xee.Attributes.SetNamedItem(AddAttribute(xee.OwnerDocument, "config", audit.Config));
              xee.Attributes.SetNamedItem(AddAttribute(xee.OwnerDocument, "deletestatus", audit.DeleteStatus.ToString()));
              xee.Attributes.SetNamedItem(AddAttribute(xee.OwnerDocument, "dts", audit.DTS.ToString("MM/dd/yyyy HH:mm:ss.fff")));
              xee.Attributes.SetNamedItem(AddAttribute(xee.OwnerDocument, "userid", audit.UserID));
              xee.Attributes.SetNamedItem(AddAttribute(xee.OwnerDocument, "actiondts", audit.ActionWhen.ToString("MM/dd/yyyy HH:mm:ss.fff")));
              xe.AppendChild(xee);
            }
          }
          xn.AppendChild(xe);
        }
      }
    }
    private void ExportAnnotation(AnnotationInfo ai, string nodename)
		{
			/*
			AnnotationID
			ItemID
			TypeID
			RtfText
			SearchText
			Config
			DTS
			UserID
			*/
			MyWriter.WriteStartElement(nodename);
			MyWriter.WriteAttributeString("annotationid", ai.AnnotationID.ToString());
			MyWriter.WriteAttributeString("itemid", ai.ItemID.ToString());
			MyWriter.WriteAttributeString("typeid", ai.TypeID.ToString());
			MyWriter.WriteAttributeString("rtftext", ai.RtfText);
			MyWriter.WriteAttributeString("searchtext", ai.SearchText);
			MyWriter.WriteAttributeString("config", ai.Config);
			MyWriter.WriteAttributeString("dts", ai.DTS.ToString("MM/dd/yyyy HH:mm:ss.fff"));
			MyWriter.WriteAttributeString("userid", ai.UserID.ToString());
			MyWriter.WriteEndElement();
		}
		#endregion
		#region Import for Merge

		// jsj 4-29-2016  appears to not be used
		//private void AddExternalTransition(XmlReader xr, XmlDocument xd)
		//{
		//	XmlElement xe = xd.CreateElement("transition");
		//	XmlAttribute xa = AddAttribute(xd, "folder", xr.GetAttribute("folder"));
		//	xe.Attributes.SetNamedItem(xa);
		//	xa = AddAttribute(xd, "transitionid", xr.GetAttribute("transitionid"));
		//	xe.Attributes.SetNamedItem(xa);
		//	xa = AddAttribute(xd, "fromid", xr.GetAttribute("fromid"));
		//	xe.Attributes.SetNamedItem(xa);
		//	xa = AddAttribute(xd, "toid", xr.GetAttribute("toid"));
		//	xe.Attributes.SetNamedItem(xa);
		//	xa = AddAttribute(xd, "rangeid", xr.GetAttribute("rangeid"));
		//	xe.Attributes.SetNamedItem(xa);
		//	xa = AddAttribute(xd, "isrange", xr.GetAttribute("isrange"));
		//	xe.Attributes.SetNamedItem(xa);
		//	xa = AddAttribute(xd, "trantype", xr.GetAttribute("trantype"));
		//	xe.Attributes.SetNamedItem(xa);
		//	xa = AddAttribute(xd, "config", xr.GetAttribute("config"));
		//	xe.Attributes.SetNamedItem(xa);
		//	xa = AddAttribute(xd, "userid", xr.GetAttribute("userid"));
		//	xe.Attributes.SetNamedItem(xa);
		//	xa = AddAttribute(xd, "dts", xr.GetAttribute("dts"));
		//	xe.Attributes.SetNamedItem(xa);
		//	xd.SelectSingleNode("externaltransitions/transitions").AppendChild(xe);
		//}

		// jsj 4-29-2016  appears to not be used
		//private void AddTransitions(XmlReader xr)
		//{
		//	int transitionid = int.Parse(xr.GetAttribute("transitionid"));
		//	int fromid = int.Parse(xr.GetAttribute("fromid"));
		//	int toid = int.Parse(xr.GetAttribute("toid"));
		//	int rangeid = int.Parse(xr.GetAttribute("rangeid"));
		//	int isrange = int.Parse(xr.GetAttribute("isrange"));
		//	int trantype = int.Parse(xr.GetAttribute("trantype"));
		//	string config = xr.GetAttribute("config");
		//	string userid = xr.GetAttribute("userid");
		//	DateTime dts = DateTime.Parse(xr.GetAttribute("dts"));
		//	string lookfor;
		//	if (isrange == 0)
		//		lookfor = string.Format("#Link:Transition:{0} {1} {2}", trantype, transitionid, toid);
		//	else
		//		lookfor = string.Format("#Link:TransitionRange:{0} {1} {2} {3}", trantype, transitionid, toid, rangeid);
		//	fromid = Old2NewContent[fromid];
		//	toid = Old2NewItem[toid];
		//	rangeid = Old2NewItem[rangeid];
		//	Content cc = Content.Get(fromid);
		//	Transition tt = Transition.MakeTransition(cc, Item.Get(toid), Item.Get(rangeid), isrange, trantype, config, dts, userid);
		//	transitionid = tt.TransitionID;
		//	string replacewith;
		//	if (isrange == 0)
		//		replacewith = string.Format("#Link:Transition:{0} {1} {2}", trantype, transitionid, toid);
		//	else
		//		replacewith = string.Format("#Link:TransitionRange:{0} {1} {2} {3}", trantype, transitionid, toid, rangeid);
		//	cc.Text = cc.Text.Replace(lookfor, replacewith);
		//	cc.Save();
		//}

		private void AddTransitions(Content content, XmlNode xn)
		{
			/*
			Content
			Item
			Item
			int
			int
			string
			dts
			string
			<transition transitionid="1" fromid="186" toid="175" rangeid="177" isrange="1" trantype="2" config="" dts="4/11/1997 1:20:00 PM" userid="MH" />

			#Link:Transition:1 2 187
			type,id,toid

			#Link:TransitionRange:2 1 175 177
			type,id,toid,rangeid
			*/
			XmlNodeList nl = xn.SelectNodes("./transition");
			foreach (XmlNode nd in nl)
			{
				int toid = int.Parse(nd.Attributes.GetNamedItem("toid").InnerText);
				int rangeid = int.Parse(nd.Attributes.GetNamedItem("rangeid").InnerText);
				if (Old2NewItem.ContainsKey(toid) && Old2NewItem.ContainsKey(rangeid))
				{
					int transitionid = int.Parse(nd.Attributes.GetNamedItem("transitionid").InnerText);
					int isrange = int.Parse(nd.Attributes.GetNamedItem("isrange").InnerText);
					int trantype = int.Parse(nd.Attributes.GetNamedItem("trantype").InnerText);
					string config = nd.Attributes.GetNamedItem("config").InnerText;
					string userid = nd.Attributes.GetNamedItem("userid").InnerText;
					DateTime dts = DateTime.Parse(nd.Attributes.GetNamedItem("dts").InnerText);
					string lookfor;
					if (isrange == 0)
						lookfor = string.Format("#Link:Transition:{0} {1} {2}", trantype, transitionid, toid);
					else
						lookfor = string.Format("#Link:TransitionRange:{0} {1} {2} {3}", trantype, transitionid, toid, rangeid);
					//fromid = content.ContentID;
					toid = Old2NewItem[toid];
					rangeid = Old2NewItem[rangeid];
					Transition tt = Transition.MakeTransition(content, Item.Get(toid), Item.Get(rangeid), isrange, trantype, config, dts, userid);
					transitionid = tt.TransitionID;
					string replacewith;
					if (isrange == 0)
						replacewith = string.Format("#Link:Transition:{0} {1} {2}", trantype, transitionid, toid);
					else
						replacewith = string.Format("#Link:TransitionRange:{0} {1} {2} {3}", trantype, transitionid, toid, rangeid);
					content.Text = content.Text.Replace(lookfor, replacewith);
					if (content.MyGrid != null && content.MyGrid.Data != "")
						content.MyGrid.Data = content.MyGrid.Data.Replace(lookfor, replacewith);
					content.FixTransitionText(TransitionInfo.Get(tt.TransitionID));
					// B2017=003 make sure any grid changes are saved.
					// done here because FixTransitionText() could update the transitions in the grid
					if (content.MyGrid != null && content.MyGrid.Data != "")
						content.MyGrid.Save();
					content.Save();
				}
				else
				{
					PendingTransitions.DocumentElement.AppendChild(PendingTransitions.ImportNode(nd, true));
					//save to holding pen
				}
			}
		}
    private void AddTransitions()
    {
      AddTransitions(PendingTransitions);
    }
		private void AddTransitions(XmlDocument xd)
		{
			/*
			Content
			Item
			Item
			int
			int
			string
			dts
			string
			<transition transitionid="1" fromid="186" toid="175" rangeid="177" isrange="1" trantype="2" config="" dts="4/11/1997 1:20:00 PM" userid="MH" />

			#Link:Transition:1 2 187
			type,id,toid

			#Link:TransitionRange:2 1 175 177
			type,id,toid,rangeid
			*/
			XmlNodeList nl = xd.SelectNodes("//transition");
			lblImportStatus.Text = string.Format("Updating {0} Tranistions", nl.Count.ToString());
			foreach (XmlNode nd in nl)
			{
				int fromid = int.Parse(nd.Attributes.GetNamedItem("fromid").InnerText);
				int toid = int.Parse(nd.Attributes.GetNamedItem("toid").InnerText);
				int rangeid = int.Parse(nd.Attributes.GetNamedItem("rangeid").InnerText);
				int trantype = int.Parse(nd.Attributes.GetNamedItem("trantype").InnerText);
				if (Old2NewContent.ContainsKey(fromid)) //transition from new contentid
				{
					if (Old2NewItem.ContainsKey(toid) && Old2NewItem.ContainsKey(rangeid))	//transition to new itemid (internal)
					{
						int transitionid = int.Parse(nd.Attributes.GetNamedItem("transitionid").InnerText);
						int isrange = int.Parse(nd.Attributes.GetNamedItem("isrange").InnerText);
						string config = nd.Attributes.GetNamedItem("config").InnerText;
						string userid = nd.Attributes.GetNamedItem("userid").InnerText;
						DateTime dts = DateTime.Parse(nd.Attributes.GetNamedItem("dts").InnerText);
						string lookfor;
						if (isrange == 0)
							lookfor = string.Format("#Link:Transition:{0} {1} {2}", trantype, transitionid, toid);
						else
							lookfor = string.Format("#Link:TransitionRange:{0} {1} {2} {3}", trantype, transitionid, toid, rangeid);
						fromid = Old2NewContent[fromid];
						toid = Old2NewItem[toid];
						rangeid = Old2NewItem[rangeid];
						Content cc = Content.Get(fromid);
						Transition tt = Transition.MakeTransition(cc, Item.Get(toid), Item.Get(rangeid), isrange, trantype, config, dts, userid);
						transitionid = tt.TransitionID;
						string replacewith;
						if (isrange == 0)
							replacewith = string.Format("#Link:Transition:{0} {1} {2}", trantype, transitionid, toid);
						else
							replacewith = string.Format("#Link:TransitionRange:{0} {1} {2} {3}", trantype, transitionid, toid, rangeid);
						cc.Text = cc.Text.Replace(lookfor, replacewith);
						if (cc.MyGrid != null && cc.MyGrid.Data != "")
							cc.MyGrid.Data = cc.MyGrid.Data.Replace(lookfor, replacewith);
						bool forceConvertToText = false;
						if (TransitionInfo.Get(tt.TransitionID).MyItemToID.ActiveSection != null)
						{
							SectionConfig sc = TransitionInfo.Get(tt.TransitionID).MyItemToID.ActiveSection.MyConfig as SectionConfig;
							forceConvertToText = (sc.SubSection_Edit == "N");
						}
						cc.FixTransitionText(TransitionInfo.Get(tt.TransitionID), forceConvertToText);
						// B2017=003 make sure any grid changes are saved.
						// done here because FixTransitionText() could update the transitions in the grid
						if (cc.MyGrid != null && cc.MyGrid.Data != "")
							cc.MyGrid.Save();
						cc.Save();
						nd.InnerText = "done";
					}
					else  //transition to existing itemid (external)
					{
						bool forceConvertToText = false;
						int transitionid = int.Parse(nd.Attributes.GetNamedItem("transitionid").InnerText);
						int isrange = int.Parse(nd.Attributes.GetNamedItem("isrange").InnerText);
						string config = nd.Attributes.GetNamedItem("config").InnerText;
						string userid = nd.Attributes.GetNamedItem("userid").InnerText;
						DateTime dts = DateTime.Parse(nd.Attributes.GetNamedItem("dts").InnerText);
						string lookfor;
						if (isrange == 0)
							lookfor = string.Format("#Link:Transition:{0} {1} {2}", trantype, transitionid, toid);
						else
							lookfor = string.Format("#Link:TransitionRange:{0} {1} {2} {3}", trantype, transitionid, toid, rangeid);
						fromid = Old2NewContent[fromid];
						Content cc = Content.Get(fromid);
						Transition tt = Transition.MakeTransition(cc, Item.Get(toid), Item.Get(rangeid), isrange, trantype, config, dts, userid);
						if (tt.TransitionID < 0)
						{
							forceConvertToText = true;
							cc.FixTransitionText(TransitionInfo.Get(tt.TransitionID), forceConvertToText);
							cc.Save();
							nd.InnerText = "done";
						}
						else
						{
							transitionid = tt.TransitionID;
							string replacewith;
							if (isrange == 0)
								replacewith = string.Format("#Link:Transition:{0} {1} {2}", trantype, transitionid, toid);
							else
								replacewith = string.Format("#Link:TransitionRange:{0} {1} {2} {3}", trantype, transitionid, toid, rangeid);
							cc.Text = cc.Text.Replace(lookfor, replacewith);
							if (cc.MyGrid != null && cc.MyGrid.Data != "")
								cc.MyGrid.Data = cc.MyGrid.Data.Replace(lookfor, replacewith);
							if (TransitionInfo.Get(tt.TransitionID).MyItemToID.ActiveSection != null)
							{
								SectionConfig sc = TransitionInfo.Get(tt.TransitionID).MyItemToID.ActiveSection.MyConfig as SectionConfig;
								forceConvertToText = (sc.SubSection_Edit == "N");
							}
							// B2016-176, B2016197 - external transitions should be convert to text
							forceConvertToText = true;
							//if (!forceConvertToText)	//check to see if external with internal format
							//{
							//	TransitionInfo tran = TransitionInfo.Get(transitionid);
							//	if (tran.MyContent.ContentItems[0].MyProcedure.ItemID != tran.MyItemToID.MyProcedure.ItemID)
							//		if (!tran.MyContent.ContentItems[0].ActiveFormat.PlantFormat.FormatData.TransData.TransTypeList[tran.TranType].TransMenu.Contains("Proc"))
							//			forceConvertToText = true;
							//}
							//if (!forceConvertToText)	//check to see if external to different doc version
							//{
							//	TransitionInfo tran = TransitionInfo.Get(transitionid);
							//	if (tran.MyContent.ContentItems[0].MyDocVersion.VersionID != tran.MyItemToID.MyDocVersion.VersionID)
							//		forceConvertToText = true;
							//}
							cc.FixTransitionText(TransitionInfo.Get(tt.TransitionID), forceConvertToText);
							// B2017=003 make sure any grid changes are saved.
							// done here because FixTransitionText() could update the transitions in the grid
							if (cc.MyGrid != null && cc.MyGrid.Data != "")
								cc.MyGrid.Save();
							cc.Save();
							nd.InnerText = "done";
							_DidConvertTransitionsToText |= forceConvertToText;  // B2016-225 - notify user when transitions are converted to text
						}
					}
				}
			}
		}

		private Dictionary<int, int> Old2NewItem;
		private Dictionary<int, int> Old2NewContent;
    private Dictionary<int, int> Old2NewLibDoc;
    private XmlDocument PendingTransitions;
		private RODb MyRODb = null;

		// jsj 4-29-2016  appears to not be used
		//private Folder AddFolder(Folder folder, XmlReader xr)
		//{
		//	Old2NewItem = new Dictionary<int, int>();
		//	Old2NewContent = new Dictionary<int, int>();
		//	Old2NewLibDoc = new Dictionary<int, int>();
		//	string title = xr.GetAttribute("title");
		//	string name = xr.GetAttribute("name");
		//	string shortname = xr.GetAttribute("shortname");
		//	string usrid = xr.GetAttribute("usrid");
		//	DateTime dts = DateTime.Parse(xr.GetAttribute("dts"));
		//	string formatid = xr.GetAttribute("formatid");
		//	string formatfilename = xr.GetAttribute("formatfilename"); //Bug fix B2016-103  the formatid in an Export file may not match the formatid where you are importing to
		//	Format format = formatid == string.Empty ? null : OldToNewFormat(int.Parse(formatid),formatfilename);
		//	folder = Folder.MakeFolder(folder, folder.MyConnection, name, title, shortname, format, null, dts, usrid);
		//	//f.Save();
		//	return folder;
		//}

		private Folder AddFolder(Folder p, XmlDocument xd)
		{
      lblImportStatus.Text = "Creating Folder...";
      Application.DoEvents();
      string title = xd.DocumentElement.Attributes.GetNamedItem("title").InnerText;
			string name = xd.DocumentElement.Attributes.GetNamedItem("name").InnerText;
			string shortname = xd.DocumentElement.Attributes.GetNamedItem("shortname").InnerText;
			string usrid = xd.DocumentElement.Attributes.GetNamedItem("usrid").InnerText;
			DateTime dts = DateTime.Parse(xd.DocumentElement.Attributes.GetNamedItem("dts").InnerText);
      string formatid = xd.DocumentElement.Attributes.GetNamedItem("formatid").InnerText;
			XmlNode fnNode = xd.DocumentElement.Attributes.GetNamedItem("formatfilename"); //Bug fix B2016-103  the formatid in an Export file may not match the formatid where you are importing to
			string formatfilename = (fnNode != null) ? fnNode.InnerText : "";
      Format format = formatid == string.Empty ? null : OldToNewFormat(int.Parse(formatid),formatfilename);
      if (Folder.GetByParentID_Name(p.FolderID, name) != null)
        return null;
			Folder f = Folder.MakeFolder(p, p.MyConnection, name, title, shortname, format, null, dts, usrid);
			return f;
		}
    private Format OldToNewFormat(int formatID, string formatFileName)
    {
			try
			{
				string formatName = formatFileName; // B2016-103,  new export files include the format filename use that if it exists
				if (formatFileName == string.Empty)
				{
					if (formatID >= oldFormat.Count) return null; // formatID not found, use default file name
					formatName = oldFormat[formatID];  // for backwards compatibility with older export files
				}
				formatID = newFormat[formatName];
				return Format.Get(formatID);
			}
			catch
			{
				return null; // format not found return null to use default format
			}
    }
		private DocVersion AddDocVersion(Folder f, XmlReader xr)
		{
			int versiontype = int.Parse(xr.GetAttribute("versiontype"));
			string name = xr.GetAttribute("name");
			string config = xr.GetAttribute("config");
			string userid = xr.GetAttribute("userid");
			DateTime dts = DateTime.Parse(xr.GetAttribute("dts"));
			string formatid = xr.GetAttribute("formatid");
			string formatfilename = xr.GetAttribute("formatfilename"); //Bug fix B2016-103  the formatid in an Export file may not match the formatid where you are importing to
      Format format = formatid == string.Empty ? null : OldToNewFormat(int.Parse(formatid),formatfilename);
			DocVersion dv = DocVersion.MakeDocVersion(f, versiontype, name, null, null, format, config, dts, userid);
			return dv;
		}
    private void AddAnnotationTypes(XmlDocument xd)
    {
      XmlNodeList nl = xd.SelectNodes("folder/annotationtypes/annotationtype");
      foreach (XmlNode nd in nl)
      {
        AnnotationTypeInfo ati = AnnotationTypeInfo.GetByName(nd.Attributes.GetNamedItem("name").InnerText);
        if (ati == null)
          AnnotationType.MakeAnnotationType(nd.Attributes.GetNamedItem("name").InnerText, nd.Attributes.GetNamedItem("config").InnerText, DateTime.Parse(nd.Attributes.GetNamedItem("dts").InnerText), nd.Attributes.GetNamedItem("userid").InnerText);
      }
    }
		private DocVersionInfo AddDocVersion(Folder f, XmlDocument xd)
		{
      lblImportStatus.Text = "Creating DocVersion...";
      Application.DoEvents();
      XmlElement xe = (XmlElement)xd.SelectSingleNode("folder/docversion");
			int versiontype = int.Parse(xe.Attributes.GetNamedItem("versiontype").InnerText);
			string name = xe.Attributes.GetNamedItem("name").InnerText;
			string config = xe.Attributes.GetNamedItem("config").InnerText;
			config = StripEnhanced(config);
			string userid = xe.Attributes.GetNamedItem("userid").InnerText;
			DateTime dts = DateTime.Parse(xe.Attributes.GetNamedItem("dts").InnerText);
			string formatid = xe.Attributes.GetNamedItem("formatid").InnerText;
			XmlNode fnNode = xe.Attributes.GetNamedItem("formatfilename"); //Bug fix B2016-103  the formatid in an Export file may not match the formatid where you are importing to
			string formatfilename = (fnNode != null) ? fnNode.InnerText : "";
      Format format = formatid == string.Empty ? null : OldToNewFormat(int.Parse(formatid),formatfilename);
			DocVersion dv = DocVersion.MakeDocVersion(f, versiontype, name, null, null, format, config, dts, userid);
			XmlNode xassoc = xe.SelectSingleNode("association");
      if (xassoc != null)
      {
        XmlNode xrofst = xassoc.SelectSingleNode("rofst");
        XmlNode xrodb = xrofst.SelectSingleNode("rodb");
				MyRODb = AddRODb(xrodb);
        ROFst rofst = AddROFst(xrofst);
        DocVersionAssociation dva = dv.DocVersionAssociations.Add(rofst);
        dv.Save();
      }
			return DocVersionInfo.Get(dv.VersionID);
		}

		// jsj 4-29-2016  appears to not be used
		//private Dictionary<string, string> GetROFstData(XmlReader xr)
		//{
		//	Dictionary<string, string> rv = new Dictionary<string, string>();
		//	rv.Add("rolookup", xr.GetAttribute("rolookup"));
		//	rv.Add("config", xr.GetAttribute("config"));
		//	rv.Add("userid", xr.GetAttribute("userid"));
		//	rv.Add("dts", xr.GetAttribute("dts"));
		//	return rv;
		//}

		// jsj 4-29-2016  appears to not be used
		//private ROFst AddROFst(Dictionary<string,string> dic)
		//{
		//	byte[] rolookup = Convert.FromBase64String(dic["rolookup"]);
		//	string config = dic["config"];
		//	string userid = dic["userid"];
		//	DateTime dts = DateTime.Parse(dic["dts"]);
		//	ROFst rv = null;
		//	rv = ROFst.GetByRODbID_DTS(MyRODb.RODbID, dts);	//MyRODb.DTS);
		//	if (rv == null)
		//		rv = ROFst.MakeROFst(MyRODb, rolookup, config, dts, userid);
		//	return rv;
		//}

		private ROFst AddROFst(XmlNode xrofst)
		{
      lblImportStatus.Text = "Creating ROFst...";
      Application.DoEvents();
      byte[] rolookup = Convert.FromBase64String(xrofst.Attributes.GetNamedItem("rolookup").InnerText);
			string config = xrofst.Attributes.GetNamedItem("config").InnerText;
			string userid = xrofst.Attributes.GetNamedItem("userid").InnerText;
			DateTime dts = DateTime.Parse(xrofst.Attributes.GetNamedItem("dts").InnerText);
			ROFst rv = null;
			rv = ROFst.GetByRODbID_DTS(MyRODb.RODbID, dts);	
			// if the RO database is not found in the current data (does not have the same RODBid nor date/time stamp
			// then spin through the list of RO databases and compare the FST information.
			// If the RO FST information is the same, then use that current RO database when importing
			if (rv == null)
			{
				RODbInfoList rodblst = RODbInfoList.Get();
				foreach (RODbInfo roinfo in rodblst)
				{
					rv = ROFst.GetByRODbID_DTS(roinfo.RODbID, dts);
					if (rv != null && Same(rv.ROLookup,rolookup)) return rv;
				}
				rv = ROFst.MakeROFst(MyRODb, rolookup, config, dts, userid);
				XmlNode xfigures = xrofst.SelectSingleNode("figures");
				if (xfigures != null)
					AddFigures(xfigures, rv);
			}
			return rv;
		}

		private bool Same(byte[] p, byte[] rolookup)
		{
			if (p.Length != rolookup.Length) return false;
			for (int i = 0; i < p.Length; i++)
				if (p[i] != rolookup[i]) return false;
			return true;
		}

		private void AddFigures(XmlNode xfigures, ROFst rofst)
		{
			foreach (XmlNode nd in xfigures.SelectNodes("figure"))
			{
				XmlNode image = nd.SelectSingleNode("image");
				int imageid = int.Parse(image.Attributes.GetNamedItem("imageid").InnerText);
				using (ROImage roimage = ROImage.GetJustROImage(imageid))//Dispose when done
				{
					string config;
					DateTime dts;
					string userid;
					if (roimage == null)
					{
						string filename = image.Attributes.GetNamedItem("filename").InnerText;
						byte[] content = Convert.FromBase64String(image.Attributes.GetNamedItem("content").InnerText);
						config = image.Attributes.GetNamedItem("config").InnerText;
						dts = DateTime.Parse(image.Attributes.GetNamedItem("dts").InnerText);
						userid = image.Attributes.GetNamedItem("userid").InnerText;
						// Dispose when done
						using (ROImage roimage1 = ROImage.MakeROImage(MyRODb, filename, content, config, dts, userid))
						{
							config = nd.Attributes.GetNamedItem("config").InnerText;
							dts = DateTime.Parse(nd.Attributes.GetNamedItem("dts").InnerText);
							userid = nd.Attributes.GetNamedItem("userid").InnerText;
							// Dispose when done
							using(Figure fig = Figure.MakeFigure(rofst, roimage, config, dts, userid)){;}
						}
					}
					else
					{
						config = nd.Attributes.GetNamedItem("config").InnerText;
						dts = DateTime.Parse(nd.Attributes.GetNamedItem("dts").InnerText);
						userid = nd.Attributes.GetNamedItem("userid").InnerText;
						// Dispose when done
						using(Figure fig = Figure.MakeFigure(rofst, roimage, config, dts, userid)){;}
					}
				}
			}
		}

		// jsj 4-29-2016  appears to not be used
		//private RODb AddRODb(XmlReader xr)
		//{
		//	oldRODbID = int.Parse(xr.GetAttribute("rodbid"));
		//	string roname = xr.GetAttribute("roname");
		//	string folderpath = xr.GetAttribute("folderpath");
		//	string dbconnectionstring = xr.GetAttribute("dbconnectionstring");
		//	string config = xr.GetAttribute("config");
		//	string userid = xr.GetAttribute("userid");
		//	DateTime dts = DateTime.Parse(xr.GetAttribute("dts"));
		//	RODb rv = null;
		//	rv = RODb.GetByFolderPath(folderpath);
		//	if (rv == null)
		//		rv = RODb.MakeRODb(roname, folderpath, dbconnectionstring, config, dts, userid);
		//	newRODbID = rv.RODbID;
		//	return rv;
		//}

		private RODb AddRODb(XmlNode xrodb)
		{
      lblImportStatus.Text = "Creating RODb...";
      Application.DoEvents();
      oldRODbID = int.Parse(xrodb.Attributes.GetNamedItem("rodbid").InnerText);
      string roname = xrodb.Attributes.GetNamedItem("roname").InnerText;
			string folderpath = xrodb.Attributes.GetNamedItem("folderpath").InnerText;
			string dbconnectionstring = xrodb.Attributes.GetNamedItem("dbconnectionstring").InnerText;
			string config = xrodb.Attributes.GetNamedItem("config").InnerText;
			string userid = xrodb.Attributes.GetNamedItem("userid").InnerText;
			DateTime dts = DateTime.Parse(xrodb.Attributes.GetNamedItem("dts").InnerText);
			RODb rv = null;
			rv = RODb.GetByFolderPath(folderpath);
			if (rv == null)
			{
				// create a list of the RO databases currently in the database
				List<string> roDbNameList = new List<string>();
				RODbInfoList rolist = RODbInfoList.Get();
				foreach (RODbInfo rodbinfo in rolist)
				{
					if (!roDbNameList.Contains(rodbinfo.ROName))
						roDbNameList.Add(rodbinfo.ROName);
				}
				rolist.Dispose();
				int cnt = 0;
				string roNameNew = roname;
				// if the ROname we are importing is the same as one already in the database
				// and the ROpaths are different, then rename the one we are importing
				while (roDbNameList.Contains(roNameNew))
					roNameNew = string.Format("{0}_{1}",roname,(++cnt).ToString());
				rv = RODb.MakeRODb(roNameNew, folderpath, dbconnectionstring, config, dts, userid);
			}
      newRODbID = rv.RODbID;
			return rv;
		}

		// jsj 4-29-2016 appears to not be used
		//private int GetProcedureData(XmlReader xr)
		//{
		//	return int.Parse(xr.GetAttribute("itemid"));
		//}

		// jsj 4-29-2016 appears to not be used
		//private ItemInfo AddProcedure(XmlReader xr, DocVersion dv, ItemInfo procInfo, int oldid)
		//{
		//	DocVersionInfo dvInfo = DocVersionInfo.Get(dv.VersionID);
		//	string number = xr.GetAttribute("number");
		//	string text = xr.GetAttribute("text");
		//	int proctype = int.Parse(xr.GetAttribute("type"));
		//	string formatid = xr.GetAttribute("formatid");
		//	string config = xr.GetAttribute("config");
		//	string userid = xr.GetAttribute("userid");
		//	DateTime dts = DateTime.Parse(xr.GetAttribute("dts"));
		//	Procedure p = Procedure.MakeProcedure(dvInfo, procInfo, number, text, proctype);
		//	p.DTS = dts;
		//	p.UserID = userid;
		//	string formatfilename = xr.GetAttribute("formatfilename"); //Bug fix B2016-103  the formatid in an Export file may not match the formatid where you are importing to
		//	if (formatid != string.Empty)
		//		p.MyContent.MyFormat = OldToNewFormat(int.Parse(formatid),formatfilename);
		//	p.MyContent.Config = config;
		//	p.MyContent.DTS = dts;
		//	p.MyContent.UserID = userid;
		//	p.Save();
		//	Old2NewItem.Add(oldid, p.ItemID);
		//	Old2NewContent.Add(int.Parse(xr.GetAttribute("contentid")), p.MyContent.ContentID);
		//	procInfo = ProcedureInfo.Get(p.ItemID);
		//	return procInfo;
		//}
		private ProcedureInfo AddProcedure(XmlNode xn, DocVersionInfo dvInfo, ProcedureInfo procInfo)
		{
			pbImportProcedure.PerformStep();
			lblImportProcedure.Text = string.Format("{0} of {1} Procedures", pbImportProcedure.Value.ToString(), pbImportProcedure.Maximum.ToString());
      TimeSpan elapsed = DateTime.Now.Subtract(MyStart);
      lblImportTime.Text = "Elapsed Time: " + elapsed.ToString();
      Application.DoEvents();
			XmlNode xc = xn.SelectSingleNode("content");
			string number = xc.Attributes.GetNamedItem("number").InnerText;
			string text = xc.Attributes.GetNamedItem("text").InnerText;
			int proctype = int.Parse(xc.Attributes.GetNamedItem("type").InnerText);
			string formatid = xc.Attributes.GetNamedItem("formatid").InnerText;
			string config = xc.Attributes.GetNamedItem("config").InnerText;
			config = StripEnhanced(config);
			string userid = xc.Attributes.GetNamedItem("userid").InnerText;
			DateTime dts = DateTime.Parse(xc.Attributes.GetNamedItem("dts").InnerText);
			Procedure p = Procedure.MakeProcedure(dvInfo, procInfo, number, text, proctype);
			p.DTS = dts;
			p.UserID = userid;
			// check for a null in case an older export file is being imported (the older files will not have the fromatfilename attribute)
			XmlNode fnNode = xc.Attributes.GetNamedItem("formatfilename"); //Bug fix B2016-103  the formatid in an Export file may not match the formatid where you are importing to
			string formatfilename = (fnNode !=null)? fnNode.InnerText : "";
			if (formatid != string.Empty)
        p.MyContent.MyFormat = OldToNewFormat(int.Parse(formatid),formatfilename);
			p.MyContent.Config = config;
			p.MyContent.DTS = dts;
			p.MyContent.UserID = userid;
			p.Save();
			if (!Old2NewItem.ContainsKey(int.Parse(xn.Attributes.GetNamedItem("itemid").InnerText)))
				Old2NewItem.Add(int.Parse(xn.Attributes.GetNamedItem("itemid").InnerText), p.ItemID);
			else
				Old2NewItem[int.Parse(xn.Attributes.GetNamedItem("itemid").InnerText)] = p.ItemID; // B2016-176, B2016-197 refresh saved ItemId with current ItemID
			if (!Old2NewContent.ContainsKey(int.Parse(xc.Attributes.GetNamedItem("contentid").InnerText)))
				Old2NewContent.Add(int.Parse(xc.Attributes.GetNamedItem("contentid").InnerText), p.MyContent.ContentID);
			else
				Old2NewContent[int.Parse(xc.Attributes.GetNamedItem("contentid").InnerText)] = p.MyContent.ContentID; // B2016-176, B2016-197 refresh saved ContentID with current ContentID
			if (xn.SelectNodes("annotation").Count > 0)
				AddAnnotations(p.ItemID, xn);
			if (xc.SelectNodes("rousage").Count > 0)
				AddROUsages(p.MyContent, xc);
      if (xc.SelectNodes("transition").Count > 0)
        AddTransitions(p.MyContent, xc); 
			procInfo = ProcedureInfo.Get(p.ItemID);
			if (xc.HasChildNodes)
				AddParts(xc, procInfo);
			FixSectionStart(procInfo);
			return procInfo;
		}
		// jsj 2016Feb16 - This appears to not be used
		//private void AddROUsage(XmlReader xr)
		//{
		//	int contentid = int.Parse(xr.GetAttribute("contentid"));
		//	contentid = Old2NewContent[contentid];
		//	Content content = Content.Get(contentid);
		//	string rousageid = xr.GetAttribute("rousageid");
		//	string roid = xr.GetAttribute("roid");
		//	string config = xr.GetAttribute("config");
		//	string userid = xr.GetAttribute("userid");
		//	DateTime dts = DateTime.Parse(xr.GetAttribute("dts"));
		//	RoUsage rou = RoUsage.MakeRoUsage(content, roid, config, dts, userid, MyRODb);
		//	rou.Save();
		//	string lookFor = string.Format("#Link:ReferencedObject:{0} {1} {2}[END>", rousageid, roid, oldRODbID.ToString());
		//	string replaceWith = (cbxCvrtROsToText.Checked) ? "" : string.Format("#Link:ReferencedObject:{0} {1} {2}[END>", rou.ROUsageID.ToString(), roid, newRODbID.ToString());
		//	if (lookFor != replaceWith)
		//	{
		//		content.Text = content.Text.Replace(lookFor, replaceWith);
		//		content.Save();
		//	}
		//}
		private string GetMyPrefix(string text, int start, int lastIndex)
		{
			string defPrefix = text.Substring(start - 3, 3);
			if (defPrefix != @"\v ") throw new Exception(string.Format("rtf string {0} does not match expected format", defPrefix));
			string txt = text.Substring(lastIndex, start - lastIndex - 3);
			int lastSlash = txt.LastIndexOf(@"\");
			int lastSpace = txt.LastIndexOf(" ");
			int lastCR = txt.LastIndexOf("\r");
			if (lastSpace < lastCR)
				lastSpace = lastCR;
			if (lastSlash <= lastSpace) //this will return "\v "
				return defPrefix;
			txt = txt.Substring(lastSlash);
			if (txt.StartsWith(@"\'"))	//this is a hex
				return defPrefix;
			if (Regex.IsMatch(txt, @"\\u[0-9].*"))	//this is unicode
				return defPrefix;
			return @"\v";
		}
		private string GetMySuffix(string text, int start)
		{
			string txt = text.Substring(start);
			int firstSlashVeeZero = txt.IndexOf(@"\v0");
			if (firstSlashVeeZero == 0 && txt.Length > 3 && txt[3] == ' ')	//"\v0 "
				return text.Substring(start, 4);
			return text.Substring(start, firstSlashVeeZero + 3);	//everything upto \v0"
		}
		private void ConvertImportProcedureROsToText(Content content, XmlNode xn)
		{
				foreach (XmlNode nd in xn.SelectNodes("rousage"))
			{
				string rousageid = nd.Attributes.GetNamedItem("rousageid").InnerText;
				string roid = nd.Attributes.GetNamedItem("roid").InnerText;

				string findLink = @"<START\].*?\[END>";
				MatchCollection ms = Regex.Matches(content.Text, findLink);
				string lookFor = string.Format(@"^<START\](\\[^v \\]+)*\\v0(\\[^v '?{{}}~\\]+)*( |\\u[0-9]{{1,4}}?|\\'[0-9a-fA-F]{{2}}|\\[{{}}~])(.*?)(\\[^v'?{{}}~ \\]+)*\\v(\\[^v \\]+)* #Link:ReferencedObject:{0} .*?\[END>$", rousageid);
				int lastIndex = 0;
				string newText = content.Text;
				foreach (Match mm in ms)
				{
					int offset = mm.Index;
					Match m = Regex.Match(mm.Value, lookFor, RegexOptions.Singleline);
					if (m != null && m.Groups.Count > 1)
					{
						string prefix = GetMyPrefix(content.Text, mm.Index, lastIndex);
						string suffix = GetMySuffix(content.Text, mm.Index + mm.Length);
						int myIndex = m.Groups[4].Index + mm.Index;
						int myLength = m.Groups[4].Length;
						if (m.Groups[3].Value != " ")
						{
							myIndex = m.Groups[3].Index + mm.Index;
							myLength += m.Groups[3].Length;
						}
						string gg = newText.Substring(myIndex, myLength);
						gg = gg.Replace("{", @"\{").Replace("}", @"\}");
						string part1 = newText.Substring(0, mm.Index);
						string part2 = gg;
						string part3 = newText.Substring(mm.Index + mm.Length);
						//modify part1 based on prefix
						if (prefix == @"\v ")
							part1 = part1.Substring(0, part1.Length - 3);
						else
							part1 = part1.Substring(0, part1.Length - 3) + " ";
						//modify part3 based on suffix
						if (suffix == @"\v0 ")
							part3 = part3.Substring(4);
						else
							part3 = suffix.Replace(@"\v0", "") + part3.Substring(suffix.Length);
						content.Text = part1 + part2 + part3;
						ROToTextAnnotation(content, part2); // B2016-225 (follow through) add annotation when RO is converted to text
					}
					lastIndex = mm.Index + mm.Length;
				}
			}
			content.Save();
		}

		// B2016-225 (follow through) add annotation when RO is converted to text
		private void ROToTextAnnotation(Content content, string txtRO)
		{
			// replace unicode symbols to DOS code symbols
			txtRO = txtRO.Replace(@"\u8209?", "-"); // dash
			txtRO = txtRO.Replace(@"\u9586?", @"\\"); // backslash
			txtRO = txtRO.Replace(@"\'b0", "\xb0"); //degree
			txtRO = txtRO.Replace(@"\u160?"," "); //hard space
			txtRO = txtRO.Replace(@"\u916?", "\x7F"); // delta
			txtRO = txtRO.Replace(@"\u8805?", "\xF2"); //greater than or equal
			txtRO = txtRO.Replace(@"\u8804?", "\xF3");	// less than or equal
			txtRO = txtRO.Replace(@"\u931?", "\xE4");		// sigma
			txtRO = txtRO.Replace(@"\u947?", "\xE7");		// gamma
			txtRO = txtRO.Replace(@"\u9604?", "\xFE");	// accum 2584
			txtRO = txtRO.Replace(@"\u9679?", "\x7");		// bullet 25CF
			txtRO = txtRO.Replace(@"\u8776?", "\xF7");	// approx eq
			txtRO = txtRO.Replace(@"\u8773?", "\xF0");	// similar eq 2245
			txtRO = txtRO.Replace(@"\u8730?", "\xFB");	// square root
			txtRO = txtRO.Replace(@"\u961?", "\xE2");		// rho 3C1
			txtRO = txtRO.Replace(@"\u960?", "\xE3");		// pi
			txtRO = txtRO.Replace(@"\u956?", "\xE6");	// micro
			txtRO = txtRO.Replace(@"\u948?", "\xEB");	// lower case delta
			txtRO = txtRO.Replace(@"\u963?", "\xE5");	// lower case sigma
			txtRO = txtRO.Replace(@"\u274?", "\x90");		// energy, 112
			txtRO = txtRO.Replace(@"\u949?", "\xEE");	// epsilon	
			txtRO = txtRO.Replace(@"\u952?", "\xE9");	// theta, 3B8
			txtRO = txtRO.Replace(@"\u8857?", "\xEC");	// dot in oval, 2299
			txtRO = txtRO.Replace(@"\u964?", "\xA8");		// tau, 3C4
			txtRO = txtRO.Replace(@"\u9830?", "\xA9");	// diamond, 2666
			txtRO = txtRO.Replace(@"\u8593?", "\x18"); // Up Arrow - changes to \xff
			txtRO = txtRO.Replace(@"\u8595?", "\x19"); // Down Arrow - changes to \xd6

			Item myitem = content.ContentItems[0].MyItem; // The Using statement caused the content.text to disappear
			//using (Item myitem = content.ContentItems[0].MyItem) // so that myitem does not stay in cache
			//{
				Annotation.MakeAnnotation(myitem, AnnotationType.GetByNameOrCreate("Link Converted To Text"), "", string.Format("RO value ({0}) converted to text", txtRO), null);
			//}
			_DidConvertROsToText |= true;
		}
		private void AddROUsages(Content content, XmlNode xn)
		{
			AddROUsages(content, xn, false);
		}
		// part of bug fix B2017-060 added the isGrid parameter
		private void AddROUsages(Content content, XmlNode xn, bool isGrid)
		{
			if (_ConvertROsToTextDuringImport)
				ConvertImportProcedureROsToText(content, xn);
			else
			{
				foreach (XmlNode nd in xn.SelectNodes("rousage"))
				{
					string rousageid = nd.Attributes.GetNamedItem("rousageid").InnerText;
					string roid = nd.Attributes.GetNamedItem("roid").InnerText;
					string config = nd.Attributes.GetNamedItem("config").InnerText;
					string userid = nd.Attributes.GetNamedItem("userid").InnerText;
					DateTime dts = DateTime.Parse(nd.Attributes.GetNamedItem("dts").InnerText);
					if (MyDocVersion.DocVersionAssociations == null)
						MyDocVersion.RefreshDocVersionAssociations();
					ROFSTLookup lookup = MyDocVersion.DocVersionAssociations[0].MyROFst.GetROFSTLookup(MyDocVersion);
					string roval = lookup.GetRoValue(roid);
					if (roval == "?")
					{
						RoUsageInfo roui = RoUsageInfo.Get(int.Parse(rousageid));
						content.FixContentText(roui, roval, 0, MyDocVersion.DocVersionAssociations[0].MyROFst, null, rousageid); // + " " + roid);
						_DidConvertROsToText |= true; // B2016-225 (follow through) add annotation when RO is converted to text
					}
					else
					{
						RoUsage rou = RoUsage.MakeRoUsage(content, roid, config, dts, userid, MyRODb);
						rou.Save();
						RoUsageInfo roui = RoUsageInfo.Get(rou.ROUsageID);
						string lookFor = string.Format("#Link:ReferencedObject:{0} {1} {2}[END>", rousageid, roid, oldRODbID.ToString());
						string replaceWith = string.Format("#Link:ReferencedObject:{0} {1} {2}[END>", rou.ROUsageID.ToString(), roid, newRODbID.ToString());
						if (lookFor != replaceWith)
						{
							content.Text = content.Text.Replace(lookFor, replaceWith);
							content.FixContentText(roui, roval, 0, MyDocVersion.DocVersionAssociations[0].MyROFst);
						}
						if (isGrid) // B2017-060 when importing a grid, also update the grid's xml defination
						{
							string glookFor = string.Format("#Link:ReferencedObject:{0} {1} {2}[END&gt;", rousageid, roid, oldRODbID.ToString());
							string greplaceWith = string.Format("#Link:ReferencedObject:{0} {1} {2}[END&gt;", rou.ROUsageID.ToString(), roid, newRODbID.ToString());
							if (glookFor != greplaceWith)
							{
								content.MyGrid.Data = content.MyGrid.Data.Replace(glookFor, greplaceWith);
							}
						}
					}
				}
				content.Save();
				if (isGrid)
					GridInfo.Refresh(content.MyGrid); // force the updated grid (table) to refresh
			}
		}

		// jsj 4-29-2016 appears to not be used
		//private void AddAnnotation(XmlReader xr)
		//{
		//	int itemid = int.Parse(xr.GetAttribute("itemid"));
		//	itemid = Old2NewItem[itemid];
		//	Item itm = Item.Get(itemid);
		//	int typeid = int.Parse(xr.GetAttribute("typeid"));
		//	string rtftext = xr.GetAttribute("rtftext");
		//	string searchtext = xr.GetAttribute("searchtext");
		//	string config = xr.GetAttribute("config");
		//	string userid = xr.GetAttribute("userid");
		//	DateTime dts = DateTime.Parse(xr.GetAttribute("dts"));
		//	Annotation ann = Annotation.MakeAnnotation(itm, AnnotationType.Get(typeid), rtftext, searchtext, config, dts, userid);
		//}
		private void AddImage(Content content, XmlNode xc)
		{
			XmlNode xn = xc.SelectSingleNode("image");
			int imagetype = int.Parse(xn.Attributes.GetNamedItem("imagetype").InnerText);
			string filename = xn.Attributes.GetNamedItem("filename").InnerText;
			byte[] data = Convert.FromBase64String(xn.Attributes.GetNamedItem("data").InnerText);
			string config = xn.Attributes.GetNamedItem("config").InnerText;
			string userid = xn.Attributes.GetNamedItem("userid").InnerText;
			DateTime dts = DateTime.Parse(xn.Attributes.GetNamedItem("dts").InnerText);
			VEPROMS.CSLA.Library.Image img = VEPROMS.CSLA.Library.Image.MakeImage(content, imagetype, filename, data, config, dts, userid);
			img.Save();
		}
		private void AddAnnotations(int itemID, XmlNode xn)
		{
			Item itm = Item.Get(itemID);
			foreach (XmlNode nd in xn.SelectNodes("annotation"))
			{
				int typeid = int.Parse(nd.Attributes.GetNamedItem("typeid").InnerText);
				string rtftext = nd.Attributes.GetNamedItem("rtftext").InnerText;
				string searchtext = nd.Attributes.GetNamedItem("searchtext").InnerText;
				string config = nd.Attributes.GetNamedItem("config").InnerText;
				string userid = nd.Attributes.GetNamedItem("userid").InnerText;
				DateTime dts = DateTime.Parse(nd.Attributes.GetNamedItem("dts").InnerText);
        AnnotationType annType = AnnotationType.GetByNameOrCreate(nd.Attributes.GetNamedItem("typename").InnerText);
				Annotation ann = Annotation.MakeAnnotation(itm, annType, rtftext, searchtext, config, dts, userid);
				ann.Save();
			}
		}
		private void AddParts(XmlNode myNode, ItemInfo parentInfo)
		{
			foreach (XmlNode xn in myNode.ChildNodes)
			{
				switch (xn.Name)
				{
					case "sections":
						AddSections(xn, parentInfo);
						break;
					case "cautions":
						AddCautions(xn, parentInfo);
						break;
					case "notes":
						AddNotes(xn, parentInfo);
						break;
					case "rnos":
						AddRNOs(xn, parentInfo);
						break;
					case "steps":
						AddSteps(xn, parentInfo);
						break;
					case "supinfos":
						AddSupInfos(xn, parentInfo);
						break;
					case "tables":
						AddTables(xn, parentInfo);
						break;
					case "entry": // this is word section max out the status bar
						lblImportStep.Text = "Word Section Data";
						pbImportStep.Maximum = 1;
						pbImportStep.PerformStep();
						break;
					default:
						break;
				}
			}
		}
		private void AddTables(XmlNode xn, ItemInfo parentInfo)
		{
			if (parentInfo.IsProcedure)
			{
				pbImportSection.Value = 0;
				pbImportStep.Value = 0;
				pbImportSection.Maximum = xn.ChildNodes.Count;
			}
			if (parentInfo.IsSection)
			{
				pbImportStep.Value = 0;
				pbImportStep.Maximum = xn.ChildNodes.Count;
			}
			ItemInfo prevInfo = null;
			foreach (XmlNode nd in xn.ChildNodes)
				prevInfo = AddTable(nd, parentInfo, prevInfo);
		}
		// jsj 2016Feb16 - This appears to not be used
		//private ItemInfo AddTable(XmlReader xr, ItemInfo parentInfo, ItemInfo prevInfo, int oldid)
		//{
		//	string number = xr.GetAttribute("number");
		//	string text = xr.GetAttribute("text");
		//	int steptype = int.Parse(xr.GetAttribute("type"));
		//	string formatid = xr.GetAttribute("formatid");
		//	string config = xr.GetAttribute("config");
		//	string userid = xr.GetAttribute("userid");
		//	DateTime dts = DateTime.Parse(xr.GetAttribute("dts"));
		//	Step step = Step.MakeStep(parentInfo, prevInfo, number, text, steptype, E_FromType.Table);
		//	step.DTS = dts;
		//	step.UserID = userid;
		//	if (formatid != string.Empty)
		//		step.MyContent.MyFormat = OldToNewFormat(int.Parse(formatid));
		//	step.MyContent.Config = config;
		//	step.MyContent.DTS = dts;
		//	step.MyContent.UserID = userid;
		//	step.Save();
		//	Old2NewItem.Add(oldid, step.ItemID);
		//	Old2NewContent.Add(int.Parse(xr.GetAttribute("contentid")), step.MyContent.ContentID);
		//	prevInfo = StepInfo.Get(step.ItemID);
		//	return prevInfo;
		//}
		private ItemInfo AddTable(XmlNode xn, ItemInfo parentInfo, ItemInfo prevInfo)
		{
			pbImportStep.PerformStep();
			lblImportStep.Text = string.Format("{0} of {1} Steps", pbImportStep.Value.ToString(), pbImportStep.Maximum.ToString());
			Application.DoEvents();
			XmlNode xc = xn.SelectSingleNode("content");
			Step step;
			string number = xc.Attributes.GetNamedItem("number").InnerText;
			string text = xc.Attributes.GetNamedItem("text").InnerText;
			int steptype = int.Parse(xc.Attributes.GetNamedItem("type").InnerText);
			string formatid = xc.Attributes.GetNamedItem("formatid").InnerText;
			string config = xc.Attributes.GetNamedItem("config").InnerText;
			config = StripEnhanced(config);
			int contentid = int.Parse(xc.Attributes.GetNamedItem("contentid").InnerText);
      CheckForFloatingFoldout(contentid, config);
      string userid = xc.Attributes.GetNamedItem("userid").InnerText;
			DateTime dts = DateTime.Parse(xc.Attributes.GetNamedItem("dts").InnerText);
			using (step = Step.MakeStep(parentInfo, prevInfo, number, text, steptype, E_FromType.Table))
			{
				step.DTS = dts;
				step.UserID = userid;
				// check for a null in case an older export file is being imported (the older files will not have the fromatfilename attribute)
				XmlNode fnNode = xc.Attributes.GetNamedItem("formatfilename"); //Bug fix B2016-103  the formatid in an Export file may not match the formatid where you are importing to
				string formatfilename = (fnNode != null) ? fnNode.InnerText : "";
				if (formatid != string.Empty)
					step.MyContent.MyFormat = OldToNewFormat(int.Parse(formatid), formatfilename);
				step.MyContent.Config = config;
				step.MyContent.DTS = dts;
				step.MyContent.UserID = userid;
				step.Save();
				if (!Old2NewItem.ContainsKey(int.Parse(xn.Attributes.GetNamedItem("itemid").InnerText)))
					Old2NewItem.Add(int.Parse(xn.Attributes.GetNamedItem("itemid").InnerText), step.ItemID);
				else
					Old2NewItem[int.Parse(xn.Attributes.GetNamedItem("itemid").InnerText)] = step.ItemID; // B2016-176, B2016-197 refresh saved ItemId with current ItemID
				if (!Old2NewContent.ContainsKey(int.Parse(xc.Attributes.GetNamedItem("contentid").InnerText)))
					Old2NewContent.Add(int.Parse(xc.Attributes.GetNamedItem("contentid").InnerText), step.MyContent.ContentID);
				else
					Old2NewContent[int.Parse(xc.Attributes.GetNamedItem("contentid").InnerText)] = step.MyContent.ContentID;  // B2016-176, B2016-197 refresh saved ContentID with current ContentID
				if (xc.SelectNodes("grid").Count > 0)
					AddGrid(step.MyContent, xc);
				if (xc.SelectNodes("image").Count > 0)
					AddImage(step.MyContent, xc);
				if (xn.SelectNodes("annotation").Count > 0)
					AddAnnotations(step.ItemID, xn);
				if (xc.SelectNodes("rousage").Count > 0)
					AddROUsages(step.MyContent, xc, true); // part of bug fix:  B2017060 to properly convert invalid RO to text
				if (xc.SelectNodes("transition").Count > 0)
					AddTransitions(step.MyContent, xc);
				prevInfo = StepInfo.Get(step.ItemID);
				if (xc.HasChildNodes)
					AddParts(xc, prevInfo);
			}
			return prevInfo;
		}
		private void AddSteps(XmlNode xn, ItemInfo parentInfo)
		{
			if (parentInfo.IsProcedure)
			{
				pbImportSection.Value = 0;
				pbImportStep.Value = 0;
				pbImportSection.Maximum = xn.ChildNodes.Count;
			}
			if (parentInfo.IsSection)
			{
				pbImportStep.Value = 0;
				pbImportStep.Maximum = xn.ChildNodes.Count;
			}
			ItemInfo prevInfo = null;
			foreach (XmlNode nd in xn.ChildNodes)
				prevInfo = AddStep(nd, parentInfo, prevInfo);
		}

		// jsj 4-29-2016 appears to not be used
		//private ItemInfo AddStep(XmlReader xr, ItemInfo parentInfo, ItemInfo prevInfo, int oldid)
		//{
		//	string number = xr.GetAttribute("number");
		//	string text = xr.GetAttribute("text");
		//	int steptype = int.Parse(xr.GetAttribute("type"));
		//	string formatid = xr.GetAttribute("formatid");
		//	string config = xr.GetAttribute("config");
		//	string userid = xr.GetAttribute("userid");
		//	DateTime dts = DateTime.Parse(xr.GetAttribute("dts"));
		//	Step step = Step.MakeStep(parentInfo, prevInfo, number, text, steptype, E_FromType.Step);
		//	step.DTS = dts;
		//	step.UserID = userid;
		//	string formatfilename = xr.GetAttribute("formatfilename"); //Bug fix B2016-103  the formatid in an Export file may not match the formatid where you are importing to
		//	if (formatid != string.Empty)
		//		step.MyContent.MyFormat = OldToNewFormat(int.Parse(formatid),formatfilename);
		//	step.MyContent.Config = config;
		//	step.MyContent.DTS = dts;
		//	step.MyContent.UserID = userid;
		//	step.Save();
		//	Old2NewItem.Add(oldid, step.ItemID);
		//	Old2NewContent.Add(int.Parse(xr.GetAttribute("contentid")), step.MyContent.ContentID);
		//	prevInfo = StepInfo.Get(step.ItemID);
		//	return prevInfo;
		//}
		private ItemInfo AddStep(XmlNode xn, ItemInfo parentInfo, ItemInfo prevInfo)
		{
			pbImportStep.PerformStep();
			lblImportStep.Text = string.Format("{0} of {1} Steps", pbImportStep.Value.ToString(), pbImportStep.Maximum.ToString());
			Application.DoEvents();
			XmlNode xc = xn.SelectSingleNode("content");
			Step step;
			string number = xc.Attributes.GetNamedItem("number").InnerText;
			string text = xc.Attributes.GetNamedItem("text").InnerText;
			int steptype = int.Parse(xc.Attributes.GetNamedItem("type").InnerText);
			string formatid = xc.Attributes.GetNamedItem("formatid").InnerText;
			string config = xc.Attributes.GetNamedItem("config").InnerText;
			config = StripEnhanced(config);
			int contentid = int.Parse(xc.Attributes.GetNamedItem("contentid").InnerText);
      CheckForFloatingFoldout(contentid, config);
      string userid = xc.Attributes.GetNamedItem("userid").InnerText;
			DateTime dts = DateTime.Parse(xc.Attributes.GetNamedItem("dts").InnerText);
			using (step = Step.MakeStep(parentInfo, prevInfo, number, text, steptype, E_FromType.Step))
			{
				step.DTS = dts;
				step.UserID = userid;
				// check for a null in case an older export file is being imported (the older files will not have the fromatfilename attribute)
				XmlNode fnNode = xc.Attributes.GetNamedItem("formatfilename"); //Bug fix B2016-103  the formatid in an Export file may not match the formatid where you are importing to
				string formatfilename = (fnNode != null) ? fnNode.InnerText : "";
				if (formatid != string.Empty)
					step.MyContent.MyFormat = OldToNewFormat(int.Parse(formatid), formatfilename);
				step.MyContent.Config = config;
				step.MyContent.DTS = dts;
				step.MyContent.UserID = userid;
				step.Save();
				if (!Old2NewItem.ContainsKey(int.Parse(xn.Attributes.GetNamedItem("itemid").InnerText)))
					Old2NewItem.Add(int.Parse(xn.Attributes.GetNamedItem("itemid").InnerText), step.ItemID);
				else
					Old2NewItem[int.Parse(xn.Attributes.GetNamedItem("itemid").InnerText)] = step.ItemID;  // B2016-176, B2016-197 refresh saved ItemId with current ItemID
				if (!Old2NewContent.ContainsKey(int.Parse(xc.Attributes.GetNamedItem("contentid").InnerText)))
					Old2NewContent.Add(int.Parse(xc.Attributes.GetNamedItem("contentid").InnerText), step.MyContent.ContentID);
				else
					Old2NewContent[int.Parse(xc.Attributes.GetNamedItem("contentid").InnerText)] = step.MyContent.ContentID;  // B2016-176, B2016-197 refresh saved ContentID with current ContentID
				if (xn.SelectNodes("annotation").Count > 0)
					AddAnnotations(step.ItemID, xn);
				if (xc.SelectNodes("rousage").Count > 0)
					AddROUsages(step.MyContent, xc);
				if (xc.SelectNodes("transition").Count > 0)
					AddTransitions(step.MyContent, xc);
				prevInfo = StepInfo.Get(step.ItemID);
				if (xc.HasChildNodes)
					AddParts(xc, prevInfo);
			}
			return prevInfo;
		}
		private void AddRNOs(XmlNode xn, ItemInfo parentInfo)
		{
			if (parentInfo.IsProcedure)
			{
				pbImportSection.Value = 0;
				pbImportStep.Value = 0;
				pbImportSection.Maximum = xn.ChildNodes.Count;
			}
			if (parentInfo.IsSection)
			{
				pbImportStep.Value = 0;
				pbImportStep.Maximum = xn.ChildNodes.Count;
			}
			ItemInfo prevInfo = null;
			foreach (XmlNode nd in xn.ChildNodes)
				prevInfo = AddRNO(nd, parentInfo, prevInfo);
		}
		private void AddSupInfos(XmlNode xn, ItemInfo parentInfo)
		{
			if (parentInfo.IsProcedure)
			{
				pbImportSection.Value = 0;
				pbImportStep.Value = 0;
				pbImportSection.Maximum = xn.ChildNodes.Count;
			}
			if (parentInfo.IsSection)
			{
				pbImportStep.Value = 0;
				pbImportStep.Maximum = xn.ChildNodes.Count;
			}
			ItemInfo prevInfo = null;
			foreach (XmlNode nd in xn.ChildNodes)
				prevInfo = AddSupInfo(nd, parentInfo, prevInfo);
		}
		// jsj 4-29-2016 appears to not be used
		//private ItemInfo AddRNO(XmlReader xr, ItemInfo parentInfo, ItemInfo prevInfo, int oldid)
		//{
		//	string number = xr.GetAttribute("number");
		//	string text = xr.GetAttribute("text");
		//	int steptype = int.Parse(xr.GetAttribute("type"));
		//	string formatid = xr.GetAttribute("formatid");
		//	string config = xr.GetAttribute("config");
		//	string userid = xr.GetAttribute("userid");
		//	DateTime dts = DateTime.Parse(xr.GetAttribute("dts"));
		//	Step step = Step.MakeStep(parentInfo, prevInfo, number, text, steptype, E_FromType.RNO);
		//	step.DTS = dts;
		//	step.UserID = userid;
		//	string formatfilename = xr.GetAttribute("formatfilename"); //Bug fix B2016-103  the formatid in an Export file may not match the formatid where you are importing to
		//	if (formatid != string.Empty)
		//		step.MyContent.MyFormat = OldToNewFormat(int.Parse(formatid), formatfilename);
		//	step.MyContent.Config = config;
		//	step.MyContent.DTS = dts;
		//	step.MyContent.UserID = userid;
		//	step.Save();
		//	Old2NewItem.Add(oldid, step.ItemID);
		//	Old2NewContent.Add(int.Parse(xr.GetAttribute("contentid")), step.MyContent.ContentID);
		//	prevInfo = StepInfo.Get(step.ItemID);
		//	return prevInfo;
		//}

		private ItemInfo AddRNO(XmlNode xn, ItemInfo parentInfo, ItemInfo prevInfo)
		{
			pbImportStep.PerformStep();
			lblImportStep.Text = string.Format("{0} of {1} Steps", pbImportStep.Value.ToString(), pbImportStep.Maximum.ToString());
			Application.DoEvents();
			XmlNode xc = xn.SelectSingleNode("content");
			Step step;
			string number = xc.Attributes.GetNamedItem("number").InnerText;
			string text = xc.Attributes.GetNamedItem("text").InnerText;
			int steptype = int.Parse(xc.Attributes.GetNamedItem("type").InnerText);
			string formatid = xc.Attributes.GetNamedItem("formatid").InnerText;
			string config = xc.Attributes.GetNamedItem("config").InnerText;
			config = StripEnhanced(config);
			int contentid = int.Parse(xc.Attributes.GetNamedItem("contentid").InnerText);
      CheckForFloatingFoldout(contentid, config);
      string userid = xc.Attributes.GetNamedItem("userid").InnerText;
			DateTime dts = DateTime.Parse(xc.Attributes.GetNamedItem("dts").InnerText);
			using (step = Step.MakeStep(parentInfo, prevInfo, number, text, steptype, E_FromType.RNO))
			{
				step.DTS = dts;
				step.UserID = userid;
				// check for a null in case an older export file is being imported (the older files will not have the fromatfilename attribute)
				XmlNode fnNode = xc.Attributes.GetNamedItem("formatfilename"); //Bug fix B2016-103  the formatid in an Export file may not match the formatid where you are importing to
				string formatfilename = (fnNode != null) ? fnNode.InnerText : "";
				if (formatid != string.Empty)
					step.MyContent.MyFormat = OldToNewFormat(int.Parse(formatid), formatfilename);
				step.MyContent.Config = config;
				step.MyContent.DTS = dts;
				step.MyContent.UserID = userid;
				step.Save();
				if (!Old2NewItem.ContainsKey(int.Parse(xn.Attributes.GetNamedItem("itemid").InnerText)))
					Old2NewItem.Add(int.Parse(xn.Attributes.GetNamedItem("itemid").InnerText), step.ItemID);
				else
					Old2NewItem[int.Parse(xn.Attributes.GetNamedItem("itemid").InnerText)] = step.ItemID;  // B2016-176, B2016-197 refresh saved ItemId with current ItemID
				if (!Old2NewContent.ContainsKey(int.Parse(xc.Attributes.GetNamedItem("contentid").InnerText)))
					Old2NewContent.Add(int.Parse(xc.Attributes.GetNamedItem("contentid").InnerText), step.MyContent.ContentID);
				else
					Old2NewContent[int.Parse(xc.Attributes.GetNamedItem("contentid").InnerText)] = step.MyContent.ContentID;  // B2016-176, B2016-197 refresh saved ContentID with current ContentID
				if (xn.SelectNodes("annotation").Count > 0)
					AddAnnotations(step.ItemID, xn);
				if (xc.SelectNodes("rousage").Count > 0)
					AddROUsages(step.MyContent, xc);
				if (xc.SelectNodes("transition").Count > 0)
					AddTransitions(step.MyContent, xc);
				prevInfo = StepInfo.Get(step.ItemID);
				if (xc.HasChildNodes)
					AddParts(xc, prevInfo);
			}
			return prevInfo;
		}
		private ItemInfo AddSupInfo(XmlNode xn, ItemInfo parentInfo, ItemInfo prevInfo)
		{
			pbImportStep.PerformStep();
			lblImportStep.Text = string.Format("{0} of {1} Steps", pbImportStep.Value.ToString(), pbImportStep.Maximum.ToString());
			Application.DoEvents();
			XmlNode xc = xn.SelectSingleNode("content");
			Step step;
			string number = xc.Attributes.GetNamedItem("number").InnerText;
			string text = xc.Attributes.GetNamedItem("text").InnerText;
			int steptype = int.Parse(xc.Attributes.GetNamedItem("type").InnerText);
			string formatid = xc.Attributes.GetNamedItem("formatid").InnerText;
			string config = xc.Attributes.GetNamedItem("config").InnerText;
			config = StripEnhanced(config);
			int contentid = int.Parse(xc.Attributes.GetNamedItem("contentid").InnerText);
			CheckForFloatingFoldout(contentid, config);
			string userid = xc.Attributes.GetNamedItem("userid").InnerText;
			DateTime dts = DateTime.Parse(xc.Attributes.GetNamedItem("dts").InnerText);
			using (step = Step.MakeStep(parentInfo, prevInfo, number, text, steptype, E_FromType.SupInfo))
			{
				step.DTS = dts;
				step.UserID = userid;
				// check for a null in case an older export file is being imported (the older files will not have the fromatfilename attribute)
				XmlNode fnNode = xc.Attributes.GetNamedItem("formatfilename"); //Bug fix B2016-103  the formatid in an Export file may not match the formatid where you are importing to
				string formatfilename = (fnNode != null) ? fnNode.InnerText : "";
				if (formatid != string.Empty)
					step.MyContent.MyFormat = OldToNewFormat(int.Parse(formatid), formatfilename);
				step.MyContent.Config = config;
				step.MyContent.DTS = dts;
				step.MyContent.UserID = userid;
				step.Save();
				if (!Old2NewItem.ContainsKey(int.Parse(xn.Attributes.GetNamedItem("itemid").InnerText)))
					Old2NewItem.Add(int.Parse(xn.Attributes.GetNamedItem("itemid").InnerText), step.ItemID);
				if (!Old2NewContent.ContainsKey(int.Parse(xc.Attributes.GetNamedItem("contentid").InnerText)))
					Old2NewContent.Add(int.Parse(xc.Attributes.GetNamedItem("contentid").InnerText), step.MyContent.ContentID);
				if (xn.SelectNodes("annotation").Count > 0)
					AddAnnotations(step.ItemID, xn);
				if (xc.SelectNodes("rousage").Count > 0)
					AddROUsages(step.MyContent, xc);
				if (xc.SelectNodes("transition").Count > 0)
					AddTransitions(step.MyContent, xc);
				prevInfo = StepInfo.Get(step.ItemID);
				if (xc.HasChildNodes)
					AddParts(xc, prevInfo);
			}
			return prevInfo;
		}
		private void AddNotes(XmlNode xn, ItemInfo parentInfo)
		{
			if (parentInfo.IsProcedure)
			{
				pbImportSection.Value = 0;
				pbImportStep.Value = 0;
				pbImportSection.Maximum = xn.ChildNodes.Count;
			}
			if (parentInfo.IsSection)
			{
				pbImportStep.Value = 0;
				pbImportStep.Maximum = xn.ChildNodes.Count;
			}
			ItemInfo prevInfo = null;
			foreach (XmlNode nd in xn.ChildNodes)
				prevInfo = AddNote(nd, parentInfo, prevInfo);
		}

		// jsj 4-29-2016 appears to not be used
		//private ItemInfo AddNote(XmlReader xr, ItemInfo parentInfo, ItemInfo prevInfo, int oldid)
		//{
		//	string number = xr.GetAttribute("number");
		//	string text = xr.GetAttribute("text");
		//	int steptype = int.Parse(xr.GetAttribute("type"));
		//	string formatid = xr.GetAttribute("formatid");
		//	string config = xr.GetAttribute("config");
		//	string userid = xr.GetAttribute("userid");
		//	DateTime dts = DateTime.Parse(xr.GetAttribute("dts"));
		//	Step step = Step.MakeStep(parentInfo, prevInfo, number, text, steptype, E_FromType.Note);
		//	step.DTS = dts;
		//	step.UserID = userid;
		//	string formatfilename = xr.GetAttribute("formatfilename"); //Bug fix B2016-103  the formatid in an Export file may not match the formatid where you are importing to
		//	if (formatid != string.Empty)
		//		step.MyContent.MyFormat = OldToNewFormat(int.Parse(formatid), formatfilename);
		//	step.MyContent.Config = config;
		//	step.MyContent.DTS = dts;
		//	step.MyContent.UserID = userid;
		//	step.Save();
		//	Old2NewItem.Add(oldid, step.ItemID);
		//	Old2NewContent.Add(int.Parse(xr.GetAttribute("contentid")), step.MyContent.ContentID);
		//	prevInfo = StepInfo.Get(step.ItemID);
		//	return prevInfo;
		//}

		private ItemInfo AddNote(XmlNode xn, ItemInfo parentInfo, ItemInfo prevInfo)
		{
			pbImportStep.PerformStep();
			lblImportStep.Text = string.Format("{0} of {1} Steps", pbImportStep.Value.ToString(), pbImportStep.Maximum.ToString());
			Application.DoEvents();
			XmlNode xc = xn.SelectSingleNode("content");
			Step step;
			string number = xc.Attributes.GetNamedItem("number").InnerText;
			string text = xc.Attributes.GetNamedItem("text").InnerText;
			int steptype = int.Parse(xc.Attributes.GetNamedItem("type").InnerText);
			string formatid = xc.Attributes.GetNamedItem("formatid").InnerText;
			string config = xc.Attributes.GetNamedItem("config").InnerText;
			config = StripEnhanced(config);
			int contentid = int.Parse(xc.Attributes.GetNamedItem("contentid").InnerText);
      CheckForFloatingFoldout(contentid, config);
      string userid = xc.Attributes.GetNamedItem("userid").InnerText;
			DateTime dts = DateTime.Parse(xc.Attributes.GetNamedItem("dts").InnerText);
			using (step = Step.MakeStep(parentInfo, prevInfo, number, text, steptype, E_FromType.Note))
			{
				step.DTS = dts;
				step.UserID = userid;
				// check for a null in case an older export file is being imported (the older files will not have the fromatfilename attribute)
				XmlNode fnNode = xc.Attributes.GetNamedItem("formatfilename"); //Bug fix B2016-103  the formatid in an Export file may not match the formatid where you are importing to
				string formatfilename = (fnNode != null) ? fnNode.InnerText : "";
				if (formatid != string.Empty)
					step.MyContent.MyFormat = OldToNewFormat(int.Parse(formatid), formatfilename);
				step.MyContent.Config = config;
				step.MyContent.DTS = dts;
				step.MyContent.UserID = userid;
				step.Save();
				if (!Old2NewItem.ContainsKey(int.Parse(xn.Attributes.GetNamedItem("itemid").InnerText)))
					Old2NewItem.Add(int.Parse(xn.Attributes.GetNamedItem("itemid").InnerText), step.ItemID);
				else
					Old2NewItem[int.Parse(xn.Attributes.GetNamedItem("itemid").InnerText)] = step.ItemID;  // B2016-176, B2016-197 refresh saved ItemId with current ItemID
				if (!Old2NewContent.ContainsKey(int.Parse(xc.Attributes.GetNamedItem("contentid").InnerText)))
					Old2NewContent.Add(int.Parse(xc.Attributes.GetNamedItem("contentid").InnerText), step.MyContent.ContentID);
				else
					Old2NewContent[int.Parse(xc.Attributes.GetNamedItem("contentid").InnerText)] = step.MyContent.ContentID;  // B2016-176, B2016-197 refresh saved ContentID with current ContentID
				if (xn.SelectNodes("annotation").Count > 0)
					AddAnnotations(step.ItemID, xn);
				if (xc.SelectNodes("rousage").Count > 0)
					AddROUsages(step.MyContent, xc);
				if (xc.SelectNodes("transition").Count > 0)
					AddTransitions(step.MyContent, xc);
				prevInfo = StepInfo.Get(step.ItemID);
				if (xc.HasChildNodes)
					AddParts(xc, prevInfo);
			}
			return prevInfo;
		}
		private void AddCautions(XmlNode xn, ItemInfo parentInfo)
		{
			if (parentInfo.IsProcedure)
			{
				pbImportSection.Value = 0;
				pbImportStep.Value = 0;
				pbImportSection.Maximum = xn.ChildNodes.Count;
			}
			if (parentInfo.IsSection)
			{
				pbImportStep.Value = 0;
				pbImportStep.Maximum = xn.ChildNodes.Count;
			}
			ItemInfo prevInfo = null;
			foreach (XmlNode nd in xn.ChildNodes)
				prevInfo = AddCaution(nd, parentInfo, prevInfo);
		}

		// jsj 4-29-2016 appears to not be used
		//private ItemInfo AddCaution(XmlReader xr, ItemInfo parentInfo, ItemInfo prevInfo, int oldid)
		//{
		//	string number = xr.GetAttribute("number");
		//	string text = xr.GetAttribute("text");
		//	int steptype = int.Parse(xr.GetAttribute("type"));
		//	string formatid = xr.GetAttribute("formatid");
		//	string config = xr.GetAttribute("config");
		//	string userid = xr.GetAttribute("userid");
		//	DateTime dts = DateTime.Parse(xr.GetAttribute("dts"));
		//	Step step = Step.MakeStep(parentInfo, prevInfo, number, text, steptype, E_FromType.Caution);
		//	step.DTS = dts;
		//	step.UserID = userid;
		//	string formatfilename = xr.GetAttribute("formatfilename"); //Bug fix B2016-103  the formatid in an Export file may not match the formatid where you are importing to
		//	if (formatid != string.Empty)
		//		step.MyContent.MyFormat = OldToNewFormat(int.Parse(formatid), formatfilename);
		//	step.MyContent.Config = config;
		//	step.MyContent.DTS = dts;
		//	step.MyContent.UserID = userid;
		//	step.Save();
		//	Old2NewItem.Add(oldid, step.ItemID);
		//	Old2NewContent.Add(int.Parse(xr.GetAttribute("contentid")), step.MyContent.ContentID);
		//	prevInfo = StepInfo.Get(step.ItemID);
		//	return prevInfo;
		//}

		private ItemInfo AddCaution(XmlNode xn, ItemInfo parentInfo, ItemInfo prevInfo)
		{
			pbImportStep.PerformStep();
			lblImportStep.Text = string.Format("{0} of {1} Steps", pbImportStep.Value.ToString(), pbImportStep.Maximum.ToString());
			Application.DoEvents();
			XmlNode xc = xn.SelectSingleNode("content");
			Step step;
			string number = xc.Attributes.GetNamedItem("number").InnerText;
			string text = xc.Attributes.GetNamedItem("text").InnerText;
			int steptype = int.Parse(xc.Attributes.GetNamedItem("type").InnerText);
			string formatid = xc.Attributes.GetNamedItem("formatid").InnerText;
			string config = xc.Attributes.GetNamedItem("config").InnerText;
			config = StripEnhanced(config);
			int contentid = int.Parse(xc.Attributes.GetNamedItem("contentid").InnerText);
      CheckForFloatingFoldout(contentid, config);
      string userid = xc.Attributes.GetNamedItem("userid").InnerText;
			DateTime dts = DateTime.Parse(xc.Attributes.GetNamedItem("dts").InnerText);
			using (step = Step.MakeStep(parentInfo, prevInfo, number, text, steptype, E_FromType.Caution))
			{
				step.DTS = dts;
				step.UserID = userid;
				// check for a null in case an older export file is being imported (the older files will not have the fromatfilename attribute)
				XmlNode fnNode = xc.Attributes.GetNamedItem("formatfilename"); //Bug fix B2016-103  the formatid in an Export file may not match the formatid where you are importing to
				string formatfilename = (fnNode != null) ? fnNode.InnerText : "";
				if (formatid != string.Empty)
					step.MyContent.MyFormat = OldToNewFormat(int.Parse(formatid), formatfilename);
				step.MyContent.Config = config;
				step.MyContent.DTS = dts;
				step.MyContent.UserID = userid;
				step.Save();
				if (!Old2NewItem.ContainsKey(int.Parse(xn.Attributes.GetNamedItem("itemid").InnerText)))
					Old2NewItem.Add(int.Parse(xn.Attributes.GetNamedItem("itemid").InnerText), step.ItemID);
				else
					Old2NewItem[int.Parse(xn.Attributes.GetNamedItem("itemid").InnerText)] = step.ItemID;  // B2016-176, B2016-197 refresh saved ItemId with current ItemID
				if (!Old2NewContent.ContainsKey(int.Parse(xc.Attributes.GetNamedItem("contentid").InnerText)))
					Old2NewContent.Add(int.Parse(xc.Attributes.GetNamedItem("contentid").InnerText), step.MyContent.ContentID);
				else
					Old2NewContent[int.Parse(xc.Attributes.GetNamedItem("contentid").InnerText)] = step.MyContent.ContentID;  // B2016-176, B2016-197 refresh saved ContentID with current ContentID
				if (xn.SelectNodes("annotation").Count > 0)
					AddAnnotations(step.ItemID, xn);
				if (xc.SelectNodes("rousage").Count > 0)
					AddROUsages(step.MyContent, xc);
				if (xc.SelectNodes("transition").Count > 0)
					AddTransitions(step.MyContent, xc);
				prevInfo = StepInfo.Get(step.ItemID);
				if (xc.HasChildNodes)
					AddParts(xc, prevInfo);
			}
			return prevInfo;
		}
		private void AddSections(XmlNode xn, ItemInfo parentInfo)
		{
			if (parentInfo.IsProcedure)
			{
				pbImportSection.Value = 0;
				pbImportStep.Value = 0;
				pbImportSection.Maximum = xn.ChildNodes.Count;
			}
			if (parentInfo.IsSection)
			{
				pbImportStep.Value = 0;
				pbImportStep.Maximum = xn.ChildNodes.Count;
			}
			ItemInfo prevInfo = null;
			foreach (XmlNode nd in xn.ChildNodes)
				prevInfo = AddSection(nd, parentInfo, prevInfo);
		}
		private Dictionary<string, string> GetSectionData(XmlReader xr)
		{
			Dictionary<string, string> rv = new Dictionary<string, string>();
			rv.Add("itemid", xr.GetAttribute("itemid"));
			return rv;
		}

		// js j4-29-2016 appears to not be used
		//private ItemInfo AddSection(XmlReader xr, ItemInfo parentInfo, ItemInfo prevInfo, int oldid)
		//{
		//	string number = xr.GetAttribute("number");
		//	string text = xr.GetAttribute("text");
		//	int sectiontype = int.Parse(xr.GetAttribute("type"));
		//	string formatid = xr.GetAttribute("formatid");
		//	string config = xr.GetAttribute("config");
		//	string userid = xr.GetAttribute("userid");
		//	DateTime dts = DateTime.Parse(xr.GetAttribute("dts"));
		//	Section sect = Section.MakeSection(parentInfo, prevInfo, number, text, sectiontype);
		//	sect.DTS = dts;
		//	sect.UserID = userid;
		//	string formatfilename = xr.GetAttribute("formatfilename"); //Bug fix B2016-103  the formatid in an Export file may not match the formatid where you are importing to
		//	if (formatid != string.Empty)
		//		sect.MyContent.MyFormat = OldToNewFormat(int.Parse(formatid), formatfilename);
		//	sect.MyContent.Config = config;
		//	sect.MyContent.DTS = dts;
		//	sect.MyContent.UserID = userid;
		//	sect.Save();
		//	Old2NewItem.Add(oldid, sect.ItemID);
		//	Old2NewContent.Add(int.Parse(xr.GetAttribute("contentid")), sect.MyContent.ContentID);
		//	prevInfo = SectionInfo.Get(sect.ItemID);
		//	return prevInfo;
		//}

		private ItemInfo AddSection(XmlNode xn, ItemInfo parentInfo, ItemInfo prevInfo)
		{
			pbImportSection.PerformStep();
			lblImportSection.Text = string.Format("{0} of {1} Sections", pbImportSection.Value.ToString(), pbImportSection.Maximum.ToString());
			Application.DoEvents();
			XmlNode xc = xn.SelectSingleNode("content");
			Section sect;
			string number = xc.Attributes.GetNamedItem("number").InnerText;
			string text = xc.Attributes.GetNamedItem("text").InnerText;
			int sectiontype = int.Parse(xc.Attributes.GetNamedItem("type").InnerText);
			string formatid = xc.Attributes.GetNamedItem("formatid").InnerText;
			string config = xc.Attributes.GetNamedItem("config").InnerText;
			config = StripEnhanced(config);
      int contentid = int.Parse(xc.Attributes.GetNamedItem("contentid").InnerText);
      CheckForFloatingFoldout(contentid, config);
			string userid = xc.Attributes.GetNamedItem("userid").InnerText;
			DateTime dts = DateTime.Parse(xc.Attributes.GetNamedItem("dts").InnerText);
			sect = Section.MakeSection(parentInfo, prevInfo, number, text, sectiontype);
			sect.DTS = dts;
			sect.UserID = userid;
			// check for a null in case an older export file is being imported (the older files will not have the fromatfilename attribute)
			XmlNode fnNode = xc.Attributes.GetNamedItem("formatfilename"); //Bug fix B2016-103  the formatid in an Export file may not match the formatid where you are importing to
			string formatfilename = (fnNode != null) ? fnNode.InnerText : "";
			if (formatid != string.Empty)
				sect.MyContent.MyFormat = OldToNewFormat(int.Parse(formatid), formatfilename);
			sect.MyContent.Config = config;
			sect.MyContent.DTS = dts;
			sect.MyContent.UserID = userid;
			sect.Save();
			if (!Old2NewContent.ContainsKey(int.Parse(xc.Attributes.GetNamedItem("contentid").InnerText)))
				Old2NewContent.Add(int.Parse(xc.Attributes.GetNamedItem("contentid").InnerText), sect.MyContent.ContentID);
			else
				Old2NewContent[int.Parse(xc.Attributes.GetNamedItem("contentid").InnerText)] = sect.MyContent.ContentID;  // B2016-176, B2016-197 refresh saved ContentID with current ContentID
			if (!Old2NewItem.ContainsKey(int.Parse(xn.Attributes.GetNamedItem("itemid").InnerText)))
				Old2NewItem.Add(int.Parse(xn.Attributes.GetNamedItem("itemid").InnerText), sect.ItemID);
			else
				Old2NewItem[int.Parse(xn.Attributes.GetNamedItem("itemid").InnerText)] = sect.ItemID;  // B2016-176, B2016-197 refresh saved ItemId with current ItemID
			if (xn.SelectNodes("annotation").Count > 0)
				AddAnnotations(sect.ItemID, xn);
			if (xc.SelectNodes("entry").Count > 0)
				AddEntry(sect.MyContent, xc);
			if (xc.SelectNodes("rousage").Count > 0)
				AddROUsages(sect.MyContent, xc);
      if (xc.SelectNodes("transition").Count > 0)
        AddTransitions(sect.MyContent, xc);
      prevInfo = SectionInfo.Get(sect.ItemID);
			if (xc.HasChildNodes)
				AddParts(xc, prevInfo);
			return prevInfo;
		}
		private string StripEnhanced(string config)
		{
			if (config.Length > 0)
			{
				XmlDocument xd = new XmlDocument();
				xd.LoadXml(config);
				XmlNodeList nl = xd.DocumentElement.SelectNodes("//Enhanced");
				foreach (XmlNode nd in nl)
					nd.ParentNode.RemoveChild(nd);
				return xd.OuterXml;
			}
			return config;
		}
    private void CheckForFloatingFoldout(int contentid, string config)
    {
      if (config != string.Empty)
      {
        XmlDocument xd = new XmlDocument();
        xd.LoadXml(config);
        XmlNode xn = xd.SelectSingleNode("Config/Step/@FloatingFoldout");
        if (xn != null)
          floatFoldout.Add(contentid, int.Parse(xn.InnerText));
      }
    }

		// jsj 2016Feb16 - This appears to not be used
		//private void AddGrid(XmlReader xr)
		//{
		//	int contentid = int.Parse(xr.GetAttribute("contentid"));
		//	contentid = Old2NewContent[contentid];
		//	Content content = Content.Get(contentid);
		//	string data = xr.GetAttribute("data");
		//	string config = xr.GetAttribute("config");
		//	string userid = xr.GetAttribute("userid");
		//	DateTime dts = DateTime.Parse(xr.GetAttribute("dts"));
		//	Grid gg = Grid.MakeGrid(content, data, config, dts, userid);
		//}

		private void AddGrid(Content content, XmlNode xc)
		{
			XmlNode nd = xc.SelectSingleNode("grid");
			string data = nd.Attributes.GetNamedItem("data").InnerText;
      XmlDocument xd = new XmlDocument();
      xd.LoadXml(data);
      XmlNode gn = xd.SelectSingleNode("C1FlexGrid/Control/IsRoTable");
			if (gn.InnerText.ToLower() == "true")
			{
				if (_ConvertROsToTextDuringImport)
				{
					gn.InnerText = "False";
					ROToTextAnnotation(content, "RO Table"); // B2016-225 (follow through) add annotation when RO is converted to text 
				}
				else
				{
					gn = xd.SelectSingleNode("C1FlexGrid/Control/RODbId");
					gn.InnerText = newRODbID.ToString();
				}
				data = xd.OuterXml;
			}
			else
			{
				XmlNodeList nl = xd.SelectNodes("C1FlexGrid/Cells/Cell/Data");
				bool modified = false;
				if (_ConvertROsToTextDuringImport)
				{
					string newvalue = "";
					// if it's an ro within a table, need to process into an flex grid to save the grid data:
					string findLinkXml = @"&lt;START\].*?\[END&gt;";
					//string lookForXml = string.Format(@"^&lt;START\](\\[^v \\]+)*\\v0(\\[^v '?{{}}\\]+)*( |\\u[0-9]{{1,4}}?|\\'[0-9a-fA-F]{{2}}|\\[{{}}~])(.*?)(\\[^v'?{{}} \\]+)*\\v(\\[^v \\]+)* #Link:ReferencedObject:{0} .*?\[END&gt;$", rousageid);
					string lookForXml = @"^&lt;START\](\\[^v \\]+)*\\v0(\\[^v '?{{}}\\]+)*( |\\u[0-9]{{1,4}}?|\\'[0-9a-fA-F]{{2}}|\\[{{}}~])(.*?)(\\[^v'?{{}} \\]+)*\\v(\\[^v \\]+)* #Link:ReferencedObject:.*?\[END&gt;$";
					MatchCollection msg = Regex.Matches(data, findLinkXml);
					int nmsg = msg.Count;
					for (int i = nmsg - 1; i >= 0; i--)
					{
						Match mmg = msg[i];
						Match mg = Regex.Match(mmg.Value, lookForXml);// Regex.Match(MyGrid.Data, lookForXml);
						if (mg != null && mg.Groups.Count > 1)
						{
							int myIndex = mg.Groups[4].Index + mmg.Index;
							int myLength = mg.Groups[4].Length;
							if (mg.Groups[3].Value != " ")
							{
								myIndex = mg.Groups[3].Index + mmg.Index;
								myLength += mg.Groups[3].Length;
							}
							string ss = data.Substring(myIndex, myLength);
							if (ss != newvalue)
							{
								data = Content.ConvertGridROsToText(data, mmg, mg, ss); // part of bug fix:  B2017060 to properly convert invalid RO to text
							}
						}
					}
				}
				else
				{
					string lookFor = string.Format(" {0}[END", oldRODbID.ToString());
					string replaceWith = string.Format(" {0}[END", newRODbID.ToString());
					foreach (XmlNode nn in nl)
					{
						if (nn.InnerText.Contains("#Link:ReferencedObject:"))
						{
							nn.InnerText = nn.InnerText.Replace(lookFor, replaceWith);
							modified = true;
						}
					}
					if (modified)
						data = xd.OuterXml;
				}
			}
			string config = nd.Attributes.GetNamedItem("config").InnerText;
			string userid = nd.Attributes.GetNamedItem("userid").InnerText;
			DateTime dts = DateTime.Parse(nd.Attributes.GetNamedItem("dts").InnerText);
			Grid gg = Grid.MakeGrid(content, data, config, dts, userid);
			gg.Save();
			content.MyGrid = gg;
		}


		// jsj 4-29-2016 appears to not be used
		//private Dictionary<string, string> AddEntry(XmlReader xr)
		//{
		//	Dictionary<string, string> dic = new Dictionary<string, string>();
		//	dic.Add("contentid", xr.GetAttribute("contentid"));
		//	dic.Add("dts", xr.GetAttribute("dts"));
		//	dic.Add("userid", xr.GetAttribute("userid"));
		//	return dic;
		//}

		private void AddEntry(Content content, XmlNode xc)
		{
			XmlNode nd = xc.SelectSingleNode("entry");
			string userid = nd.Attributes.GetNamedItem("userid").InnerText;
			DateTime dts = DateTime.Parse(nd.Attributes.GetNamedItem("dts").InnerText);
			Document dd = AddDocument(nd.SelectSingleNode("document"));
			Entry ee = Entry.MakeEntry(content, dd, dts, userid);
			ee.Save();
		}
		// jsj 2016Feb16 - This appears to not be used
		//private void AddDocument(XmlReader xr, Dictionary<string, string> dic)
		//{
		//	string libtitle = xr.GetAttribute("libtitle");
		//	byte[] doccontent = Convert.FromBase64String(xr.GetAttribute("doccontent"));
		//	string docascii = xr.GetAttribute("docascii");
		//	string config = xr.GetAttribute("config");
		//	string userid = xr.GetAttribute("userid");
		//	DateTime dts = DateTime.Parse(xr.GetAttribute("dts"));
		//	string fileextension = xr.GetAttribute("fileextension");
		//	Document dd = Document.MakeDocument(libtitle, doccontent, docascii, config, dts, userid, fileextension);
		//	int contentid = int.Parse(dic["contentid"]);
		//	contentid = Old2NewContent[contentid];
		//	Content content = Content.Get(contentid);
		//	dts = DateTime.Parse(dic["dts"]);
		//	userid = dic["userid"];
		//	Entry ee = Entry.MakeEntry(content, dd, dts, userid);
		//}
		private Document AddDocument(XmlNode xn)
		{
      Document d;
      int docid = int.Parse(xn.Attributes.GetNamedItem("docid").InnerText);
      if (Old2NewLibDoc.ContainsKey(docid))
      {
        docid = Old2NewLibDoc[docid];
        d = Document.Get(docid);
      }
      else
      {
        string libtitle = xn.Attributes.GetNamedItem("libtitle").InnerText;
        DateTime dts = DateTime.Parse(xn.Attributes.GetNamedItem("dts").InnerText);
				if (libtitle != "")
				{
					DocumentInfoList dil = DocumentInfoList.GetLibraries(true);
					foreach (DocumentInfo di in dil)
					{
						if (di.LibTitle == libtitle && di.DTS == dts)
							return di.Get(); // found library document in exiting database
					}
				}
        byte[] doccontent = Convert.FromBase64String(xn.Attributes.GetNamedItem("doccontent").InnerText);
        string docascii = xn.Attributes.GetNamedItem("docascii").InnerText;
        string config = xn.Attributes.GetNamedItem("config").InnerText;
        string userid = xn.Attributes.GetNamedItem("userid").InnerText;
        string fileextension = xn.Attributes.GetNamedItem("fileextension").InnerText;
        d = Document.MakeDocument(libtitle, doccontent, docascii, config, dts, userid, fileextension);
        d.Save();
        Old2NewLibDoc.Add(docid, d.DocID);
      }
			return d;
		}
		#endregion

    private void btnCloseExport_Click(object sender, EventArgs e)
    {
      this.Close();
    }

    private void btnCloseImport_Click(object sender, EventArgs e)
    {
      this.Close();
    }
	}
}
