/// <summary>
        /// constructor
        /// </summary>
        /// <param name="hWnd"></param>
        public TDlgSelectCSVSeparatorTester(IntPtr hWnd)
        {
            TheObject = (TDlgSelectCSVSeparator)Form.FromHandle(hWnd);

            if (TheObject == null)
            {
                throw new Exception("cannot find form for TDlgSelectCSVSeparatorTester");
            }
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="AExchangeRateDT">The corporate or daily exchange rate table</param>
        /// <param name="AImportMode">Determines whether corporate or daily exchange rates specified - either 'Daily' or 'Corporate'</param>
        /// <param name="AResultCollection">A validation collection to which errors will be added</param>
        /// <returns>The number of rows that were actually imported.  Rows that duplicate existing rows do not count.
        /// This is usually because this is an attempt to import again after a failed previous attempt.</returns>
        public static int ImportCurrencyExRates(TTypedDataTable AExchangeRateDT, string AImportMode, TVerificationResultCollection AResultCollection)
        {
            OpenFileDialog DialogBox = new OpenFileDialog();

            DialogBox.Title = Catalog.GetString("Import exchange rates from spreadsheet file");
            DialogBox.Filter = Catalog.GetString("Spreadsheet files (*.csv)|*.csv");

            if (DialogBox.ShowDialog() == DialogResult.OK)
            {
                String dateFormatString = TUserDefaults.GetStringDefault("Imp Date", "MDY");
                String impOptions = TUserDefaults.GetStringDefault("Imp Options", ";" + TDlgSelectCSVSeparator.NUMBERFORMAT_AMERICAN);

                TDlgSelectCSVSeparator DlgSeparator = new TDlgSelectCSVSeparator(false);
                Boolean fileCanOpen = DlgSeparator.OpenCsvFile(DialogBox.FileName);

                if (!fileCanOpen)
                {
                    MessageBox.Show(Catalog.GetString("Unable to open file."),
                        Catalog.GetString("Import Exchange Rates"),
                        MessageBoxButtons.OK,
                        MessageBoxIcon.Stop);
                    return 0;
                }

                DlgSeparator.DateFormat = dateFormatString;

                if (impOptions.Length > 1)
                {
                    DlgSeparator.NumberFormat = impOptions.Substring(1);
                }

                DlgSeparator.SelectedSeparator = impOptions.Substring(0, 1);

                if (DlgSeparator.ShowDialog() == DialogResult.OK)
                {
                    // Save the settings that we specified
                    impOptions = DlgSeparator.SelectedSeparator;
                    impOptions += DlgSeparator.NumberFormat;
                    TUserDefaults.SetDefault("Imp Options", impOptions);
                    TUserDefaults.SetDefault("Imp Date", DlgSeparator.DateFormat);
                    TUserDefaults.SaveChangedUserDefaults();

                    // Do the import and retuen the number of rows imported and any messages
                    return ImportCurrencyExRatesFromCSV(AExchangeRateDT,
                        DialogBox.FileName,
                        DlgSeparator.SelectedSeparator,
                        DlgSeparator.NumberFormat,
                        DlgSeparator.DateFormat,
                        AImportMode,
                        AResultCollection);
                }
            }

            return 0;
        }
        /// <summary>
        /// convert from all sorts of formats into xml document;
        /// shows a dialog to the user to select the file to import
        /// </summary>
        /// <returns></returns>
        public static XmlDocument ImportWithDialog(string ADialogTitle, out string AFilename)
        {
            // TODO support import from Excel and OpenOffice files
            // See also http://sourceforge.net/apps/mediawiki/openpetraorg/index.php?title=Data_liberation
            OpenFileDialog DialogOpen = new OpenFileDialog();

            AFilename = "";

            DialogOpen.Filter = Catalog.GetString(
                "Text file (*.yml)|*.yml|XML file (*.xml)|*.xml|Spreadsheet file (*.csv)|All supported file formats (*.yml, *.xml, *.csv)|*.csv;*.yml;*.xml|");
            DialogOpen.FilterIndex      = 4;
            DialogOpen.RestoreDirectory = true;
            DialogOpen.Title            = ADialogTitle;

            if (DialogOpen.ShowDialog() == DialogResult.OK)
            {
                AFilename = DialogOpen.FileName;

                if (DialogOpen.FileName.ToLower().EndsWith("csv"))
                {
                    // select separator, make sure there is a header line with the column captions/names
                    TDlgSelectCSVSeparator dlgSeparator = new TDlgSelectCSVSeparator(true);
                    Boolean fileCanOpen = dlgSeparator.OpenCsvFile(DialogOpen.FileName);

                    if (!fileCanOpen)
                    {
                        throw new Exception(String.Format(Catalog.GetString("File {0} Cannot be opened."), DialogOpen.FileName));
                    }

                    dlgSeparator.SelectedSeparator = StringHelper.GetCSVSeparator(dlgSeparator.FileContent);

                    if (dlgSeparator.ShowDialog() == DialogResult.OK)
                    {
                        XmlDocument doc = TCsv2Xml.ParseCSVContent2Xml(dlgSeparator.FileContent, dlgSeparator.SelectedSeparator);
                        return(doc);
                    }
                }
                else if (DialogOpen.FileName.ToLower().EndsWith("xml"))
                {
                    XmlDocument doc = new XmlDocument();
                    doc.Load(DialogOpen.FileName);
                    return(doc);
                }
                else if (DialogOpen.FileName.ToLower().EndsWith("yml"))
                {
                    TYml2Xml yml = new TYml2Xml(DialogOpen.FileName);
                    return(yml.ParseYML2XML());
                }
            }

            return(null);
        }
        /// <summary>
        /// convert from all sorts of formats into xml document;
        /// shows a dialog to the user to select the file to import
        /// </summary>
        /// <returns></returns>
        public static XmlDocument ImportWithDialog(string ADialogTitle, out string AFilename)
        {
            // TODO support import from Excel and OpenOffice files
            // See also http://sourceforge.net/apps/mediawiki/openpetraorg/index.php?title=Data_liberation
            OpenFileDialog DialogOpen = new OpenFileDialog();

            AFilename = "";

            DialogOpen.Filter = Catalog.GetString(
                "Text file (*.yml)|*.yml|XML file (*.xml)|*.xml|Spreadsheet file (*.csv)|All supported file formats (*.yml, *.xml, *.csv)|*.csv;*.yml;*.xml|");
            DialogOpen.FilterIndex = 4;
            DialogOpen.RestoreDirectory = true;
            DialogOpen.Title = ADialogTitle;

            if (DialogOpen.ShowDialog() == DialogResult.OK)
            {
                AFilename = DialogOpen.FileName;

                if (DialogOpen.FileName.ToLower().EndsWith("csv"))
                {
                    // select separator, make sure there is a header line with the column captions/names
                    TDlgSelectCSVSeparator dlgSeparator = new TDlgSelectCSVSeparator(true);
                    Boolean fileCanOpen = dlgSeparator.OpenCsvFile(DialogOpen.FileName);

                    if (!fileCanOpen)
                    {
                        throw new Exception(String.Format(Catalog.GetString("File {0} Cannot be opened."), DialogOpen.FileName));
                    }

                    if (dlgSeparator.ShowDialog() == DialogResult.OK)
                    {
                        XmlDocument doc = TCsv2Xml.ParseCSV2Xml(DialogOpen.FileName, dlgSeparator.SelectedSeparator);
                        return doc;
                    }
                }
                else if (DialogOpen.FileName.ToLower().EndsWith("xml"))
                {
                    XmlDocument doc = new XmlDocument();
                    doc.Load(DialogOpen.FileName);
                    return doc;
                }
                else if (DialogOpen.FileName.ToLower().EndsWith("yml"))
                {
                    TYml2Xml yml = new TYml2Xml(DialogOpen.FileName);
                    return yml.ParseYML2XML();
                }
            }

            return null;
        }
        /// <summary>
        /// Display File open dialog box and read file into memory
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OpenFile(System.Object sender, EventArgs e)
        {
            if (!FPetraUtilsObject.IsEnabled("actStartImport"))
            {
                MessageBox.Show(Catalog.GetString("Please cancel the current import before selecting a different file"));
                return;
            }

            txtPartnerInfo.Text = "";
            OpenFileDialog DialogOpen = new OpenFileDialog();

            DialogOpen.Filter =
                Catalog.GetString(
                    "All supported formats|*.yml;*.csv;*.ext|Text file (*.yml)|*.yml|Partner Extract (*.ext)|*.ext|Partner List (*.csv)|.csv");
            DialogOpen.FilterIndex = 1;

            DialogOpen.RestoreDirectory = true;
            DialogOpen.Title = Catalog.GetString("Select the file for importing partners");

            if (DialogOpen.ShowDialog() == DialogResult.OK)
            {
                txtFilename.Text = DialogOpen.FileName;

                TVerificationResultCollection VerificationResult = null;

                AddStatus(String.Format("Reading {0}\r\n", Path.GetFileName(DialogOpen.FileName)));

                if (Path.GetExtension(DialogOpen.FileName) == ".yml")
                {
                    TYml2Xml yml = new TYml2Xml(DialogOpen.FileName);
                    AddStatus(Catalog.GetString("Parsing file. Please wait..\r\n"));
                    FMainDS = TRemote.MPartner.ImportExport.WebConnectors.ImportPartnersFromYml(TXMLParser.XmlToString(
                            yml.ParseYML2XML()), out VerificationResult);
                }

                if (Path.GetExtension(DialogOpen.FileName) == ".csv")
                {
                    // select separator, make sure there is a header line with the column captions/names
                    TDlgSelectCSVSeparator dlgSeparator = new TDlgSelectCSVSeparator(true);
                    Boolean fileCanOpen = dlgSeparator.OpenCsvFile(DialogOpen.FileName);

                    if (!fileCanOpen)
                    {
                        MessageBox.Show(Catalog.GetString("Unable to open file."),
                            Catalog.GetString("Import Partners"),
                            MessageBoxButtons.OK,
                            MessageBoxIcon.Stop);
                        return;
                    }

                    if (dlgSeparator.ShowDialog() == DialogResult.OK)
                    {
                        XmlDocument doc = TCsv2Xml.ParseCSV2Xml(DialogOpen.FileName, dlgSeparator.SelectedSeparator);
                        FMainDS = TRemote.MPartner.ImportExport.WebConnectors.ImportFromCSVFile(TXMLParser.XmlToString(doc), out VerificationResult);
                    }
                }
                else if (Path.GetExtension(DialogOpen.FileName) == ".ext")
                {
                    StreamReader sr = new StreamReader(DialogOpen.FileName, true);
                    string[] FileContent = sr.ReadToEnd().Replace("\r", "").Split(new char[] { '\n' });
                    sr.Close();
                    AddStatus(String.Format("{0} lines.\r\n", FileContent.Length));
                    AddStatus(Catalog.GetString("Parsing file. Please wait..\r\n"));
                    FMainDS = TRemote.MPartner.ImportExport.WebConnectors.ImportFromPartnerExtract(FileContent, out VerificationResult);
                }

                AddStatus(FormatVerificationResult("Imported file verification: ", VerificationResult));

                if (!TVerificationHelper.IsNullOrOnlyNonCritical(VerificationResult))
                {
                    string ErrorMessages = String.Empty;

                    foreach (TVerificationResult verif in VerificationResult)
                    {
                        ErrorMessages += "[" + verif.ResultContext + "] " +
                                         verif.ResultTextCaption + ": " +
                                         verif.ResultText + Environment.NewLine;
                    }

                    MessageBox.Show(ErrorMessages, Catalog.GetString("Import of partners failed!"));

                    FMainDS = null;

                    return;
                }

                AddStatus(String.Format(Catalog.GetString("File read OK ({0} partners) - press Start to import.\r\n"), FMainDS.PPartner.Rows.Count));
            }
        }
        private void ImportBudget(System.Object sender, EventArgs e)
        {
            decimal numRecsImported = 0;

            if (FPetraUtilsObject.HasChanges)
            {
                // saving failed, therefore do not try to post
                MessageBox.Show(Catalog.GetString("Please save before calling this function!"), Catalog.GetString(
                        "Failure"), MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            String dateFormatString = TUserDefaults.GetStringDefault("Imp Date", "MDY");
            OpenFileDialog dialog = new OpenFileDialog();

            dialog.FileName = TUserDefaults.GetStringDefault("Imp Filename",
                TClientSettings.GetExportPath() + Path.DirectorySeparatorChar + "import.csv");

            dialog.Title = Catalog.GetString("Import budget(s) from csv file");
            dialog.Filter = Catalog.GetString("Budget files (*.csv)|*.csv");
            String impOptions = TUserDefaults.GetStringDefault("Imp Options", ";American");

            if (dialog.ShowDialog() == DialogResult.OK)
            {
                FdlgSeparator = new TDlgSelectCSVSeparator(false);

                try
                {
                    Boolean fileCanOpen = FdlgSeparator.OpenCsvFile(dialog.FileName);

                    if (!fileCanOpen)
                    {
                        throw new Exception(String.Format(Catalog.GetString("File {0} Cannot be opened."), dialog.FileName));
                    }

                    FdlgSeparator.DateFormat = dateFormatString;

                    if (impOptions.Length > 1)
                    {
                        FdlgSeparator.NumberFormat = impOptions.Substring(1);
                    }

                    FdlgSeparator.SelectedSeparator = impOptions.Substring(0, 1);

                    if (FdlgSeparator.ShowDialog() == DialogResult.OK)
                    {
                        TVerificationResultCollection AMessages;

                        string[] FdlgSeparatorVal = new string[] {
                            FdlgSeparator.SelectedSeparator, FdlgSeparator.DateFormat, FdlgSeparator.NumberFormat
                        };

                        //TODO return the budget from the year, and -99 for fail
                        numRecsImported = TRemote.MFinance.Budget.WebConnectors.ImportBudgets(FLedgerNumber,
                            FCurrentBudgetYear,
                            dialog.FileName,
                            FdlgSeparatorVal,
                            ref FMainDS,
                            out AMessages);
                    }
                }
                catch (Exception ex)
                {
                    numRecsImported = -2;
                    MessageBox.Show(ex.Message, Catalog.GetString("Budget Import"), MessageBoxButtons.OK, MessageBoxIcon.Error);
                }

                if (numRecsImported > 0)
                {
                    Int32 totalImported = Convert.ToInt32(Math.Truncate(numRecsImported));
                    Int32 totalUpdated = Convert.ToInt32((numRecsImported - totalImported) * 10000);

                    string msg = String.Format(Catalog.GetString("{0} budget records imported successfully!"), totalImported);

                    if (totalUpdated > 0)
                    {
                        msg += Environment.NewLine + Environment.NewLine + String.Format(Catalog.GetString(
                                "({0} of which updated existing budgets)"), totalImported);
                    }

                    MessageBox.Show(msg,
                        Catalog.GetString("Success"),
                        MessageBoxButtons.OK,
                        MessageBoxIcon.Information);

                    SetBudgetDefaultView();

                    SelectRowInGrid(1);

                    FPetraUtilsObject.SetChangedFlag();
                }
                else if (numRecsImported == -1)
                {
                    MessageBox.Show(Catalog.GetString("The year contained in the import file is different to the current selected year."));

                    SelectRowInGrid(1);
                }
                else if (numRecsImported == -2)
                {
                    SelectRowInGrid(1);
                }
                else //0
                {
                    MessageBox.Show(Catalog.GetString("No records found to import"));
                }
            }
        }
        /// <summary>
        /// this supports the batch export files from Petra 2.x.
        /// Each line starts with a type specifier, B for batch, J for journal, T for transaction
        /// </summary>
        public void ImportBatches(TGiftImportDataSourceEnum AImportSource)
        {
            bool ok = false;
            String importString;
            String impOptions;
            OpenFileDialog dialog = null;

            if (FPetraUtilsObject.HasChanges)
            {
                // saving failed, therefore do not try to post
                MessageBox.Show(Catalog.GetString("Please save before calling this function!"), Catalog.GetString(
                        "Failure"), MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            FdlgSeparator = new TDlgSelectCSVSeparator(false);

            if (AImportSource == TGiftImportDataSourceEnum.FromClipboard)
            {
                importString = Clipboard.GetText(TextDataFormat.UnicodeText);

                if ((importString == null) || (importString.Length == 0))
                {
                    MessageBox.Show(Catalog.GetString("Please first copy data from your spreadsheet application!"),
                        Catalog.GetString("Failure"), MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                impOptions = TUserDefaults.GetStringDefault("Imp Options", ";American");
                String dateFormatString = TUserDefaults.GetStringDefault("Imp Date", "MDY");
                FdlgSeparator = new TDlgSelectCSVSeparator(false);
                FdlgSeparator.SelectedSeparator = "\t";
                FdlgSeparator.CSVData = importString;
                FdlgSeparator.DateFormat = dateFormatString;

                if (impOptions.Length > 1)
                {
                    FdlgSeparator.NumberFormat = impOptions.Substring(1);
                }
            }
            else if (AImportSource == TGiftImportDataSourceEnum.FromFile)
            {
                dialog = new OpenFileDialog();

                dialog.FileName = TUserDefaults.GetStringDefault("Imp Filename",
                    TClientSettings.GetExportPath() + Path.DirectorySeparatorChar + "import.csv");

                dialog.Title = Catalog.GetString("Import Batches from CSV File");
                dialog.Filter = Catalog.GetString("Gift Batches files (*.csv)|*.csv");
                impOptions = TUserDefaults.GetStringDefault("Imp Options", ";" + TDlgSelectCSVSeparator.NUMBERFORMAT_AMERICAN);

                if (dialog.ShowDialog() == DialogResult.OK)
                {
                    Boolean fileCanOpen = FdlgSeparator.OpenCsvFile(dialog.FileName);

                    if (!fileCanOpen)
                    {
                        MessageBox.Show(Catalog.GetString("Unable to open file."),
                            Catalog.GetString("Gift Import"),
                            MessageBoxButtons.OK,
                            MessageBoxIcon.Stop);
                        return;
                    }

                    importString = File.ReadAllText(dialog.FileName);

                    String dateFormatString = TUserDefaults.GetStringDefault("Imp Date", "MDY");
                    FdlgSeparator.DateFormat = dateFormatString;

                    if (impOptions.Length > 1)
                    {
                        FdlgSeparator.NumberFormat = impOptions.Substring(1);
                    }

                    FdlgSeparator.SelectedSeparator = impOptions.Substring(0, 1);
                }
                else
                {
                    return;
                }
            }
            else
            {
                // unknown source!!  The following need a value...
                impOptions = String.Empty;
                importString = String.Empty;
            }

            if (FdlgSeparator.ShowDialog() == DialogResult.OK)
            {
                Hashtable requestParams = new Hashtable();

                requestParams.Add("ALedgerNumber", FLedgerNumber);
                requestParams.Add("Delimiter", FdlgSeparator.SelectedSeparator);
                requestParams.Add("DateFormatString", FdlgSeparator.DateFormat);
                requestParams.Add("NumberFormat", FdlgSeparator.NumberFormat);
                requestParams.Add("NewLine", Environment.NewLine);

                bool Repeat = true;

                while (Repeat)
                {
                    Repeat = false;

                    TVerificationResultCollection AMessages = new TVerificationResultCollection();
                    GiftBatchTDSAGiftDetailTable NeedRecipientLedgerNumber = new GiftBatchTDSAGiftDetailTable();

                    Thread ImportThread = new Thread(() => ImportGiftBatches(
                            requestParams,
                            importString,
                            out AMessages,
                            out ok,
                            out NeedRecipientLedgerNumber));

                    using (TProgressDialog ImportDialog = new TProgressDialog(ImportThread))
                    {
                        ImportDialog.ShowDialog();
                    }

                    // If NeedRecipientLedgerNumber contains data then AMessages will only ever contain
                    // one message alerting the user that no data has been imported.
                    // We do not want to show this as we will be displaying another more detailed message.
                    if (NeedRecipientLedgerNumber.Rows.Count == 0)
                    {
                        ShowMessages(AMessages);
                    }

                    // if the import contains gifts with Motivation Group 'GIFT' and that have a Family recipient with no Gift Destination
                    // then the import will have failed and we need to alert the user
                    if (NeedRecipientLedgerNumber.Rows.Count > 0)
                    {
                        bool OfferToRunImportAgain = true;
                        bool DoNotShowMessageBoxEverytime = false;
                        TFrmExtendedMessageBox.TResult Result = TFrmExtendedMessageBox.TResult.embrUndefined;
                        int count = 1;

                        // for each gift in which the recipient needs a Git Destination
                        foreach (GiftBatchTDSAGiftDetailRow Row in NeedRecipientLedgerNumber.Rows)
                        {
                            if (!DoNotShowMessageBoxEverytime)
                            {
                                string CheckboxText = string.Empty;

                                // only show checkbox if there is at least one more occurance of this error
                                if (NeedRecipientLedgerNumber.Rows.Count - count > 0)
                                {
                                    CheckboxText = string.Format(
                                        Catalog.GetString("Do this for all further occurances ({0})?"), NeedRecipientLedgerNumber.Rows.Count - count);
                                }

                                TFrmExtendedMessageBox extendedMessageBox = new TFrmExtendedMessageBox(FPetraUtilsObject.GetForm());

                                extendedMessageBox.ShowDialog(string.Format(
                                        Catalog.GetString(
                                            "Gift Import has been cancelled as the recipient '{0}' ({1}) has no Gift Destination assigned."),
                                        Row.RecipientDescription, Row.RecipientKey) +
                                    "\n\r\n\r\n\r" +
                                    Catalog.GetString("Do you want to assign a Gift Destination to this partner now?"),
                                    Catalog.GetString("Import Errors"),
                                    CheckboxText,
                                    TFrmExtendedMessageBox.TButtons.embbYesNo, TFrmExtendedMessageBox.TIcon.embiWarning);
                                Result = extendedMessageBox.GetResult(out DoNotShowMessageBoxEverytime);
                            }

                            if (Result == TFrmExtendedMessageBox.TResult.embrYes)
                            {
                                // allow the user to assign a Gift Destingation
                                TFrmGiftDestination GiftDestinationForm = new TFrmGiftDestination(FPetraUtilsObject.GetForm(), Row.RecipientKey);
                                GiftDestinationForm.ShowDialog();
                            }
                            else
                            {
                                OfferToRunImportAgain = false;

                                if (DoNotShowMessageBoxEverytime)
                                {
                                    break;
                                }
                            }

                            count++;
                        }

                        // if the user has clicked yes to assigning Gift Destinations then offer to restart the import
                        if (OfferToRunImportAgain
                            && (MessageBox.Show(Catalog.GetString("Would you like to import this Gift Batch again?"),
                                    Catalog.GetString("Gift Import"), MessageBoxButtons.YesNo, MessageBoxIcon.Question,
                                    MessageBoxDefaultButton.Button2)
                                == DialogResult.Yes))
                        {
                            Repeat = true;
                        }
                    }
                }
            }

            if (ok)
            {
                MessageBox.Show(Catalog.GetString("Your data was imported successfully!"),
                    Catalog.GetString("Gift Import"),
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Information);

                SaveUserDefaults(dialog, impOptions);
                FMyUserControl.LoadBatchesForCurrentYear();
                FPetraUtilsObject.DisableSaveButton();
            }
        }
        /// <summary>
        /// Import a transactions file or a clipboard equivalent
        /// </summary>
        /// <param name="ACurrentBatchRow">The batch to import to</param>
        /// <param name="AImportSource">The import source - eg File or Clipboard</param>
        /// <returns>True if the import was successful</returns>
        public bool ImportTransactions(AGiftBatchRow ACurrentBatchRow, TGiftImportDataSourceEnum AImportSource)
        {
            bool ok = false;
            String importString;
            String impOptions;
            OpenFileDialog dialog = null;

            if (FPetraUtilsObject.HasChanges)
            {
                // saving failed, therefore do not try to import
                MessageBox.Show(Catalog.GetString("Please save before calling this function!"), Catalog.GetString(
                        "Gift Import"), MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }

            if ((ACurrentBatchRow == null) || (ACurrentBatchRow.BatchStatus != MFinanceConstants.BATCH_UNPOSTED))
            {
                MessageBox.Show(Catalog.GetString("Please select an unposted batch to import transactions."), Catalog.GetString(
                        "Gift Import"), MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }

            if (ACurrentBatchRow.LastGiftNumber > 0)
            {
                if (MessageBox.Show(Catalog.GetString(
                            "The current batch already contains some gift transactions.  Do you really want to add more transactions to this batch?"),
                        Catalog.GetString("Gift Transaction Import"),
                        MessageBoxButtons.YesNo,
                        MessageBoxIcon.Question,
                        MessageBoxDefaultButton.Button2) == DialogResult.No)
                {
                    return false;
                }
            }

            FdlgSeparator = new TDlgSelectCSVSeparator(false);

            if (AImportSource == TGiftImportDataSourceEnum.FromClipboard)
            {
                importString = Clipboard.GetText(TextDataFormat.UnicodeText);

                if ((importString == null) || (importString.Length == 0))
                {
                    MessageBox.Show(Catalog.GetString("Please first copy data from your spreadsheet application!"),
                        Catalog.GetString("Failure"), MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return false;
                }

                impOptions = TUserDefaults.GetStringDefault("Imp Options", ";American");
                String dateFormatString = TUserDefaults.GetStringDefault("Imp Date", "MDY");
                FdlgSeparator = new TDlgSelectCSVSeparator(false);
                FdlgSeparator.SelectedSeparator = "\t";
                FdlgSeparator.CSVData = importString;
                FdlgSeparator.DateFormat = dateFormatString;

                if (impOptions.Length > 1)
                {
                    FdlgSeparator.NumberFormat = impOptions.Substring(1);
                }
            }
            else if (AImportSource == TGiftImportDataSourceEnum.FromFile)
            {
                dialog = new OpenFileDialog();

                dialog.FileName = TUserDefaults.GetStringDefault("Imp Filename",
                    TClientSettings.GetExportPath() + Path.DirectorySeparatorChar + "import.csv");

                dialog.Title = Catalog.GetString("Import Transactions from CSV File");
                dialog.Filter = Catalog.GetString("Gift Transactions files (*.csv)|*.csv");
                impOptions = TUserDefaults.GetStringDefault("Imp Options", ";" + TDlgSelectCSVSeparator.NUMBERFORMAT_AMERICAN);

                if (dialog.ShowDialog() == DialogResult.OK)
                {
                    Boolean fileCanOpen = FdlgSeparator.OpenCsvFile(dialog.FileName);

                    if (!fileCanOpen)
                    {
                        MessageBox.Show(Catalog.GetString("Unable to open file."),
                            Catalog.GetString("Gift Import"),
                            MessageBoxButtons.OK,
                            MessageBoxIcon.Stop);
                        return false;
                    }

                    importString = File.ReadAllText(dialog.FileName);

                    String dateFormatString = TUserDefaults.GetStringDefault("Imp Date", "MDY");
                    FdlgSeparator.DateFormat = dateFormatString;

                    if (impOptions.Length > 1)
                    {
                        FdlgSeparator.NumberFormat = impOptions.Substring(1);
                    }

                    FdlgSeparator.SelectedSeparator = impOptions.Substring(0, 1);
                }
                else
                {
                    return false;
                }
            }
            else
            {
                // unknown source!!  The following need a value...
                impOptions = String.Empty;
                importString = String.Empty;
            }

            if (FdlgSeparator.ShowDialog() == DialogResult.OK)
            {
                Hashtable requestParams = new Hashtable();

                requestParams.Add("ALedgerNumber", FLedgerNumber);
                requestParams.Add("Delimiter", FdlgSeparator.SelectedSeparator);
                requestParams.Add("DateFormatString", FdlgSeparator.DateFormat);
                requestParams.Add("NumberFormat", FdlgSeparator.NumberFormat);
                requestParams.Add("NewLine", Environment.NewLine);

                bool Repeat = true;

                while (Repeat)
                {
                    Repeat = false;

                    TVerificationResultCollection AMessages = new TVerificationResultCollection();
                    GiftBatchTDSAGiftDetailTable NeedRecipientLedgerNumber = new GiftBatchTDSAGiftDetailTable();

                    Thread ImportThread = new Thread(() => ImportGiftTransactions(
                            requestParams,
                            importString,
                            ACurrentBatchRow.BatchNumber,
                            out AMessages,
                            out ok,
                            out NeedRecipientLedgerNumber));

                    using (TProgressDialog ImportDialog = new TProgressDialog(ImportThread))
                    {
                        ImportDialog.ShowDialog();
                    }

                    ShowMessages(AMessages);

                    // if the import contains gifts with Motivation Group 'GIFT' and that have a Family recipient with no Gift Destination
                    // then the import will have failed and we need to alert the user
                    if (NeedRecipientLedgerNumber.Rows.Count > 0)
                    {
                        bool OfferToRunImportAgain = true;

                        // for each gift in which the recipient needs a Git Destination
                        foreach (GiftBatchTDSAGiftDetailRow Row in NeedRecipientLedgerNumber.Rows)
                        {
                            if (MessageBox.Show(string.Format(
                                        Catalog.GetString(
                                            "Gift Import has been cancelled as the recipient '{0}' ({1}) has no Gift Destination assigned."),
                                        Row.RecipientDescription, Row.RecipientKey) +
                                    "\n\n" +
                                    Catalog.GetString("Do you want to assign a Gift Destination to this partner now?"),
                                    Catalog.GetString("Gift Import"), MessageBoxButtons.YesNo, MessageBoxIcon.Warning)
                                == DialogResult.Yes)
                            {
                                // allow the user to assign a Gift Destingation
                                TFrmGiftDestination GiftDestinationForm = new TFrmGiftDestination(FPetraUtilsObject.GetForm(), Row.RecipientKey);
                                GiftDestinationForm.ShowDialog();
                            }
                            else
                            {
                                OfferToRunImportAgain = false;
                            }
                        }

                        // if the user has clicked yes to assigning Gift Destinations then offer to restart the import
                        if (OfferToRunImportAgain
                            && (MessageBox.Show(Catalog.GetString("Would you like to import these Gift Transactions again?"),
                                    Catalog.GetString("Gift Import"), MessageBoxButtons.YesNo, MessageBoxIcon.Question,
                                    MessageBoxDefaultButton.Button1)
                                == DialogResult.Yes))
                        {
                            Repeat = true;
                        }
                    }
                }
            }

            if (ok)
            {
                MessageBox.Show(Catalog.GetString("Your data was imported successfully!"),
                    Catalog.GetString("Gift Import"),
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Information);

                SaveUserDefaults(dialog, impOptions);
                //FMyUserControl.LoadBatchesForCurrentYear();
                FPetraUtilsObject.DisableSaveButton();
            }

            return ok;
        }
        /// <summary>
        /// asks the user to open a csv file and imports the contents according to the config file
        /// </summary>
        /// <param name="AStatementKey">this returns the first key of a statement that was imported. depending on the implementation, several statements can be created from one file</param>
        /// <param name="ALedgerNumber">the current ledger number</param>
        /// <param name="ABankAccountCode">the bank account against which the statement should be stored</param>
        /// <returns></returns>
        public bool ImportBankStatement(out Int32 AStatementKey, Int32 ALedgerNumber, string ABankAccountCode)
        {
            OpenFileDialog DialogOpen = new OpenFileDialog();

            DialogOpen.Filter = Catalog.GetString("bank statement (*.csv)|*.csv");
            DialogOpen.RestoreDirectory = true;
            DialogOpen.Title = Catalog.GetString("Please select the bank statement to import");

            if (DialogOpen.ShowDialog() != DialogResult.OK)
            {
                AStatementKey = -1;
                return false;
            }

            string BankStatementFilename = DialogOpen.FileName;

            TDlgSelectCSVSeparator DlgSeparator = new TDlgSelectCSVSeparator(false);

            Boolean fileCanOpen = DlgSeparator.OpenCsvFile(DialogOpen.FileName);

            if (!fileCanOpen)
            {
                MessageBox.Show(Catalog.GetString("Unable to open file."),
                    Catalog.GetString("Import Bank Statement"),
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Stop);
                AStatementKey = -1;
                return false;
            }

            String dateFormatString = TUserDefaults.GetStringDefault("BankimportCSVDateFormat", "MDY");
            String impOptions = TUserDefaults.GetStringDefault("BankimportCSVNumberFormat", ";" + TDlgSelectCSVSeparator.NUMBERFORMAT_AMERICAN);

            DlgSeparator.DateFormat = dateFormatString;

            if (impOptions.Length > 1)
            {
                DlgSeparator.NumberFormat = impOptions.Substring(1);
            }

            DlgSeparator.SelectedSeparator = impOptions.Substring(0, 1);

            if (DlgSeparator.ShowDialog() != DialogResult.OK)
            {
                AStatementKey = -1;
                return false;
            }

            TUserDefaults.SetDefault("BankimportCSVDateFormat", DlgSeparator.DateFormat);
            TUserDefaults.SetDefault("BankimportCSVNumberFormat", DlgSeparator.SelectedSeparator + DlgSeparator.NumberFormat);

            StreamReader dataFile = new StreamReader(BankStatementFilename, TTextFile.GetFileEncoding(BankStatementFilename), false);
            string StatementData = dataFile.ReadToEnd();
            dataFile.Close();

            BankImportTDS MainDS = ImportBankStatementNonInteractive(
                ALedgerNumber,
                ABankAccountCode,
                DlgSeparator.SelectedSeparator,
                DlgSeparator.DateFormat,
                DlgSeparator.NumberFormat,
                TUserDefaults.GetStringDefault(
                    "BankimportCSVColumnsUsage",
                    "unused,DateEffective,Description,Amount,Currency"),
                BankStatementFilename,
                StatementData);

            if (MainDS != null)
            {
                TMBankimportNamespace PluginRemote = new TMBankimportNamespace();

                if (PluginRemote.WebConnectors.StoreNewBankStatement(
                        MainDS,
                        out AStatementKey) == TSubmitChangesResult.scrOK)
                {
                    return AStatementKey != -1;
                }
            }

            AStatementKey = -1;
            return false;
        }
        /// <summary>
        /// Display File open dialog box and read file into memory
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OpenFile(System.Object sender, EventArgs e)
        {
            if (!btnStartImport.Enabled && btnCancelImport.Enabled)
            {
                MessageBox.Show(Catalog.GetString("Please stop the current import before selecting a different file"));
                return;
            }

            txtPartnerInfo.Text = "";
            OpenFileDialog DialogOpen = new OpenFileDialog();

            DialogOpen.Filter =
                Catalog.GetString(
                    "All supported formats|*.yml;*.csv;*.ext|Text file (*.yml)|*.yml|Partner Extract (*.ext)|*.ext|Partner List (*.csv)|.csv");
            DialogOpen.FilterIndex = 1;

            DialogOpen.RestoreDirectory = true;
            DialogOpen.Title = Catalog.GetString("Select the file for importing partners");

            if (DialogOpen.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    this.Cursor = Cursors.WaitCursor;

                    TVerificationResultCollection VerificationResult = null;

                    FFileName = DialogOpen.FileName;

                    AddStatus(String.Format("Reading {0}\r\n", Path.GetFileName(FFileName)));

                    if (Path.GetExtension(FFileName) == ".yml")
                    {
                        TYml2Xml yml = new TYml2Xml(FFileName);
                        AddStatus(Catalog.GetString("Parsing file. Please wait...\r\n"));
                        FFileContent = TXMLParser.XmlToString(yml.ParseYML2XML());

                        LoadDataSet(ref VerificationResult);
                    }

                    if (Path.GetExtension(FFileName) == ".csv")
                    {
                        // select separator, make sure there is a header line with the column captions/names
                        TDlgSelectCSVSeparator dlgSeparator = new TDlgSelectCSVSeparator(true);
                        Boolean fileCanOpen = dlgSeparator.OpenCsvFile(FFileName);

                        if (!fileCanOpen)
                        {
                            MessageBox.Show(Catalog.GetString("Unable to open file."),
                                Catalog.GetString("Import Partners"),
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Stop);
                            return;
                        }

                        if (dlgSeparator.ShowDialog() == DialogResult.OK)
                        {
                            try
                            {
                                XmlDocument doc = TCsv2Xml.ParseCSV2Xml(FFileName, dlgSeparator.SelectedSeparator);
                                FFileContent = TXMLParser.XmlToString(doc);

                                LoadDataSet(ref VerificationResult);
                            }
                            catch (Exception ex)
                            {
                                MessageBox.Show(ex.Message, Catalog.GetString("Import Partners"));
                                AddStatus("\r\n" + ex.Message + "\r\n\r\n" +
                                    String.Format("Import of file {0} cancelled!", Path.GetFileName(FFileName)) + "\r\n");

                                return;
                            }
                        }
                        else
                        {
                            AddStatus(String.Format("\r\nImport of file {0} cancelled!\r\n", Path.GetFileName(FFileName)));

                            return;
                        }
                    }
                    else if (Path.GetExtension(FFileName) == ".ext")
                    {
                        StreamReader sr = new StreamReader(FFileName, true);

                        FFileContent = sr.ReadToEnd().Replace("\r", "");
                        sr.Close();

                        AddStatus(String.Format("{0} lines.\r\n", FFileContent.Length));
                        AddStatus(Catalog.GetString("Parsing file. Please wait...\r\n"));

                        LoadDataSet(ref VerificationResult);
                    }

                    AddStatus(FormatVerificationResult("Imported file verification: ", VerificationResult));

                    if (!TVerificationHelper.IsNullOrOnlyNonCritical(VerificationResult))
                    {
                        string ErrorMessages = String.Empty;

                        foreach (TVerificationResult verif in VerificationResult)
                        {
                            ErrorMessages += "[" + verif.ResultContext + "] " +
                                             verif.ResultTextCaption + ": " +
                                             verif.ResultText + Environment.NewLine;
                        }

                        MessageBox.Show(ErrorMessages, Catalog.GetString("Import of partners failed!"));

                        FMainDS = null;

                        return;
                    }

                    txtFilename.Text = FFileName;

                    grpStepTwo.Enabled = true;
                    btnStartImport.Enabled = true;

                    // Determine the 'Primary E-Mail Address' of all Partners that are contained in the import file
                    FPartnersOverallContactSettings = Calculations.DeterminePrimaryOrWithinOrgSettings(FMainDS.PPartnerAttribute,
                        Calculations.TOverallContSettingKind.ocskPrimaryEmailAddress);

                    AddStatus(String.Format(Catalog.GetString("File read OK ({0} partners) - press Start to import.\r\n"),
                            FMainDS.PPartner.Rows.Count));
                }
                finally
                {
                    if (FMainDS == null)
                    {
                        FMainDSBackup = new PartnerImportExportTDS();
                    }
                    else
                    {
                        FMainDSBackup.Merge(FMainDS.Copy());
                    }

                    this.Cursor = Cursors.Default;
                }
            }
        }
        /// <summary>
        /// this supports the batch export files from Petra 2.x.
        /// Each line starts with a type specifier, B for batch, J for journal, T for transaction
        /// The code handles importing from file or clipboard
        /// </summary>
        public void ImportBatches(TImportDataSourceEnum AImportDataSource)
        {
            bool ok = false;
            String importString;
            String impOptions;
            OpenFileDialog dialog = null;

            if (FPetraUtilsObject.HasChanges)
            {
                // saving failed, therefore do not try to import
                MessageBox.Show(Catalog.GetString("Please save before calling this function!"), Catalog.GetString(
                        "Failure"), MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            FdlgSeparator = new TDlgSelectCSVSeparator(false);

            if (AImportDataSource == TImportDataSourceEnum.FromClipboard)
            {
                importString = Clipboard.GetText(TextDataFormat.UnicodeText);

                if ((importString == null) || (importString.Length == 0))
                {
                    MessageBox.Show(Catalog.GetString("Please first copy data from your spreadsheet application!"),
                        Catalog.GetString("Failure"), MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                impOptions = TUserDefaults.GetStringDefault("Imp Options", ";American");
                String dateFormatString = TUserDefaults.GetStringDefault("Imp Date", "MDY");
                FdlgSeparator = new TDlgSelectCSVSeparator(false);
                FdlgSeparator.SelectedSeparator = "\t";
                FdlgSeparator.CSVData = importString;
                FdlgSeparator.DateFormat = dateFormatString;

                if (impOptions.Length > 1)
                {
                    FdlgSeparator.NumberFormat = impOptions.Substring(1);
                }
            }
            else if (AImportDataSource == TImportDataSourceEnum.FromFile)
            {
                dialog = new OpenFileDialog();

                string exportPath = TClientSettings.GetExportPath();
                string fullPath = TUserDefaults.GetStringDefault("Imp Filename",
                    exportPath + Path.DirectorySeparatorChar + "import.csv");
                TImportExportDialogs.SetOpenFileDialogFilePathAndName(dialog, fullPath, exportPath);

                dialog.Title = Catalog.GetString("Import Batches from CSV File");
                dialog.Filter = Catalog.GetString("GL Batches files (*.csv)|*.csv");
                impOptions = TUserDefaults.GetStringDefault("Imp Options", ";" + TDlgSelectCSVSeparator.NUMBERFORMAT_AMERICAN);

                // This call fixes Windows7 Open File Dialogs.  It must be the line before ShowDialog()
                TWin7FileOpenSaveDialog.PrepareDialog(Path.GetFileName(fullPath));

                if (dialog.ShowDialog() == DialogResult.OK)
                {
                    Boolean fileCanOpen = FdlgSeparator.OpenCsvFile(dialog.FileName);

                    if (!fileCanOpen)
                    {
                        MessageBox.Show(Catalog.GetString("Unable to open file."),
                            Catalog.GetString("Batch Import"),
                            MessageBoxButtons.OK,
                            MessageBoxIcon.Stop);
                        return;
                    }

                    importString = File.ReadAllText(dialog.FileName, Encoding.Default);

                    String dateFormatString = TUserDefaults.GetStringDefault("Imp Date", "MDY");
                    FdlgSeparator.DateFormat = dateFormatString;

                    if (impOptions.Length > 1)
                    {
                        FdlgSeparator.NumberFormat = impOptions.Substring(1);
                    }

                    FdlgSeparator.SelectedSeparator = impOptions.Substring(0, 1);
                }
                else
                {
                    return;
                }
            }
            else
            {
                // unknown source!!  The following need a value...
                impOptions = String.Empty;
                importString = String.Empty;
            }

            if (FdlgSeparator.ShowDialog() == DialogResult.OK)
            {
                Hashtable requestParams = new Hashtable();

                requestParams.Add("ALedgerNumber", FLedgerNumber);
                requestParams.Add("Delimiter", FdlgSeparator.SelectedSeparator);
                requestParams.Add("DateFormatString", FdlgSeparator.DateFormat);
                requestParams.Add("NumberFormat", FdlgSeparator.NumberFormat);
                requestParams.Add("NewLine", Environment.NewLine);


                TVerificationResultCollection AMessages = new TVerificationResultCollection();

                Thread ImportThread = new Thread(() => ImportGLBatches(
                        requestParams,
                        importString,
                        out AMessages,
                        out ok));

                using (TProgressDialog ImportDialog = new TProgressDialog(ImportThread))
                {
                    ImportDialog.ShowDialog();
                }

                // We save the defaults even if ok is false - because the client will probably want to try and import
                //   the same file again after correcting any errors
                SaveUserDefaults(dialog, impOptions);
                ShowMessages(AMessages);
            }

            if (ok)
            {
                MessageBox.Show(Catalog.GetString("Your data was imported successfully!"),
                    Catalog.GetString("Batch Import"),
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Information);

                FMyUserControl.ReloadBatches();
                FPetraUtilsObject.DisableSaveButton();
            }
        }
        /// <summary>
        /// this supports the transaction export files from Petra 2.x.
        /// Lines do NOT start with T for transaction
        /// </summary>
        public void ImportTransactions(ABatchRow ACurrentBatchRow, AJournalRow ACurrentJournalRow, TImportDataSourceEnum AImportDataSource)
        {
            bool ok = false;
            String importString;
            String impOptions;
            OpenFileDialog dialog = null;

            if (FPetraUtilsObject.HasChanges && !FMyForm.SaveChanges())
            {
                // saving failed, therefore do not try to import
                MessageBox.Show(Catalog.GetString("Please save your changes before Importing new transactions"), Catalog.GetString(
                        "Import GL Transactions"), MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            if ((ACurrentBatchRow == null)
                || (ACurrentJournalRow == null)
                || (ACurrentJournalRow.JournalStatus != MFinanceConstants.BATCH_UNPOSTED))
            {
                MessageBox.Show(Catalog.GetString("Please select an unposted journal to import transactions."),
                    Catalog.GetString("Import GL Transactions"));
                return;
            }

            if (ACurrentJournalRow.LastTransactionNumber > 0)
            {
                if (MessageBox.Show(Catalog.GetString(
                            "The current journal already contains some transactions.  Do you really want to add more transactions to this journal?"),
                        Catalog.GetString("Import GL Transactions"),
                        MessageBoxButtons.YesNo,
                        MessageBoxIcon.Question,
                        MessageBoxDefaultButton.Button2) == DialogResult.No)
                {
                    return;
                }
            }

            FdlgSeparator = new TDlgSelectCSVSeparator(false);

            if (AImportDataSource == TImportDataSourceEnum.FromClipboard)
            {
                importString = Clipboard.GetText(TextDataFormat.UnicodeText);

                if ((importString == null) || (importString.Length == 0))
                {
                    MessageBox.Show(Catalog.GetString("Please first copy data from your spreadsheet application!"),
                        Catalog.GetString("Failure"), MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                impOptions = TUserDefaults.GetStringDefault("Imp Options", ";American");
                String dateFormatString = TUserDefaults.GetStringDefault("Imp Date", "MDY");
                FdlgSeparator = new TDlgSelectCSVSeparator(false);
                FdlgSeparator.SelectedSeparator = "\t";
                FdlgSeparator.CSVData = importString;
                FdlgSeparator.DateFormat = dateFormatString;

                if (impOptions.Length > 1)
                {
                    FdlgSeparator.NumberFormat = impOptions.Substring(1);
                }
            }
            else if (AImportDataSource == TImportDataSourceEnum.FromFile)
            {
                dialog = new OpenFileDialog();

                string exportPath = TClientSettings.GetExportPath();
                string fullPath = TUserDefaults.GetStringDefault("Imp Filename",
                    exportPath + Path.DirectorySeparatorChar + "import.csv");
                TImportExportDialogs.SetOpenFileDialogFilePathAndName(dialog, fullPath, exportPath);

                dialog.Title = Catalog.GetString("Import Transactions from CSV File");
                dialog.Filter = Catalog.GetString("GL Transactions files (*.csv)|*.csv");
                impOptions = TUserDefaults.GetStringDefault("Imp Options", ";" + TDlgSelectCSVSeparator.NUMBERFORMAT_AMERICAN);

                // This call fixes Windows7 Open File Dialogs.  It must be the line before ShowDialog()
                TWin7FileOpenSaveDialog.PrepareDialog(Path.GetFileName(fullPath));

                if (dialog.ShowDialog() == DialogResult.OK)
                {
                    Boolean fileCanOpen = FdlgSeparator.OpenCsvFile(dialog.FileName);

                    if (!fileCanOpen)
                    {
                        MessageBox.Show(Catalog.GetString("Unable to open file."),
                            Catalog.GetString("Transaction Import"),
                            MessageBoxButtons.OK,
                            MessageBoxIcon.Stop);
                        return;
                    }

                    importString = File.ReadAllText(dialog.FileName, Encoding.Default);

                    String dateFormatString = TUserDefaults.GetStringDefault("Imp Date", "MDY");
                    FdlgSeparator.DateFormat = dateFormatString;

                    if (impOptions.Length > 1)
                    {
                        FdlgSeparator.NumberFormat = impOptions.Substring(1);
                    }

                    FdlgSeparator.SelectedSeparator = impOptions.Substring(0, 1);
                }
                else
                {
                    return;
                }
            }
            else
            {
                // unknown source!!  The following need a value...
                impOptions = String.Empty;
                importString = String.Empty;
            }

            if (FdlgSeparator.ShowDialog() == DialogResult.OK)
            {
                Hashtable requestParams = new Hashtable();

                requestParams.Add("ALedgerNumber", FLedgerNumber);
                requestParams.Add("Delimiter", FdlgSeparator.SelectedSeparator);
                requestParams.Add("DateFormatString", FdlgSeparator.DateFormat);
                requestParams.Add("NumberFormat", FdlgSeparator.NumberFormat);
                requestParams.Add("NewLine", Environment.NewLine);

                TVerificationResultCollection AMessages = new TVerificationResultCollection();

                Thread ImportThread = new Thread(() => ImportGLTransactions(requestParams,
                        importString,
                        ACurrentBatchRow.BatchNumber,
                        ACurrentJournalRow.JournalNumber,
                        out AMessages,
                        out ok));

                using (TProgressDialog ImportDialog = new TProgressDialog(ImportThread))
                {
                    ImportDialog.ShowDialog();
                }

                // It is important to save user defaults here, even if there were errors
                //   because in that case the user will want to import the same file again after fixing it.
                SaveUserDefaults(dialog, impOptions);
                ShowMessages(AMessages);
            }

            if (ok)
            {
                MessageBox.Show(Catalog.GetString("Your data was imported successfully!"),
                    Catalog.GetString("Transactions Import"),
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Information);

                // Update the client side with new information from the server
                FMyForm.Cursor = Cursors.WaitCursor;
                FMainDS.Merge(TRemote.MFinance.GL.WebConnectors.LoadABatchAJournal(FLedgerNumber, ACurrentBatchRow.BatchNumber));
                FMainDS.Merge(TRemote.MFinance.GL.WebConnectors.LoadATransactionATransAnalAttrib(FLedgerNumber,
                        ACurrentBatchRow.BatchNumber, ACurrentJournalRow.JournalNumber));
                FMainDS.AcceptChanges();
                FMyForm.Cursor = Cursors.Default;

                FMyForm.GetTransactionsControl().SelectRow(1);
            }
        }
        /// <summary>
        /// Imports budgets from a file
        /// </summary>
        /// <param name="ASelectedBudgetYear"></param>
        /// <param name="AMainDS"></param>
        public void ImportBudget(int ASelectedBudgetYear, ref BudgetTDS AMainDS)
        {
            TVerificationResultCollection Messages = new TVerificationResultCollection();

            int NumBudgetsToImport = 0;
            int NumRecsUpdated = 0;
            int NumRowsFailed = 0;

            if (FPetraUtilsObject.HasChanges)
            {
                // saving failed, therefore do not try to post
                MessageBox.Show(Catalog.GetString("Please save before trying to import!"), Catalog.GetString(
                        "Failure"), MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }

            String DateFormatString = TUserDefaults.GetStringDefault("Imp Date", "MDY");
            OpenFileDialog OFDialog = new OpenFileDialog();

            string ExportPath = TClientSettings.GetExportPath();
            string FullPath = TUserDefaults.GetStringDefault("Imp Filename",
                ExportPath + Path.DirectorySeparatorChar + "import.csv");
            TImportExportDialogs.SetOpenFileDialogFilePathAndName(OFDialog, FullPath, ExportPath);

            OFDialog.Title = Catalog.GetString("Import budget(s) from csv file");
            OFDialog.Filter = Catalog.GetString("Budget files (*.csv)|*.csv");
            String ImportOptions = TUserDefaults.GetStringDefault("Imp Options", ";" + TDlgSelectCSVSeparator.NUMBERFORMAT_AMERICAN);

            // This call fixes Windows7 Open File Dialogs.  It must be the line before ShowDialog()
            TWin7FileOpenSaveDialog.PrepareDialog(Path.GetFileName(FullPath));

            if (OFDialog.ShowDialog() == DialogResult.OK)
            {
                FdlgSeparator = new TDlgSelectCSVSeparator(false);

                try
                {
                    FParentForm.UseWaitCursor = true;

                    Boolean fileCanOpen = FdlgSeparator.OpenCsvFile(OFDialog.FileName);

                    if (!fileCanOpen)
                    {
                        throw new Exception(String.Format(Catalog.GetString("File {0} cannot be opened."), OFDialog.FileName));
                    }

                    FdlgSeparator.DateFormat = DateFormatString;

                    if (ImportOptions.Length > 1)
                    {
                        FdlgSeparator.NumberFormat = ImportOptions.Substring(1);
                    }

                    FdlgSeparator.SelectedSeparator = ImportOptions.Substring(0, 1);

                    if (FdlgSeparator.ShowDialog() == DialogResult.OK)
                    {
                        string[] FdlgSeparatorVal = new string[] {
                            FdlgSeparator.SelectedSeparator, FdlgSeparator.DateFormat, FdlgSeparator.NumberFormat
                        };

                        // read contents of file
                        string ImportString = File.ReadAllText(OFDialog.FileName);

                        //TODO return the budget from the year, and -99 for fail
                        NumBudgetsToImport = TRemote.MFinance.Budget.WebConnectors.ImportBudgets(FLedgerNumber,
                            ASelectedBudgetYear,
                            ImportString,
                            OFDialog.FileName,
                            FdlgSeparatorVal,
                            ref AMainDS,
                            out NumRecsUpdated,
                            out NumRowsFailed,
                            out Messages);

                        ShowMessages(Messages, NumBudgetsToImport, NumRecsUpdated, NumRowsFailed);
                    }
                }
                catch (Exception ex)
                {
                    NumBudgetsToImport = -1;
                    MessageBox.Show(ex.Message, Catalog.GetString("Budget Import"), MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                finally
                {
                    // We save the defaults even if ok is false - because the client will probably want to try and import
                    //   the same file again after correcting any errors
                    SaveUserDefaults(OFDialog, ImportOptions);

                    FParentForm.UseWaitCursor = false;
                }

                // update grid
                if (NumBudgetsToImport > 0)
                {
                    FParentForm.UseWaitCursor = true;
                    UpdateABudgetPeriodAmounts(AMainDS, ASelectedBudgetYear);
                    FUserControl.SetBudgetDefaultView();
                    FParentForm.UseWaitCursor = false;

                    FUserControl.SelectRowInGrid(1);

                    FPetraUtilsObject.SetChangedFlag();
                }
                else if (NumBudgetsToImport <= 0)
                {
                    FUserControl.SelectRowInGrid(1);
                }
            }
        }