コード例 #1
0
        private void ShowMessages(TVerificationResultCollection AMessages)
        {
            StringBuilder ErrorMessages = new StringBuilder();

            if (AMessages.Count > 0)
            {
                foreach (TVerificationResult message in AMessages)
                {
                    ErrorMessages.AppendFormat("[{0}] {1}: {2}{3}", message.ResultContext, message.ResultTextCaption,
                                               message.ResultText.Replace(Environment.NewLine, " "), Environment.NewLine);
                }
            }

            if (ErrorMessages.Length > 0)
            {
                TFrmExtendedMessageBox extendedMessageBox = new TFrmExtendedMessageBox(FPetraUtilsObject.GetForm());
                extendedMessageBox.ShowDialog(ErrorMessages.ToString(), Catalog.GetString("Import Errors"), String.Empty,
                                              TFrmExtendedMessageBox.TButtons.embbOK, TFrmExtendedMessageBox.TIcon.embiError);
            }
        }
コード例 #2
0
        // The Preview button has been clicked
        private void PreviewLayout(Object sender, EventArgs e)
        {
            // perform standard validation to make sure the layout text has no errors
            if (ValidateAllData(true, TErrorProcessingMode.Epm_IgnoreNonCritical))
            {
                this.Cursor = Cursors.WaitCursor;

                TFrmExtendedMessageBox msgBox = new TFrmExtendedMessageBox(this);

                string s = Catalog.GetString("This is how your address layout will look when printed :");
                s += Environment.NewLine + Environment.NewLine;

                // Get the layout from the server using the same method used by Templater
                s += TRemote.MPartner.Partner.WebConnectors.PreviewAddressBlock(txtDetailAddressBlockText.Text);

                this.Cursor = Cursors.Default;

                msgBox.ShowDialog(s, Catalog.GetString("Layout Printing Example"), String.Empty,
                                  TFrmExtendedMessageBox.TButtons.embbOK, TFrmExtendedMessageBox.TIcon.embiInformation);
            }
        }
コード例 #3
0
        /// <summary>
        /// Runs a test on posting a batch
        /// </summary>
        /// <param name="ACurrentBatchRow">The data row corresponding to the batch to post</param>
        public void TestPostBatch(ABatchRow ACurrentBatchRow)
        {
            if (!SaveBatchForPosting())
            {
                return;
            }

            TVerificationResultCollection Verifications;
            TFrmExtendedMessageBox        ExtendedMessageBox = new TFrmExtendedMessageBox(FMyForm);

            FMyForm.Cursor = Cursors.WaitCursor;

            List <TVariant> Result = TRemote.MFinance.GL.WebConnectors.TestPostGLBatch(FLedgerNumber, ACurrentBatchRow.BatchNumber, out Verifications);

            try
            {
                if ((Verifications != null) && (Verifications.Count > 0))
                {
                    string ErrorMessages = string.Empty;

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

                    ExtendedMessageBox.ShowDialog(ErrorMessages,
                                                  Catalog.GetString("Test Post Failed"), string.Empty,
                                                  TFrmExtendedMessageBox.TButtons.embbOK,
                                                  TFrmExtendedMessageBox.TIcon.embiWarning);
                }
                else
                {
                    string header  = string.Empty;
                    string message = string.Empty;

                    foreach (TVariant value in Result)
                    {
                        ArrayList compValues = value.ToComposite();

                        message += String.Format(Catalog.GetString("--{1}/{0} ({3}/{2}) is: {4} and would be: {5}{6}"),
                                                 ((TVariant)compValues[0]).ToString(),
                                                 ((TVariant)compValues[2]).ToString(),
                                                 ((TVariant)compValues[1]).ToString(),
                                                 ((TVariant)compValues[3]).ToString(),
                                                 StringHelper.FormatCurrency((TVariant)compValues[4], "currency"),
                                                 StringHelper.FormatCurrency((TVariant)compValues[5], "currency"),
                                                 Environment.NewLine);
                    }

                    if (Result.Count > 25)
                    {
                        string line = new String('_', 70);
                        header =
                            String.Format(Catalog.GetString(
                                              "{0}{1}{1}{2} results listed below. Do you want to export this list to a CSV file?{1}{0}{1}{1}"),
                                          line,
                                          Environment.NewLine,
                                          Result.Count);

                        if (ExtendedMessageBox.ShowDialog((header + message),
                                                          Catalog.GetString("Result of Test Posting"), string.Empty,
                                                          TFrmExtendedMessageBox.TButtons.embbYesNo,
                                                          TFrmExtendedMessageBox.TIcon.embiQuestion) == TFrmExtendedMessageBox.TResult.embrYes)
                        {
                            // store to CSV file
                            string cSVForExport  = string.Empty;
                            string messageExport = string.Empty;

                            foreach (TVariant value in Result)
                            {
                                ArrayList compValues = value.ToComposite();

                                string[] columns = new string[] {
                                    ((TVariant)compValues[0]).ToString(),
                                    ((TVariant)compValues[1]).ToString(),
                                    ((TVariant)compValues[2]).ToString(),
                                    ((TVariant)compValues[3]).ToString(),
                                    StringHelper.FormatCurrency((TVariant)compValues[4], "CurrencyCSV"),
                                    StringHelper.FormatCurrency((TVariant)compValues[5], "CurrencyCSV")
                                };

                                cSVForExport += StringHelper.StrMerge(columns,
                                                                      Thread.CurrentThread.CurrentCulture.TextInfo.ListSeparator[0]) +
                                                Environment.NewLine;
                            }

                            try
                            {
                                string CSVFilePath = TClientSettings.PathLog + Path.DirectorySeparatorChar + "Batch" +
                                                     ACurrentBatchRow.BatchNumber.ToString() +
                                                     "_TestPosting.csv";

                                StreamWriter sw = new StreamWriter(CSVFilePath, false, System.Text.Encoding.UTF8);
                                sw.Write(cSVForExport);
                                sw.Close();

                                messageExport = String.Format(Catalog.GetString("Please see the results in the file:{1}{1}'{0}'{1}{1}"),
                                                              CSVFilePath,
                                                              Environment.NewLine);
                                messageExport += "Do you want to open the file for viewing now?";

                                if (MessageBox.Show(messageExport,
                                                    Catalog.GetString("Result of Test Posting"),
                                                    MessageBoxButtons.YesNo,
                                                    MessageBoxIcon.Question) == DialogResult.Yes)
                                {
                                    try
                                    {
                                        ProcessStartInfo si = new ProcessStartInfo(CSVFilePath);
                                        si.UseShellExecute = true;
                                        si.Verb            = "open";

                                        Process p = new Process();
                                        p.StartInfo = si;
                                        p.Start();
                                    }
                                    catch
                                    {
                                        MessageBox.Show(Catalog.GetString(
                                                            "Unable to launch the default application to open: '") + CSVFilePath + "'!", Catalog.GetString(
                                                            "Result of Test Posting"), MessageBoxButtons.OK, MessageBoxIcon.Exclamation);


                                        //If windows start Windows File Explorer
                                        TExecutingOSEnum osVersion = Utilities.DetermineExecutingOS();

                                        if ((osVersion >= TExecutingOSEnum.eosWinXP) &&
                                            (osVersion < TExecutingOSEnum.oesUnsupportedPlatform))
                                        {
                                            try
                                            {
                                                Process.Start("explorer.exe", string.Format("/select,\"{0}\"", CSVFilePath));
                                            }
                                            catch
                                            {
                                                MessageBox.Show(Catalog.GetString(
                                                                    "Unable to launch Windows File Explorer to open: '") + CSVFilePath + "'!", Catalog.GetString(
                                                                    "Result of Test Posting"), MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                                            }
                                        }
                                    }
                                }
                            }
                            catch (Exception ex)
                            {
                                MessageBox.Show("Error trying to export test posting results to CSV file: " + ex.Message,
                                                "Test Posting Results Export",
                                                MessageBoxButtons.OK,
                                                MessageBoxIcon.Error);
                            }
                        }
                    }
                    else
                    {
                        ExtendedMessageBox.ShowDialog(message,
                                                      Catalog.GetString("Result of Test Posting"), string.Empty,
                                                      TFrmExtendedMessageBox.TButtons.embbOK,
                                                      TFrmExtendedMessageBox.TIcon.embiInformation);
                    }
                }
            }
            finally
            {
                FMyForm.Cursor = Cursors.Default;
            }
        }
コード例 #4
0
        /// <summary>
        /// Main method to post a specified batch
        /// </summary>
        /// <param name="ACurrentBatchRow">The batch row to post</param>
        /// <param name="APostingAlreadyConfirmed">True means ask user if they want to post</param>
        /// <param name="AWarnOfInactiveValues">True means user is warned if inactive values exist</param>
        /// <param name="ADonorZeroIsValid"></param>
        /// <param name="ARecipientZeroIsValid"></param>
        /// <returns>True if the batch was successfully posted</returns>
        public bool PostBatch(AGiftBatchRow ACurrentBatchRow,
                              bool APostingAlreadyConfirmed = false,
                              bool AWarnOfInactiveValues    = true,
                              bool ADonorZeroIsValid        = false,
                              bool ARecipientZeroIsValid    = false)
        {
            //This assumes that all gift data etc is loaded into the batch before arriving here

            bool RetVal = false;

            if ((ACurrentBatchRow == null) || (ACurrentBatchRow.BatchStatus != MFinanceConstants.BATCH_UNPOSTED))
            {
                return(RetVal);
            }

            FSelectedBatchNumber = ACurrentBatchRow.BatchNumber;
            TVerificationResultCollection Verifications;

            try
            {
                //Make sure that all control data is in dataset
                FMyForm.GetControlDataForPosting();

                GiftBatchTDSAGiftDetailTable batchGiftDetails = new GiftBatchTDSAGiftDetailTable();
                DataView batchGiftDetailsDV = new DataView(FMainDS.AGiftDetail);

                batchGiftDetailsDV.RowFilter = string.Format("{0}={1}",
                                                             AGiftDetailTable.GetBatchNumberDBName(),
                                                             FSelectedBatchNumber);

                batchGiftDetailsDV.Sort = string.Format("{0} ASC, {1} ASC, {2} ASC",
                                                        AGiftDetailTable.GetBatchNumberDBName(),
                                                        AGiftDetailTable.GetGiftTransactionNumberDBName(),
                                                        AGiftDetailTable.GetDetailNumberDBName());

                foreach (DataRowView drv in batchGiftDetailsDV)
                {
                    GiftBatchTDSAGiftDetailRow gBRow = (GiftBatchTDSAGiftDetailRow)drv.Row;

                    batchGiftDetails.Rows.Add((object[])gBRow.ItemArray.Clone());
                }

                bool CancelledDueToExWorkerOrAnonDonor;

                // save first, then post
                if (!FMyForm.SaveChangesForPosting(batchGiftDetails, out CancelledDueToExWorkerOrAnonDonor))
                {
                    FMyForm.Cursor = Cursors.Default;

                    if (!CancelledDueToExWorkerOrAnonDonor)
                    {
                        // saving failed, therefore do not try to post
                        MessageBox.Show(Catalog.GetString("The batch was not posted due to problems during saving; ") + Environment.NewLine +
                                        Catalog.GetString("Please first correct and save the batch, and then post it!"));
                    }

                    return(RetVal);
                }
            }
            catch (Exception ex)
            {
                TLogging.LogException(ex, Utilities.GetMethodSignature());
                throw;
            }

            //Check for missing international exchange rate
            bool IsTransactionInIntlCurrency = false;

            FMyForm.WarnAboutMissingIntlExchangeRate = true;

            if (FMyForm.InternationalCurrencyExchangeRate(ACurrentBatchRow, out IsTransactionInIntlCurrency, true) == 0)
            {
                return(RetVal);
            }

            //Check for zero Donors or Recipients
            if (!ADonorZeroIsValid)
            {
                DataView batchGiftDV = new DataView(FMainDS.AGift);

                batchGiftDV.RowFilter = string.Format("{0}={1} And {2}=0",
                                                      AGiftTable.GetBatchNumberDBName(),
                                                      FSelectedBatchNumber,
                                                      AGiftTable.GetDonorKeyDBName());

                int numDonorZeros = batchGiftDV.Count;

                if (numDonorZeros > 0)
                {
                    string messageListOfOffendingGifts =
                        String.Format(Catalog.GetString(
                                          "Gift Batch {0} contains {1} gift detail(s) with Donor 0000000. Please fix before posting!{2}{2}"),
                                      FSelectedBatchNumber,
                                      numDonorZeros,
                                      Environment.NewLine);

                    string listOfOffendingRows = string.Empty;

                    listOfOffendingRows += "Gift" + Environment.NewLine;
                    listOfOffendingRows += "------------";

                    foreach (DataRowView drv in batchGiftDV)
                    {
                        AGiftRow giftRow = (AGiftRow)drv.Row;

                        listOfOffendingRows += String.Format("{0}{1:0000}",
                                                             Environment.NewLine,
                                                             giftRow.GiftTransactionNumber);
                    }

                    TFrmExtendedMessageBox extendedMessageBox = new TFrmExtendedMessageBox(FMyForm);

                    extendedMessageBox.ShowDialog((messageListOfOffendingGifts + listOfOffendingRows),
                                                  Catalog.GetString("Post Batch Error"), string.Empty,
                                                  TFrmExtendedMessageBox.TButtons.embbOK,
                                                  TFrmExtendedMessageBox.TIcon.embiWarning);

                    return(RetVal);
                }
            }

            if (!ARecipientZeroIsValid)
            {
                DataView batchGiftDetailsDV = new DataView(FMainDS.AGiftDetail);

                batchGiftDetailsDV.RowFilter = string.Format("{0}={1} And {2}=0",
                                                             AGiftDetailTable.GetBatchNumberDBName(),
                                                             FSelectedBatchNumber,
                                                             AGiftDetailTable.GetRecipientKeyDBName());

                int numRecipientZeros = batchGiftDetailsDV.Count;

                if (numRecipientZeros > 0)
                {
                    string messageListOfOffendingGifts =
                        String.Format(Catalog.GetString(
                                          "Gift Batch {0} contains {1} gift detail(s) with Recipient 0000000. Please fix before posting!{2}{2}"),
                                      FSelectedBatchNumber,
                                      numRecipientZeros,
                                      Environment.NewLine);

                    string listOfOffendingRows = string.Empty;

                    listOfOffendingRows += "Gift   Detail" + Environment.NewLine;
                    listOfOffendingRows += "-------------------";

                    foreach (DataRowView drv in batchGiftDetailsDV)
                    {
                        AGiftDetailRow giftDetailRow = (AGiftDetailRow)drv.Row;

                        listOfOffendingRows += String.Format("{0}{1:0000}  {2:00}",
                                                             Environment.NewLine,
                                                             giftDetailRow.GiftTransactionNumber,
                                                             giftDetailRow.DetailNumber);
                    }

                    TFrmExtendedMessageBox extendedMessageBox = new TFrmExtendedMessageBox(FMyForm);

                    extendedMessageBox.ShowDialog((messageListOfOffendingGifts + listOfOffendingRows),
                                                  Catalog.GetString("Post Batch Error"), string.Empty,
                                                  TFrmExtendedMessageBox.TButtons.embbOK,
                                                  TFrmExtendedMessageBox.TIcon.embiWarning);

                    return(RetVal);
                }
            }

            //Check for inactive KeyMinistries
            DataTable GiftsWithInactiveKeyMinistries;
            bool      ModifiedDetails = false;

            if (AWarnOfInactiveValues && TRemote.MFinance.Gift.WebConnectors.InactiveKeyMinistriesFoundInBatch(FLedgerNumber, FSelectedBatchNumber,
                                                                                                               out GiftsWithInactiveKeyMinistries, false))
            {
                int numInactiveValues = GiftsWithInactiveKeyMinistries.Rows.Count;

                string messageNonModifiedBatch =
                    String.Format(Catalog.GetString("Gift Batch {0} contains {1} inactive key ministries. Please fix before posting!{2}{2}"),
                                  FSelectedBatchNumber,
                                  numInactiveValues,
                                  Environment.NewLine);
                string messageModifiedBatch =
                    String.Format(Catalog.GetString(
                                      "Reversal/Adjustment Gift Batch {0} contains {1} inactive key ministries. Do you still want to post?{2}{2}"),
                                  FSelectedBatchNumber,
                                  numInactiveValues,
                                  Environment.NewLine);

                string listOfOffendingRows = string.Empty;

                listOfOffendingRows += "Gift      Detail   Recipient          KeyMinistry" + Environment.NewLine;
                listOfOffendingRows += "-------------------------------------------------------------------------------";

                foreach (DataRow dr in GiftsWithInactiveKeyMinistries.Rows)
                {
                    listOfOffendingRows += String.Format("{0}{1:0000}    {2:00}        {3:00000000000}    {4}",
                                                         Environment.NewLine,
                                                         dr[0],
                                                         dr[1],
                                                         dr[2],
                                                         dr[3]);

                    bool isModified = Convert.ToBoolean(dr[4]);

                    if (isModified)
                    {
                        ModifiedDetails = true;
                    }
                }

                TFrmExtendedMessageBox extendedMessageBox = new TFrmExtendedMessageBox(FMyForm);

                if (ModifiedDetails)
                {
                    if (extendedMessageBox.ShowDialog((messageModifiedBatch + listOfOffendingRows),
                                                      Catalog.GetString("Post Batch"), string.Empty,
                                                      TFrmExtendedMessageBox.TButtons.embbYesNo,
                                                      TFrmExtendedMessageBox.TIcon.embiWarning) == TFrmExtendedMessageBox.TResult.embrYes)
                    {
                        APostingAlreadyConfirmed = true;
                    }
                    else
                    {
                        return(RetVal);
                    }
                }
                else
                {
                    extendedMessageBox.ShowDialog((messageNonModifiedBatch + listOfOffendingRows),
                                                  Catalog.GetString("Post Batch Error"), string.Empty,
                                                  TFrmExtendedMessageBox.TButtons.embbOK,
                                                  TFrmExtendedMessageBox.TIcon.embiWarning);

                    return(RetVal);
                }
            }

            // ask if the user really wants to post the batch
            if (!APostingAlreadyConfirmed &&
                (MessageBox.Show(String.Format(Catalog.GetString("Do you really want to post gift batch {0}?"), FSelectedBatchNumber),
                                 Catalog.GetString("Confirm posting of Gift Batch"),
                                 MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes))
            {
                return(RetVal);
            }

            Verifications = new TVerificationResultCollection();

            try
            {
                FPostingInProgress = true;

                Thread postingThread = new Thread(() => PostGiftBatch(out Verifications));

                using (TProgressDialog dialog = new TProgressDialog(postingThread))
                {
                    dialog.ShowDialog();
                }

                if (!TVerificationHelper.IsNullOrOnlyNonCritical(Verifications))
                {
                    TFrmExtendedMessageBox extendedMessageBox = new TFrmExtendedMessageBox(FMyForm);

                    StringBuilder errorMessages = new StringBuilder();
                    int           counter       = 0;

                    errorMessages.AppendLine(Catalog.GetString("________________________Gift Posting Errors________________________"));
                    errorMessages.AppendLine();

                    foreach (TVerificationResult verif in Verifications)
                    {
                        counter++;
                        errorMessages.AppendLine(counter.ToString("000") + " - " + verif.ResultText);
                        errorMessages.AppendLine();
                    }

                    extendedMessageBox.ShowDialog(errorMessages.ToString(),
                                                  Catalog.GetString("Post Batch Error"),
                                                  string.Empty,
                                                  TFrmExtendedMessageBox.TButtons.embbOK,
                                                  TFrmExtendedMessageBox.TIcon.embiWarning);
                }
                else
                {
                    MessageBox.Show(Catalog.GetString("The batch has been posted successfully!"));

                    RetVal = true;
                }
            }
            catch (Exception ex)
            {
                TLogging.LogException(ex, Utilities.GetMethodSignature());
                throw;
            }
            finally
            {
                FPostingInProgress = false;
            }

            return(RetVal);
        }
コード例 #5
0
        private bool AllowInactiveFieldValues(int ABatchNumber, out int ANumInactiveValues)
        {
            bool RetVal = false;

            TVerificationResultCollection VerificationResult = new TVerificationResultCollection();
            string VerificationMessage = string.Empty;

            DataView TransDV  = new DataView(FMainDS.ATransaction);
            DataView AttribDV = new DataView(FMainDS.ATransAnalAttrib);

            int NumInactiveAccounts      = 0;
            int NumInactiveCostCentres   = 0;
            int NumInactiveAccountTypes  = 0;
            int NumInactiveAccountValues = 0;

            try
            {
                //Check for inactive account or cost centre codes
                TransDV.RowFilter = String.Format("{0}={1}",
                                                  ATransactionTable.GetBatchNumberDBName(),
                                                  ABatchNumber);
                TransDV.Sort = String.Format("{0} ASC, {1} ASC",
                                             ATransactionTable.GetJournalNumberDBName(),
                                             ATransactionTable.GetTransactionNumberDBName());

                foreach (DataRowView drv in TransDV)
                {
                    ATransactionRow transRow = (ATransactionRow)drv.Row;

                    if (!AccountIsActive(transRow.AccountCode))
                    {
                        VerificationMessage += String.Format(" Account '{0}' in Journal:{1} Transaction:{2}.{3}",
                                                             transRow.AccountCode,
                                                             transRow.JournalNumber,
                                                             transRow.TransactionNumber,
                                                             Environment.NewLine);

                        NumInactiveAccounts++;
                    }

                    if (!CostCentreIsActive(transRow.CostCentreCode))
                    {
                        VerificationMessage += String.Format(" Cost Centre '{0}' in Journal:{1} Transaction:{2}.{3}",
                                                             transRow.CostCentreCode,
                                                             transRow.JournalNumber,
                                                             transRow.TransactionNumber,
                                                             Environment.NewLine);

                        NumInactiveCostCentres++;
                    }
                }

                //Check anlysis attributes
                AttribDV.RowFilter = String.Format("{0}={1}",
                                                   ATransAnalAttribTable.GetBatchNumberDBName(),
                                                   ABatchNumber);
                AttribDV.Sort = String.Format("{0} ASC, {1} ASC, {2} ASC",
                                              ATransAnalAttribTable.GetJournalNumberDBName(),
                                              ATransAnalAttribTable.GetTransactionNumberDBName(),
                                              ATransAnalAttribTable.GetAnalysisTypeCodeDBName());

                foreach (DataRowView drv2 in AttribDV)
                {
                    ATransAnalAttribRow analAttribRow = (ATransAnalAttribRow)drv2.Row;

                    if (!AnalysisCodeIsActive(analAttribRow.AccountCode, analAttribRow.AnalysisTypeCode))
                    {
                        VerificationMessage += String.Format(" Analysis Code '{0}' in Journal:{1} Transaction:{2}.{3}",
                                                             analAttribRow.AnalysisTypeCode,
                                                             analAttribRow.JournalNumber,
                                                             analAttribRow.TransactionNumber,
                                                             Environment.NewLine);

                        NumInactiveAccountTypes++;
                    }

                    if (!AnalysisAttributeValueIsActive(analAttribRow.AnalysisTypeCode, analAttribRow.AnalysisAttributeValue))
                    {
                        VerificationMessage += String.Format(" Analysis Value '{0}' in Journal:{1} Transaction:{2}.{3}",
                                                             analAttribRow.AnalysisAttributeValue,
                                                             analAttribRow.JournalNumber,
                                                             analAttribRow.TransactionNumber,
                                                             Environment.NewLine);

                        NumInactiveAccountValues++;
                    }
                }
            }
            catch (Exception ex)
            {
                TLogging.LogException(ex, Utilities.GetMethodSignature());
                throw;
            }

            ANumInactiveValues = (NumInactiveAccounts + NumInactiveCostCentres + NumInactiveAccountTypes + NumInactiveAccountValues);

            if (ANumInactiveValues > 0)
            {
                VerificationResult.Add(new TVerificationResult(string.Format(Catalog.GetString("Inactive Values:{0}"), Environment.NewLine),
                                                               VerificationMessage,
                                                               TResultSeverity.Resv_Noncritical));

                StringBuilder errorMessages = new StringBuilder();

                errorMessages.AppendFormat(Catalog.GetString("{0} inactive value(s) found in GL Batch {1}. Do you still want to post?{2}"),
                                           ANumInactiveValues,
                                           ABatchNumber,
                                           Environment.NewLine);

                foreach (TVerificationResult message in VerificationResult)
                {
                    errorMessages.AppendFormat("{0}{1}",
                                               Environment.NewLine,
                                               message.ResultText);
                }

                TFrmExtendedMessageBox extendedMessageBox = new TFrmExtendedMessageBox(FMyForm);

                RetVal = (extendedMessageBox.ShowDialog(errorMessages.ToString(),
                                                        Catalog.GetString("Post Batch"), string.Empty,
                                                        TFrmExtendedMessageBox.TButtons.embbYesNo,
                                                        TFrmExtendedMessageBox.TIcon.embiQuestion) == TFrmExtendedMessageBox.TResult.embrYes);
            }
            else
            {
                RetVal = true;
            }

            return(RetVal);
        }
コード例 #6
0
        /// <summary>
        /// Looks for gifts where the recipient is an ExWorker and asks the user if they want to continue.
        /// (Make sure GetDataFromControls is called before this method so that AMainDS is up-to-date.)
        /// </summary>
        /// <param name="AAction">Why this method is being called</param>
        /// <param name="AMainDS"></param>
        /// <param name="APetraUtilsObject"></param>
        /// <param name="APostingGiftDetails">Only used when being called in order to carry out a batch posting</param>
        /// <returns>Returns true if saving/posting can continue</returns>
        public static bool CanContinueWithAnyExWorkers(GiftBatchAction AAction,
                                                       GiftBatchTDS AMainDS,
                                                       TFrmPetraEditUtils APetraUtilsObject,
                                                       DataTable APostingGiftDetails = null)
        {
            DataTable ExWorkers     = null;
            string    Msg           = string.Empty;
            int       BatchNumber   = -1;
            int       ExWorkerGifts = 0;

            string ExWorkerSpecialType = TSystemDefaults.GetStringDefault(SharedConstants.SYSDEFAULT_EXWORKERSPECIALTYPE, "EX-WORKER");

            // first check for Ex-Workers in the batch that is being posted/submitted (if a batch is being posted/submitted)
            if ((APostingGiftDetails != null) && (APostingGiftDetails.Rows.Count > 0))
            {
                ExWorkers      = TRemote.MFinance.Gift.WebConnectors.FindGiftRecipientExWorker(APostingGiftDetails, BatchNumber);
                ExWorkerGifts += ExWorkers.Rows.Count;

                Msg = GetExWorkersString(AAction, ExWorkerSpecialType, ExWorkers);

                if (ExWorkers.Rows.Count > 0)
                {
                    BatchNumber = (int)APostingGiftDetails.Rows[0][GiftBatchTDSAGiftDetailTable.GetBatchNumberDBName()];
                }
            }

            // check for Ex-Workers in all added and modified data
            if (APetraUtilsObject.HasChanges)
            {
                DataTable Changes = new DataTable();

                if (AMainDS.AGiftDetail.GetChangesTyped() != null)
                {
                    Changes.Merge(AMainDS.AGiftDetail.GetChangesTyped());
                }
                else if (AMainDS.ARecurringGiftDetail.GetChangesTyped() != null)
                {
                    Changes.Merge(AMainDS.ARecurringGiftDetail.GetChangesTyped());
                }

                if ((Changes != null) && (Changes.Rows.Count > 0))
                {
                    ExWorkers      = TRemote.MFinance.Gift.WebConnectors.FindGiftRecipientExWorker(Changes, BatchNumber);
                    ExWorkerGifts += ExWorkers.Rows.Count;

                    Msg += GetExWorkersString(null, ExWorkerSpecialType, ExWorkers);
                }
            }

            // alert the user to any recipients who are Ex-Workers
            if (Msg != string.Empty)
            {
                if (AAction == GiftBatchAction.SAVING)
                {
                    Msg += Environment.NewLine + Environment.NewLine;
                    Msg += Catalog.GetString("Do you want to continue with saving anyway?");
                }
                else
                {
                    Msg += Environment.NewLine + Environment.NewLine;
                    Msg += Catalog.GetString("(any changes will also need to be saved before ");

                    if (AAction == GiftBatchAction.NEWBATCH)
                    {
                        Msg += Catalog.GetString("a new batch can be created");
                    }
                    else //POSTING, CANCELLING, SUBMITTING, DELETING
                    {
                        Msg += Catalog.GetString("this batch continues with " + AAction.ToString().ToLower());
                    }

                    Msg += ")" + Environment.NewLine + Environment.NewLine;
                    Msg += Catalog.GetString("Do you want to continue?");
                }

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

                if (extendedMessageBox.ShowDialog(Msg,
                                                  Catalog.GetString("Ex-Workers Found"), string.Empty,
                                                  TFrmExtendedMessageBox.TButtons.embbYesNo,
                                                  TFrmExtendedMessageBox.TIcon.embiWarning)
                    == TFrmExtendedMessageBox.TResult.embrNo)
                {
                    return(false);
                }
            }

            return(true);
        }
コード例 #7
0
        /// <summary>
        /// Delete subscription for Partners in selected Extract
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void DeleteSubscription(System.Object sender, EventArgs e)
        {
            String  PublicationCode;
            Boolean DeleteAllSubscriptions = false;
            Boolean DeleteThisSubscription = false;
            Boolean AllDeletionsSucceeded  = true;
            int     CountDeleted           = 0;

            if (!WarnIfNotSingleSelection(Catalog.GetString("Delete Subscription")) &&
                (GetSelectedDetailRow() != null))
            {
                TFrmUpdateExtractDeleteSubscriptionDialog dialog = new TFrmUpdateExtractDeleteSubscriptionDialog(this.FindForm());
                dialog.SetExtractName(GetSelectedDetailRow().ExtractName);

                if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    dialog.GetReturnedParameters(out PublicationCode);

                    ExtractTDSMExtractTable ExtractTable;

                    // retrieve all partners of extract from server
                    ExtractTable = TRemote.MPartner.Partner.WebConnectors.GetExtractRowsWithPartnerData(GetSelectedDetailRow().ExtractId);

                    foreach (ExtractTDSMExtractRow Row in ExtractTable.Rows)
                    {
                        if (TRemote.MPartner.Partner.WebConnectors.SubscriptionExists
                                (Row.PartnerKey, PublicationCode))
                        {
                            DeleteThisSubscription = false;

                            if (!DeleteAllSubscriptions)
                            {
                                TFrmExtendedMessageBox.TResult Result;
                                TFrmExtendedMessageBox         ExtMsgBox = new TFrmExtendedMessageBox(this.FindForm());
                                Result = ExtMsgBox.ShowDialog(Catalog.GetString("You have chosen to delete the subscription of ") +
                                                              PublicationCode + "\r\n" +
                                                              Catalog.GetString("for Partner ") +
                                                              Row.PartnerShortName + " (" + Row.PartnerKey + ")\r\n\r\n" +
                                                              Catalog.GetString("Do you really want to delete it?"),
                                                              Catalog.GetString("Delete Subscription"),
                                                              "",
                                                              TFrmExtendedMessageBox.TButtons.embbYesYesToAllNoCancel,
                                                              TFrmExtendedMessageBox.TIcon.embiQuestion);

                                switch (Result)
                                {
                                case TFrmExtendedMessageBox.TResult.embrYesToAll:
                                    DeleteAllSubscriptions = true;
                                    break;

                                case TFrmExtendedMessageBox.TResult.embrYes:
                                    DeleteThisSubscription = true;
                                    break;

                                case TFrmExtendedMessageBox.TResult.embrNo:
                                    DeleteThisSubscription = false;
                                    break;

                                case TFrmExtendedMessageBox.TResult.embrCancel:
                                    MessageBox.Show(Catalog.GetString("Further deletion of Subscriptions cancelled"),
                                                    Catalog.GetString("Delete Subscription"),
                                                    MessageBoxButtons.OK,
                                                    MessageBoxIcon.Information);
                                    return;

                                default:
                                    break;
                                }
                            }

                            if (DeleteAllSubscriptions ||
                                DeleteThisSubscription)
                            {
                                if (!TRemote.MPartner.Partner.WebConnectors.DeleteSubscription
                                        (GetSelectedDetailRow().ExtractId, Row.PartnerKey, PublicationCode))
                                {
                                    MessageBox.Show(Catalog.GetString("Error while deleting Subscription ") +
                                                    PublicationCode + Catalog.GetString(" for Partner ") +
                                                    Row.PartnerShortName + " (" + Row.PartnerKey + ")",
                                                    Catalog.GetString("Delete Subscription"),
                                                    MessageBoxButtons.OK,
                                                    MessageBoxIcon.Error);
                                    AllDeletionsSucceeded = false;
                                }
                                else
                                {
                                    CountDeleted++;
                                }
                            }
                        }
                    }

                    if (AllDeletionsSucceeded)
                    {
                        MessageBox.Show(String.Format(Catalog.GetString("Subscription {0} successfully deleted for {1} Partners in Extract {2}"),
                                                      PublicationCode, CountDeleted, GetSelectedDetailRow().ExtractName),
                                        Catalog.GetString("Delete Subscription"),
                                        MessageBoxButtons.OK,
                                        MessageBoxIcon.Information);
                    }
                    else
                    {
                        MessageBox.Show(String.Format(Catalog.GetString(
                                                          "Error while deleting Subscription {0} for some Partners in Extract {1}. Subscription deleted for {2} Partners."),
                                                      PublicationCode, GetSelectedDetailRow().ExtractName, CountDeleted),
                                        Catalog.GetString("Delete Subscription"),
                                        MessageBoxButtons.OK,
                                        MessageBoxIcon.Error);
                    }
                }
            }
        }
コード例 #8
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;
            }
        }
コード例 #9
0
        private static bool CheckForInactiveKeyMinistries(GiftBatchTDS AChangesDS, Int32 ALedgerNumber, Int32 ABatchNumber)
        {
            bool RetVal = false;

            //int CurrentBatchNumber = 0;

            //Check for inactive KeyMinistries
            DataTable GiftsWithInactiveKeyMinistries;
            bool      ModifiedDetails = false;

            if (TRemote.MFinance.Gift.WebConnectors.InactiveKeyMinistriesFoundInBatch(ALedgerNumber, ABatchNumber,
                                                                                      out GiftsWithInactiveKeyMinistries, false))
            {
                int numInactiveValues = GiftsWithInactiveKeyMinistries.Rows.Count;

                string messageNonModifiedBatch =
                    String.Format(Catalog.GetString("Gift Batch {0} contains {1} inactive key ministries. Please fix before saving!{2}{2}"),
                                  ABatchNumber,
                                  numInactiveValues,
                                  Environment.NewLine);
                string messageModifiedBatch =
                    String.Format(Catalog.GetString(
                                      "Reversal/Adjustment Gift Batch {0} contains {1} inactive key ministries. Do you still want to save?{2}{2}"),
                                  ABatchNumber,
                                  numInactiveValues,
                                  Environment.NewLine);

                string listOfOffendingRows = string.Empty;

                listOfOffendingRows += "Gift      Detail   Recipient          KeyMinistry" + Environment.NewLine;
                listOfOffendingRows += "-------------------------------------------------------------------------------";

                foreach (DataRow dr in GiftsWithInactiveKeyMinistries.Rows)
                {
                    listOfOffendingRows += String.Format("{0}{1:0000}    {2:00}        {3:00000000000}    {4}",
                                                         Environment.NewLine,
                                                         dr[0],
                                                         dr[1],
                                                         dr[2],
                                                         dr[3]);

                    bool isModified = Convert.ToBoolean(dr[4]);

                    if (isModified)
                    {
                        ModifiedDetails = true;
                    }
                }

                //TODO: work on how to relate to form
                TFrmExtendedMessageBox extendedMessageBox = null;  // new TFrmExtendedMessageBox(FMyForm);

                if (ModifiedDetails)
                {
                    if (extendedMessageBox.ShowDialog((messageModifiedBatch + listOfOffendingRows),
                                                      Catalog.GetString("Post Batch"), string.Empty,
                                                      TFrmExtendedMessageBox.TButtons.embbYesNo,
                                                      TFrmExtendedMessageBox.TIcon.embiWarning) == TFrmExtendedMessageBox.TResult.embrYes)
                    {
                        //TODO: Check this
                        //APostingAlreadyConfirmed = true;
                    }
                }
                else
                {
                    extendedMessageBox.ShowDialog((messageNonModifiedBatch + listOfOffendingRows),
                                                  Catalog.GetString("Post Batch Error"), string.Empty,
                                                  TFrmExtendedMessageBox.TButtons.embbOK,
                                                  TFrmExtendedMessageBox.TIcon.embiWarning);
                }
            }

            return(RetVal);
        }
コード例 #10
0
        private void Import(System.Object sender, EventArgs e)
        {
            if (ValidateAllData(true, TErrorProcessingMode.Epm_All))
            {
                TVerificationResultCollection results = FPetraUtilsObject.VerificationResultCollection;

                int nRowsImported = TImportExchangeRates.ImportCurrencyExRates(FMainDS.ACorporateExchangeRate, "Corporate", results);

                if (results.Count > 0)
                {
                    string formatter;

                    if (nRowsImported == 0)
                    {
                        formatter = MCommonResourcestrings.StrExchRateImportNoRows;
                    }
                    else if (nRowsImported == 1)
                    {
                        formatter = MCommonResourcestrings.StrExchRateImportOneRow;
                    }
                    else
                    {
                        formatter = MCommonResourcestrings.StrExchRateImportMultiRow;
                    }

                    formatter += "{0}{0}{1}{0}{0}{3}{0}{0}{4}";

                    TFrmExtendedMessageBox messageBox = new TFrmExtendedMessageBox(this);
                    messageBox.ShowDialog(String.Format(
                                              formatter,
                                              Environment.NewLine,
                                              results[0].ResultText,
                                              nRowsImported,
                                              results[0].ResultSeverity ==
                                              TResultSeverity.Resv_Critical ? MCommonResourcestrings.StrExchRateImportTryAgain : String.Empty,
                                              results[0].ResultCode),
                                          MCommonResourcestrings.StrExchRateImportTitle, String.Empty, TFrmExtendedMessageBox.TButtons.embbOK,
                                          results[0].ResultSeverity ==
                                          TResultSeverity.Resv_Critical ? TFrmExtendedMessageBox.TIcon.embiError : TFrmExtendedMessageBox.TIcon.embiInformation);

                    results.Clear();
                }
                else if (nRowsImported == 0)
                {
                    MessageBox.Show(MCommonResourcestrings.StrExchRateImportNoRows, MCommonResourcestrings.StrExchRateImportTitle);
                }
                else if (nRowsImported == 1)
                {
                    MessageBox.Show(MCommonResourcestrings.StrExchRateImportOneRowSuccess, MCommonResourcestrings.StrExchRateImportTitle);
                }
                else
                {
                    MessageBox.Show(String.Format(MCommonResourcestrings.StrExchRateImportMultiRowSuccess,
                                                  nRowsImported), MCommonResourcestrings.StrExchRateImportTitle);
                }

                if (nRowsImported > 0)
                {
                    FPetraUtilsObject.SetChangedFlag();
                }
            }
        }
コード例 #11
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();
            }
        }
コード例 #12
0
        /// <summary>
        /// Main method to post a specified batch
        /// </summary>
        /// <param name="ACurrentBatchRow">The batch row to post</param>
        /// <param name="ARefreshGUIAfterPosting">Will be set to true if the GUI should be updated.  Can be true even if Posting fails
        /// <param name="AWarnOfInactiveValues">True means user is warned if inactive values exist</param>
        /// <param name="ADonorZeroIsValid"></param>
        /// <param name="ARecipientZeroIsValid"></param>
        /// <param name="APostingAlreadyConfirmed">True means ask user if they want to post</param>
        /// if the server gets a SerializableTransactionException</param>
        /// <returns>True if the batch was successfully posted</returns>
        public bool PostBatch(AGiftBatchRow ACurrentBatchRow,
                              out bool ARefreshGUIAfterPosting,
                              bool AWarnOfInactiveValues    = true,
                              bool ADonorZeroIsValid        = false,
                              bool ARecipientZeroIsValid    = false,
                              bool APostingAlreadyConfirmed = false)
        {
            ARefreshGUIAfterPosting = false;

            if ((ACurrentBatchRow == null) || (ACurrentBatchRow.BatchStatus != MFinanceConstants.BATCH_UNPOSTED))
            {
                return(false);
            }

            FSelectedBatchNumber = ACurrentBatchRow.BatchNumber;

            //Make sure that all control data is in dataset
            FMyForm.GetLatestControlData();

            //Copy all batch data to new table
            GiftBatchTDSAGiftDetailTable BatchGiftDetails = new GiftBatchTDSAGiftDetailTable();
            DataView BatchGiftDetailsDV = new DataView(FMainDS.AGiftDetail);

            BatchGiftDetailsDV.RowFilter = string.Format("{0}={1}",
                                                         AGiftDetailTable.GetBatchNumberDBName(),
                                                         FSelectedBatchNumber);

            BatchGiftDetailsDV.Sort = string.Format("{0} ASC, {1} ASC, {2} ASC",
                                                    AGiftDetailTable.GetBatchNumberDBName(),
                                                    AGiftDetailTable.GetGiftTransactionNumberDBName(),
                                                    AGiftDetailTable.GetDetailNumberDBName());

            foreach (DataRowView drv in BatchGiftDetailsDV)
            {
                GiftBatchTDSAGiftDetailRow gBRow = (GiftBatchTDSAGiftDetailRow)drv.Row;
                BatchGiftDetails.Rows.Add((object[])gBRow.ItemArray.Clone());
            }

            //Save and check for inactive values and ex-workers and anonymous gifts
            if (FPetraUtilsObject.HasChanges)
            {
                //Keep this conditional check separate from the one above so that it only gets called
                // when necessary and doesn't result in the executon of the same method
                if (!FMyForm.SaveChangesForPosting(BatchGiftDetails))
                {
                    return(false);
                }
                else
                {
                    APostingAlreadyConfirmed = true;
                }
            }
            else
            {
                //This has to be called here because if there are no changes then the DataSavingValidating
                // method which calls the method below, will not run.
                if (!FMyForm.GetBatchControl().AllowInactiveFieldValues(ref APostingAlreadyConfirmed,
                                                                        TExtraGiftBatchChecks.GiftBatchAction.POSTING) ||
                    FMyForm.GiftHasExWorkerOrAnon(BatchGiftDetails)
                    )
                {
                    return(false);
                }
            }

            //Check hash total validity
            if ((ACurrentBatchRow.HashTotal != 0) &&
                (ACurrentBatchRow.BatchTotal != ACurrentBatchRow.HashTotal))
            {
                MessageBox.Show(String.Format(Catalog.GetString(
                                                  "The gift batch total ({0}) for batch {1} does not equal the hash total ({2})!"),
                                              StringHelper.FormatUsingCurrencyCode(ACurrentBatchRow.BatchTotal, ACurrentBatchRow.CurrencyCode),
                                              ACurrentBatchRow.BatchNumber,
                                              StringHelper.FormatUsingCurrencyCode(ACurrentBatchRow.HashTotal, ACurrentBatchRow.CurrencyCode)),
                                "Post Gift Batch");

                return(false);
            }

            //Check for missing international exchange rate
            bool IsTransactionInIntlCurrency = false;

            FMyForm.WarnAboutMissingIntlExchangeRate = true;

            if (FMyForm.InternationalCurrencyExchangeRate(ACurrentBatchRow, out IsTransactionInIntlCurrency, true) == 0)
            {
                return(false);
            }

            //Check for zero Donors or Recipients
            if (!ADonorZeroIsValid)
            {
                DataView batchGiftDV = new DataView(FMainDS.AGift);

                batchGiftDV.RowFilter = string.Format("{0}={1} And {2}=0",
                                                      AGiftTable.GetBatchNumberDBName(),
                                                      FSelectedBatchNumber,
                                                      AGiftTable.GetDonorKeyDBName());

                int numDonorZeros = batchGiftDV.Count;

                if (numDonorZeros > 0)
                {
                    string messageListOfOffendingGifts =
                        String.Format(Catalog.GetString(
                                          "Gift Batch {0} contains {1} gift detail(s) with Donor 0000000. Please fix before posting!{2}{2}"),
                                      FSelectedBatchNumber,
                                      numDonorZeros,
                                      Environment.NewLine);

                    string listOfOffendingRows = string.Empty;

                    listOfOffendingRows += "Gift" + Environment.NewLine;
                    listOfOffendingRows += "------------";

                    foreach (DataRowView drv in batchGiftDV)
                    {
                        AGiftRow giftRow = (AGiftRow)drv.Row;

                        listOfOffendingRows += String.Format("{0}{1:0000}",
                                                             Environment.NewLine,
                                                             giftRow.GiftTransactionNumber);
                    }

                    TFrmExtendedMessageBox extendedMessageBox = new TFrmExtendedMessageBox(FMyForm);

                    extendedMessageBox.ShowDialog((messageListOfOffendingGifts + listOfOffendingRows),
                                                  Catalog.GetString("Post Batch Error"), string.Empty,
                                                  TFrmExtendedMessageBox.TButtons.embbOK,
                                                  TFrmExtendedMessageBox.TIcon.embiWarning);

                    return(false);
                }
            }

            if (!ARecipientZeroIsValid)
            {
                DataView batchGiftDetailsDV = new DataView(FMainDS.AGiftDetail);

                batchGiftDetailsDV.RowFilter = string.Format("{0}={1} And {2}=0",
                                                             AGiftDetailTable.GetBatchNumberDBName(),
                                                             FSelectedBatchNumber,
                                                             AGiftDetailTable.GetRecipientKeyDBName());

                int numRecipientZeros = batchGiftDetailsDV.Count;

                if (numRecipientZeros > 0)
                {
                    string messageListOfOffendingGifts =
                        String.Format(Catalog.GetString(
                                          "Gift Batch {0} contains {1} gift detail(s) with Recipient 0000000. Please fix before posting!{2}{2}"),
                                      FSelectedBatchNumber,
                                      numRecipientZeros,
                                      Environment.NewLine);

                    string listOfOffendingRows = string.Empty;

                    listOfOffendingRows += "Gift   Detail" + Environment.NewLine;
                    listOfOffendingRows += "-------------------";

                    foreach (DataRowView drv in batchGiftDetailsDV)
                    {
                        AGiftDetailRow giftDetailRow = (AGiftDetailRow)drv.Row;

                        listOfOffendingRows += String.Format("{0}{1:0000}  {2:00}",
                                                             Environment.NewLine,
                                                             giftDetailRow.GiftTransactionNumber,
                                                             giftDetailRow.DetailNumber);
                    }

                    TFrmExtendedMessageBox extendedMessageBox = new TFrmExtendedMessageBox(FMyForm);

                    extendedMessageBox.ShowDialog((messageListOfOffendingGifts + listOfOffendingRows),
                                                  Catalog.GetString("Post Batch Error"), string.Empty,
                                                  TFrmExtendedMessageBox.TButtons.embbOK,
                                                  TFrmExtendedMessageBox.TIcon.embiWarning);

                    return(false);
                }
            }

            //Check for inactive KeyMinistries
            DataTable GiftsWithInactiveKeyMinistries;
            bool      ModifiedDetails = false;

            if (AWarnOfInactiveValues && TRemote.MFinance.Gift.WebConnectors.InactiveKeyMinistriesFoundInBatch(FLedgerNumber, FSelectedBatchNumber,
                                                                                                               out GiftsWithInactiveKeyMinistries, false))
            {
                int numInactiveValues = GiftsWithInactiveKeyMinistries.Rows.Count;

                string messageNonModifiedBatch =
                    String.Format(Catalog.GetString("Gift Batch {0} contains {1} inactive key ministries. Please fix before posting!{2}{2}"),
                                  FSelectedBatchNumber,
                                  numInactiveValues,
                                  Environment.NewLine);
                string messageModifiedBatch =
                    String.Format(Catalog.GetString(
                                      "Reversal/Adjustment Gift Batch {0} contains {1} inactive key ministries. Do you still want to post?{2}{2}"),
                                  FSelectedBatchNumber,
                                  numInactiveValues,
                                  Environment.NewLine);

                string listOfOffendingRows = string.Empty;

                listOfOffendingRows += "Gift      Detail   Recipient          KeyMinistry" + Environment.NewLine;
                listOfOffendingRows += "-------------------------------------------------------------------------------";

                foreach (DataRow dr in GiftsWithInactiveKeyMinistries.Rows)
                {
                    listOfOffendingRows += String.Format("{0}{1:0000}    {2:00}        {3:00000000000}    {4}",
                                                         Environment.NewLine,
                                                         dr[0],
                                                         dr[1],
                                                         dr[2],
                                                         dr[3]);

                    bool isModified = Convert.ToBoolean(dr[4]);

                    if (isModified)
                    {
                        ModifiedDetails = true;
                    }
                }

                TFrmExtendedMessageBox extendedMessageBox = new TFrmExtendedMessageBox(FMyForm);

                if (ModifiedDetails)
                {
                    if (extendedMessageBox.ShowDialog((messageModifiedBatch + listOfOffendingRows),
                                                      Catalog.GetString("Post Batch"), string.Empty,
                                                      TFrmExtendedMessageBox.TButtons.embbYesNo,
                                                      TFrmExtendedMessageBox.TIcon.embiWarning) == TFrmExtendedMessageBox.TResult.embrYes)
                    {
                        APostingAlreadyConfirmed = true;
                    }
                    else
                    {
                        return(false);
                    }
                }
                else
                {
                    extendedMessageBox.ShowDialog((messageNonModifiedBatch + listOfOffendingRows),
                                                  Catalog.GetString("Post Batch Error"), string.Empty,
                                                  TFrmExtendedMessageBox.TButtons.embbOK,
                                                  TFrmExtendedMessageBox.TIcon.embiWarning);

                    return(false);
                }
            }

            // ask if the user really wants to post the batch
            if (!APostingAlreadyConfirmed &&
                (MessageBox.Show(String.Format(Catalog.GetString("Do you really want to post gift batch {0}?"), FSelectedBatchNumber),
                                 Catalog.GetString("Confirm posting of Gift Batch"),
                                 MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes))
            {
                return(false);
            }

            TVerificationResultCollection Verifications = new TVerificationResultCollection();

            try
            {
                FPostingInProgress = true;

                Thread postingThread = new Thread(() => PostGiftBatch(out Verifications));
                postingThread.SetApartmentState(ApartmentState.STA);
                using (TProgressDialog dialog = new TProgressDialog(postingThread))
                {
                    dialog.ShowDialog();
                }

                if (TVerificationHelper.ResultsContainErrorCode(Verifications, PetraErrorCodes.ERR_DB_SERIALIZATION_EXCEPTION))
                {
                    TConcurrentServerTransactions.ShowTransactionSerializationExceptionDialog();
                    ARefreshGUIAfterPosting = true;
                    return(false);
                }
                else if (!TVerificationHelper.IsNullOrOnlyNonCritical(Verifications))
                {
                    TFrmExtendedMessageBox extendedMessageBox = new TFrmExtendedMessageBox(FMyForm);

                    StringBuilder errorMessages = new StringBuilder();
                    int           counter       = 0;

                    errorMessages.AppendLine(Catalog.GetString("________________________Gift Posting Errors________________________"));
                    errorMessages.AppendLine();

                    foreach (TVerificationResult verif in Verifications)
                    {
                        counter++;
                        errorMessages.AppendLine(counter.ToString("000") + " - " + verif.ResultText);
                        errorMessages.AppendLine();
                    }

                    extendedMessageBox.ShowDialog(errorMessages.ToString(),
                                                  Catalog.GetString("Post Batch Error"),
                                                  string.Empty,
                                                  TFrmExtendedMessageBox.TButtons.embbOK,
                                                  TFrmExtendedMessageBox.TIcon.embiWarning);
                }
                else
                {
                    MessageBox.Show(Catalog.GetString("The batch has been posted successfully!"));
                    ARefreshGUIAfterPosting = true;
                }
            }
            catch (Exception ex)
            {
                TLogging.LogException(ex, Utilities.GetMethodSignature());
                throw;
            }
            finally
            {
                FPostingInProgress = false;
            }

            return(true);
        }
コード例 #13
0
        /// <summary>
        /// Verify and if necessary update partner data in an extract
        /// </summary>
        public static void VerifyAndUpdateExtract(System.Windows.Forms.Form AForm,
                                                  ref ExtractTDSMExtractTable AExtractTable,
                                                  out bool AChangesMade)
        {
            bool                   AddressExists;
            bool                   AddressNeitherCurrentNorMailing;
            bool                   ReplaceAddressYesToAll = false;
            bool                   ReplaceAddressNoToAll  = false;
            string                 CountryName;
            PLocationTable         LocationTable;
            PLocationRow           LocationRow;
            TFrmExtendedMessageBox MsgBox;

            TFrmExtendedMessageBox.TResult MsgBoxResult;
            bool DontShowPartnerRemovePartnerKeyNonExistent = false;
            bool DontShowReplaceAddress         = false;
            bool DontShowPartnerRemoveNoAddress = false;


            // initialize output parameter
            AChangesMade = false;

            // build a collection of objects to be deleted before actually deleting them (as otherwise indexes may not be valid any longer)
            List <ExtractTDSMExtractRow> ReplaceAddressList = new List <ExtractTDSMExtractRow>();

            // collection of partners that need their address updated
            List <ExtractTDSMExtractRow> RowsToDelete = new List <ExtractTDSMExtractRow>();

            // collection of partners who's addresses no longer exist
            List <ExtractTDSMExtractRow> AddressNotExistsList = new List <ExtractTDSMExtractRow>();

            // collection of partners who's addresses are not current or mailing
            List <ExtractTDSMExtractRow> AddressNeitherCurrentNorMailingList = new List <ExtractTDSMExtractRow>();

            // prepare mouse cursor so user knows something is happening
            AForm.Cursor = Cursors.WaitCursor;

            // look at every single extract row
            foreach (ExtractTDSMExtractRow Row in AExtractTable.Rows)
            {
                // check if the partner record still exists, otherwise remove from extract
                if (!TRemote.MPartner.Partner.ServerLookups.WebConnectors.VerifyPartner(Row.PartnerKey))
                {
                    RowsToDelete.Add(Row);
                }
                else
                {
                    AddressExists = TRemote.MPartner.Partner.ServerLookups.WebConnectors.VerifyPartnerAtLocation
                                        (Row.PartnerKey, new TLocationPK(Row.SiteKey, Row.LocationKey), out AddressNeitherCurrentNorMailing);

                    if (!AddressExists) // if address no longer exists
                    {
                        AddressNotExistsList.Add(Row);
                    }
                    else if (AddressNeitherCurrentNorMailing) // address still exists but is not longer current or mailing
                    {
                        AddressNeitherCurrentNorMailingList.Add(Row);
                    }
                }
            }

            int i = 1;

            // for each partner that needs removed from the extract
            foreach (ExtractTDSMExtractRow Row in RowsToDelete)
            {
                MsgBox = new TFrmExtendedMessageBox(AForm);

                if (!DontShowPartnerRemovePartnerKeyNonExistent) // if user has not requested to not see these messages
                {
                    // warn the user what is happening
                    if (RowsToDelete.Count != i) // multiple left to delete
                    {
                        MsgBox.ShowDialog(String.Format(Catalog.GetString("The following partner record does not exist any longer and " +
                                                                          "will therefore be removed from this extract: \n\r\n\r" +
                                                                          "{0} ({1})"), Row.PartnerShortName, Row.PartnerKey),
                                          Catalog.GetString("Verify and Update Extract"),
                                          String.Format(Catalog.GetString("Don't show this message again ({0} more)"), RowsToDelete.Count - i),
                                          TFrmExtendedMessageBox.TButtons.embbOK,
                                          TFrmExtendedMessageBox.TIcon.embiInformation);
                    }
                    else // only one left to delete
                    {
                        MsgBox.ShowDialog(String.Format(Catalog.GetString("The following partner record does not exist any longer and " +
                                                                          "will therefore be removed from this extract: \n\r\n\r" +
                                                                          "{0} ({1})"), Row.PartnerShortName, Row.PartnerKey),
                                          Catalog.GetString("Verify and Update Extract"),
                                          "",
                                          TFrmExtendedMessageBox.TButtons.embbOK,
                                          TFrmExtendedMessageBox.TIcon.embiInformation);
                    }

                    MsgBoxResult = MsgBox.GetResult(out DontShowPartnerRemovePartnerKeyNonExistent);
                }

                AChangesMade = true;
                Row.Delete();  // now delete the actual row

                i++;
            }

            i = 1;

            // for each partner that has an address that no longer exists
            foreach (ExtractTDSMExtractRow Row in AddressNotExistsList)
            {
                MsgBox = new TFrmExtendedMessageBox(AForm);

                if (!DontShowReplaceAddress) // if user has not requested to not see these messages
                {
                    // warn the user what is happening
                    if (AddressNotExistsList.Count != i) // multiple rows left
                    {
                        MsgBox.ShowDialog(String.Format(Catalog.GetString("Address for {0} ({1}) in this extract no longer exists and " +
                                                                          "will therefore be replaced with a current address."),
                                                        Row.PartnerShortName, Row.PartnerKey),
                                          Catalog.GetString("Verify and Update Extract"),
                                          String.Format(Catalog.GetString("Don't show this message again ({0} more)"), AddressNotExistsList.Count - i),
                                          TFrmExtendedMessageBox.TButtons.embbOK,
                                          TFrmExtendedMessageBox.TIcon.embiInformation);
                    }
                    else // only one row left
                    {
                        MsgBox.ShowDialog(String.Format(Catalog.GetString("Address for {0} ({1}) in this extract no longer exists and " +
                                                                          "will therefore be replaced with a current address."),
                                                        Row.PartnerShortName, Row.PartnerKey),
                                          Catalog.GetString("Verify and Update Extract"),
                                          "",
                                          TFrmExtendedMessageBox.TButtons.embbOK,
                                          TFrmExtendedMessageBox.TIcon.embiInformation);
                    }

                    MsgBoxResult = MsgBox.GetResult(out DontShowReplaceAddress);
                }

                ReplaceAddressList.Add(Row);

                i++;
            }

            i = 1;

            // for each partner that has an address that is no longer current or mailing
            foreach (ExtractTDSMExtractRow Row in AddressNeitherCurrentNorMailingList)
            {
                MsgBox = new TFrmExtendedMessageBox(AForm);

                if (!ReplaceAddressYesToAll && !ReplaceAddressNoToAll) // if user has not requested to not see these messages
                {
                    // ask the user if the address should be updates
                    if (AddressNeitherCurrentNorMailingList.Count != i) // multiple rows left
                    {
                        MsgBoxResult =
                            MsgBox.ShowDialog(String.Format(Catalog.GetString("Address for {0} ({1}) in this extract is not current. " +
                                                                              "Do you want to update it with a current address if there is one?{2}{2}" +
                                                                              "({3} more like this.)"),
                                                            Row.PartnerShortName, Row.PartnerKey, Environment.NewLine, AddressNeitherCurrentNorMailingList.Count - i),
                                              Catalog.GetString("Verify and Update Extract"),
                                              "",
                                              TFrmExtendedMessageBox.TButtons.embbYesYesToAllNoNoToAll,
                                              TFrmExtendedMessageBox.TIcon.embiQuestion);
                    }
                    else // only one row left
                    {
                        MsgBoxResult =
                            MsgBox.ShowDialog(String.Format(Catalog.GetString("Address for {0} ({1}) in this extract is not current. " +
                                                                              "Do you want to update it with a current address if there is one?"),
                                                            Row.PartnerShortName, Row.PartnerKey),
                                              Catalog.GetString("Verify and Update Extract"),
                                              "",
                                              TFrmExtendedMessageBox.TButtons.embbYesNo,
                                              TFrmExtendedMessageBox.TIcon.embiQuestion);
                    }

                    if (MsgBoxResult == TFrmExtendedMessageBox.TResult.embrYesToAll)
                    {
                        ReplaceAddressYesToAll = true;
                    }
                    else if (MsgBoxResult == TFrmExtendedMessageBox.TResult.embrYes)
                    {
                        ReplaceAddressList.Add(Row);
                    }
                    else if (MsgBoxResult == TFrmExtendedMessageBox.TResult.embrNoToAll)
                    {
                        ReplaceAddressNoToAll = true;
                    }
                }

                // need to set the flag each time we come through here.
                if (ReplaceAddressYesToAll)
                {
                    ReplaceAddressList.Add(Row);
                }

                i++;
            }

            // for each partner that needs their address updated
            foreach (ExtractTDSMExtractRow Row in ReplaceAddressList)
            {
                MsgBox = new TFrmExtendedMessageBox(AForm);

                if (!TRemote.MPartner.Mailing.WebConnectors.GetBestAddress(Row.PartnerKey,
                                                                           out LocationTable, out CountryName))
                {
                    // in this case there is no address at all for this partner (should not really happen)
                    if (!DontShowPartnerRemoveNoAddress)
                    {
                        MsgBox.ShowDialog(String.Format(Catalog.GetString("No address could be found for {0} ({1}). " +
                                                                          "Therefore the partner record will be removed from this extract"),
                                                        Row.PartnerShortName, Row.PartnerKey),
                                          Catalog.GetString("Verify and Update Extract"),
                                          Catalog.GetString("Don't show this message again"),
                                          TFrmExtendedMessageBox.TButtons.embbOK,
                                          TFrmExtendedMessageBox.TIcon.embiInformation);
                        MsgBoxResult = MsgBox.GetResult(out DontShowPartnerRemoveNoAddress);
                    }

                    RowsToDelete.Add(Row);
                }
                else
                {
                    if (LocationTable.Rows.Count > 0)
                    {
                        LocationRow = (PLocationRow)LocationTable.Rows[0];

                        /* it could be that GetBestAddress still returns a non-current address if
                         * there is no better one */
                        if ((Row.SiteKey != LocationRow.SiteKey) ||
                            (Row.LocationKey != LocationRow.LocationKey))
                        {
                            AChangesMade = true;

                            Row.SiteKey     = LocationRow.SiteKey;
                            Row.LocationKey = LocationRow.LocationKey;
                        }
                    }
                }
            }

            // prepare mouse cursor so user knows something is happening
            AForm.Cursor = Cursors.Default;
        }
コード例 #14
0
        private void ShowMessages(TVerificationResultCollection AMessages,
                                  int ABudgetsImported,
                                  int ABudgetsAdded,
                                  int ABudgetsUpdated,
                                  int ABudgetsFailed)
        {
            StringBuilder ErrorMessages = new StringBuilder();

            int BudgetsSuccessful = ABudgetsImported - ABudgetsFailed;
            int BudgetsDuplicate  = BudgetsSuccessful - (ABudgetsAdded + ABudgetsUpdated);

            if (ABudgetsImported != 0)
            {
                // if there were budgets to import
                if (ABudgetsImported > 0)
                {
                    ErrorMessages.AppendFormat
                        (Catalog.GetPluralString("{0} budget row was found in the file ", "{0} budget rows were found in the file ",
                                                 ABudgetsImported, true),
                        ABudgetsImported);

                    ErrorMessages.AppendFormat
                        (Catalog.GetPluralString("and {0} was successfully imported!", "and {0} were successfully imported!",
                                                 BudgetsSuccessful, true),
                        (BudgetsSuccessful));

                    if (ABudgetsUpdated > 0)
                    {
                        ErrorMessages.AppendFormat(Catalog.GetPluralString("{0} - {1} existing budget row was updated",
                                                                           "{0} - {1} existing budget rows were updated", ABudgetsUpdated, true),
                                                   Environment.NewLine,
                                                   ABudgetsUpdated);
                    }

                    if (ABudgetsAdded > 0)
                    {
                        ErrorMessages.AppendFormat(Catalog.GetPluralString("{0} - {1} new budget row was added",
                                                                           "{0} - {1} new budget rows were added", ABudgetsAdded, true),
                                                   Environment.NewLine,
                                                   ABudgetsAdded);
                    }

                    if (BudgetsDuplicate > 0)
                    {
                        ErrorMessages.AppendFormat(Catalog.GetPluralString("{0} - {1} identical budget row was not needed",
                                                                           "{0} - {1} identical budget rows were not needed", BudgetsDuplicate, true),
                                                   Environment.NewLine,
                                                   BudgetsDuplicate);
                    }

                    ErrorMessages.Append(Environment.NewLine + Environment.NewLine);
                }

                //Check for import errors
                if (AMessages.Count > 0)
                {
                    ErrorMessages.AppendFormat(
                        Catalog.GetPluralString("{0} budget row failed on import:", "{0} budget rows failed on import:",
                                                ABudgetsFailed, true),
                        ABudgetsFailed);

                    foreach (TVerificationResult message in AMessages)
                    {
                        ErrorMessages.AppendFormat("{0}[{1}] {2}: {3}",
                                                   Environment.NewLine,
                                                   message.ResultContext, message.ResultTextCaption, message.ResultText);
                    }
                }

                TFrmExtendedMessageBox extendedMessageBox = new TFrmExtendedMessageBox(FParentForm);

                if ((ABudgetsFailed > 0) || (ABudgetsImported == -1))
                {
                    extendedMessageBox.ShowDialog(ErrorMessages.ToString(),
                                                  Catalog.GetString("Budget Import"), string.Empty,
                                                  TFrmExtendedMessageBox.TButtons.embbOK, TFrmExtendedMessageBox.TIcon.embiError);
                }
                else
                {
                    extendedMessageBox.ShowDialog(ErrorMessages.ToString(),
                                                  Catalog.GetString("Budget Import"), string.Empty,
                                                  TFrmExtendedMessageBox.TButtons.embbOK, TFrmExtendedMessageBox.TIcon.embiInformation);
                }
            }
            else //0
            {
                MessageBox.Show(Catalog.GetString("No records found to import"), Catalog.GetString(
                                    "Budget Import"), MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
        }
コード例 #15
0
        private void ShowMessages(TVerificationResultCollection AMessages,
                                  int ANumBudgetsToImport, int ANumRecsUpdated, int ANumRowsFailed)
        {
            StringBuilder ErrorMessages = new StringBuilder();

            if (ANumBudgetsToImport != 0)
            {
                // if there were budgets to import
                if (ANumBudgetsToImport > 0)
                {
                    ErrorMessages.AppendFormat
                        (Catalog.GetPluralString("{0} budget row was found in the file ", "{0} budget rows were found in the file ",
                                                 ANumBudgetsToImport, true),
                        ANumBudgetsToImport);

                    ErrorMessages.AppendFormat
                        (Catalog.GetPluralString("and {0} was successfully imported!", "and {0} were successfully imported!",
                                                 ANumBudgetsToImport - ANumRowsFailed, true),
                        (ANumBudgetsToImport - ANumRowsFailed));

                    if (ANumRecsUpdated > 0)
                    {
                        ErrorMessages.AppendFormat(Catalog.GetPluralString("{0}({1} of which updated an existing budget row.)",
                                                                           "{0}({1} of which updated existing budget rows.)", ANumRecsUpdated),
                                                   Environment.NewLine,
                                                   ANumRecsUpdated);
                    }

                    ErrorMessages.Append(Environment.NewLine + Environment.NewLine);
                }

                //Check for import errors
                if (AMessages.Count > 0)
                {
                    ErrorMessages.AppendFormat(
                        Catalog.GetPluralString("{0} row failed to import:{1}", "{0} rows failed to import:{1}",
                                                ANumRowsFailed, true),
                        ANumRowsFailed, Environment.NewLine);

                    foreach (TVerificationResult message in AMessages)
                    {
                        ErrorMessages.AppendFormat("{0}[{1}] {2}: {3}",
                                                   Environment.NewLine,
                                                   message.ResultContext, message.ResultTextCaption, message.ResultText);
                    }
                }

                TFrmExtendedMessageBox extendedMessageBox = new TFrmExtendedMessageBox(FParentForm);

                if ((ANumRowsFailed > 0) || (ANumBudgetsToImport == -1))
                {
                    extendedMessageBox.ShowDialog(ErrorMessages.ToString(),
                                                  Catalog.GetString("Budget Import"), string.Empty,
                                                  TFrmExtendedMessageBox.TButtons.embbOK, TFrmExtendedMessageBox.TIcon.embiError);
                }
                else
                {
                    extendedMessageBox.ShowDialog(ErrorMessages.ToString(),
                                                  Catalog.GetString("Budget Import"), string.Empty,
                                                  TFrmExtendedMessageBox.TButtons.embbOK, TFrmExtendedMessageBox.TIcon.embiInformation);
                }
            }
            else //0
            {
                MessageBox.Show(Catalog.GetString("No records found to import"), Catalog.GetString(
                                    "Budget Import"), MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
        }
コード例 #16
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();
        }
コード例 #17
0
        /// <summary>
        /// Posts a batch
        /// </summary>
        /// <param name="ACurrentBatchRow">The data row corresponding to the batch to post</param>
        /// <param name="AEffectiveDate">The effective date for the batch</param>
        /// <param name="AStartDateCurrentPeriod">The earliest postable date</param>
        /// <param name="AEndDateLastForwardingPeriod">The latest postable date</param>
        /// <returns>
        /// True if the batch was successfully posted
        /// </returns>
        public bool PostBatch(ABatchRow ACurrentBatchRow,
                              DateTime AEffectiveDate,
                              DateTime AStartDateCurrentPeriod,
                              DateTime AEndDateLastForwardingPeriod)
        {
            if ((ACurrentBatchRow == null) || (ACurrentBatchRow.BatchStatus != MFinanceConstants.BATCH_UNPOSTED))
            {
                return(false);
            }

            int CurrentBatchNumber = ACurrentBatchRow.BatchNumber;

            //Make sure that all control data is in dataset
            FMyForm.GetLatestControlData();

            if (FPetraUtilsObject.HasChanges)
            {
                //Keep this conditional check separate so that it only gets called when necessary
                // and doesn't result in the executon of the next else if which calls same method
                if (!FMyForm.SaveChangesManual(FMyForm.FCurrentGLBatchAction))
                {
                    return(false);
                }
            }
            //This has to be called here as if there are no changes then the DataSavingValidating method
            // which calls the method below, will not run.
            else if (!FMyForm.GetTransactionsControl().AllowInactiveFieldValues(FLedgerNumber,
                                                                                CurrentBatchNumber, FMyForm.FCurrentGLBatchAction))
            {
                return(false);
            }

            //Load all Batch data
            FMainDS.Merge(TRemote.MFinance.GL.WebConnectors.LoadABatchAndRelatedTables(FLedgerNumber, CurrentBatchNumber));

            if (FCacheDS == null)
            {
                FCacheDS = TRemote.MFinance.GL.WebConnectors.LoadAAnalysisAttributes(FLedgerNumber, false);
            }

            if (FAccountTable == null)
            {
                SetAccountCostCentreTableVariables();
            }

            if ((AEffectiveDate.Date < AStartDateCurrentPeriod) || (AEffectiveDate.Date > AEndDateLastForwardingPeriod))
            {
                MessageBox.Show(String.Format(Catalog.GetString(
                                                  "The Date Effective is outside the periods available for posting. Enter a date between {0:d} and {1:d}."),
                                              AStartDateCurrentPeriod,
                                              AEndDateLastForwardingPeriod));

                return(false);
            }

            // check that a corportate exchange rate exists
            FMyForm.WarnAboutMissingIntlExchangeRate = true;

            if (FMyForm.GetInternationalCurrencyExchangeRate() == 0)
            {
                return(false);
            }

            if ((MessageBox.Show(String.Format(Catalog.GetString("Are you sure you want to post GL batch {0}?"),
                                               CurrentBatchNumber),
                                 Catalog.GetString("Question"),
                                 MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1) != System.Windows.Forms.DialogResult.Yes))
            {
                return(false);
            }

            TVerificationResultCollection Verifications = new TVerificationResultCollection();

            try
            {
                Cursor.Current = Cursors.WaitCursor;

                Thread postingThread = new Thread(() => PostGLBatch(CurrentBatchNumber, out Verifications));
                postingThread.SetApartmentState(ApartmentState.STA);

                using (TProgressDialog dialog = new TProgressDialog(postingThread))
                {
                    dialog.ShowDialog();
                }

                if (TVerificationHelper.ResultsContainErrorCode(Verifications, PetraErrorCodes.ERR_DB_SERIALIZATION_EXCEPTION))
                {
                    TConcurrentServerTransactions.ShowTransactionSerializationExceptionDialog();
                }
                else if (!TVerificationHelper.IsNullOrOnlyNonCritical(Verifications))
                {
                    TFrmExtendedMessageBox extendedMessageBox = new TFrmExtendedMessageBox(FMyForm);

                    StringBuilder errorMessages = new StringBuilder();
                    int           counter       = 0;

                    errorMessages.AppendLine(Catalog.GetString("________________________GL Posting Errors________________________"));
                    errorMessages.AppendLine();

                    foreach (TVerificationResult verif in Verifications)
                    {
                        counter++;
                        errorMessages.AppendLine(counter.ToString("000") + " - " + verif.ResultText);
                        errorMessages.AppendLine();
                    }

                    extendedMessageBox.ShowDialog(errorMessages.ToString(),
                                                  Catalog.GetString("Post Batch Error"),
                                                  string.Empty,
                                                  TFrmExtendedMessageBox.TButtons.embbOK,
                                                  TFrmExtendedMessageBox.TIcon.embiWarning);
                }
                else
                {
                    MessageBox.Show(Catalog.GetString("The batch has been posted successfully!"),
                                    Catalog.GetString("Success"),
                                    MessageBoxButtons.OK,
                                    MessageBoxIcon.Information);
                }

                // refresh the grid, to reflect that the batch has been posted (or even maybe had been posted by another user)
                FMainDS.Merge(TRemote.MFinance.GL.WebConnectors.LoadABatchAndRelatedTables(FLedgerNumber, CurrentBatchNumber));

                // make sure that the current dataset is clean,
                // otherwise the next save would try to modify the posted batch, even though no values have been changed
                FMainDS.AcceptChanges();

                // Ensure these tabs will ask the server for updates
                FMyForm.GetTransactionsControl().ClearCurrentSelection();
                FMyForm.GetJournalsControl().ClearCurrentSelection();

                FMyUserControl.UpdateDisplay();
            }
            catch (Exception ex)
            {
                TLogging.LogException(ex, Utilities.GetMethodSignature());
                throw;
            }
            finally
            {
                Cursor.Current = Cursors.Default;
            }

            return(true);
        }
コード例 #18
0
        /// <summary>
        /// Check for inactive field values
        /// </summary>
        /// <param name="AAction"></param>
        /// <returns></returns>
        public bool AllowInactiveFieldValues(TExtraGiftBatchChecks.GiftBatchAction AAction)
        {
            TFrmRecurringGiftBatch MainForm = (TFrmRecurringGiftBatch)this.ParentForm;

            bool InSubmitting    = (AAction == TExtraGiftBatchChecks.GiftBatchAction.SUBMITTING);
            bool InDeleting      = (AAction == TExtraGiftBatchChecks.GiftBatchAction.DELETING);
            bool InDeletingTrans = (AAction == TExtraGiftBatchChecks.GiftBatchAction.DELETINGTRANS);

            int CurrentBatch = FPreviouslySelectedDetailRow.BatchNumber;

            //Variables for building warning message
            string        WarningMessage = string.Empty;
            string        WarningHeader  = string.Empty;
            StringBuilder WarningList    = new StringBuilder();

            //Find batches that have changed
            List <ARecurringGiftBatchRow> BatchesToCheck = MainForm.GetUnsavedBatchRowsList(CurrentBatch);
            List <int> BatchesWithInactiveValues         = new List <int>();

            if (BatchesToCheck.Count > 0)
            {
                int    currentBatchListNo;
                string batchNoList = string.Empty;

                int    numInactiveFieldsPresent = 0;
                string bankCostCentre;
                string bankAccount;

                foreach (ARecurringGiftBatchRow gBR in BatchesToCheck)
                {
                    currentBatchListNo = gBR.BatchNumber;

                    bool checkingCurrentBatch = (currentBatchListNo == CurrentBatch);

                    bool batchVerified     = false;
                    bool batchExistsInDict = FRecurringBatchesVerifiedOnSavingDict.TryGetValue(currentBatchListNo, out batchVerified);

                    if (batchExistsInDict)
                    {
                        if (batchVerified && !(InSubmitting && checkingCurrentBatch && FWarnOfInactiveValuesOnSubmitting))
                        {
                            continue;
                        }
                    }
                    else if (!(InDeleting && checkingCurrentBatch))
                    {
                        FRecurringBatchesVerifiedOnSavingDict.Add(currentBatchListNo, false);
                    }

                    //If processing batch about to be submitted, only warn according to user preferences
                    if ((InSubmitting && checkingCurrentBatch && !FWarnOfInactiveValuesOnSubmitting) ||
                        (InDeleting && checkingCurrentBatch))
                    {
                        continue;
                    }

                    //Check for inactive Bank Cost Centre & Account
                    bankCostCentre = gBR.BankCostCentre;
                    bankAccount    = gBR.BankAccountCode;

                    if (!FAccountAndCostCentreLogicObject.CostCentreIsActive(bankCostCentre))
                    {
                        WarningList.AppendFormat("   Cost Centre '{0}' in batch: {1}{2}",
                                                 gBR.BankAccountCode,
                                                 gBR.BatchNumber,
                                                 Environment.NewLine);

                        numInactiveFieldsPresent++;
                        BatchesWithInactiveValues.Add(currentBatchListNo);
                    }

                    if (!FAccountAndCostCentreLogicObject.AccountIsActive(bankAccount))
                    {
                        WarningList.AppendFormat(" Bank Account '{0}' in batch: {1}{2}",
                                                 gBR.BankAccountCode,
                                                 gBR.BatchNumber,
                                                 Environment.NewLine);

                        numInactiveFieldsPresent++;

                        if (!BatchesWithInactiveValues.Contains(currentBatchListNo))
                        {
                            BatchesWithInactiveValues.Add(currentBatchListNo);
                        }
                    }
                }

                if (numInactiveFieldsPresent > 0)
                {
                    string batchList           = string.Empty;
                    string otherChangedBatches = string.Empty;

                    BatchesWithInactiveValues.Sort();

                    //Update the dictionary
                    foreach (int batch in BatchesWithInactiveValues)
                    {
                        if (batch == CurrentBatch)
                        {
                            if ((!InSubmitting && (FRecurringBatchesVerifiedOnSavingDict[batch] == false)) ||
                                (InSubmitting && FWarnOfInactiveValuesOnSubmitting))
                            {
                                FRecurringBatchesVerifiedOnSavingDict[batch] = true;
                                batchList += (string.IsNullOrEmpty(batchList) ? "" : ", ") + batch.ToString();
                            }
                        }
                        else if (FRecurringBatchesVerifiedOnSavingDict[batch] == false)
                        {
                            FRecurringBatchesVerifiedOnSavingDict[batch] = true;
                            batchList += (string.IsNullOrEmpty(batchList) ? "" : ", ") + batch.ToString();
                            //Build a list of all batches except current batch
                            otherChangedBatches += (string.IsNullOrEmpty(otherChangedBatches) ? "" : ", ") + batch.ToString();
                        }
                    }

                    //Create header message
                    WarningHeader  = "{0} inactive value(s) found in recurring batch{1}{4}{4}Do you still want to continue with ";
                    WarningHeader += (!InDeletingTrans ? AAction.ToString().ToLower() : "deleting gift detail(s) and saving changes to") +
                                     " batch: {2}";
                    WarningHeader += (otherChangedBatches.Length > 0 ? " and with saving: {3}" : "") + " ?{4}";

                    if (!InSubmitting || (otherChangedBatches.Length > 0))
                    {
                        WarningHeader += "{4}(You will only be warned once about inactive values when saving any batch!){4}";
                    }

                    //Handle plural
                    batchList = (otherChangedBatches.Length > 0 ? "es: " : ": ") + batchList;

                    WarningMessage = String.Format(Catalog.GetString(WarningHeader + "{4}Inactive values:{4}{5}{4}{6}{5}"),
                                                   numInactiveFieldsPresent,
                                                   batchList,
                                                   CurrentBatch,
                                                   otherChangedBatches,
                                                   Environment.NewLine,
                                                   new String('-', 44),
                                                   WarningList);

                    TFrmExtendedMessageBox extendedMessageBox = new TFrmExtendedMessageBox((TFrmRecurringGiftBatch)ParentForm);

                    string header = string.Empty;

                    if (InSubmitting)
                    {
                        header = "Submit";
                    }
                    else if (InDeleting)
                    {
                        header = "Delete";
                    }
                    else if (InDeletingTrans)
                    {
                        header = "Delete Gift Detail From";
                    }
                    else
                    {
                        header = "Save";
                    }

                    return(extendedMessageBox.ShowDialog(WarningMessage,
                                                         Catalog.GetString(header + " Recurring Gift Batch"), string.Empty,
                                                         TFrmExtendedMessageBox.TButtons.embbYesNo,
                                                         TFrmExtendedMessageBox.TIcon.embiQuestion) == TFrmExtendedMessageBox.TResult.embrYes);
                }
            }

            return(true);
        }
コード例 #19
0
        /// <summary>
        /// Main method to Submit a specified batch
        /// </summary>
        /// <param name="ACurrentRecurringBatchRow">The batch row to Submit</param>
        /// <param name="ATxtDetailHashTotal">True means ask user if they want to Submit</param>
        /// <param name="ASubmittingAlreadyConfirmed">True means ask user if they want to Submit</param>
        /// <returns>True if the batch was successfully Submited</returns>
        public bool SubmitBatch(ARecurringGiftBatchRow ACurrentRecurringBatchRow,
                                Ict.Common.Controls.TTxtCurrencyTextBox ATxtDetailHashTotal,
                                ref bool ASubmittingAlreadyConfirmed)
        {
            int SelectedBatchNumber = ACurrentRecurringBatchRow.BatchNumber;

            GiftBatchTDSARecurringGiftDetailTable RecurringBatchGiftDetails = new GiftBatchTDSARecurringGiftDetailTable();

            foreach (ARecurringGiftDetailRow Row in FMainDS.ARecurringGiftDetail.Rows)
            {
                if (Row.BatchNumber == SelectedBatchNumber)
                {
                    RecurringBatchGiftDetails.Rows.Add((object[])Row.ItemArray.Clone());
                }
            }

            if (FPetraUtilsObject.HasChanges)
            {
                bool CancelledDueToExWorker;

                // save first, then submit
                if (!FMyForm.SaveChangesForSubmitting(RecurringBatchGiftDetails, out CancelledDueToExWorker))
                {
                    if (!CancelledDueToExWorker)
                    {
                        // saving failed, therefore do not try to submit
                        MessageBox.Show(Catalog.GetString(
                                            "The recurring batch was not submitted due to problems during saving; ") + Environment.NewLine +
                                        Catalog.GetString("Please fix the batch first and then submit it."),
                                        Catalog.GetString("Submit Failure"), MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }

                    return(false);
                }
            }

            if ((ACurrentRecurringBatchRow.HashTotal != 0) &&
                (ACurrentRecurringBatchRow.BatchTotal != ACurrentRecurringBatchRow.HashTotal))
            {
                MessageBox.Show(String.Format(Catalog.GetString(
                                                  "The recurring gift batch total ({0}) for batch {1} does not equal the hash total ({2})."),
                                              StringHelper.FormatUsingCurrencyCode(ACurrentRecurringBatchRow.BatchTotal, ACurrentRecurringBatchRow.CurrencyCode),
                                              ACurrentRecurringBatchRow.BatchNumber,
                                              StringHelper.FormatUsingCurrencyCode(ACurrentRecurringBatchRow.HashTotal, ACurrentRecurringBatchRow.CurrencyCode)),
                                "Submit Recurring Gift Batch");

                ATxtDetailHashTotal.Focus();
                ATxtDetailHashTotal.SelectAll();
                return(false);
            }

            //Check for inactive KeyMinistries
            DataTable GiftsWithInactiveKeyMinistries;

            if (TRemote.MFinance.Gift.WebConnectors.InactiveKeyMinistriesFoundInBatch(FLedgerNumber, SelectedBatchNumber,
                                                                                      out GiftsWithInactiveKeyMinistries, true))
            {
                int numInactiveValues = GiftsWithInactiveKeyMinistries.Rows.Count;

                string listOfOffendingRows =
                    String.Format(Catalog.GetString(
                                      "{0} inactive key ministries found in Recurring Gift Batch {1}. Do you still want to submit?{2}{2}"),
                                  numInactiveValues,
                                  SelectedBatchNumber,
                                  Environment.NewLine);

                listOfOffendingRows += "Gift      Detail   Recipient          KeyMinistry" + Environment.NewLine;
                listOfOffendingRows += "-------------------------------------------------------------------------------";

                foreach (DataRow dr in GiftsWithInactiveKeyMinistries.Rows)
                {
                    listOfOffendingRows += String.Format("{0}{1:0000}    {2:00}        {3:00000000000}    {4}",
                                                         Environment.NewLine,
                                                         dr[0],
                                                         dr[1],
                                                         dr[2],
                                                         dr[3]);
                }

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

                if (extendedMessageBox.ShowDialog(listOfOffendingRows.ToString(),
                                                  Catalog.GetString("Submit Batch"), string.Empty,
                                                  TFrmExtendedMessageBox.TButtons.embbYesNo,
                                                  TFrmExtendedMessageBox.TIcon.embiWarning) != TFrmExtendedMessageBox.TResult.embrYes)
                {
                    return(false);
                }
            }

            TFrmRecurringGiftBatchSubmit SubmitForm = new TFrmRecurringGiftBatchSubmit(FPetraUtilsObject.GetForm());

            try
            {
                FMyForm.ShowInTaskbar = false;
                SubmitForm.MainDS     = FMainDS;
                SubmitForm.BatchRow   = ACurrentRecurringBatchRow;
                SubmitForm.ShowDialog();
            }
            finally
            {
                SubmitForm.Dispose();
                FMyForm.ShowInTaskbar = true;
            }

            return(true);
        }
コード例 #20
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);
        }
コード例 #21
0
        /// <summary>
        /// Main method to Submit a specified batch
        /// </summary>
        /// <param name="ACurrentRecurringBatchRow">The batch row to Submit</param>
        /// <param name="AWarnOfInactiveValues">True means user is warned if inactive values exist</param>
        /// <param name="ADonorZeroIsValid"></param>
        /// <param name="ARecipientZeroIsValid"></param>
        /// <returns>True if the batch was successfully Submited</returns>
        public bool SubmitBatch(ARecurringGiftBatchRow ACurrentRecurringBatchRow,
                                bool AWarnOfInactiveValues = true,
                                bool ADonorZeroIsValid     = false,
                                bool ARecipientZeroIsValid = false)
        {
            if (ACurrentRecurringBatchRow == null)
            {
                return(false);
            }

            FSelectedBatchNumber = ACurrentRecurringBatchRow.BatchNumber;

            //Make sure that all control data is in dataset
            FMyForm.GetLatestControlData();

            //Copy all batch data to new table
            GiftBatchTDSARecurringGiftDetailTable RecurringBatchGiftDetails = new GiftBatchTDSARecurringGiftDetailTable();

            //Filter ARecurringGiftDetail
            DataView RecurringGiftDetailDV = new DataView(FMainDS.ARecurringGiftDetail);

            RecurringGiftDetailDV.RowFilter = string.Format("{0}={1}",
                                                            ARecurringGiftDetailTable.GetBatchNumberDBName(),
                                                            FSelectedBatchNumber);

            RecurringGiftDetailDV.Sort = string.Format("{0} ASC, {1} ASC, {2} ASC",
                                                       ARecurringGiftDetailTable.GetBatchNumberDBName(),
                                                       ARecurringGiftDetailTable.GetGiftTransactionNumberDBName(),
                                                       ARecurringGiftDetailTable.GetDetailNumberDBName());

            foreach (DataRowView dRV in RecurringGiftDetailDV)
            {
                GiftBatchTDSARecurringGiftDetailRow rGBR = (GiftBatchTDSARecurringGiftDetailRow)dRV.Row;
                RecurringBatchGiftDetails.Rows.Add((object[])rGBR.ItemArray.Clone());
            }

            //Save and check for inactive values and ex-workers and anonymous gifts
            if (FPetraUtilsObject.HasChanges)
            {
                //Keep this conditional check separate from the one above so that it only gets called
                // when necessary and doesn't result in the executon of the same method
                if (!FMyForm.SaveChangesForSubmitting(RecurringBatchGiftDetails))
                {
                    return(false);
                }
            }
            else
            {
                //This has to be called here because if there are no changes then the DataSavingValidating
                // method which calls the method below, will not run.
                if (!FMyForm.GetBatchControl().AllowInactiveFieldValues(TExtraGiftBatchChecks.GiftBatchAction.SUBMITTING) ||
                    FMyForm.GiftHasExWorkerOrAnon(RecurringBatchGiftDetails)
                    )
                {
                    return(false);
                }
            }

            //Check hash total validity
            if ((ACurrentRecurringBatchRow.HashTotal != 0) &&
                (ACurrentRecurringBatchRow.BatchTotal != ACurrentRecurringBatchRow.HashTotal))
            {
                MessageBox.Show(String.Format(Catalog.GetString(
                                                  "The recurring gift batch total ({0}) for batch {1} does not equal the hash total ({2})."),
                                              StringHelper.FormatUsingCurrencyCode(ACurrentRecurringBatchRow.BatchTotal, ACurrentRecurringBatchRow.CurrencyCode),
                                              ACurrentRecurringBatchRow.BatchNumber,
                                              StringHelper.FormatUsingCurrencyCode(ACurrentRecurringBatchRow.HashTotal, ACurrentRecurringBatchRow.CurrencyCode)),
                                "Submit Recurring Gift Batch");

                FMyForm.GetBatchControl().Controls["txtDetailHashTotal"].Focus();
                FMyForm.GetBatchControl().Controls["txtDetailHashTotal"].Select();
                return(false);
            }

            //Check for zero Donors or Recipients
            if (!ADonorZeroIsValid)
            {
                DataView recurringBatchGiftDV = new DataView(FMainDS.ARecurringGift);

                recurringBatchGiftDV.RowFilter = string.Format("{0}={1} And {2}=0",
                                                               ARecurringGiftTable.GetBatchNumberDBName(),
                                                               FSelectedBatchNumber,
                                                               ARecurringGiftTable.GetDonorKeyDBName());

                int numDonorZeros = recurringBatchGiftDV.Count;

                if (numDonorZeros > 0)
                {
                    string messageListOfOffendingGifts =
                        String.Format(Catalog.GetString(
                                          "Recurring Gift Batch {0} contains {1} gift detail(s) with Donor 0000000. Please fix before posting!{2}{2}"),
                                      FSelectedBatchNumber,
                                      numDonorZeros,
                                      Environment.NewLine);

                    string listOfOffendingRows = string.Empty;

                    listOfOffendingRows += "Gift" + Environment.NewLine;
                    listOfOffendingRows += "------------";

                    foreach (DataRowView drv in recurringBatchGiftDV)
                    {
                        ARecurringGiftRow giftRow = (ARecurringGiftRow)drv.Row;

                        listOfOffendingRows += String.Format("{0}{1:0000}",
                                                             Environment.NewLine,
                                                             giftRow.GiftTransactionNumber);
                    }

                    TFrmExtendedMessageBox extendedMessageBox = new TFrmExtendedMessageBox(FMyForm);

                    extendedMessageBox.ShowDialog((messageListOfOffendingGifts + listOfOffendingRows),
                                                  Catalog.GetString("Submit Batch Error"), string.Empty,
                                                  TFrmExtendedMessageBox.TButtons.embbOK,
                                                  TFrmExtendedMessageBox.TIcon.embiWarning);

                    return(false);
                }
            }

            if (!ARecipientZeroIsValid)
            {
                DataView recurringBatchGiftDetailsDV = new DataView(FMainDS.ARecurringGiftDetail);

                recurringBatchGiftDetailsDV.RowFilter = string.Format("{0}={1} And {2}=0",
                                                                      ARecurringGiftDetailTable.GetBatchNumberDBName(),
                                                                      FSelectedBatchNumber,
                                                                      ARecurringGiftDetailTable.GetRecipientKeyDBName());

                int numRecipientZeros = recurringBatchGiftDetailsDV.Count;

                if (numRecipientZeros > 0)
                {
                    string messageListOfOffendingGifts =
                        String.Format(Catalog.GetString(
                                          "Recurring Gift Batch {0} contains {1} gift detail(s) with Recipient 0000000. Please fix before posting!{2}{2}"),
                                      FSelectedBatchNumber,
                                      numRecipientZeros,
                                      Environment.NewLine);

                    string listOfOffendingRows = string.Empty;

                    listOfOffendingRows += "Gift   Detail" + Environment.NewLine;
                    listOfOffendingRows += "-------------------";

                    foreach (DataRowView drv in recurringBatchGiftDetailsDV)
                    {
                        ARecurringGiftDetailRow giftDetailRow = (ARecurringGiftDetailRow)drv.Row;

                        listOfOffendingRows += String.Format("{0}{1:0000}  {2:00}",
                                                             Environment.NewLine,
                                                             giftDetailRow.GiftTransactionNumber,
                                                             giftDetailRow.DetailNumber);
                    }

                    TFrmExtendedMessageBox extendedMessageBox = new TFrmExtendedMessageBox(FMyForm);

                    extendedMessageBox.ShowDialog((messageListOfOffendingGifts + listOfOffendingRows),
                                                  Catalog.GetString("Submit Batch Error"), string.Empty,
                                                  TFrmExtendedMessageBox.TButtons.embbOK,
                                                  TFrmExtendedMessageBox.TIcon.embiWarning);

                    return(false);
                }
            }

            //Check for inactive KeyMinistries
            DataTable GiftsWithInactiveKeyMinistries;

            if (TRemote.MFinance.Gift.WebConnectors.InactiveKeyMinistriesFoundInBatch(FLedgerNumber, FSelectedBatchNumber,
                                                                                      out GiftsWithInactiveKeyMinistries, true))
            {
                int numInactiveValues = GiftsWithInactiveKeyMinistries.Rows.Count;

                string listOfOffendingRows =
                    String.Format(Catalog.GetString(
                                      "{0} inactive key ministries found in Recurring Gift Batch {1}. Do you still want to submit?{2}{2}"),
                                  numInactiveValues,
                                  FSelectedBatchNumber,
                                  Environment.NewLine);

                listOfOffendingRows += "Gift      Detail   Recipient          KeyMinistry" + Environment.NewLine;
                listOfOffendingRows += "-------------------------------------------------------------------------------";

                foreach (DataRow dr in GiftsWithInactiveKeyMinistries.Rows)
                {
                    listOfOffendingRows += String.Format("{0}{1:0000}    {2:00}        {3:00000000000}    {4}",
                                                         Environment.NewLine,
                                                         dr[0],
                                                         dr[1],
                                                         dr[2],
                                                         dr[3]);
                }

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

                if (extendedMessageBox.ShowDialog(listOfOffendingRows.ToString(),
                                                  Catalog.GetString("Submit Batch"), string.Empty,
                                                  TFrmExtendedMessageBox.TButtons.embbYesNo,
                                                  TFrmExtendedMessageBox.TIcon.embiWarning) != TFrmExtendedMessageBox.TResult.embrYes)
                {
                    return(false);
                }
            }

            TFrmRecurringGiftBatchSubmit SubmitForm = new TFrmRecurringGiftBatchSubmit(FPetraUtilsObject.GetForm());

            try
            {
                FMyForm.ShowInTaskbar = false;
                SubmitForm.MainDS     = FMainDS;
                SubmitForm.BatchRow   = ACurrentRecurringBatchRow;
                SubmitForm.ShowDialog();
            }
            finally
            {
                SubmitForm.Dispose();
                FMyForm.ShowInTaskbar = true;
            }

            return(true);
        }
コード例 #22
0
        // starts the merge process
        private void BtnOK_Click(Object Sender, EventArgs e)
        {
            // Title for all message boxes
            string mergePartnersTitle = Catalog.GetString("Merge Partners");
            string mergeCancelledText = Catalog.GetString("Merge cancelled.");

            FFromPartnerKey = Convert.ToInt64(txtMergeFrom.Text);
            FToPartnerKey   = Convert.ToInt64(txtMergeTo.Text);

            if (CheckPartnersCanBeMerged() &&
                (MessageBox.Show(Catalog.GetString("WARNING: A Partner Merge operation cannot be undone and the From-Partner will be no longer " +
                                                   "accessible after the Partner Merge operation!") + "\n\n" + Catalog.GetString("Are you sure you want to continue?"),
                                 mergePartnersTitle, MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes))
            {
                bool[] Categories = new bool[25];

                for (int i = 1; i < 25; i++)
                {
                    Categories[i] = true;
                }

                FSiteKeys              = null;
                FLocationKeys          = null;
                FContactDetails        = null;
                FMainBankingDetailsKey = -1;
                TFrmExtendedMessageBox msgBox = null;
                string msg = string.Empty;
                bool   DifferentFamilies = false;

                // open a dialog to select which From Partner's addresses should be merged
                if (GetSelectedAddresses() == false)
                {
                    MessageBox.Show(mergeCancelledText, mergePartnersTitle, MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }

                // open a dialog to select which From Partner's contact details should be merged
                if (GetSelectedContactDetails() == false)
                {
                    MessageBox.Show(mergeCancelledText, mergePartnersTitle, MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }

                // open a dialog to select which bank account should be set to MAIN (if necessary)
                if (GetMainBankAccount() == false)
                {
                    MessageBox.Show(mergeCancelledText, mergePartnersTitle, MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }

                //
                if ((((FFromPartnerClass == TPartnerClass.FAMILY) && (FToPartnerClass == TPartnerClass.FAMILY)) ||
                     (FFromPartnerClass == TPartnerClass.PERSON)) &&
                    (GiftDestinationToMerge(out Categories[0]) == false))
                {
                    MessageBox.Show(mergeCancelledText, mergePartnersTitle, MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }

                Thread t =
                    new Thread(() => MergeTwoPartners(Categories, ref DifferentFamilies));

                using (TProgressDialog dialog = new TProgressDialog(t))
                {
                    if ((dialog.ShowDialog() == DialogResult.Cancel) && (FWebConnectorResult == false))
                    {
                        MessageBox.Show(mergeCancelledText, mergePartnersTitle, MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return;
                    }
                    else if (FWebConnectorResult == false)   // if merge is unsuccessful
                    {
                        msg = Catalog.GetString("The merge operation failed");

                        // Anything to display from the verification results?
                        if (FVerificationResultsOfMerge.Count > 0)
                        {
                            for (int i = 0; i < FVerificationResultsOfMerge.Count; i++)
                            {
                                if (FVerificationResultsOfMerge[i].ResultSeverity == TResultSeverity.Resv_Critical)
                                {
                                    msg += Environment.NewLine;
                                    msg += FVerificationResultsOfMerge[i].ResultText;
                                }
                            }

                            msg += Environment.NewLine;
                            msg += Catalog.GetString("More information is available in the Server.log file on the server at the date and time shown.");
                            msg += Environment.NewLine;
                            msg += Catalog.GetString("You can copy this message to the clipboard by clicking the button below.");
                        }

                        msgBox = new TFrmExtendedMessageBox(this);
                        msgBox.ShowDialog(msg, mergePartnersTitle, string.Empty,
                                          TFrmExtendedMessageBox.TButtons.embbOK, TFrmExtendedMessageBox.TIcon.embiError);

                        dialog.Close();
                        return;
                    }
                }

                if (DifferentFamilies)
                {
                    MessageBox.Show(String.Format(Catalog.GetString("Partners were in different families.")) + "\n\n" +
                                    Catalog.GetString("FAMILY relations of the From Partner are not taken over to the To Partner!") + "\n\n" +
                                    Catalog.GetString("Please check the family relations of the To Partner after completion."),
                                    mergePartnersTitle, MessageBoxButtons.OK, MessageBoxIcon.Information);
                }

                msg = String.Format(Catalog.GetString("Merge of Partner {0} ({1}) into {2} ({3}) completed successfully."),
                                    txtMergeFrom.LabelText, FFromPartnerKey, txtMergeTo.LabelText, FToPartnerKey);

                if (FVerificationResultsOfMerge.Count > 0)
                {
                    msg += Environment.NewLine;

                    for (int i = 0; i < FVerificationResultsOfMerge.Count; i++)
                    {
                        msg += Environment.NewLine;
                        msg += FVerificationResultsOfMerge[i].ResultText;
                    }

                    msg += Environment.NewLine;
                }

                msg += Environment.NewLine;
                msg += Catalog.GetString("If necessary, edit the merged Partner to correct any information that may not have been " +
                                         "merged and correct information that may have been overwritten.") + Environment.NewLine + Environment.NewLine;
                msg += Catalog.GetString("Tip: You can use the 'Work with Last Partner' command in the Partner module and the " +
                                         "'Work with Last Person' command in the Personnel module to view and edit the merged Partner.") + Environment.NewLine +
                       Environment.NewLine;
                msg += Catalog.GetString("You can copy this message to the clipboard by clicking the button below.");

                msgBox = new TFrmExtendedMessageBox(this);
                msgBox.ShowDialog(msg, mergePartnersTitle, string.Empty, TFrmExtendedMessageBox.TButtons.embbOK,
                                  TFrmExtendedMessageBox.TIcon.embiInformation);

                this.DialogResult = System.Windows.Forms.DialogResult.OK;
                this.Close();
            }
        }