Exemple #1
0
        private void ImportGiftBatch(DateTime AEffectiveDate)
        {
            TGiftImporting importer = new TGiftImporting();

            string       testFile    = TAppSettingsManager.GetValue("GiftBatch.file", "../../csharp/ICT/Testing/lib/MFinance/SampleData/sampleGiftBatch.csv");
            StreamReader sr          = new StreamReader(testFile);
            string       FileContent = sr.ReadToEnd();

            FileContent = FileContent.Replace("{ledgernumber}", FLedgerNumber.ToString());
            FileContent = FileContent.Replace("{thisyear}-01-01", AEffectiveDate.ToString("yyyy-MM-dd"));

            sr.Close();

            Hashtable parameters = new Hashtable();

            parameters.Add("Delimiter", ",");
            parameters.Add("ALedgerNumber", FLedgerNumber);
            parameters.Add("DateFormatString", "yyyy-MM-dd");
            parameters.Add("NumberFormat", "American");
            parameters.Add("NewLine", Environment.NewLine);

            TVerificationResultCollection VerificationResult;
            GiftBatchTDSAGiftDetailTable  NeedRecipientLedgerNumber;

            importer.ImportGiftBatches(parameters, FileContent, out NeedRecipientLedgerNumber, out VerificationResult);
            Assert.True(TVerificationHelper.IsNullOrOnlyNonCritical(VerificationResult),
                        "Failed to import the test gift batch.  The file contains critical error(s): " + VerificationResult.BuildVerificationResultString());
        }
Exemple #2
0
        public void Test_01_GL_Batch_Import()
        {
            Hashtable requestParams = new Hashtable();

            requestParams.Add("ALedgerNumber", FLedgerNumber);
            requestParams.Add("Delimiter", ";");
            requestParams.Add("DateFormatString", "dd/MM/yyyy");
            requestParams.Add("DatesMayBeIntegers", false);
            requestParams.Add("NumberFormat", "European");
            requestParams.Add("NewLine", Environment.NewLine);

            string strContent = CommonNUnitFunctions.LoadCSVFileToString("csharp\\ICT\\Testing\\lib\\MFinance\\GL\\" +
                                                                         "test-csv\\glbatch-import.csv");

            strContent = strContent.Replace("31/07/2010", "31/07/" + DateTime.Now.Year.ToString());
            strContent = strContent.Replace("02/07/2010", "02/07/" + DateTime.Now.Year.ToString());
            strContent = strContent.Replace("{ledgernumber}", FLedgerNumber.ToString());

            TVerificationResultCollection verificationResult;
            bool refreshRequired;

            bool importSuccess = TGLTransactionWebConnector.ImportGLBatches(requestParams, strContent, out refreshRequired, out verificationResult);

            if (!TVerificationHelper.IsNullOrOnlyNonCritical(verificationResult))
            {
                TLogging.Log(verificationResult.BuildVerificationResultString());
            }

            Assert.IsTrue(importSuccess, "Import glbatch-import.csv done well ....");
        }
        public void EnterInvalidDates()
        {
            TtxtPetraDate dtpDate = new TtxtPetraDate();

            dtpDate.Name         = "dtpDate";
            dtpDate.DateChanged += new TPetraDateChangedEventHandler(DateChanged);
            dtpDate.TextChanged += new EventHandler(TextChanged);

            Form TestForm = new Form();

            TestForm.Controls.Add(dtpDate);

            TestForm.Show();

            TTxtPetraDateTester tester = new TTxtPetraDateTester("dtpDate");

            TextChangedCalled    = 0;
            DateChangedCalled    = 0;
            NumberOfMessageBoxes = 0;

            DialogBoxHandler       = HandleMessageBox;
            tester.Properties.Text = "30";

            Assert.AreEqual(1, NumberOfMessageBoxes, "entering an invalid date should only show a messagebox once");
            Assert.IsTrue(TVerificationHelper.AreVerificationResultsIdentical(tester.Properties.DateVerificationResult,
                                                                              Ict.Common.Verification.TDateChecks.GetInvalidDateVerificationResult("Date", null), false, false));

            TextChangedCalled    = 0;
            DateChangedCalled    = 0;
            NumberOfMessageBoxes = 0;

            DialogBoxHandler       = HandleMessageBox;
            tester.Properties.Text = "301210000";

            Assert.AreEqual(1, NumberOfMessageBoxes, "entering an invalid date should only show a messagebox once: year 10000");

            DialogBoxHandler = null;

            NumberOfMessageBoxes = 0;

            DialogBoxHandler = HandleMessageBox;

            tester.Properties.AllowEmpty = false;
            tester.Properties.Text       = "01-JAN-2010";
            tester.Properties.Text       = "";

            Assert.AreEqual(1, NumberOfMessageBoxes, "entering an invalid date should only show a messagebox once: year 10000");
            Assert.IsTrue(TVerificationHelper.AreVerificationResultsIdentical(tester.Properties.DateVerificationResult,
                                                                              new TVerificationResult(null, ErrorCodes.GetErrorInfo(CommonErrorCodes.ERR_NOUNDEFINEDDATE,
                                                                                                                                    CommonResourcestrings.StrInvalidDateEntered + Environment.NewLine +
                                                                                                                                    "{0} must not be empty.", new string[] { "'Date'" }))));

            DialogBoxHandler = null;
        }
        /// <summary>
        /// Checks that a <see cref="TVerificationResultCollection" /> is either null or that it doesn't contain
        /// any <see cref="TVerificationResult" /> items that are CriticalErrors. If it isn't null and it contains such items, an Assert.Fail
        /// call is issued by this Method!
        /// </summary>
        /// <remarks>
        /// Can be used for 'Guard Asserts' to check that the <see cref="TVerificationResultCollection" />
        /// that is returned from server calls is null or holds only non-critical <see cref="TVerificationResult" /> items.
        /// </remarks>
        /// <param name="AVerificationResult"><see cref="TVerificationResultCollection" /> reference (can be null!).</param>
        /// <param name="AMessage">String to append before the Assert message that this Method produces (optional).</param>
        public static void EnsureNullOrOnlyNonCriticalVerificationResults(TVerificationResultCollection AVerificationResult, string AMessage = "")
        {
            string VerificationResultStr;

            if ((AMessage != String.Empty) &&
                (!AMessage.EndsWith(" ")))
            {
                AMessage = AMessage + " ";
            }

            if (!TVerificationHelper.IsNullOrOnlyNonCritical(AVerificationResult))
            {
                VerificationResultStr = AVerificationResult.BuildVerificationResultString();

                TLogging.Log(VerificationResultStr);

                Assert.Fail(AMessage + "*** TVerificationResult HAS CRITICAL ERRORS *** : " +
                            VerificationResultStr);
            }
        }
Exemple #5
0
        public static TSubmitChangesResult SavePersonnelTDS(ref PersonnelTDS AInspectDS,
                                                            out TVerificationResultCollection AVerificationResult)
        {
            TSubmitChangesResult SubmissionResult = TSubmitChangesResult.scrError;
            bool AllDataValidationsOK             = true;

            AVerificationResult = new TVerificationResultCollection();

            // TODO: calculate debit and credit sums for journal and batch?

            if (AInspectDS.Tables.Contains(PmStaffDataTable.GetTableName()))
            {
                if (AInspectDS.PmStaffData.Rows.Count > 0)
                {
                    ValidatePersonnelStaff(ref AVerificationResult, AInspectDS.PmStaffData);
                    ValidatePersonnelStaffManual(ref AVerificationResult, AInspectDS.PmStaffData);

                    if (!TVerificationHelper.IsNullOrOnlyNonCritical(AVerificationResult))
                    {
                        AllDataValidationsOK = false;
                    }
                }
            }

            if (AllDataValidationsOK)
            {
                PersonnelTDSAccess.SubmitChanges(AInspectDS);

                SubmissionResult = TSubmitChangesResult.scrOK;
            }
            else if (AVerificationResult.Count > 0)
            {
                // Downgrade TScreenVerificationResults to TVerificationResults in order to allow
                // Serialisation (needed for .NET Remoting).
                TVerificationResultCollection.DowngradeScreenVerificationResults(AVerificationResult);
            }

            return(SubmissionResult);
        }
Exemple #6
0
        private static void ProcessDeletion(Form AMainWindow, Int32 ALedgerNumber, string ALedgerNameAndNumber)
        {
            TVerificationResultCollection VerificationResult;
            MethodInfo method;

            if (!TRemote.MFinance.Setup.WebConnectors.DeleteLedger(ALedgerNumber, out VerificationResult))
            {
                if (TVerificationHelper.ResultsContainErrorCode(VerificationResult, PetraErrorCodes.ERR_DB_SERIALIZATION_EXCEPTION))
                {
                    TConcurrentServerTransactions.ShowTransactionSerializationExceptionDialog();
                }
                else
                {
                    MessageBox.Show(
                        string.Format(Catalog.GetString("Deletion of Ledger '{0}' failed"), ALedgerNameAndNumber) + "\r\n\r\n" +
                        VerificationResult.BuildVerificationResultString(),
                        Catalog.GetString("Deletion failed"),
                        MessageBoxButtons.OK,
                        MessageBoxIcon.Error);
                }
            }
            else
            {
                MessageBox.Show(
                    string.Format(Catalog.GetString("Ledger '{0}' has been deleted"), ALedgerNameAndNumber),
                    Catalog.GetString("Deletion successful"),
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Information);
            }

            method = AMainWindow.GetType().GetMethod("ShowCurrentLedgerInfoInStatusBar");

            if (method != null)
            {
                method.Invoke(AMainWindow, new object[] { });
            }
        }
        void FPetraUtilsObject_DataSavingStarted(object Sender, EventArgs e)
        {
            // The user has clicked Save.  We need to consider if we need to make any Inverse currency additions...
            // We need to update the details and validate them first
            // When we return from this method the standard code will do the validation again and might not allow the save to go ahead
            FPetraUtilsObject.VerificationResultCollection.Clear();
            ValidateAllData(false, TErrorProcessingMode.Epm_None);

            if (!TVerificationHelper.IsNullOrOnlyNonCritical(FPetraUtilsObject.VerificationResultCollection))
            {
                return;
            }

            // Now go through all the grid rows (view) checking all the added rows.  Keep a list of inverses
            List <tInverseItem> lstInverses = new List <tInverseItem>();
            DataView            gridView    = ((DevAge.ComponentModel.BoundDataView)grdDetails.DataSource).DataView;

            for (int i = 0; i < gridView.Count; i++)
            {
                ACorporateExchangeRateRow ARow = (ACorporateExchangeRateRow)gridView[i].Row;

                if (ARow.RowState == DataRowState.Added)
                {
                    tInverseItem item = new tInverseItem();
                    item.FromCurrencyCode = ARow.ToCurrencyCode;
                    item.ToCurrencyCode   = ARow.FromCurrencyCode;
                    item.RateOfExchange   = Math.Round(1 / ARow.RateOfExchange, 10);
                    item.DateEffective    = ARow.DateEffectiveFrom;
                    lstInverses.Add(item);
                }
            }

            if (lstInverses.Count == 0)
            {
                return;
            }

            // Now go through our list and check if any items need adding to the data Table
            // The user may already have put an inverse currency in by hand
            DataView dv = new DataView(FMainDS.ACorporateExchangeRate);

            for (int i = 0; i < lstInverses.Count; i++)
            {
                tInverseItem item = lstInverses[i];

                // Does the item exist already?
                dv.RowFilter = String.Format(CultureInfo.InvariantCulture, "{0}='{1}' AND {2}='{3}' AND {4}=#{5}#",
                                             ACorporateExchangeRateTable.GetFromCurrencyCodeDBName(),
                                             item.FromCurrencyCode,
                                             ACorporateExchangeRateTable.GetToCurrencyCodeDBName(),
                                             item.ToCurrencyCode,
                                             ACorporateExchangeRateTable.GetDateEffectiveFromDBName(),
                                             item.DateEffective.ToString("d", CultureInfo.InvariantCulture));

                if (dv.Count == 0)
                {
                    ACorporateExchangeRateRow NewRow = FMainDS.ACorporateExchangeRate.NewRowTyped();
                    NewRow.FromCurrencyCode  = item.FromCurrencyCode;
                    NewRow.ToCurrencyCode    = item.ToCurrencyCode;
                    NewRow.DateEffectiveFrom = DateTime.Parse(item.DateEffective.ToLongDateString());
                    NewRow.RateOfExchange    = item.RateOfExchange;

                    FMainDS.ACorporateExchangeRate.Rows.Add(NewRow);
                }
            }

            // Now make sure to select the row that was currently selected when we started the Save operation
            SelectRowInGrid(grdDetails.DataSourceRowToIndex2(FPreviouslySelectedDetailRow) + 1);
        }
        /// <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);
        }
        /// <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>
        private void BtnOK_Click(object sender, EventArgs e)
        {
            FExportFileName = txtFilename.Text;
            String fileContents = string.Empty;
            Int32  budgetCount  = 0;

            if (FExportFileName == String.Empty)
            {
                MessageBox.Show(Catalog.GetString("Please choose a location for the Export File."),
                                Catalog.GetString("Error"),
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Error);
                return;
            }
            else if (!FExportFileName.EndsWith(".csv",
                                               StringComparison.CurrentCultureIgnoreCase) && !FExportFileName.EndsWith(".txt", StringComparison.CurrentCultureIgnoreCase))
            {
                FExportFileName += ".csv";
                txtFilename.Text = FExportFileName;
            }

            if (!Directory.Exists(Path.GetDirectoryName(FExportFileName)))
            {
                MessageBox.Show(Catalog.GetString("Please select an existing directory for this file!"),
                                Catalog.GetString("Error"),
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Error);

                FExportFileName = string.Empty;
                return;
            }

            if (File.Exists(FExportFileName))
            {
                if (MessageBox.Show(Catalog.GetString("The file already exists. Is it OK to overwrite it?"),
                                    Catalog.GetString("Export Budget"),
                                    MessageBoxButtons.YesNo,
                                    MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.No)
                {
                    return;
                }

                try
                {
                    File.Delete(FExportFileName);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(String.Format(
                                        Catalog.GetString(
                                            "Failed to delete the file. Maybe it is already open in another application?  The system message was:{0}{1}"),
                                        Environment.NewLine, ex.Message),
                                    Catalog.GetString("Export Budget"),
                                    MessageBoxButtons.OK,
                                    MessageBoxIcon.Error);
                    return;
                }
            }

            //Hashtable requestParams = new Hashtable();

            //requestParams.Add("ALedgerNumber", FLedgerNumber);
            //requestParams.Add("Delimiter", ConvertDelimiter(cmbDelimiter.GetSelectedString(), false));
            //requestParams.Add("DateFormatString", cmbDateFormat.GetSelectedString());
            //requestParams.Add("NumberFormat", ConvertNumberFormat(cmbNumberFormat));

            TVerificationResultCollection AMessages;

            string[] delims = new string[1];
            delims[0] = ConvertDelimiter(cmbDelimiter.GetSelectedString(), false);

            TFrmStatusDialog dlgStatus = null;

            try
            {
                this.Cursor = Cursors.WaitCursor;

                dlgStatus = new TFrmStatusDialog(FPetraUtilsObject.GetForm());

                dlgStatus.Show();
                dlgStatus.Heading       = Catalog.GetString("Exporting Budgets");
                dlgStatus.CurrentStatus = Catalog.GetString("Exporting budget data for this year and next...");

                budgetCount = TRemote.MFinance.Budget.WebConnectors.ExportBudgets(FLedgerNumber,
                                                                                  FExportFileName,
                                                                                  delims,
                                                                                  ref fileContents,
                                                                                  ref FBudgetDS,
                                                                                  out AMessages);

                dlgStatus.Close();
                dlgStatus = null;

                this.Cursor = Cursors.Default;

                if ((AMessages != null) && (AMessages.Count > 0))
                {
                    if (!TVerificationHelper.IsNullOrOnlyNonCritical(AMessages))
                    {
                        MessageBox.Show(AMessages.BuildVerificationResultString(), Catalog.GetString("Error"),
                                        MessageBoxButtons.OK,
                                        MessageBoxIcon.Error);

                        FExportFileName = string.Empty;
                        return;
                    }
                    else
                    {
                        MessageBox.Show(AMessages.BuildVerificationResultString(), Catalog.GetString("Warnings"),
                                        MessageBoxButtons.OK,
                                        MessageBoxIcon.Information);
                    }
                }

                SaveUserDefaults();

                if (budgetCount == 0)
                {
                    MessageBox.Show(Catalog.GetString("There are no Budgets matching your criteria"),
                                    Catalog.GetString("Error"),
                                    MessageBoxButtons.OK,
                                    MessageBoxIcon.Error);

                    FExportFileName = string.Empty;
                    return;
                }

                StreamWriter sw1 = new StreamWriter(FExportFileName);
                sw1.Write(fileContents);
                sw1.Close();
            }
            catch (Exception ex)
            {
                TLogging.LogException(ex, Utilities.GetMethodSignature());
                throw;
            }
            finally
            {
                this.Cursor = Cursors.Default;

                if (dlgStatus != null)
                {
                    dlgStatus.Close();
                    dlgStatus = null;
                }
            }

            bool ShowExportedFileInExplorer = false;

            // Offer the client the chance to open the file in Excel or whatever
            if (MessageBox.Show(String.Format(Catalog.GetString(
                                                  "{0} Budget rows were exported successfully! Would you like to open the file in your default application?"),
                                              budgetCount.ToString()),
                                Catalog.GetString("Budget Export"),
                                MessageBoxButtons.YesNo,
                                MessageBoxIcon.Information,
                                MessageBoxDefaultButton.Button2) == System.Windows.Forms.DialogResult.Yes)
            {
                try
                {
                    ProcessStartInfo si = new ProcessStartInfo(FExportFileName);
                    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: '") + FExportFileName + "'!", Catalog.GetString(
                                        "Budget Export"), MessageBoxButtons.OK, MessageBoxIcon.Exclamation);

                    ShowExportedFileInExplorer = true;
                }
            }
            else
            {
                ShowExportedFileInExplorer = true;
            }

            if (ShowExportedFileInExplorer)
            {
                //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}\"", FExportFileName));
                    }
                    catch
                    {
                        MessageBox.Show(Catalog.GetString(
                                            "Unable to launch Windows File Explorer to open: '") + FExportFileName + "'!", Catalog.GetString(
                                            "Budget Export"), MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    }
                }
            }

            Close();
        }
        /// <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);
        }
Exemple #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>
        private void ExportBudget(object sender, EventArgs e)
        {
            FExportFileName = txtFilename.Text;
            String fileContents = string.Empty;
            Int32  budgetCount  = 0;

            if (!Directory.Exists(Path.GetDirectoryName(FExportFileName)))
            {
                MessageBox.Show(Catalog.GetString("Please select an existing directory for this file!"),
                                Catalog.GetString("Error"),
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Error);

                FExportFileName = string.Empty;
                return;
            }

            if (File.Exists(FExportFileName))
            {
                if (MessageBox.Show(Catalog.GetString("The file already exists. Is it OK to overwrite it?"),
                                    Catalog.GetString("Export Budget"),
                                    MessageBoxButtons.YesNo,
                                    MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.No)
                {
                    return;
                }
            }

            Hashtable requestParams = new Hashtable();

            requestParams.Add("ALedgerNumber", FLedgerNumber);
            requestParams.Add("Delimiter", ConvertDelimiter(cmbDelimiter.GetSelectedString(), false));
            requestParams.Add("DateFormatString", cmbDateFormat.GetSelectedString());
            requestParams.Add("NumberFormat", ConvertNumberFormat(cmbNumberFormat));

            TVerificationResultCollection AMessages;

            string[] delims = new string[1];
            delims[0] = ConvertDelimiter(cmbDelimiter.GetSelectedString(), false);

            try
            {
                Cursor.Current = Cursors.WaitCursor;

                budgetCount = TRemote.MFinance.Budget.WebConnectors.ExportBudgets(FLedgerNumber,
                                                                                  FExportFileName,
                                                                                  delims,
                                                                                  ref fileContents,
                                                                                  ref FBudgetDS,
                                                                                  out AMessages);
            }
            finally
            {
                Cursor.Current = Cursors.Default;
            }

            if ((AMessages != null) && (AMessages.Count > 0))
            {
                if (!TVerificationHelper.IsNullOrOnlyNonCritical(AMessages))
                {
                    MessageBox.Show(AMessages.BuildVerificationResultString(), Catalog.GetString("Error"),
                                    MessageBoxButtons.OK,
                                    MessageBoxIcon.Error);

                    FExportFileName = string.Empty;
                    return;
                }
                else
                {
                    MessageBox.Show(AMessages.BuildVerificationResultString(), Catalog.GetString("Warnings"),
                                    MessageBoxButtons.OK,
                                    MessageBoxIcon.Information);
                }
            }

            if (budgetCount == 0)
            {
                MessageBox.Show(Catalog.GetString("There are no Budgets matching your criteria"),
                                Catalog.GetString("Error"),
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Error);

                FExportFileName = string.Empty;
                return;
            }

            StreamWriter sw1 = null;

            try
            {
                sw1 = new StreamWriter(FExportFileName);
                sw1.Write(fileContents);
            }
            finally
            {
                if (sw1 != null)
                {
                    sw1.Close();
                }
            }

            MessageBox.Show(Catalog.GetString(String.Format("Exported successfully! {0} Budget rows exported as file:{1}{1}{2}",
                                                            budgetCount.ToString(),
                                                            Environment.NewLine,
                                                            FExportFileName.ToUpper())),
                            Catalog.GetString("Budget Export"),
                            MessageBoxButtons.OK,
                            MessageBoxIcon.Information);

            SaveUserDefaults();
        }
        public static TSubmitChangesResult SaveData(string ATablename,
                                                    ref TTypedDataTable ASubmitTable,
                                                    out TVerificationResultCollection AVerificationResult)
        {
            TDBTransaction  SubmitChangesTransaction = null;
            bool            SubmissionOK             = false;
            TTypedDataTable SubmitTable = ASubmitTable;

            TVerificationResultCollection VerificationResult = null;

            // TODO: check write permissions

            if (ASubmitTable != null)
            {
                VerificationResult = new TVerificationResultCollection();

                DBAccess.GDBAccessObj.BeginAutoTransaction(IsolationLevel.Serializable, ref SubmitChangesTransaction, ref SubmissionOK,
                                                           delegate
                {
                    try
                    {
                        if (ATablename == AAccountingPeriodTable.GetTableDBName())
                        {
                            AAccountingPeriodAccess.SubmitChanges((AAccountingPeriodTable)SubmitTable, SubmitChangesTransaction);

                            TCacheableTablesManager.GCacheableTablesManager.MarkCachedTableNeedsRefreshing(
                                TCacheableFinanceTablesEnum.AccountingPeriodList.ToString());
                        }
                        else if (ATablename == ACurrencyTable.GetTableDBName())
                        {
                            ACurrencyAccess.SubmitChanges((ACurrencyTable)SubmitTable, SubmitChangesTransaction);
                        }
                        else if (ATablename == ADailyExchangeRateTable.GetTableDBName())
                        {
                            ADailyExchangeRateAccess.SubmitChanges((ADailyExchangeRateTable)SubmitTable, SubmitChangesTransaction);
                        }
                        else if (ATablename == ACorporateExchangeRateTable.GetTableDBName())
                        {
                            ACorporateExchangeRateAccess.SubmitChanges((ACorporateExchangeRateTable)SubmitTable, SubmitChangesTransaction);
                        }
                        else if (ATablename == ACurrencyLanguageTable.GetTableDBName())
                        {
                            ACurrencyLanguageAccess.SubmitChanges((ACurrencyLanguageTable)SubmitTable, SubmitChangesTransaction);
                        }
                        else if (ATablename == AFeesPayableTable.GetTableDBName())
                        {
                            AFeesPayableAccess.SubmitChanges((AFeesPayableTable)SubmitTable, SubmitChangesTransaction);

                            TCacheableTablesManager.GCacheableTablesManager.MarkCachedTableNeedsRefreshing(
                                TCacheableFinanceTablesEnum.FeesPayableList.ToString());
                        }
                        else if (ATablename == AFeesReceivableTable.GetTableDBName())
                        {
                            AFeesReceivableAccess.SubmitChanges((AFeesReceivableTable)SubmitTable, SubmitChangesTransaction);

                            TCacheableTablesManager.GCacheableTablesManager.MarkCachedTableNeedsRefreshing(
                                TCacheableFinanceTablesEnum.FeesReceivableList.ToString());
                        }
                        else if (ATablename == AGiftBatchTable.GetTableDBName())
                        {
                            // This method is called from ADailyExchangeRate Setup - please do not remove
                            // The method is not required for changes made to the gift batch screens, which use a TDS
                            AGiftBatchAccess.SubmitChanges((AGiftBatchTable)SubmitTable, SubmitChangesTransaction);
                        }
                        else if (ATablename == AJournalTable.GetTableDBName())
                        {
                            // This method is called from ADailyExchangeRate Setup - please do not remove
                            // The method is not required for changes made to the journal screens, which use a TDS
                            AJournalAccess.SubmitChanges((AJournalTable)SubmitTable, SubmitChangesTransaction);
                        }
                        else if (ATablename == ARecurringJournalTable.GetTableDBName())
                        {
                            // This method is called from Submit Recurring GL Batch form - please do not remove
                            // The method is not required for changes made to the journal screens, which use a TDS
                            ARecurringJournalAccess.SubmitChanges((ARecurringJournalTable)SubmitTable, SubmitChangesTransaction);
                        }
                        else if (ATablename == ALedgerTable.GetTableDBName())
                        {
                            // This method is called from ADailyExchangeRate Testing - please do not remove
                            ALedgerAccess.SubmitChanges((ALedgerTable)SubmitTable, SubmitChangesTransaction);
                        }
                        else if (ATablename == AAnalysisTypeTable.GetTableDBName())
                        {
                            AAnalysisTypeAccess.SubmitChanges((AAnalysisTypeTable)SubmitTable, SubmitChangesTransaction);
                        }
                        else if (ATablename == ASuspenseAccountTable.GetTableDBName())
                        {
                            ASuspenseAccountAccess.SubmitChanges((ASuspenseAccountTable)SubmitTable, SubmitChangesTransaction);

                            TCacheableTablesManager.GCacheableTablesManager.MarkCachedTableNeedsRefreshing(
                                TCacheableFinanceTablesEnum.SuspenseAccountList.ToString());
                        }
                        else if (ATablename == PcAttendeeTable.GetTableDBName())
                        {
                            PcAttendeeAccess.SubmitChanges((PcAttendeeTable)SubmitTable, SubmitChangesTransaction);
                        }
                        else if (ATablename == PcConferenceTable.GetTableDBName())
                        {
                            PcConferenceAccess.SubmitChanges((PcConferenceTable)SubmitTable, SubmitChangesTransaction);
                        }
                        else if (ATablename == PcConferenceCostTable.GetTableDBName())
                        {
                            PcConferenceCostAccess.SubmitChanges((PcConferenceCostTable)SubmitTable, SubmitChangesTransaction);
                        }
                        else if (ATablename == PcEarlyLateTable.GetTableDBName())
                        {
                            PcEarlyLateAccess.SubmitChanges((PcEarlyLateTable)SubmitTable, SubmitChangesTransaction);
                        }
                        else if (ATablename == PcSupplementTable.GetTableDBName())
                        {
                            PcSupplementAccess.SubmitChanges((PcSupplementTable)SubmitTable, SubmitChangesTransaction);
                        }
                        else if (ATablename == PcDiscountTable.GetTableDBName())
                        {
                            PcDiscountAccess.SubmitChanges((PcDiscountTable)SubmitTable, SubmitChangesTransaction);
                        }
                        else if (ATablename == PInternationalPostalTypeTable.GetTableDBName())
                        {
                            ValidateInternationalPostalType(ref VerificationResult, SubmitTable);
                            ValidateInternationalPostalTypeManual(ref VerificationResult, SubmitTable);

                            if (TVerificationHelper.IsNullOrOnlyNonCritical(VerificationResult))
                            {
                                PInternationalPostalTypeAccess.SubmitChanges((PInternationalPostalTypeTable)SubmitTable, SubmitChangesTransaction);
                            }
                        }
                        else if (ATablename == PtApplicationTypeTable.GetTableDBName())
                        {
                            PtApplicationTypeAccess.SubmitChanges((PtApplicationTypeTable)SubmitTable, SubmitChangesTransaction);

                            // mark dependent lists for needing to be refreshed since there was a change in base list
                            TCacheableTablesManager.GCacheableTablesManager.MarkCachedTableNeedsRefreshing(
                                TCacheablePersonTablesEnum.EventApplicationTypeList.ToString());
                            TCacheableTablesManager.GCacheableTablesManager.MarkCachedTableNeedsRefreshing(
                                TCacheablePersonTablesEnum.FieldApplicationTypeList.ToString());
                        }
                        else if (ATablename == PFormTable.GetTableDBName())
                        {
                            PFormAccess.SubmitChanges((PFormTable)SubmitTable, SubmitChangesTransaction);
                        }
                        else if (ATablename == PFormalityTable.GetTableDBName())
                        {
                            PFormalityAccess.SubmitChanges((PFormalityTable)SubmitTable, SubmitChangesTransaction);
                        }
                        else if (ATablename == PMailingTable.GetTableDBName())
                        {
                            PMailingAccess.SubmitChanges((PMailingTable)SubmitTable, SubmitChangesTransaction);
                        }
                        else if (ATablename == PPartnerGiftDestinationTable.GetTableDBName())
                        {
                            PPartnerGiftDestinationAccess.SubmitChanges((PPartnerGiftDestinationTable)SubmitTable, SubmitChangesTransaction);
                        }
                        else if (ATablename == PmDocumentTypeTable.GetTableDBName())
                        {
                            PmDocumentTypeAccess.SubmitChanges((PmDocumentTypeTable)SubmitTable, SubmitChangesTransaction);
                        }
                        else if (ATablename == SGroupTable.GetTableDBName())
                        {
                            SGroupAccess.SubmitChanges((SGroupTable)SubmitTable, SubmitChangesTransaction);
                        }
                        else
                        {
                            throw new EOPAppException("TCommonDataReader.SaveData: unknown table '" + ATablename + "'");
                        }

                        SubmissionOK = true;
                    }
                    catch (Exception Exc)
                    {
                        VerificationResult.Add(
                            new TVerificationResult(null, "Cannot SubmitChanges:" + Environment.NewLine +
                                                    Exc.Message, "UNDEFINED", TResultSeverity.Resv_Critical));
                    }
                });
            }

            ASubmitTable        = SubmitTable;
            AVerificationResult = VerificationResult;

            if ((AVerificationResult != null) &&
                (AVerificationResult.Count > 0))
            {
                // Downgrade TScreenVerificationResults to TVerificationResults in order to allow
                // Serialisation (needed for .NET Remoting).
                TVerificationResultCollection.DowngradeScreenVerificationResults(AVerificationResult);

                return(AVerificationResult.HasCriticalErrors ? TSubmitChangesResult.scrError : TSubmitChangesResult.scrOK);
            }

            return(TSubmitChangesResult.scrOK);
        }
        /// <summary>
        /// Main method to post a specified batch
        /// </summary>
        /// <param name="ACurrentBatchRow">The batch row to post</param>
        /// <returns>True if the batch was successfully posted</returns>
        public bool PostBatch(AGiftBatchRow ACurrentBatchRow)
        {
            if ((ACurrentBatchRow == null) || (ACurrentBatchRow.BatchStatus != MFinanceConstants.BATCH_UNPOSTED))
            {
                return(false);
            }

            FSelectedBatchNumber = ACurrentBatchRow.BatchNumber;
            TVerificationResultCollection Verifications;

            try
            {
                FMyForm.EnsureGiftDataPresent(FLedgerNumber, FSelectedBatchNumber);

                GiftBatchTDSAGiftDetailTable BatchGiftDetails = new GiftBatchTDSAGiftDetailTable();

                foreach (GiftBatchTDSAGiftDetailRow Row in FMainDS.AGiftDetail.Rows)
                {
                    if (Row.BatchNumber == FSelectedBatchNumber)
                    {
                        BatchGiftDetails.Rows.Add((object[])Row.ItemArray.Clone());
                    }
                }

                // there are no gifts in this batch!
                if (BatchGiftDetails.Rows.Count == 0)
                {
                    FMyForm.Cursor = Cursors.Default;
                    MessageBox.Show(Catalog.GetString("Batch is empty!"), Catalog.GetString("Posting failed"),
                                    MessageBoxButtons.OK, MessageBoxIcon.Stop);
                    return(false);
                }

                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(false);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }

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

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

            //Check for inactive KeyMinistries
            DataTable GiftsWithInactiveKeyMinistries;

            if (TRemote.MFinance.Gift.WebConnectors.InactiveKeyMinistriesFoundInBatch(FLedgerNumber, FSelectedBatchNumber,
                                                                                      out GiftsWithInactiveKeyMinistries))
            {
                string 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]);
                }

                string msg = String.Format(Catalog.GetString("Cannot post Batch {0} as inactive Key Ministries found in gifts:{1}{1}{2}"),
                                           FSelectedBatchNumber,
                                           Environment.NewLine,
                                           listOfOffendingRows);

                MessageBox.Show(msg, Catalog.GetString("Inactive Key Ministries Found"));

                return(false);
            }

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

            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))
                {
                    string ErrorMessages = String.Empty;

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

                    System.Windows.Forms.MessageBox.Show(ErrorMessages, Catalog.GetString("Posting failed"));
                }
                else
                {
                    MessageBox.Show(Catalog.GetString("The batch has been posted successfully!"));

                    return(true);
                }
            }
            catch (Exception ex)
            {
                string msg = (String.Format(Catalog.GetString("Unexpected error occurred during the posting of a Gift Batch!{0}{1}{2}{1}    {3}"),
                                            Utilities.GetMethodSignature(),
                                            Environment.NewLine,
                                            ex.Message,
                                            ex.InnerException.Message));

                TLogging.Log(msg);
                throw ex;
                //MessageBox.Show(msg, "Post Gift Batch Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                FPostingInProgress = false;
            }

            return(false);
        }
        // We have to have our own handler for the delete button because we need to check references
        //  while making an allowance for any reference to PDataLabelUse.
        // All the UsedBy checkboxes are backed by the PdataLLabel Use table so we know that these references exist.
        // The DeleteRecordManual method test for reference conflicts but allows for PDataLabelUse.
        // If all is ok it calls the standard code, which does NOT check for conflicts.
        private void DeleteRecordManual(Object sender, EventArgs e)
        {
            if ((FPreviouslySelectedDetailRow == null) || (FPrevRowChangedRow == -1))
            {
                return;
            }

            DataRowView[] HighlightedRows = grdDetails.SelectedDataRowsAsDataRowView;

            if ((HighlightedRows.Length == 1) && (!TVerificationHelper.IsNullOrOnlyNonCritical(FPetraUtilsObject.VerificationResultCollection)))
            {
                // If we only have 1 row highlighted and it has validation errors we can quit because the standard code will work fine
                return;
            }

            List <string> listConflicts = new List <string>();

            this.Cursor = Cursors.WaitCursor;

            foreach (DataRowView rv in HighlightedRows)
            {
                TVerificationResultCollection VerificationResults = null;

                // Get the number of references for the row, and the number of rows in PDataLabelUse
                int NumReferences = TRemote.MCommon.ReferenceCount.WebConnectors.GetCacheableRecordReferenceCount(
                    "DataLabelList",
                    DataUtilities.GetPKValuesFromDataRow(rv.Row),
                    FPetraUtilsObject.MaxReferenceCountOnDelete,
                    out VerificationResults);
                int NumDataLabelUses = rv.Row[UsedByColumnOrdinal].ToString().Split(new char[] { ',' }).Length;

                // If there are more references we need to build a message and add it to our list
                if ((NumReferences > NumDataLabelUses) && (VerificationResults != null) && (VerificationResults.Count > 0))
                {
                    string groupName = rv.Row[FMainDS.PDataLabel.ColumnGroup].ToString();
                    string labelName = rv.Row[FMainDS.PDataLabel.ColumnText].ToString();
                    string strRowID  = groupName;

                    if (strRowID != String.Empty)
                    {
                        strRowID += " - ";
                    }

                    strRowID += labelName;

                    string msg = Messages.BuildMessageFromVerificationResult(
                        String.Format(
                            Catalog.GetString("The record '{0}' cannot be deleted!{1}{2}"),
                            strRowID,
                            Environment.NewLine,
                            Catalog.GetPluralString("Reason:", "Reasons:", VerificationResults.Count)),
                        VerificationResults);
                    msg += Catalog.GetString(
                        "You can ignore the references to the 'Data Label Use' table.  They will be removed automatically.  But you must resolve the other references before this row can be deleted.");

                    listConflicts.Add(msg);
                }
            }

            this.Cursor = Cursors.Default;

            // Did we get any conflicts?
            for (int i = 0; i < listConflicts.Count; i++)
            {
                if (i < listConflicts.Count - 1)
                {
                    // There is another one to show after this so include a chance for the user to quit...
                    if (MessageBox.Show(listConflicts[i] + Environment.NewLine + Environment.NewLine + "Do you want to see the next conflict?",
                                        Catalog.GetString("Record Deletion"), MessageBoxButtons.YesNo,
                                        MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.No)
                    {
                        break;
                    }
                }
                else
                {
                    MessageBox.Show(listConflicts[i], Catalog.GetString("Record Deletion"));
                }
            }

            if (listConflicts.Count == 0)
            {
                // All OK to delete the highlighted row(s) so call the standard method
                DeletePDataLabel();
            }
        }
Exemple #15
0
        /// <summary>
        /// Import a transactions file or a clipboard equivalent
        /// </summary>
        /// <param name="ACurrentBatchRow">The batch to import to</param>
        /// <param name="AImportSource">The import source - eg File or Clipboard</param>
        /// <returns>True if the import was successful</returns>
        public bool ImportTransactions(AGiftBatchRow ACurrentBatchRow, TGiftImportDataSourceEnum AImportSource)
        {
            bool           ok = false;
            bool           RefreshGUIAfterImport = false;
            OpenFileDialog dialog      = null;
            Boolean        IsPlainText = false;

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

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

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

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

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

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

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

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

                dialog.Title  = Catalog.GetString("Import Transactions from CSV File");
                dialog.Filter = Catalog.GetString("Gift Transactions files (*.csv)|*.csv|Text Files (*.txt)|*.txt");

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

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

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

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

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

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

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

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

                bool Repeat = true;

                while (Repeat)
                {
                    Repeat = false;

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

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

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

                    // if the import contains gifts with Motivation Group 'GIFT' and that have a Family recipient with no Gift Destination
                    // then the import will have failed and we need to alert the user
                    int numberOfMissingGiftDestinations = NeedRecipientLedgerNumber.Rows.Count;

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

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

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

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

                            if (MessageBox.Show(string.Format(
                                                    Catalog.GetString(
                                                        "Error: {0:0000} of {1:0000} - Recipient '{2}' ({3}) has no Gift Destination assigned."),
                                                    currentMissingGiftDestinationNo, numberOfMissingGiftDestinations, Row.RecipientDescription,
                                                    Row.RecipientKey) +
                                                "\n\n" +
                                                Catalog.GetString("Do you want to assign a Gift Destination to this partner now?"),
                                                Catalog.GetString("Gift Import Cancelled"), MessageBoxButtons.YesNo, MessageBoxIcon.Warning)
                                == DialogResult.Yes)
                            {
                                // allow the user to assign a Gift Destingation
                                TFrmGiftDestination GiftDestinationForm = new TFrmGiftDestination(FPetraUtilsObject.GetForm(), Row.RecipientKey);
                                GiftDestinationForm.ShowDialog();
                            }
                            else
                            {
                                offerToRunImportAgain = false;
                            }

                            currentMissingGiftDestinationNo++;
                        }

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

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

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

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

            return(false);
        }
        /// <summary>
        /// this supports the batch export files from Petra 2.x.
        /// Each line starts with a type specifier, B for batch, J for journal, T for transaction
        /// </summary>
        private void BtnOK_Click(object sender, EventArgs e)
        {
            FExportFileName = txtFilename.Text;
            String fileContents = string.Empty;
            Int32  budgetCount  = 0;

            if (txtFilename.Text == String.Empty)
            {
                MessageBox.Show(Catalog.GetString("Please choose a location for the Export File."),
                                Catalog.GetString("Error"),
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Error);
                return;
            }

            if (!Directory.Exists(Path.GetDirectoryName(FExportFileName)))
            {
                MessageBox.Show(Catalog.GetString("Please select an existing directory for this file!"),
                                Catalog.GetString("Error"),
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Error);

                FExportFileName = string.Empty;
                return;
            }

            if (File.Exists(FExportFileName))
            {
                if (MessageBox.Show(Catalog.GetString("The file already exists. Is it OK to overwrite it?"),
                                    Catalog.GetString("Export Budget"),
                                    MessageBoxButtons.YesNo,
                                    MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.No)
                {
                    return;
                }

                try
                {
                    File.Delete(FExportFileName);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(String.Format(
                                        Catalog.GetString(
                                            "Failed to delete the file. Maybe it is already open in another application?  The system message was:{0}{1}"),
                                        Environment.NewLine, ex.Message),
                                    Catalog.GetString("Export Budget"),
                                    MessageBoxButtons.OK,
                                    MessageBoxIcon.Error);
                    return;
                }
            }

            //Hashtable requestParams = new Hashtable();

            //requestParams.Add("ALedgerNumber", FLedgerNumber);
            //requestParams.Add("Delimiter", ConvertDelimiter(cmbDelimiter.GetSelectedString(), false));
            //requestParams.Add("DateFormatString", cmbDateFormat.GetSelectedString());
            //requestParams.Add("NumberFormat", ConvertNumberFormat(cmbNumberFormat));

            TVerificationResultCollection AMessages;

            string[] delims = new string[1];
            delims[0] = ConvertDelimiter(cmbDelimiter.GetSelectedString(), false);

            try
            {
                this.Cursor = Cursors.WaitCursor;

                budgetCount = TRemote.MFinance.Budget.WebConnectors.ExportBudgets(FLedgerNumber,
                                                                                  FExportFileName,
                                                                                  delims,
                                                                                  ref fileContents,
                                                                                  ref FBudgetDS,
                                                                                  out AMessages);

                this.Cursor = Cursors.Default;

                if ((AMessages != null) && (AMessages.Count > 0))
                {
                    if (!TVerificationHelper.IsNullOrOnlyNonCritical(AMessages))
                    {
                        MessageBox.Show(AMessages.BuildVerificationResultString(), Catalog.GetString("Error"),
                                        MessageBoxButtons.OK,
                                        MessageBoxIcon.Error);

                        FExportFileName = string.Empty;
                        return;
                    }
                    else
                    {
                        MessageBox.Show(AMessages.BuildVerificationResultString(), Catalog.GetString("Warnings"),
                                        MessageBoxButtons.OK,
                                        MessageBoxIcon.Information);
                    }
                }

                SaveUserDefaults();

                if (budgetCount == 0)
                {
                    MessageBox.Show(Catalog.GetString("There are no Budgets matching your criteria"),
                                    Catalog.GetString("Error"),
                                    MessageBoxButtons.OK,
                                    MessageBoxIcon.Error);

                    FExportFileName = string.Empty;
                    return;
                }

                StreamWriter sw1 = new StreamWriter(FExportFileName);
                sw1.Write(fileContents);
                sw1.Close();
            }
            catch (Exception ex)
            {
                TLogging.Log("ExportBudget.ManualCode: " + ex.ToString());
                MessageBox.Show(ex.Message,
                                Catalog.GetString("Error"),
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Error);

                return;
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }

            // Offer the client the chance to open the file in Excel or whatever
            if (MessageBox.Show(String.Format(Catalog.GetString(
                                                  "{0} Budget rows were exported successfully! Would you like to open the file in your default application?"),
                                              budgetCount.ToString()),
                                Catalog.GetString("Budget Export"),
                                MessageBoxButtons.YesNo,
                                MessageBoxIcon.Information,
                                MessageBoxDefaultButton.Button2) == System.Windows.Forms.DialogResult.Yes)
            {
                ProcessStartInfo si = new ProcessStartInfo(txtFilename.Text);
                si.UseShellExecute = true;
                si.Verb            = "open";

                Process p = new Process();
                p.StartInfo = si;
                p.Start();
            }

            Close();
        }
        /// <summary>
        /// Standard method to delete the Data Row whose Details are currently displayed.
        /// There is full support for multi-row deletion.
        /// Optional manual code can be included to take action prior, during or after each deletion.
        /// When the row(s) have been deleted the highlighted row index stays the same unless the deleted row was the last one.
        /// The Details for the newly highlighted row are automatically displayed - or not, if the grid has now become empty.
        /// </summary>
        private void DeletePPostcodeRegionRange()
        {
            string CompletionMessage = String.Empty;

            if ((FPreviouslySelectedRangeRow == null) || (FPrevRangeRowChangedRow == -1))
            {
                return;
            }

            DataRowView[] HighlightedRows = grdRanges.SelectedDataRowsAsDataRowView;

            if (HighlightedRows.Length == 1)
            {
                TVerificationResultCollection VerificationResults = null;

                if (TVerificationHelper.IsNullOrOnlyNonCritical(FPetraUtilsObject.VerificationResultCollection))
                {
                    this.Cursor = Cursors.WaitCursor;
                    TRemote.MPartner.ReferenceCount.WebConnectors.GetNonCacheableRecordReferenceCount(
                        FMainDS.PPostcodeRegionRange,
                        DataUtilities.GetPKValuesFromDataRow(FPreviouslySelectedRangeRow),
                        FPetraUtilsObject.MaxReferenceCountOnDelete,
                        out VerificationResults);
                    this.Cursor = Cursors.Default;
                }

                if ((VerificationResults != null) &&
                    (VerificationResults.Count > 0))
                {
                    MessageBox.Show(Messages.BuildMessageFromVerificationResult(
                                        Catalog.GetString("Record cannot be deleted!") +
                                        Environment.NewLine +
                                        Catalog.GetPluralString("Reason:", "Reasons:", VerificationResults.Count),
                                        VerificationResults),
                                    Catalog.GetString("Record Deletion"));
                    return;
                }

                string DeletionQuestion = Catalog.GetString("Are you sure you want to delete the current row?");

                if ((FPrimaryKeyControl != null) && (FPrimaryKeyLabel != null))
                {
                    DeletionQuestion += String.Format("{0}{0}({1} {2})",
                                                      Environment.NewLine,
                                                      "Range Name:",
                                                      FPreviouslySelectedRangeRow.Range);
                }

                bool AllowDeletion     = true;
                bool DeletionPerformed = false;

                if (AllowDeletion)
                {
                    if ((MessageBox.Show(DeletionQuestion,
                                         Catalog.GetString("Confirm Delete"),
                                         MessageBoxButtons.YesNo,
                                         MessageBoxIcon.Question,
                                         MessageBoxDefaultButton.Button2) == System.Windows.Forms.DialogResult.Yes))
                    {
                        try
                        {
                            FPreviouslySelectedRangeRow.Delete();
                            DeletionPerformed = true;
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(String.Format(Catalog.GetString("An error occurred while deleting this record.{0}{0}{1}"),
                                                          Environment.NewLine, ex.Message),
                                            Catalog.GetString("Error"),
                                            MessageBoxButtons.OK,
                                            MessageBoxIcon.Warning);
                        }

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

                        // Select and display the details of the nearest row to the one previously selected
                        grdRanges.SelectRowInGrid(FPrevRangeRowChangedRow, true);

                        // Clear any errors left over from  the deleted row
                        FPetraUtilsObject.VerificationResultCollection.Clear();
                    }
                }

                if (DeletionPerformed && (CompletionMessage.Length > 0))
                {
                    MessageBox.Show(CompletionMessage,
                                    Catalog.GetString("Deletion Completed"));
                }
            }
            else
            {
                string DeletionQuestion = String.Format(Catalog.GetString(
                                                            "Do you want to delete the {0} highlighted rows?{1}{1}"), HighlightedRows.Length, Environment.NewLine);
                DeletionQuestion += Catalog.GetString("Each record will be checked to confirm that it can be deleted.");

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

                    this.Cursor = Cursors.WaitCursor;

                    foreach (DataRowView drv in HighlightedRows)
                    {
                        PPostcodeRegionRangeRow rowToDelete = (PPostcodeRegionRangeRow)(drv.Row);
                        string rowDetails = MakePKValuesStringManual(rowToDelete);

                        TVerificationResultCollection VerificationResults = null;
                        TRemote.MPartner.ReferenceCount.WebConnectors.GetNonCacheableRecordReferenceCount(
                            FMainDS.PPostcodeRegionRange,
                            DataUtilities.GetPKValuesFromDataRow(rowToDelete),
                            FPetraUtilsObject.MaxReferenceCountOnDelete,
                            out VerificationResults);

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

                        bool AllowDeletion     = true;
                        bool DeletionPerformed = false;

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

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

                    this.Cursor = Cursors.Default;

                    // Select and display the details of the nearest row to the one previously selected
                    grdRanges.SelectRowInGrid(FPrevRangeRowChangedRow, true);

                    if ((recordsDeleted > 0) && (CompletionMessage.Length > 0))
                    {
                        MessageBox.Show(CompletionMessage,
                                        Catalog.GetString("Deletion Completed"));
                    }

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

                    if (recordsDeleted > 0)
                    {
                        string s1 = Catalog.GetPluralString("record", "records", recordsDeleted);
                        string s2 = Catalog.GetPluralString("was", "were", recordsDeleted);
                        results = String.Format(Catalog.GetString("{0} {1} {2} successfully deleted."), recordsDeleted, s1, s2);
                    }
                    else
                    {
                        results = "No records were deleted.";
                    }

                    if (recordsUndeletable > 0)
                    {
                        string s1 = Catalog.GetPluralString("record", "records", recordsUndeletable);
                        string s2 = Catalog.GetPluralString("it is marked", "they are marked", recordsUndeletable);
                        results += String.Format(Catalog.GetString("{0}{1} {2} could not be deleted because {3} as non-deletable."),
                                                 Environment.NewLine,
                                                 recordsUndeletable,
                                                 s1, s2);
                    }

                    if (recordsDeleteDisallowed > 0)
                    {
                        string s1 = Catalog.GetPluralString("record was not be deleted", "records were not be deleted", recordsUndeletable);
                        results += String.Format(Catalog.GetString("{0}{1} {2} because deletion was not allowed."),
                                                 Environment.NewLine,
                                                 recordsDeleteDisallowed,
                                                 s1);
                    }

                    bool showCancel = false;

                    if (listConflicts.Count > 0)
                    {
                        showCancel = true;
                        string s1 = Catalog.GetPluralString("record", "records", listConflicts.Count);
                        string s2 = Catalog.GetPluralString("it is referenced", "they are referenced", listConflicts.Count);
                        results += String.Format(Catalog.GetString("{0}{1} {2} could not be deleted because {3} by at least one other table."),
                                                 Environment.NewLine,
                                                 listConflicts.Count,
                                                 s1, s2);
                    }

                    if (listExceptions.Count > 0)
                    {
                        showCancel = true;
                        string s1 = Catalog.GetPluralString("record", "records", listExceptions.Count);
                        results += String.Format(Catalog.GetString("{0}{1} {2} could not be deleted because the delete action failed unexpectedly."),
                                                 Environment.NewLine,
                                                 listExceptions.Count,
                                                 s1);
                    }

                    if (showCancel)
                    {
                        results +=
                            String.Format(Catalog.GetString("{0}{0}Click OK to review the details, or Cancel to return direct to the data screen"),
                                          Environment.NewLine);

                        if (MessageBox.Show(results,
                                            Catalog.GetString("Delete Action Summary"),
                                            MessageBoxButtons.OKCancel,
                                            MessageBoxIcon.Warning) == System.Windows.Forms.DialogResult.OK)
                        {
                            ReviewMultiDeleteResults(listConflicts, Catalog.GetString("Rows in this table that are referenced by other tables"));
                            ReviewMultiDeleteResults(listExceptions, Catalog.GetString("Unexpected Exceptions"));
                        }
                    }
                    else
                    {
                        MessageBox.Show(results,
                                        Catalog.GetString("Delete Action Summary"),
                                        MessageBoxButtons.OK,
                                        MessageBoxIcon.Information);
                    }
                }
            }
        }
        /// <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);
        }
Exemple #19
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 ExportBatches(object sender, EventArgs e)
        {
            if (File.Exists(txtFilename.Text))
            {
                if (MessageBox.Show(Catalog.GetString("The file already exists. Is it OK to overwrite it?"),
                                    Catalog.GetString("Export Gifts"),
                                    MessageBoxButtons.YesNo,
                                    MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.No)
                {
                    return;
                }
            }

            StreamWriter sw1 = null;

            try
            {
                sw1 = new StreamWriter(txtFilename.Text,
                                       false,
                                       Encoding.GetEncoding(TAppSettingsManager.GetInt32("ExportGiftBatchEncoding", 1252)));
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message,
                                Catalog.GetString("Failed to open file"),
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Error);
                return;
            }

            try
            {
                if (rbtBatchNumberSelection.Checked)
                {
                    if (!txtBatchNumberStart.NumberValueInt.HasValue)
                    {
                        txtBatchNumberStart.NumberValueInt = 0;
                    }

                    if (!txtBatchNumberEnd.NumberValueInt.HasValue)
                    {
                        txtBatchNumberEnd.NumberValueInt = 999999;
                    }
                }
                else
                {
                    if ((dtpDateFrom.Text == "") || (dtpDateTo.Text == ""))
                    {
                        MessageBox.Show(Catalog.GetString("Start and end dates must be provided."),
                                        Catalog.GetString("Error"),
                                        MessageBoxButtons.OK,
                                        MessageBoxIcon.Error);
                        return;
                    }

                    if ((!dtpDateFrom.ValidDate()) || (!dtpDateTo.ValidDate()))  // If ValidDate fails, it displays a helpful message.
                    {
                        return;
                    }
                }

                String numberFormat = ConvertNumberFormat(cmbNumberFormat);
                String delimiter    = ConvertDelimiter(cmbDelimiter.GetSelectedString(), false);

                if (((numberFormat == "European") && (delimiter == ",")) || ((numberFormat == "American") && (delimiter == ".")))
                {
                    MessageBox.Show(Catalog.GetString("Numeric Decimal cannot be the same as the delimiter."),
                                    Catalog.GetString("Error"),
                                    MessageBoxButtons.OK,
                                    MessageBoxIcon.Error);
                    return;
                }

                Hashtable requestParams = new Hashtable();
                requestParams.Add("ALedgerNumber", FLedgerNumber);
                requestParams.Add("Delimiter", ConvertDelimiter(cmbDelimiter.GetSelectedString(), false));
                requestParams.Add("DateFormatString", cmbDateFormat.GetSelectedString());
                requestParams.Add("Summary", rbtSummary.Checked);
                requestParams.Add("IncludeUnposted", chkIncludeUnposted.Checked);
                requestParams.Add("bUseBaseCurrency", rbtBaseCurrency.Checked);
                requestParams.Add("TransactionsOnly", chkTransactionsOnly.Checked);
                requestParams.Add("RecipientNumber", Convert.ToInt64(txtDetailRecipientKey.Text));
                requestParams.Add("FieldNumber", Convert.ToInt64(txtDetailFieldKey.Text));
                requestParams.Add("DateForSummary", dtpDateSummary.Date);
                requestParams.Add("NumberFormat", ConvertNumberFormat(cmbNumberFormat));
                requestParams.Add("ExtraColumns", chkExtraColumns.Checked);

                if (rbtBatchNumberSelection.Checked)
                {
                    requestParams.Add("BatchNumberStart", txtBatchNumberStart.NumberValueInt);
                    requestParams.Add("BatchNumberEnd", txtBatchNumberEnd.NumberValueInt);
                }
                else
                {
                    requestParams.Add("BatchDateFrom", dtpDateFrom.Date);
                    requestParams.Add("BatchDateTo", dtpDateTo.Date);
                }

                TVerificationResultCollection AMessages = new TVerificationResultCollection();
                String exportString = null;
                Int32  BatchCount   = 0;

                Thread ExportThread = new Thread(() => ExportAllGiftBatchData(
                                                     requestParams,
                                                     out exportString,
                                                     out AMessages,
                                                     out BatchCount));

                using (TProgressDialog ExportDialog = new TProgressDialog(ExportThread))
                {
                    ExportDialog.ShowDialog();
                }

                if ((AMessages != null) &&
                    (AMessages.Count > 0))
                {
                    if (!TVerificationHelper.IsNullOrOnlyNonCritical(AMessages))
                    {
                        MessageBox.Show(AMessages.BuildVerificationResultString(), Catalog.GetString("Error"),
                                        MessageBoxButtons.OK,
                                        MessageBoxIcon.Error);
                        return;
                    }
                    else
                    {
                        MessageBox.Show(AMessages.BuildVerificationResultString(), Catalog.GetString("Warnings"),
                                        MessageBoxButtons.OK,
                                        MessageBoxIcon.Information);
                    }
                }

                if (BatchCount == 0)
                {
                    MessageBox.Show(Catalog.GetString("There are no batches matching your criteria"),
                                    Catalog.GetString("Error"),
                                    MessageBoxButtons.OK,
                                    MessageBoxIcon.Error);
                    return;
                }

                sw1.Write(exportString);
                sw1.Close();

                SaveUserDefaults();
                MessageBox.Show(Catalog.GetString("Gift Batches Exported successfully."),
                                Catalog.GetString("Gift Batch Export"),
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                TLogging.Log("GiftBatchExport.ManualCode: " + ex.ToString());
                MessageBox.Show(ex.Message,
                                Catalog.GetString("Error"),
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Error);
            }
            finally
            {
                sw1.Close();
            }
        }
Exemple #20
0
        /// <summary>
        /// Checks for data verification errors and displays appropriate error messages. Returns true in case there
        /// were no data verification errors, otherwise false.
        /// </summary>
        /// <param name="ARecordChangeVerification">Set this to true if this Method is called in the context of a record change
        /// in a Grid, otherwise set it to false.</param>
        /// <param name="AVerificationResultCollection">A <see cref="TVerificationResultCollection" /> to inspect for
        /// data verification errors.</param>
        /// <param name="ATypeWhichRaisesError">Instance of the calling WinForm.</param>
        /// <param name="ARestrictToTypeWhichRaisesError">Restricts the <see cref="TVerificationResult" />s that
        /// are considered by this Method to those whose <see cref="TVerificationResult.ResultContext" /> matches
        /// <paramref name="ARestrictToTypeWhichRaisesError"></paramref> (defaults to null).</param>
        /// <param name="AIgnoreWarnings">Set to true if Warnings are to be ignored (defaults to false).</param>
        /// <returns>True in case there were no data verification errors, otherwise false.</returns>
        public static bool ProcessAnyDataValidationErrors(bool ARecordChangeVerification,
                                                          TVerificationResultCollection AVerificationResultCollection,
                                                          Type ATypeWhichRaisesError, Type ARestrictToTypeWhichRaisesError = null, bool AIgnoreWarnings = false)
        {
            bool    ReturnValue = false;
            string  ErrorMessages;
            Control FirstErrorControl;
            object  FirstErrorContext;
            bool    RecordDeletionErrorsBecauseOfReference = false;

            // In case there were only warnings, we return true and record change/saving of data can go ahead,
            // otherwise false is returned to prevent record change/saving of data.
            if (TVerificationHelper.IsNullOrOnlyNonCritical(AVerificationResultCollection))
            {
                ReturnValue = true;
            }

            if (AVerificationResultCollection.HasCriticalOrNonCriticalErrors)
            {
                // Determine data validation message, and more
                AVerificationResultCollection.BuildScreenVerificationResultList(out ErrorMessages,
                                                                                out FirstErrorControl, out FirstErrorContext, true, ARestrictToTypeWhichRaisesError, AIgnoreWarnings);

                // Tell user that there are data validation errors if there are any
                if (ErrorMessages != String.Empty)
                {
                    if (ARecordChangeVerification)
                    {
                        TMessages.MsgRecordChangeVerificationError(ErrorMessages, ReturnValue, ATypeWhichRaisesError);
                    }
                    else
                    {
                        for (int Counter = 0; Counter < AVerificationResultCollection.Count; Counter++)
                        {
                            if (AVerificationResultCollection[Counter].ResultCode == CommonErrorCodes.ERR_RECORD_DELETION_NOT_POSSIBLE_REFERENCED)
                            {
                                RecordDeletionErrorsBecauseOfReference = true;
                                break;
                            }
                        }

                        if (!RecordDeletionErrorsBecauseOfReference)
                        {
                            TMessages.MsgFormSaveVerificationError(ErrorMessages, ReturnValue, ATypeWhichRaisesError);
                        }
                        else
                        {
                            TMessages.MsgFormSaveVerificationError(ErrorMessages,
                                                                   CommonErrorCodes.ERR_RECORD_DELETION_NOT_POSSIBLE_REFERENCED,
                                                                   ReturnValue, ATypeWhichRaisesError,
                                                                   true);
                        }
                    }

                    // Put Focus on first Control that an error was recorded for
                    if (FirstErrorControl != null)
                    {
                        FirstErrorControl.Focus();
                    }
                }
                else
                {
                    ReturnValue = true;
                }
            }
            else
            {
                ReturnValue = true;
            }

            return(ReturnValue);
        }
Exemple #21
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;
            }
        }
Exemple #22
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();
        }
        public static TSubmitChangesResult SaveData(string ATablename,
                                                    ref TTypedDataTable ASubmitTable, out TVerificationResultCollection AVerificationResult,
                                                    TDBTransaction AWriteTransaction)
        {
            AVerificationResult = null;

            // TODO: check write permissions
            string context = string.Format("SaveData {0}", SharedConstants.MODULE_ACCESS_MANAGER);

            if (ASubmitTable != null)
            {
                AVerificationResult = new TVerificationResultCollection();

                try
                {
                    if (ATablename == AAccountingPeriodTable.GetTableDBName())
                    {
                        AAccountingPeriodAccess.SubmitChanges((AAccountingPeriodTable)ASubmitTable, AWriteTransaction);

                        TCacheableTablesManager.GCacheableTablesManager.MarkCachedTableNeedsRefreshing(
                            TCacheableFinanceTablesEnum.AccountingPeriodList.ToString());
                    }
                    else if (ATablename == ACurrencyTable.GetTableDBName())
                    {
                        ACurrencyAccess.SubmitChanges((ACurrencyTable)ASubmitTable, AWriteTransaction);
                    }
                    else if (ATablename == ADailyExchangeRateTable.GetTableDBName())
                    {
                        TSecurityChecks.CheckUserModulePermissions(
                            string.Format("AND({0},{1})", SharedConstants.PETRAGROUP_FINANCE1, SharedConstants.PETRAMODULE_FINEXRATE),
                            context);
                        ADailyExchangeRateAccess.SubmitChanges((ADailyExchangeRateTable)ASubmitTable, AWriteTransaction);
                    }
                    else if (ATablename == ACorporateExchangeRateTable.GetTableDBName())
                    {
                        // AlanP:  I don't think this is used any more.  There is a TDS Save method instead
                        ACorporateExchangeRateAccess.SubmitChanges((ACorporateExchangeRateTable)ASubmitTable, AWriteTransaction);
                    }
                    else if (ATablename == ACurrencyLanguageTable.GetTableDBName())
                    {
                        ACurrencyLanguageAccess.SubmitChanges((ACurrencyLanguageTable)ASubmitTable, AWriteTransaction);
                    }
                    else if (ATablename == AFeesPayableTable.GetTableDBName())
                    {
                        AFeesPayableAccess.SubmitChanges((AFeesPayableTable)ASubmitTable, AWriteTransaction);

                        TCacheableTablesManager.GCacheableTablesManager.MarkCachedTableNeedsRefreshing(
                            TCacheableFinanceTablesEnum.FeesPayableList.ToString());
                    }
                    else if (ATablename == AFeesReceivableTable.GetTableDBName())
                    {
                        AFeesReceivableAccess.SubmitChanges((AFeesReceivableTable)ASubmitTable, AWriteTransaction);

                        TCacheableTablesManager.GCacheableTablesManager.MarkCachedTableNeedsRefreshing(
                            TCacheableFinanceTablesEnum.FeesReceivableList.ToString());
                    }
                    else if (ATablename == AGiftBatchTable.GetTableDBName())
                    {
                        // This method is called from ADailyExchangeRate Setup - please do not remove
                        // The method is not required for changes made to the gift batch screens, which use a TDS
                        AGiftBatchAccess.SubmitChanges((AGiftBatchTable)ASubmitTable, AWriteTransaction);
                    }
                    else if (ATablename == AJournalTable.GetTableDBName())
                    {
                        // This method is called from ADailyExchangeRate Setup - please do not remove
                        // The method is not required for changes made to the journal screens, which use a TDS
                        AJournalAccess.SubmitChanges((AJournalTable)ASubmitTable, AWriteTransaction);
                    }
                    else if (ATablename == ARecurringJournalTable.GetTableDBName())
                    {
                        // This method is called from Submit Recurring GL Batch form - please do not remove
                        // The method is not required for changes made to the journal screens, which use a TDS
                        ARecurringJournalAccess.SubmitChanges((ARecurringJournalTable)ASubmitTable, AWriteTransaction);
                    }
                    else if (ATablename == ALedgerTable.GetTableDBName())
                    {
                        // This method is called from ADailyExchangeRate Testing - please do not remove
                        ALedgerAccess.SubmitChanges((ALedgerTable)ASubmitTable, AWriteTransaction);
                    }
                    else if (ATablename == AAnalysisTypeTable.GetTableDBName())
                    {
                        AAnalysisTypeAccess.SubmitChanges((AAnalysisTypeTable)ASubmitTable, AWriteTransaction);
                    }
                    else if (ATablename == ASuspenseAccountTable.GetTableDBName())
                    {
                        ASuspenseAccountAccess.SubmitChanges((ASuspenseAccountTable)ASubmitTable, AWriteTransaction);

                        TCacheableTablesManager.GCacheableTablesManager.MarkCachedTableNeedsRefreshing(
                            TCacheableFinanceTablesEnum.SuspenseAccountList.ToString());
                    }
                    else if (ATablename == PcAttendeeTable.GetTableDBName())
                    {
                        PcAttendeeAccess.SubmitChanges((PcAttendeeTable)ASubmitTable, AWriteTransaction);
                    }
                    else if (ATablename == PcConferenceTable.GetTableDBName())
                    {
                        PcConferenceAccess.SubmitChanges((PcConferenceTable)ASubmitTable, AWriteTransaction);
                    }
                    else if (ATablename == PcConferenceCostTable.GetTableDBName())
                    {
                        PcConferenceCostAccess.SubmitChanges((PcConferenceCostTable)ASubmitTable, AWriteTransaction);
                    }
                    else if (ATablename == PcEarlyLateTable.GetTableDBName())
                    {
                        PcEarlyLateAccess.SubmitChanges((PcEarlyLateTable)ASubmitTable, AWriteTransaction);
                    }
                    else if (ATablename == PcSupplementTable.GetTableDBName())
                    {
                        PcSupplementAccess.SubmitChanges((PcSupplementTable)ASubmitTable, AWriteTransaction);
                    }
                    else if (ATablename == PcDiscountTable.GetTableDBName())
                    {
                        PcDiscountAccess.SubmitChanges((PcDiscountTable)ASubmitTable, AWriteTransaction);
                    }
                    else if (ATablename == PInternationalPostalTypeTable.GetTableDBName())
                    {
                        ValidateInternationalPostalType(ref AVerificationResult, ASubmitTable);
                        ValidateInternationalPostalTypeManual(ref AVerificationResult, ASubmitTable);

                        if (TVerificationHelper.IsNullOrOnlyNonCritical(AVerificationResult))
                        {
                            PInternationalPostalTypeAccess.SubmitChanges((PInternationalPostalTypeTable)ASubmitTable, AWriteTransaction);
                        }
                    }
                    else if (ATablename == PtApplicationTypeTable.GetTableDBName())
                    {
                        PtApplicationTypeAccess.SubmitChanges((PtApplicationTypeTable)ASubmitTable, AWriteTransaction);

                        // mark dependent lists for needing to be refreshed since there was a change in base list
                        TCacheableTablesManager.GCacheableTablesManager.MarkCachedTableNeedsRefreshing(
                            TCacheablePersonTablesEnum.EventApplicationTypeList.ToString());
                        TCacheableTablesManager.GCacheableTablesManager.MarkCachedTableNeedsRefreshing(
                            TCacheablePersonTablesEnum.FieldApplicationTypeList.ToString());
                    }
                    else if (ATablename == PFormTable.GetTableDBName())
                    {
                        PFormAccess.SubmitChanges((PFormTable)ASubmitTable, AWriteTransaction);
                    }
                    else if (ATablename == PFormalityTable.GetTableDBName())
                    {
                        PFormalityAccess.SubmitChanges((PFormalityTable)ASubmitTable, AWriteTransaction);
                    }
                    else if (ATablename == PMailingTable.GetTableDBName())
                    {
                        PMailingAccess.SubmitChanges((PMailingTable)ASubmitTable, AWriteTransaction);
                    }
                    else if (ATablename == PPartnerGiftDestinationTable.GetTableDBName())
                    {
                        PPartnerGiftDestinationAccess.SubmitChanges((PPartnerGiftDestinationTable)ASubmitTable, AWriteTransaction);
                    }
                    else if (ATablename == PmDocumentTypeTable.GetTableDBName())
                    {
                        PmDocumentTypeAccess.SubmitChanges((PmDocumentTypeTable)ASubmitTable, AWriteTransaction);
                    }
                    else if (ATablename == SGroupTable.GetTableDBName())
                    {
                        SGroupAccess.SubmitChanges((SGroupTable)ASubmitTable, AWriteTransaction);
                    }
                    else if (ATablename == SSystemDefaultsTable.GetTableDBName())
                    {
                        SSystemDefaultsAccess.SubmitChanges((SSystemDefaultsTable)ASubmitTable, AWriteTransaction);
                    }
                    else if (ATablename == SSystemDefaultsGuiTable.GetTableDBName())
                    {
                        SSystemDefaultsGuiAccess.SubmitChanges((SSystemDefaultsGuiTable)ASubmitTable, AWriteTransaction);
                    }
                    else
                    {
                        throw new EOPAppException("TCommonDataReader.SaveData: unknown table '" + ATablename + "'");
                    }
                }
                catch (Exception Exc)
                {
                    AVerificationResult.Add(
                        new TVerificationResult(null, "Cannot SubmitChanges:" + Environment.NewLine +
                                                Exc.Message, "UNDEFINED", TResultSeverity.Resv_Critical));
                }
            }

            if ((AVerificationResult != null) &&
                (AVerificationResult.Count > 0))
            {
                // Downgrade TScreenVerificationResults to TVerificationResults in order to allow
                // Serialisation (needed for .NET Remoting).
                TVerificationResultCollection.DowngradeScreenVerificationResults(AVerificationResult);

                return(AVerificationResult.HasCriticalErrors ? TSubmitChangesResult.scrError : TSubmitChangesResult.scrOK);
            }

            return(TSubmitChangesResult.scrOK);
        }
Exemple #24
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>
        /// <returns>True if the Export succeeded and a file was created, false otherwise</returns>
        public bool ExportBatches(bool AWithInteractionOnSuccess = true)
        {
            string ExportFileName = txtFilename.Text;

            if (ExportFileName == String.Empty)
            {
                MessageBox.Show(Catalog.GetString("Please choose a location for the Export File."),
                                Catalog.GetString("Error"),
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Error);
                return(false);
            }
            else if (!ExportFileName.EndsWith(".csv",
                                              StringComparison.CurrentCultureIgnoreCase) && !ExportFileName.EndsWith(".txt", StringComparison.CurrentCultureIgnoreCase))
            {
                ExportFileName  += ".csv";
                txtFilename.Text = ExportFileName;
            }

            if (!Directory.Exists(Path.GetDirectoryName(ExportFileName)))
            {
                MessageBox.Show(Catalog.GetString("Please select an existing directory for this file!"),
                                Catalog.GetString("Error"),
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Error);

                txtFilename.Text = string.Empty;
                return(false);
            }

            if (File.Exists(ExportFileName))
            {
                if (MessageBox.Show(Catalog.GetString("The file already exists. Is it OK to overwrite it?"),
                                    Catalog.GetString("Export Gifts"),
                                    MessageBoxButtons.YesNo,
                                    MessageBoxIcon.Question,
                                    MessageBoxDefaultButton.Button2) == System.Windows.Forms.DialogResult.No)
                {
                    return(false);
                }

                try
                {
                    File.Delete(ExportFileName);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(String.Format(
                                        Catalog.GetString(
                                            "Failed to delete the file. Maybe it is already open in another application?  The system message was:{0}{1}"),
                                        Environment.NewLine, ex.Message),
                                    Catalog.GetString("Export Gift Batches"),
                                    MessageBoxButtons.OK,
                                    MessageBoxIcon.Error);
                    return(false);
                }
            }

            if (rbtBatchNumberSelection.Checked)
            {
                if (!txtBatchNumberStart.NumberValueInt.HasValue)
                {
                    txtBatchNumberStart.NumberValueInt = 0;
                }

                if (!txtBatchNumberEnd.NumberValueInt.HasValue)
                {
                    txtBatchNumberEnd.NumberValueInt = 999999;
                }
            }
            else
            {
                if ((dtpDateFrom.Text == string.Empty) || (dtpDateTo.Text == string.Empty))
                {
                    MessageBox.Show(Catalog.GetString("Start and end dates must be provided."),
                                    Catalog.GetString("Error"),
                                    MessageBoxButtons.OK,
                                    MessageBoxIcon.Error);
                    return(false);
                }

                if ((!dtpDateFrom.ValidDate()) || (!dtpDateTo.ValidDate()))  // If ValidDate fails, it displays a helpful message.
                {
                    return(false);
                }
            }

            String numberFormat = ConvertNumberFormat(cmbNumberFormat);
            String delimiter    = ConvertDelimiter(cmbDelimiter.GetSelectedString(), false);

            if (((numberFormat == "European") && (delimiter == ",")) || ((numberFormat == "American") && (delimiter == ".")))
            {
                MessageBox.Show(Catalog.GetString("Numeric Decimal cannot be the same as the delimiter."),
                                Catalog.GetString("Error"),
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Error);
                return(false);
            }

            try
            {
                Hashtable requestParams = new Hashtable();
                requestParams.Add("ALedgerNumber", FLedgerNumber);
                requestParams.Add("Delimiter", delimiter);
                requestParams.Add("DateFormatString", cmbDateFormat.GetSelectedString());
                requestParams.Add("Summary", rbtSummary.Checked);
                requestParams.Add("IncludeUnposted", chkIncludeUnposted.Checked);
                requestParams.Add("bUseBaseCurrency", rbtBaseCurrency.Checked);
                requestParams.Add("TransactionsOnly", chkTransactionsOnly.Checked);
                requestParams.Add("RecipientNumber", Convert.ToInt64(txtDetailRecipientKey.Text));
                requestParams.Add("FieldNumber", Convert.ToInt64(txtDetailFieldKey.Text));
                requestParams.Add("DateForSummary", dtpDateSummary.Date);
                requestParams.Add("NumberFormat", numberFormat);
                requestParams.Add("ExtraColumns", chkExtraColumns.Checked);

                if (rbtBatchNumberSelection.Checked)
                {
                    requestParams.Add("BatchNumberStart", txtBatchNumberStart.NumberValueInt);
                    requestParams.Add("BatchNumberEnd", txtBatchNumberEnd.NumberValueInt);
                }
                else
                {
                    requestParams.Add("BatchDateFrom", dtpDateFrom.Date);
                    requestParams.Add("BatchDateTo", dtpDateTo.Date);
                }

                TVerificationResultCollection AMessages = new TVerificationResultCollection();
                String exportString = null;
                Int32  BatchCount   = 0;

                Thread ExportThread = new Thread(() => ExportAllGiftBatchData(
                                                     requestParams,
                                                     out exportString,
                                                     out AMessages,
                                                     out BatchCount));

                using (TProgressDialog ExportDialog = new TProgressDialog(ExportThread))
                {
                    ExportDialog.ShowDialog();
                }

                if ((AMessages != null) &&
                    (AMessages.Count > 0))
                {
                    if (!TVerificationHelper.IsNullOrOnlyNonCritical(AMessages))
                    {
                        MessageBox.Show(AMessages.BuildVerificationResultString(), Catalog.GetString("Error"),
                                        MessageBoxButtons.OK,
                                        MessageBoxIcon.Error);
                        return(false);
                    }
                    else
                    {
                        MessageBox.Show(AMessages.BuildVerificationResultString(), Catalog.GetString("Warnings"),
                                        MessageBoxButtons.OK,
                                        MessageBoxIcon.Information);
                    }
                }

                SaveUserDefaults();

                //Process BatchCount value
                if (BatchCount == 0)
                {
                    MessageBox.Show(Catalog.GetString("There are no batches matching your criteria"),
                                    Catalog.GetString("Export"),
                                    MessageBoxButtons.OK,
                                    MessageBoxIcon.Exclamation);
                    return(false);
                }
                else if (BatchCount == -1)
                {
                    MessageBox.Show(Catalog.GetString("Gift batch export cancelled"),
                                    Catalog.GetString("Export"),
                                    MessageBoxButtons.OK,
                                    MessageBoxIcon.Information);
                    return(false);
                }
                else if (BatchCount == -2)
                {
                    MessageBox.Show(Catalog.GetString("Gift batch export failed"),
                                    Catalog.GetString("Export"),
                                    MessageBoxButtons.OK,
                                    MessageBoxIcon.Warning);
                    return(false);
                }

                StreamWriter sw1 = new StreamWriter(ExportFileName,
                                                    false,
                                                    Encoding.GetEncoding(TAppSettingsManager.GetInt32("ExportGiftBatchEncoding", 1252)));
                sw1.Write(exportString);
                sw1.Close();
            }
            catch (Exception ex)
            {
                TLogging.LogException(ex, Utilities.GetMethodSignature());
                throw;
            }

            bool ShowExportedFileInExplorer = false;

            if (AWithInteractionOnSuccess)
            {
                if (MessageBox.Show(Catalog.GetString(
                                        "Gift Batches Exported successfully. Would you like to open the file in your default application?"),
                                    Catalog.GetString("Gift Batch Export"),
                                    MessageBoxButtons.YesNo,
                                    MessageBoxIcon.Information,
                                    MessageBoxDefaultButton.Button2) == System.Windows.Forms.DialogResult.Yes)
                {
                    try
                    {
                        ProcessStartInfo si = new ProcessStartInfo(ExportFileName);
                        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: '") + ExportFileName + "'!", Catalog.GetString(
                                            "Gift Export"), MessageBoxButtons.OK, MessageBoxIcon.Exclamation);

                        ShowExportedFileInExplorer = true;
                    }
                }
            }
            else
            {
                ShowExportedFileInExplorer = true;
            }

            if (ShowExportedFileInExplorer)
            {
                //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}\"", ExportFileName));
                    }
                    catch
                    {
                        MessageBox.Show(Catalog.GetString(
                                            "Unable to launch Windows File Explorer to open: '") + ExportFileName + "'!", Catalog.GetString(
                                            "Gift Export"), MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    }
                }
            }

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

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

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

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

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

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

                    FdlgSeparator.CSVData = importString;
                }
                else if (AImportDataSource == TImportDataSourceEnum.FromFile)
                {
                    dialog = new OpenFileDialog();

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

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

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

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

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

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

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

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

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

                    TVerificationResultCollection AMessages = new TVerificationResultCollection();

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

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

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

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

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

                if (ok)
                {
                    FMyUserControl.ReloadBatches();
                    FMyForm.GetBatchControl().SelectRowInGrid(1);
                    FPetraUtilsObject.SetChangedFlag();
                    FMyForm.SaveChangesManual(FMyForm.FCurrentGLBatchAction);
                }
                else if (RefreshGUIAfterImport)
                {
                    // The import failed and the server needs us to refresh the GUI
                    FMyUserControl.ReloadBatches(true);
                    FMyForm.GetBatchControl().SelectRowInGrid(1);
                }
            }
            finally
            {
                FMyForm.FCurrentGLBatchAction = TGLBatchEnums.GLBatchAction.NONE;
            }
        }
Exemple #26
0
        public static bool MaintainBankAccounts(
            string action,
            Int32 ABankingDetailsKey,
            Int64 APartnerKey,
            string AAccountName,
            string AIban,
            out TVerificationResultCollection AVerificationResult)
        {
            List <string>  Dummy1, Dummy2;
            string         Dummy3, Dummy4, Dummy5;
            PartnerEditTDS MainDS = GetPartnerDetails(APartnerKey, out Dummy1, out Dummy2, out Dummy3, out Dummy4, out Dummy5);

            AVerificationResult = new TVerificationResultCollection();

            AIban = AIban.Replace(" ", "");
            string BIC      = String.Empty;
            string BankName = String.Empty;

            if ((action == "create" || action == "edit"))
            {
                // Validate IBAN, and calculate the BIC
                if (!ValidateIBAN(AIban, out BIC, out BankName, out AVerificationResult))
                {
                    return(false);
                }
            }

            if (action == "create")
            {
                PartnerEditTDSPBankingDetailsRow row = MainDS.PBankingDetails.NewRowTyped();
                row.BankingDetailsKey = -1;
                row.BankingType       = 0; // BANK ACCOUNT
                row.AccountName       = AAccountName;
                row.Iban        = AIban;
                row.BankKey     = FindOrCreateBank(BIC, BankName);
                row.MainAccount = MainDS.PBankingDetails.Count == 0;
                MainDS.PBankingDetails.Rows.Add(row);

                PPartnerBankingDetailsRow pdrow = MainDS.PPartnerBankingDetails.NewRowTyped();
                pdrow.PartnerKey        = APartnerKey;
                pdrow.BankingDetailsKey = -1;
                MainDS.PPartnerBankingDetails.Rows.Add(pdrow);

                DataSet ResponseDS = new PartnerEditTDS();
                TPartnerEditUIConnector uiconnector = new TPartnerEditUIConnector(APartnerKey);

                try
                {
                    TSubmitChangesResult result = uiconnector.SubmitChanges(
                        ref MainDS,
                        ref ResponseDS,
                        out AVerificationResult);

                    return(result == TSubmitChangesResult.scrOK);
                }
                catch (Exception e)
                {
                    TLogging.Log(e.ToString());
                    AVerificationResult.Add(new TVerificationResult("error", e.Message, TResultSeverity.Resv_Critical));
                    return(false);
                }
            }
            else if (action == "edit")
            {
                foreach (PartnerEditTDSPBankingDetailsRow row in MainDS.PBankingDetails.Rows)
                {
                    if (row.BankingDetailsKey == ABankingDetailsKey)
                    {
                        row.AccountName = AAccountName;
                        row.Iban        = AIban;
                        row.BankKey     = FindOrCreateBank(BIC, BankName);
                    }
                }

                DataSet ResponseDS = new PartnerEditTDS();
                TPartnerEditUIConnector uiconnector = new TPartnerEditUIConnector(APartnerKey);

                try
                {
                    TSubmitChangesResult result = uiconnector.SubmitChanges(
                        ref MainDS,
                        ref ResponseDS,
                        out AVerificationResult);

                    return(result == TSubmitChangesResult.scrOK);
                }
                catch (Exception e)
                {
                    TLogging.Log(e.ToString());
                    AVerificationResult.Add(new TVerificationResult("error", e.Message, TResultSeverity.Resv_Critical));
                    return(false);
                }
            }
            else if (action == "delete")
            {
                foreach (PPartnerBankingDetailsRow row in MainDS.PPartnerBankingDetails.Rows)
                {
                    if (row.BankingDetailsKey == ABankingDetailsKey)
                    {
                        row.Delete();
                    }
                }

                bool wasMainAccount = false;
                PartnerEditTDSPBankingDetailsRow otherAccount = null;
                foreach (PartnerEditTDSPBankingDetailsRow row in MainDS.PBankingDetails.Rows)
                {
                    if (row.BankingDetailsKey == ABankingDetailsKey)
                    {
                        if (!row.IsMainAccountNull())
                        {
                            wasMainAccount = row.MainAccount;
                        }
                        row.Delete();
                    }
                    else if (otherAccount == null)
                    {
                        otherAccount = row;
                    }
                }

                // make another bank account the main account
                if (wasMainAccount && (otherAccount != null))
                {
                    otherAccount.MainAccount = true;
                }

                DataSet ResponseDS = new PartnerEditTDS();
                TPartnerEditUIConnector uiconnector = new TPartnerEditUIConnector(APartnerKey);

                try
                {
                    TSubmitChangesResult result = uiconnector.SubmitChanges(
                        ref MainDS,
                        ref ResponseDS,
                        out AVerificationResult);

                    return(result == TSubmitChangesResult.scrOK);
                }
                catch (Exception e)
                {
                    TLogging.Log(e.ToString());
                    AVerificationResult.Add(new TVerificationResult("error", e.Message, TResultSeverity.Resv_Critical));
                    return(false);
                }
            }

            if (!TVerificationHelper.IsNullOrOnlyNonCritical(AVerificationResult))
            {
                TLogging.Log(AVerificationResult.BuildVerificationResultString());
            }

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

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

            string CompletionMessage = String.Empty;

            DataRowView[] HighlightedRows = AGrid.SelectedDataRowsAsDataRowView;

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

                TVerificationResultCollection VerificationResults = null;

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

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

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

                    return(false);
                }

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

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

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

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

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

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

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

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

                int recordsDeleted = 0;

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

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

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

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

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

                        string rowDetails = MakePKValuesString(rowToDelete);

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

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

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

                        bool AllowDeletion     = true;
                        bool DeletionPerformed = false;

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

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

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

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

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

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

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

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

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

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

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

                    bool showCancel = false;

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

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

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

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

                return(recordsDeleted > 0);
            }
        }
Exemple #28
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) &&
                             TVerificationHelper.ResultsContainErrorCode(FVerificationResultsOfMerge,
                                                                         PetraErrorCodes.ERR_DB_SERIALIZATION_EXCEPTION))
                    {
                        TConcurrentServerTransactions.ShowTransactionSerializationExceptionDialog();
                        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();
            }
        }