예제 #1
0
        /// <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");
            }
        }
예제 #2
0
        private static void SaveOptions(TDlgSelectCSVSeparator ASeparatorDialog)
        {
            string impOptions = ASeparatorDialog.SelectedSeparator;

            impOptions += ASeparatorDialog.NumberFormat;
            TUserDefaults.SetDefault("Imp Options", impOptions);
            TUserDefaults.SetDefault("Imp Date", ASeparatorDialog.DateFormat);
            TUserDefaults.SaveChangedUserDefaults();
        }
예제 #3
0
        /// <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);

                bool dateMayBeAnInteger = TUserDefaults.GetBooleanDefault(MCommonConstants.USERDEFAULT_IMPORTEDDATESMAYBEINTEGERS, false);
                TDlgSelectCSVSeparator DlgSeparator = new TDlgSelectCSVSeparator(false);
                DlgSeparator.DateMayBeInteger = dateMayBeAnInteger;
                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;
                DlgSeparator.NumberFormat = (impOptions.Length > 1) ? impOptions.Substring(1) : TDlgSelectCSVSeparator.NUMBERFORMAT_AMERICAN;
                DlgSeparator.SelectedSeparator = StringHelper.GetCSVSeparator(DlgSeparator.FileContent) ??
                                                 ((impOptions.Length > 0) ? impOptions.Substring(0, 1) : ";");

                if (DlgSeparator.ShowDialog() == DialogResult.OK)
                {
                    // Save the settings that we specified
                    SaveOptions(DlgSeparator);

                    // Do the import and return the number of rows imported and any messages
                    return ImportCurrencyExRatesFromCSV(AExchangeRateDT,
                        DlgSeparator.FileContent,
                        DlgSeparator.SelectedSeparator,
                        DlgSeparator.NumberFormat,
                        DlgSeparator.DateFormat,
                        dateMayBeAnInteger,
                        AImportMode,
                        AResultCollection,
                        Path.GetFileNameWithoutExtension(DialogBox.FileName));
                }
                else
                {
                    // Save the options anyway
                    SaveOptions(DlgSeparator);
                }
            }

            return 0;
        }
예제 #4
0
        /// <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);
        }
예제 #5
0
        /// <summary>
        /// This over-ride should be used for testing purposes.  It reads from the specified test file and always uses US numbers and date/time.
        /// You supply the separator character as a single character string
        /// </summary>
        /// <param name="AExchangeRateDT">The corporate or daily exchange rate table</param>
        /// <param name="AImportFileName">The test file to import</param>
        /// <param name="ACSVSeparator">The separator that the file uses</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 AImportFileName,
            string ACSVSeparator,
            string AImportMode,
            TVerificationResultCollection AResultCollection)
        {
            // Test import always uses standard file with US formats
            TDlgSelectCSVSeparator separatorDialog = new TDlgSelectCSVSeparator(false);

            separatorDialog.OpenCsvFile(AImportFileName);

            return ImportCurrencyExRatesFromCSV(AExchangeRateDT,
                separatorDialog.FileContent,
                ACSVSeparator,
                TDlgSelectCSVSeparator.NUMBERFORMAT_AMERICAN,
                "MM/dd/yyyy",
                false,
                AImportMode,
                AResultCollection,
                Path.GetFileNameWithoutExtension(AImportFileName));
        }
예제 #6
0
        /// <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();

                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("Gift 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("Gift 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);

                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;
                        }
                    }
                }

                // 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);
            }

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

                FMyUserControl.LoadBatchesForCurrentYear();
                FPetraUtilsObject.DisableSaveButton();
            }
        }
예제 #7
0
        /// <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;
            Boolean        IsPlainText = false;

            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();

                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("Gift Transactions files (*.csv)|*.csv|Text Files (*.txt)|*.txt");
                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("Gift Import"),
                                        MessageBoxButtons.OK,
                                        MessageBoxIcon.Stop);
                        return(false);
                    }

                    importString = File.ReadAllText(dialog.FileName, Encoding.Default);
                    IsPlainText  = (Path.GetExtension(dialog.FileName).ToLower() == ".txt");

                    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 (IsPlainText || (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;
                        }
                    }
                }

                // 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);
            }

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

                //FMyUserControl.LoadBatchesForCurrentYear();
                FPetraUtilsObject.DisableSaveButton();
            }

            return(ok);
        }
        /// <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;
            bool           RefreshGUIAfterImport = false;
            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;
            }

            try
            {
                FMyForm.FCurrentGLBatchAction = TGLBatchEnums.GLBatchAction.IMPORTING;

                bool datesMayBeIntegers = TUserDefaults.GetBooleanDefault(MCommonConstants.USERDEFAULT_IMPORTEDDATESMAYBEINTEGERS, false);
                FdlgSeparator = new TDlgSelectCSVSeparator(false);
                FdlgSeparator.DateMayBeInteger = datesMayBeIntegers;

                if (AImportDataSource == TImportDataSourceEnum.FromClipboard)
                {
                    string 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;
                    }

                    FdlgSeparator.CSVData = importString;
                }
                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 Batch Files (*.csv)|*.csv|Text Files (*.txt)|*.txt");

                    // 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;
                        }
                    }
                    else
                    {
                        return;
                    }
                }
                else
                {
                    // unknown source!!
                    return;
                }

                String impOptions       = TUserDefaults.GetStringDefault("Imp Options", ";" + TDlgSelectCSVSeparator.NUMBERFORMAT_AMERICAN);
                String dateFormatString = TUserDefaults.GetStringDefault("Imp Date", "MDY");

                FdlgSeparator.DateFormat        = dateFormatString;
                FdlgSeparator.NumberFormat      = (impOptions.Length > 1) ? impOptions.Substring(1) : TDlgSelectCSVSeparator.NUMBERFORMAT_AMERICAN;
                FdlgSeparator.SelectedSeparator = StringHelper.GetCSVSeparator(FdlgSeparator.FileContent) ??
                                                  ((impOptions.Length > 0) ? impOptions.Substring(0, 1) : ";");

                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("DatesMayBeIntegers", datesMayBeIntegers);
                    requestParams.Add("NumberFormat", FdlgSeparator.NumberFormat);
                    requestParams.Add("NewLine", Environment.NewLine);

                    TVerificationResultCollection AMessages = new TVerificationResultCollection();

                    Thread ImportThread = new Thread(() => ImportGLBatches(
                                                         requestParams,
                                                         FdlgSeparator.FileContent,
                                                         out AMessages,
                                                         out ok,
                                                         out RefreshGUIAfterImport));

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

                    if (TVerificationHelper.ResultsContainErrorCode(AMessages, PetraErrorCodes.ERR_DB_SERIALIZATION_EXCEPTION))
                    {
                        TConcurrentServerTransactions.ShowTransactionSerializationExceptionDialog();
                    }
                    else
                    {
                        ShowMessages(AMessages);
                    }
                }

                // 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);

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

                if (ok)
                {
                    FMyUserControl.ReloadBatches();
                    FMyForm.GetBatchControl().SelectRowInGrid(1);
                    FPetraUtilsObject.SetChangedFlag();
                    FMyForm.SaveChangesManual(FMyForm.FCurrentGLBatchAction);
                }
                else if (RefreshGUIAfterImport)
                {
                    // The import failed and the server needs us to refresh the GUI
                    FMyUserControl.ReloadBatches(true);
                    FMyForm.GetBatchControl().SelectRowInGrid(1);
                }
            }
            finally
            {
                FMyForm.FCurrentGLBatchAction = TGLBatchEnums.GLBatchAction.NONE;
            }
        }
        /// <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;
            bool           RefreshGUIAfterImport = false;
            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;
                }
            }

            bool datesMayBeIntegers = TUserDefaults.GetBooleanDefault(MCommonConstants.USERDEFAULT_IMPORTEDDATESMAYBEINTEGERS, false);

            FdlgSeparator = new TDlgSelectCSVSeparator(false);
            FdlgSeparator.DateMayBeInteger = datesMayBeIntegers;

            if (AImportDataSource == TImportDataSourceEnum.FromClipboard)
            {
                string 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;
                }

                FdlgSeparator.CSVData = importString;
            }
            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|Text Files (*.txt)|*.txt");

                // 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;
                    }
                }
                else
                {
                    return;
                }
            }
            else
            {
                // unknown source!!
                return;
            }

            String impOptions       = TUserDefaults.GetStringDefault("Imp Options", ";" + TDlgSelectCSVSeparator.NUMBERFORMAT_AMERICAN);
            String dateFormatString = TUserDefaults.GetStringDefault("Imp Date", "MDY");

            FdlgSeparator.DateFormat        = dateFormatString;
            FdlgSeparator.NumberFormat      = (impOptions.Length > 1) ? impOptions.Substring(1) : TDlgSelectCSVSeparator.NUMBERFORMAT_AMERICAN;
            FdlgSeparator.SelectedSeparator = StringHelper.GetCSVSeparator(FdlgSeparator.FileContent) ??
                                              ((impOptions.Length > 0) ? impOptions.Substring(0, 1) : ";");

            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("DatesMayBeIntegers", datesMayBeIntegers);
                requestParams.Add("NumberFormat", FdlgSeparator.NumberFormat);
                requestParams.Add("NewLine", Environment.NewLine);
                requestParams.Add("LastTransactionNumber", ACurrentJournalRow.LastTransactionNumber);

                TVerificationResultCollection AMessages = new TVerificationResultCollection();

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

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

                ShowMessages(AMessages);
            }

            // 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);

            if (ok || RefreshGUIAfterImport)
            {
                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.LoadATransactionAndRelatedTablesForJournal(FLedgerNumber,
                                                                                                           ACurrentBatchRow.BatchNumber, ACurrentJournalRow.JournalNumber));
                FMainDS.AcceptChanges();
                FMyForm.Cursor = Cursors.Default;

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

            int BudgetsImported = 0;
            int BudgetsAdded    = 0;
            int BudgetsUpdated  = 0;
            int BudgetsFailed   = 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("Text Files(*.txt) | *.txt | Delimited 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)
            {
                TFrmStatusDialog dlgStatus = new TFrmStatusDialog(FPetraUtilsObject.GetForm());

                FdlgSeparator = new TDlgSelectCSVSeparator(false);

                try
                {
                    string  fileTitle   = OFDialog.SafeFileName;
                    Boolean fileCanOpen = FdlgSeparator.OpenCsvFile(OFDialog.FileName);

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

                    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
                        };

                        Application.UseWaitCursor = true;

                        //New set of budgets to be loaded
                        dlgStatus.Show();
                        dlgStatus.Heading       = Catalog.GetString("Budget Import");
                        dlgStatus.CurrentStatus = Catalog.GetString("Importing budgets from '" + fileTitle + "' ...");

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

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

                        dlgStatus.Visible = false;

                        Application.UseWaitCursor = false;
                        ShowMessages(Messages, BudgetsImported, BudgetsAdded, BudgetsUpdated, BudgetsFailed);
                    }

                    // 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);
                }
                catch (Exception ex)
                {
                    TLogging.LogException(ex, Utilities.GetMethodSignature());
                    throw;
                }
                finally
                {
                    Application.UseWaitCursor = false;
                }

                // update grid
                if ((BudgetsAdded + BudgetsUpdated) > 0)
                {
                    try
                    {
                        dlgStatus.CurrentStatus = Catalog.GetString("Updating budget period data...");
                        dlgStatus.Visible       = true;

                        Application.UseWaitCursor = true;
                        UpdateABudgetPeriodAmounts(AMainDS, ACurrentBudgetYear);
                        FUserControl.SetBudgetDefaultView(AMainDS);
                    }
                    finally
                    {
                        Application.UseWaitCursor = false;
                        dlgStatus.Close();
                    }

                    FPetraUtilsObject.SetChangedFlag();
                }
                else
                {
                    dlgStatus.Close();
                }
            }
        }
        /// <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);
                }
            }
        }
        /// <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("Text Files(*.txt) | *.txt | GL Batch 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();
            }
        }
예제 #13
0
        /// <summary>
        /// This is the main routine to import tax data from clipboard or file
        /// </summary>
        private void BtnOK_Click(Object Sender, EventArgs e)
        {
            if (!ValidateInputs())
            {
                return;
            }

            TDlgSelectCSVSeparator dialog = new TDlgSelectCSVSeparator(chkFirstRowIsHeader.Checked);

            if (rbtFromClipboard.Checked)
            {
                dialog.CSVData           = Clipboard.GetText(TextDataFormat.UnicodeText);
                dialog.SelectedSeparator = "\t";
            }
            else
            {
                if (dialog.OpenCsvFile(txtFileName.Text) == false)
                {
                    MessageBox.Show(Catalog.GetString("Could not open the file you have chosen.  Maybe it is already open somewhere else."),
                                    this.Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    return;
                }
            }

            // work out what the separator is...
            String impOptions = TUserDefaults.GetStringDefault("Imp Options", ";" + TDlgSelectCSVSeparator.NUMBERFORMAT_AMERICAN);

            string separator = StringHelper.GetCSVSeparator(dialog.FileContent) ??
                               ((impOptions.Length > 0) ? impOptions.Substring(0, 1) : ";");
            string numberFormat = (impOptions.Length > 1) ? impOptions.Substring(1) : TDlgSelectCSVSeparator.NUMBERFORMAT_AMERICAN;

            // Now we need to convert the multi-column file/clipboard data to a simple two column list
            string twoColumnImport;

            if (ConvertInputTextToTwoColumns(dialog.FileContent, separator, Convert.ToInt16(nudPartnerKeyColumn.Value - 1),
                                             Convert.ToInt16(nudTaxCodeColumn.Value - 1), out twoColumnImport) == false)
            {
                // We got an error
                return;
            }

            dialog.CSVData = twoColumnImport;

            dialog.SelectedSeparator = separator;
            dialog.DateFormat        = "";  // This will make the combo box empty

            // Show the Preview dialog
            DialogResult dialogResult = dialog.ShowDialog();

            // Save the settings whether the result was OK or cancel
            TUserDefaults.SetDefault("Imp Options", dialog.SelectedSeparator + numberFormat);
            TUserDefaults.SaveChangedUserDefaults();

            if (dialogResult != DialogResult.OK)
            {
                // It was cancelled
                return;
            }

            // Set up the inputs for the call to the server to do the actual import
            string importString      = dialog.FileContent;
            string selectedSeparator = dialog.SelectedSeparator;
            int    emptyCodeAction   = rbtFailEmptyTaxCode.Checked ? 0 : rbtSkipEmptyTaxCode.Checked ? 1 : rbtDeleteEmptyTaxCode.Checked ? 2 : -1;

            Hashtable requestParams = new Hashtable();

            requestParams.Add("Delimiter", dialog.SelectedSeparator);
            requestParams.Add("FirstRowIsHeader", chkFirstRowIsHeader.Checked);
            requestParams.Add("FailIfNotPerson", chkFailIfNotPerson.Checked);
            requestParams.Add("FailIfInvalidPartner", chkFailInvalidPartner.Checked);
            requestParams.Add("OverwriteExistingTaxCode", chkOverwriteExistingTaxCode.Checked);
            requestParams.Add("CreateExtract", chkCreateExtract.Checked);
            requestParams.Add("ExtractName", txtExtractName.Text);
            requestParams.Add("ExtractDescription", txtExtractDescription.Text);
            requestParams.Add("CreateOutFile", chkCreateOutFile.Checked);
            requestParams.Add("EmptyTaxCode", emptyCodeAction);
            requestParams.Add("TaxCodeType", FTaxGovIdKeyName);
            // we include partner details if the user does not want a output file because we will write a sneaky one in the logs folder
            requestParams.Add("IncludePartnerDetails",
                              (chkCreateOutFile.Checked && chkIncludePartnerDetails.Checked) || (chkCreateOutFile.Checked == false));

            // Get the server to parse the file and return our results
            bool success = false;
            TVerificationResultCollection errorMessages = null;
            List <string> outputLines          = null;
            bool          newExtractCreated    = false;
            int           newExtractId         = -1;
            int           newExtractKeyCount   = -1;
            int           taxCodesImported     = -1;
            int           taxCodesDeleted      = -1;
            int           taxCodeMismatchCount = -1;

            // Do the import on the server
            Thread ImportThread = new Thread(() => ImportPartnerTaxCodes(
                                                 requestParams, importString, out success, out errorMessages, out outputLines, out newExtractCreated,
                                                 out newExtractId, out newExtractKeyCount, out taxCodesImported, out taxCodesDeleted, out taxCodeMismatchCount));

            // Show the progress dialog so that the user can cancel
            using (TProgressDialog ImportDialog = new TProgressDialog(ImportThread))
            {
                ImportDialog.ShowDialog();
            }

            if (success)
            {
                // Import was successful
                string msg = Catalog.GetString("The Import was successful.  ");

                msg += string.Format(Catalog.GetPluralString("{0} tax code was imported.  ",
                                                             "{0} tax codes were imported.  ",
                                                             taxCodesImported, true), taxCodesImported);
                msg += string.Format(Catalog.GetPluralString("{0} tax code was deleted.  ",
                                                             "{0} tax codes were deleted.  ",
                                                             taxCodesDeleted, true), taxCodesDeleted);

                if (taxCodeMismatchCount > 0)
                {
                    msg +=
                        string.Format(Catalog.GetPluralString(
                                          "{0} tax code was not imported because it did not match the existing code for the Partner.  ",
                                          "{0} tax codes were not imported because they did not match the existing code for the Partner.  ",
                                          taxCodeMismatchCount, true), taxCodeMismatchCount);
                }

                if (chkCreateOutFile.Checked)
                {
                    //msg += "  ";
                    msg += Catalog.GetString("You can see full details in the output file.");
                }

                if (chkCreateExtract.Checked)
                {
                    msg += Environment.NewLine + Environment.NewLine;

                    if (newExtractCreated)
                    {
                        msg += string.Format(Catalog.GetString("In addition an extract was created containing {0} keys."), newExtractKeyCount);
                    }
                    else
                    {
                        msg += "WARNING! The creation of a new extract failed.  Maybe the name was already in use.";
                    }
                }

                MessageBox.Show(msg, this.Text, MessageBoxButtons.OK);
            }
            else
            {
                // Import failed
                if (TVerificationHelper.ResultsContainErrorCode(errorMessages, PetraErrorCodes.ERR_DB_SERIALIZATION_EXCEPTION))
                {
                    TConcurrentServerTransactions.ShowTransactionSerializationExceptionDialog();
                    return;
                }
                else if (errorMessages.HasCriticalErrors)
                {
                    // A failed import should contain some critical errors.
                    // Concatenate them and show them in an extended message box with scroll bar
                    string msg = Catalog.GetString("The import failed") + Environment.NewLine + Environment.NewLine;

                    for (int i = 0; i < errorMessages.Count; i++)
                    {
                        msg += string.Format("[{0}] - {1}", errorMessages[i].ResultContext, errorMessages[i].ResultText);
                        msg += Environment.NewLine;
                    }

                    msg += Catalog.GetString("No data was imported into the database.");

                    TFrmExtendedMessageBox msgBox = new TFrmExtendedMessageBox(this);
                    msgBox.ShowDialog(msg, this.Text, "", TFrmExtendedMessageBox.TButtons.embbOK, TFrmExtendedMessageBox.TIcon.embiInformation);
                }
                else
                {
                    // Should not end up wit a failed import and no error messages
                    MessageBox.Show("Import failed", this.Text, MessageBoxButtons.OK);
                }
            }

            string pathToOutFile = null;

            if (chkCreateOutFile.Checked)
            {
                pathToOutFile = txtOutputFileName.Text;
            }
            else
            {
                // we try and write a log file anyway in the log folder
                string logPath = TAppSettingsManager.GetValue("OpenPetra.PathLog", "");

                if (logPath.Length > 0)
                {
                    pathToOutFile = logPath + Path.DirectorySeparatorChar + "ImportPartnerTaxCodes.log";
                }
            }

            if (pathToOutFile != null)
            {
                // Write the output file
                using (StreamWriter sw = new StreamWriter(pathToOutFile))
                {
                    for (int i = 0; i < outputLines.Count; i++)
                    {
                        sw.WriteLine(outputLines[i]);
                    }

                    sw.Close();
                }
            }

            if (chkCreateExtract.Checked)
            {
                // Tell the client about the new extract
                // refresh extract master screen if it is open
                TFormsMessage BroadcastMessage = new TFormsMessage(TFormsMessageClassEnum.mcExtractCreated);

                BroadcastMessage.SetMessageDataName(txtExtractName.Text);
                TFormsList.GFormsList.BroadcastFormMessage(BroadcastMessage);
            }

            // Save the GUI settings
            SaveGUISettings();
        }
예제 #14
0
        /// <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, GiftBatchTDS AMainDS)
        {
            bool           ImportOK = false;
            bool           RefreshGUIAfterImport = false;
            OpenFileDialog OFileDialog           = 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;
            }

            ALedgerRow LedgerRow             = (ALedgerRow)AMainDS.ALedger.Rows[0];
            int        CurrentTopBatchNumber = LedgerRow.LastGiftBatchNumber;

            try
            {
                FMyForm.FCurrentGiftBatchAction = Logic.TExtraGiftBatchChecks.GiftBatchAction.IMPORTING;

                bool datesMayBeIntegers = TUserDefaults.GetBooleanDefault(MCommonConstants.USERDEFAULT_IMPORTEDDATESMAYBEINTEGERS, false);
                FdlgSeparator = new TDlgSelectCSVSeparator(false);
                FdlgSeparator.DateMayBeInteger = datesMayBeIntegers;

                if (AImportSource == TGiftImportDataSourceEnum.FromClipboard)
                {
                    string 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;
                    }

                    FdlgSeparator.CSVData = ImportString;
                }
                else if (AImportSource == TGiftImportDataSourceEnum.FromFile)
                {
                    OFileDialog = new OpenFileDialog();

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

                    OFileDialog.Title  = Catalog.GetString("Import Batches from CSV File");
                    OFileDialog.Filter = Catalog.GetString("Gift Batch Files(*.csv)|*.csv|Text Files(*.txt)|*.txt");

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

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

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

                String impOptions       = TUserDefaults.GetStringDefault("Imp Options", ";" + TDlgSelectCSVSeparator.NUMBERFORMAT_AMERICAN);
                String dateFormatString = TUserDefaults.GetStringDefault("Imp Date", "MDY");

                FdlgSeparator.DateFormat        = dateFormatString;
                FdlgSeparator.NumberFormat      = (impOptions.Length > 1) ? impOptions.Substring(1) : TDlgSelectCSVSeparator.NUMBERFORMAT_AMERICAN;
                FdlgSeparator.SelectedSeparator = StringHelper.GetCSVSeparator(FdlgSeparator.FileContent) ??
                                                  ((impOptions.Length > 0) ? impOptions.Substring(0, 1) : ";");

                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("DatesMayBeIntegers", datesMayBeIntegers);
                    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,
                                                             FdlgSeparator.FileContent,
                                                             out AMessages,
                                                             out ImportOK,
                                                             out RefreshGUIAfterImport,
                                                             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)
                        {
                            if (TVerificationHelper.ResultsContainErrorCode(AMessages, PetraErrorCodes.ERR_DB_SERIALIZATION_EXCEPTION))
                            {
                                TConcurrentServerTransactions.ShowTransactionSerializationExceptionDialog();
                            }
                            else
                            {
                                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 occurrence of this error
                                    if (NeedRecipientLedgerNumber.Rows.Count - count > 0)
                                    {
                                        CheckboxText = string.Format(
                                            Catalog.GetString(
                                                "Do this for all further occurrences ({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;
                            }
                        }
                    }
                }

                // 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(OFileDialog);

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

                if (ImportOK)
                {
                    FMyUserControl.LoadBatchesForCurrentYear();
                    FMyForm.GetBatchControl().SelectRowInBatchGrid(1);

                    DataView allNewBatches = new DataView(AMainDS.AGiftBatch);

                    allNewBatches.RowFilter = String.Format("{0} > {1}",
                                                            AGiftBatchTable.GetBatchNumberDBName(),
                                                            CurrentTopBatchNumber);

                    foreach (DataRowView drv in allNewBatches)
                    {
                        drv.Row.SetModified();
                    }

                    FPetraUtilsObject.SetChangedFlag();
                    //Force initial inactive values check
                    FMyForm.SaveChangesManual(FMyForm.FCurrentGiftBatchAction);
                }
                else if (RefreshGUIAfterImport)
                {
                    FMyUserControl.LoadBatchesForCurrentYear();
                    FMyForm.GetBatchControl().SelectRowInBatchGrid(1);
                }
            }
            finally
            {
                FMyForm.FCurrentGiftBatchAction = Logic.TExtraGiftBatchChecks.GiftBatchAction.NONE;
            }
        }
예제 #15
0
        /// <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;
            bool           RefreshGUIAfterImport = false;
            OpenFileDialog dialog      = null;
            Boolean        IsPlainText = false;

            if (FPetraUtilsObject.HasChanges)
            {
                // saving failed, therefore do not try to import
                MessageBox.Show(Catalog.GetString("Please save any changes 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);
            FdlgSeparator.DateMayBeInteger = TUserDefaults.GetBooleanDefault(MCommonConstants.USERDEFAULT_IMPORTEDDATESMAYBEINTEGERS, false);

            if (AImportSource == TGiftImportDataSourceEnum.FromClipboard)
            {
                string 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);
                }

                FdlgSeparator.CSVData = importString;
            }
            else if (AImportSource == TGiftImportDataSourceEnum.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("Gift Transactions files (*.csv)|*.csv|Text Files (*.txt)|*.txt");

                // 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("Gift Import"),
                                        MessageBoxButtons.OK,
                                        MessageBoxIcon.Stop);
                        return(false);
                    }

                    IsPlainText = (Path.GetExtension(dialog.FileName).ToLower() == ".txt");
                }
                else
                {
                    return(false);
                }
            }
            else
            {
                // unknown source!!  The following need a value...
                return(false);
            }

            String impOptions       = TUserDefaults.GetStringDefault("Imp Options", ";" + TDlgSelectCSVSeparator.NUMBERFORMAT_AMERICAN);
            String dateFormatString = TUserDefaults.GetStringDefault("Imp Date", "MDY");

            FdlgSeparator.DateFormat        = dateFormatString;
            FdlgSeparator.NumberFormat      = (impOptions.Length > 1) ? impOptions.Substring(1) : TDlgSelectCSVSeparator.NUMBERFORMAT_AMERICAN;
            FdlgSeparator.SelectedSeparator = StringHelper.GetCSVSeparator(FdlgSeparator.FileContent) ??
                                              ((impOptions.Length > 0) ? impOptions.Substring(0, 1) : ";");

            if (IsPlainText || (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,
                                                         FdlgSeparator.FileContent,
                                                         ACurrentBatchRow.BatchNumber,
                                                         out AMessages,
                                                         out ok,
                                                         out RefreshGUIAfterImport,
                                                         out NeedRecipientLedgerNumber));

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

                    // 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
                    int numberOfMissingGiftDestinations = NeedRecipientLedgerNumber.Rows.Count;

                    if (numberOfMissingGiftDestinations == 0)
                    {
                        if (TVerificationHelper.ResultsContainErrorCode(AMessages, PetraErrorCodes.ERR_DB_SERIALIZATION_EXCEPTION))
                        {
                            TConcurrentServerTransactions.ShowTransactionSerializationExceptionDialog();
                        }
                        else
                        {
                            ShowMessages(AMessages);
                        }
                    }

                    if (numberOfMissingGiftDestinations > 0)
                    {
                        bool offerToRunImportAgain           = true;
                        int  currentMissingGiftDestinationNo = 1;

                        // for each gift in which the recipient needs a Git Destination
                        foreach (GiftBatchTDSAGiftDetailRow Row in NeedRecipientLedgerNumber.Rows)
                        {
                            //Lookup the partner shortname
                            string        partnerShortName = string.Empty;
                            TPartnerClass partnerClass;

                            if (TServerLookup.TMPartner.GetPartnerShortName(Row.RecipientKey, out partnerShortName, out partnerClass))
                            {
                                Row.RecipientDescription = partnerShortName;
                            }

                            if (MessageBox.Show(string.Format(
                                                    Catalog.GetString(
                                                        "Error: {0:0000} of {1:0000} - Recipient '{2}' ({3}) has no Gift Destination assigned."),
                                                    currentMissingGiftDestinationNo, numberOfMissingGiftDestinations, Row.RecipientDescription,
                                                    Row.RecipientKey) +
                                                "\n\n" +
                                                Catalog.GetString("Do you want to assign a Gift Destination to this partner now?"),
                                                Catalog.GetString("Gift Import Cancelled"), 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;
                            }

                            currentMissingGiftDestinationNo++;
                        }

                        // 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;
                        }
                    }
                }
            }

            // 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
            if (!IsPlainText)
            {
                SaveUserDefaults(dialog);
            }

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

            if (ok || RefreshGUIAfterImport)
            {
                FMyUserControl.LoadBatchesForCurrentYear();
                FPetraUtilsObject.DisableSaveButton();
                return(true);        // This completes the refresh
            }

            return(false);
        }
        /// <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();

                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("GL Transactions files (*.csv)|*.csv");
                impOptions    = TUserDefaults.GetStringDefault("Imp Options", ";American");

                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);

                    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();
                }

                ShowMessages(AMessages);
            }

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

                SaveUserDefaults(dialog, impOptions);

                // 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);
            }
        }