Пример #1
0
        /// <summary>
        /// The main method of this class.  It deletes one or more rows selected in a grid on the caller form
        /// </summary>
        /// <param name="ACallerFormOrControl">The form or user control that is making the call.  The form must implement the IDeleteGridRows interface</param>
        /// <param name="AGrid">A reference to the grid object</param>
        /// <param name="APetraUtilsObject">A reference to the PetraUtilsObject associated with the form or control making the call</param>
        /// <param name="AButtonPanel">A reference a form or control that implements the IButtonPanel interface.  This parameter can be null.</param>
        /// <returns>True if any rows were actually deleted</returns>
        public static bool DeleteRows(IDeleteGridRows ACallerFormOrControl,
                                      TSgrdDataGrid AGrid,
                                      TFrmPetraEditUtils APetraUtilsObject,
                                      IButtonPanel AButtonPanel)
        {
            DataRow currentDataRow  = ACallerFormOrControl.GetSelectedDataRow();
            Int32   currentRowIndex = ACallerFormOrControl.GetSelectedRowIndex();

            if ((currentDataRow == null) || (currentRowIndex == -1))
            {
                return(false);
            }

            string CompletionMessage = String.Empty;

            DataRowView[] HighlightedRows = AGrid.SelectedDataRowsAsDataRowView;

            if (HighlightedRows.Length == 1)
            {
                // Single row deletion

                TVerificationResultCollection VerificationResults = null;

                if (TVerificationHelper.IsNullOrOnlyNonCritical(APetraUtilsObject.VerificationResultCollection))
                {
                    ACallerFormOrControl.GetReferenceCount(currentDataRow, APetraUtilsObject.MaxReferenceCountOnDelete, out VerificationResults);
                }

                if ((VerificationResults != null) &&
                    (VerificationResults.Count > 0))
                {
                    TCascadingReferenceCountHandler countHandler = new TCascadingReferenceCountHandler();
                    TFrmExtendedMessageBox.TResult  result       = countHandler.HandleReferences(APetraUtilsObject, VerificationResults, true);

                    if (result == TFrmExtendedMessageBox.TResult.embrYes)
                    {
                        // repeat the count but with no limit to the number of references
                        ACallerFormOrControl.GetReferenceCount(currentDataRow, 0, out VerificationResults);
                        countHandler.HandleReferences(APetraUtilsObject, VerificationResults, false);
                    }

                    return(false);
                }

                string DeletionQuestion  = ACallerFormOrControl.GetDefaultDeletionQuestion();
                bool   AllowDeletion     = true;
                bool   DeletionPerformed = false;

                ACallerFormOrControl.HandlePreDelete(currentDataRow, ref AllowDeletion, ref DeletionQuestion);

                if (AllowDeletion)
                {
                    if ((MessageBox.Show(DeletionQuestion,
                                         MCommonResourcestrings.StrConfirmDeleteTitle,
                                         MessageBoxButtons.YesNo,
                                         MessageBoxIcon.Question,
                                         MessageBoxDefaultButton.Button2) == System.Windows.Forms.DialogResult.Yes))
                    {
                        try
                        {
                            if (!ACallerFormOrControl.HandleDeleteRow(currentDataRow, ref DeletionPerformed, ref CompletionMessage))
                            {
                                currentDataRow.Delete();
                                DeletionPerformed = true;
                            }
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(String.Format(MCommonResourcestrings.StrErrorWhileDeleting,
                                                          Environment.NewLine, ex.Message),
                                            MCommonResourcestrings.StrGenericError,
                                            MessageBoxButtons.OK,
                                            MessageBoxIcon.Warning);
                        }

                        if (DeletionPerformed)
                        {
                            APetraUtilsObject.SetChangedFlag();
                        }

                        // Select and display the details of the nearest row to the one previously selected
                        ACallerFormOrControl.SelectRowInGrid(currentRowIndex);
                        // Clear any errors left over from  the deleted row
                        APetraUtilsObject.VerificationResultCollection.Clear();

                        if (AButtonPanel != null)
                        {
                            AButtonPanel.UpdateRecordNumberDisplay();
                        }
                    }
                }

                if (!ACallerFormOrControl.HandlePostDelete(currentDataRow, AllowDeletion, DeletionPerformed, CompletionMessage))
                {
                    if (DeletionPerformed && (CompletionMessage.Length > 0))
                    {
                        MessageBox.Show(CompletionMessage, MCommonResourcestrings.StrDeletionCompletedTitle);
                    }
                }

                return(DeletionPerformed);
            }
            else
            {
                // Multi-row deletion

                int recordsDeleted = 0;

                string DeletionQuestion = String.Format(MCommonResourcestrings.StrMultiRowDeletionQuestion,
                                                        HighlightedRows.Length,
                                                        Environment.NewLine);
                DeletionQuestion += MCommonResourcestrings.StrMultiRowDeletionCheck;

                if (MessageBox.Show(DeletionQuestion,
                                    MCommonResourcestrings.StrConfirmDeleteTitle,
                                    MessageBoxButtons.YesNo,
                                    MessageBoxIcon.Question,
                                    MessageBoxDefaultButton.Button2) == System.Windows.Forms.DialogResult.Yes)
                {
                    int recordsUndeletable                   = 0;
                    int recordsDeleteDisallowed              = 0;
                    List <TMultiDeleteResult> listConflicts  = new List <TMultiDeleteResult>();
                    List <TMultiDeleteResult> listExceptions = new List <TMultiDeleteResult>();

                    APetraUtilsObject.GetForm().Cursor = Cursors.WaitCursor;

                    foreach (DataRowView drv in HighlightedRows)
                    {
                        DataRow rowToDelete = drv.Row;

                        if (rowToDelete.RowState == DataRowState.Detached)
                        {
                            continue;
                        }

                        string rowDetails = MakePKValuesString(rowToDelete);

                        if (!ACallerFormOrControl.IsRowDeletable(rowToDelete))
                        {
                            recordsUndeletable++;
                            continue;
                        }

                        TVerificationResultCollection VerificationResults = null;
                        ACallerFormOrControl.GetReferenceCount(rowToDelete, APetraUtilsObject.MaxReferenceCountOnDelete, out VerificationResults);

                        if ((VerificationResults != null) && (VerificationResults.Count > 0))
                        {
                            TMultiDeleteResult result = new TMultiDeleteResult(rowDetails,
                                                                               Messages.BuildMessageFromVerificationResult(String.Empty, VerificationResults));
                            listConflicts.Add(result);
                            continue;
                        }

                        bool AllowDeletion     = true;
                        bool DeletionPerformed = false;

                        ACallerFormOrControl.HandlePreDelete(rowToDelete, ref AllowDeletion, ref DeletionQuestion);

                        if (AllowDeletion)
                        {
                            try
                            {
                                if (!ACallerFormOrControl.HandleDeleteRow(rowToDelete, ref DeletionPerformed, ref CompletionMessage))
                                {
                                    rowToDelete.Delete();
                                    DeletionPerformed = true;
                                }
                            }
                            catch (Exception ex)
                            {
                                TMultiDeleteResult result = new TMultiDeleteResult(rowDetails, ex.Message);
                                listExceptions.Add(result);
                            }
                        }
                        else
                        {
                            recordsDeleteDisallowed++;
                        }

                        if (DeletionPerformed)
                        {
                            APetraUtilsObject.SetChangedFlag();
                            recordsDeleted++;
                        }

                        ACallerFormOrControl.HandlePostDelete(rowToDelete, AllowDeletion, DeletionPerformed, String.Empty);
                    }

                    APetraUtilsObject.GetForm().Cursor = Cursors.Default;
                    ACallerFormOrControl.SelectRowInGrid(currentRowIndex);

                    if (AButtonPanel != null)
                    {
                        AButtonPanel.UpdateRecordNumberDisplay();
                    }

                    if ((recordsDeleted > 0) && (CompletionMessage.Length > 0))
                    {
                        MessageBox.Show(CompletionMessage, MCommonResourcestrings.StrDeletionCompletedTitle);
                    }

                    //  Show the results of the multi-deletion
                    string results = null;

                    if (recordsDeleted > 0)
                    {
                        results = String.Format(
                            Catalog.GetPluralString(MCommonResourcestrings.StrRecordSuccessfullyDeleted,
                                                    MCommonResourcestrings.StrRecordsSuccessfullyDeleted, recordsDeleted),
                            recordsDeleted);
                    }
                    else
                    {
                        results = MCommonResourcestrings.StrNoRecordsWereDeleted;
                    }

                    if (recordsUndeletable > 0)
                    {
                        results += String.Format(
                            Catalog.GetPluralString(MCommonResourcestrings.StrRowNotDeletedBecauseNonDeletable,
                                                    MCommonResourcestrings.StrRowsNotDeletedBecauseNonDeletable,
                                                    recordsUndeletable),
                            Environment.NewLine,
                            recordsUndeletable);
                    }

                    if (recordsDeleteDisallowed > 0)
                    {
                        results += String.Format(
                            Catalog.GetPluralString(MCommonResourcestrings.StrRowNotDeletedBecauseDeleteNotAllowed,
                                                    MCommonResourcestrings.StrRowsNotDeletedBecauseDeleteNotAllowed,
                                                    recordsDeleteDisallowed),
                            Environment.NewLine,
                            recordsDeleteDisallowed);
                    }

                    bool showCancel = false;

                    if (listConflicts.Count > 0)
                    {
                        showCancel = true;
                        results   += String.Format(
                            Catalog.GetPluralString(MCommonResourcestrings.StrRowNotDeletedBecauseReferencedElsewhere,
                                                    MCommonResourcestrings.StrRowsNotDeletedBecauseReferencedElsewhere,
                                                    listConflicts.Count),
                            Environment.NewLine,
                            listConflicts.Count);
                    }

                    if (listExceptions.Count > 0)
                    {
                        showCancel = true;
                        results   += String.Format(
                            Catalog.GetPluralString(MCommonResourcestrings.StrRowNotDeletedDueToUnexpectedException,
                                                    MCommonResourcestrings.StrRowNotDeletedDueToUnexpectedException,
                                                    listExceptions.Count),
                            Environment.NewLine,
                            listExceptions.Count);
                    }

                    if (showCancel)
                    {
                        results += String.Format(MCommonResourcestrings.StrClickToReviewDeletionOrCancel, Environment.NewLine);

                        if (MessageBox.Show(results,
                                            MCommonResourcestrings.StrDeleteActionSummaryTitle,
                                            MessageBoxButtons.OKCancel,
                                            MessageBoxIcon.Warning) == System.Windows.Forms.DialogResult.OK)
                        {
                            ReviewMultiDeleteResults(listConflicts, MCommonResourcestrings.StrRowsReferencedByOtherTables);
                            ReviewMultiDeleteResults(listExceptions, MCommonResourcestrings.StrExceptions);
                        }
                    }
                    else
                    {
                        MessageBox.Show(results,
                                        MCommonResourcestrings.StrDeleteActionSummaryTitle,
                                        MessageBoxButtons.OK,
                                        MessageBoxIcon.Information);
                    }
                }

                return(recordsDeleted > 0);
            }
        }
Пример #2
0
        /// <summary>
        /// Saves any changed preferences to s_user_defaults
        /// </summary>
        /// <returns>void</returns>
        public DialogResult SaveGeneralTab()
        {
            // First, we need to show any dialogs that may result in Cancel
            if (chkSaveWindowProperties.Checked && !WasSaveWindowPropertiesInitiallyChecked)
            {
                // The user wants to start saving the window positions etc.
                // If we have some information about this that we stored previously, we can offer to use it again...
                string localAppDataPath = Path.Combine(
                    TAppSettingsManager.GetLocalAppDataPath(),
                    CommonFormsResourcestrings.StrFolderOrganisationName,
                    System.Diagnostics.FileVersionInfo.GetVersionInfo(Assembly.GetExecutingAssembly().Location).ProductName);
                string settingsFileName = String.Format(CommonFormsResourcestrings.StrScreenPositionsFileName, UserInfo.GUserInfo.UserID);
                string settingsPath     = Path.Combine(localAppDataPath, settingsFileName);

                if (File.Exists(settingsPath))
                {
                    string msg = String.Format("{0}{1}{1}{2}",
                                               CommonFormsResourcestrings.StrReuseScreenPositionsMessage1,
                                               Environment.NewLine,
                                               CommonFormsResourcestrings.StrReuseScreenPositionsMessage2);

                    bool DoNotShowMessageBoxEverytime = false;

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

                    // customise button text
                    extendedMessageBox.YesButtonText = Catalog.GetString("Keep");
                    extendedMessageBox.NoButtonText  = Catalog.GetString("Discard");

                    extendedMessageBox.ShowDialog(msg,
                                                  CommonFormsResourcestrings.StrReuseScreenPositionsTitle,
                                                  string.Empty,
                                                  TFrmExtendedMessageBox.TButtons.embbYesNoCancel, TFrmExtendedMessageBox.TIcon.embiQuestion);
                    TFrmExtendedMessageBox.TResult result = extendedMessageBox.GetResult(out DoNotShowMessageBoxEverytime);

                    if (result == TFrmExtendedMessageBox.TResult.embrCancel)
                    {
                        return(DialogResult.Cancel);
                    }
                    else if (result == TFrmExtendedMessageBox.TResult.embrNo)
                    {
                        try
                        {
                            // Delete the old file
                            File.Delete(settingsPath);
                        }
                        catch (Exception ex)
                        {
                            TLogging.Log(String.Format("Exception occurred while deleting the window position file '{0}': {1}",
                                                       settingsPath,
                                                       ex.Message), TLoggingType.ToLogfile);
                        }
                    }
                    else if (result == TFrmExtendedMessageBox.TResult.embrYes)
                    {
                        // Load the information we have already
                        PetraUtilsObject.LoadWindowPositionsFromFile();
                    }
                }
            }

            if (LanguageChanged)
            {
                string LanguageCode = cmbLanguage.GetSelectedString();
                string CultureCode  = cmbCulture.GetSelectedString();

                // send to server
                TRemote.MSysMan.Maintenance.WebConnectors.SetLanguageAndCulture(LanguageCode, CultureCode);

                // set local settings for client
                Catalog.Init(LanguageCode, CultureCode);

                // TODO: can we reload the main window with the new language?
                MessageBox.Show(Catalog.GetString("Please restart the OpenPetra client to see the new language"),
                                Catalog.GetString("Restart the client"),
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Information);
            }

            TUserDefaults.SetDefault(MSysManConstants.USERDEFAULT_NUMBEROFRECENTPARTNERS, nudNumberOfPartners.Value);
            TUserDefaults.SetDefault(TUserDefaults.NamedDefaults.USERDEFAULT_ESC_CLOSES_SCREEN, chkEscClosesScreen.Checked);
            TUserDefaults.SetDefault(TUserDefaults.NamedDefaults.USERDEFAULT_SAVE_WINDOW_POS_AND_SIZE, chkSaveWindowProperties.Checked);
            TUserDefaults.SetDefault(TUserDefaults.NamedDefaults.MODULE_TO_OPEN_AT_STARTUP, cmbInitialSelectedModule.GetSelectedString());

            return(DialogResult.OK);
        }
Пример #3
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();
            }
        }
Пример #4
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;
            }
        }