/// <summary> /// create a new batch with a consecutive batch number in the ledger /// for call inside a server function /// for performance reasons submitting (save the data in the database) is done later (not here) /// </summary> /// <param name="AMainDS"></param> /// <param name="ATransaction"></param> /// <param name="ALedgerTbl"></param> /// <param name="ALedgerNumber"></param> /// <param name="ADateEffective"></param> /// <param name="AForceEffectiveDateToFit"></param> /// <returns>the new gift batch row</returns> public static AGiftBatchRow CreateANewGiftBatchRow(ref GiftBatchTDS AMainDS, ref TDBTransaction ATransaction, ref ALedgerTable ALedgerTbl, Int32 ALedgerNumber, DateTime ADateEffective, bool AForceEffectiveDateToFit = true) { #region Validate Arguments if (AMainDS == null) { throw new EFinanceSystemDataObjectNullOrEmptyException(String.Format(Catalog.GetString( "Function:{0} - The Gift Batch dataset is NULL!"), Utilities.GetMethodName(true))); } else if (ATransaction == null) { throw new EFinanceSystemDBTransactionNullException(String.Format(Catalog.GetString( "Function:{0} - Database Transaction must not be NULL!"), Utilities.GetMethodName(true))); } else if ((ALedgerTbl == null) || (ALedgerTbl.Count == 0)) { throw new EFinanceSystemDataObjectNullOrEmptyException(String.Format(Catalog.GetString( "Function:{0} - The Ledger table is NULL or is empty!"), Utilities.GetMethodName(true))); } else if (ALedgerNumber <= 0) { throw new EFinanceSystemInvalidLedgerNumberException(String.Format(Catalog.GetString( "Function:{0} - The Ledger number must be greater than 0!"), Utilities.GetMethodName(true)), ALedgerNumber); } #endregion Validate Arguments AGiftBatchRow NewRow = null; try { NewRow = AMainDS.AGiftBatch.NewRowTyped(true); NewRow.LedgerNumber = ALedgerNumber; NewRow.BatchNumber = ++ALedgerTbl[0].LastGiftBatchNumber; Int32 BatchYear, BatchPeriod; // if DateEffective is outside the range of open periods, use the most fitting date TFinancialYear.GetLedgerDatePostingPeriod(ALedgerNumber, ref ADateEffective, out BatchYear, out BatchPeriod, ATransaction, AForceEffectiveDateToFit); TLedgerInfo info = new TLedgerInfo(ALedgerNumber, ATransaction.DataBaseObj); NewRow.BatchYear = BatchYear; NewRow.BatchPeriod = BatchPeriod; NewRow.GlEffectiveDate = ADateEffective; NewRow.ExchangeRateToBase = 1.0M; NewRow.BatchDescription = "PLEASE ENTER A DESCRIPTION"; NewRow.BankAccountCode = info.GetDefaultBankAccount(); NewRow.BankCostCentre = info.GetStandardCostCentre(); NewRow.CurrencyCode = ALedgerTbl[0].BaseCurrency; AMainDS.AGiftBatch.Rows.Add(NewRow); } catch (Exception ex) { TLogging.LogException(ex, Utilities.GetMethodSignature()); throw; } return(NewRow); }
/// <summary> /// Imports budgets from a file /// </summary> /// <param name="ACurrentBudgetYear"></param> /// <param name="AMainDS"></param> public void ImportBudget(int ACurrentBudgetYear, ref BudgetTDS AMainDS) { TVerificationResultCollection Messages = new TVerificationResultCollection(); int BudgetsImported = 0; int BudgetsAdded = 0; int BudgetsUpdated = 0; int BudgetsFailed = 0; if (FPetraUtilsObject.HasChanges) { // saving failed, therefore do not try to post MessageBox.Show(Catalog.GetString("Please save before trying to import!"), Catalog.GetString( "Failure"), MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return; } String DateFormatString = TUserDefaults.GetStringDefault("Imp Date", "MDY"); OpenFileDialog OFDialog = new OpenFileDialog(); string ExportPath = TClientSettings.GetExportPath(); string FullPath = TUserDefaults.GetStringDefault("Imp Filename", ExportPath + Path.DirectorySeparatorChar + "import.csv"); TImportExportDialogs.SetOpenFileDialogFilePathAndName(OFDialog, FullPath, ExportPath); OFDialog.Title = Catalog.GetString("Import budget(s) from CSV file"); OFDialog.Filter = Catalog.GetString("Text Files(*.txt) | *.txt | Delimited Files(*.csv) | *.csv"); String ImportOptions = TUserDefaults.GetStringDefault("Imp Options", ";" + TDlgSelectCSVSeparator.NUMBERFORMAT_AMERICAN); // This call fixes Windows7 Open File Dialogs. It must be the line before ShowDialog() TWin7FileOpenSaveDialog.PrepareDialog(Path.GetFileName(FullPath)); if (OFDialog.ShowDialog() == DialogResult.OK) { TFrmStatusDialog dlgStatus = new TFrmStatusDialog(FPetraUtilsObject.GetForm()); FdlgSeparator = new TDlgSelectCSVSeparator(false); try { string fileTitle = OFDialog.SafeFileName; Boolean fileCanOpen = FdlgSeparator.OpenCsvFile(OFDialog.FileName); if (!fileCanOpen) { MessageBox.Show(Catalog.GetString("Unable to open file."), Catalog.GetString("Budget Import"), MessageBoxButtons.OK, MessageBoxIcon.Stop); return; } FdlgSeparator.DateFormat = DateFormatString; if (ImportOptions.Length > 1) { FdlgSeparator.NumberFormat = ImportOptions.Substring(1); } FdlgSeparator.SelectedSeparator = ImportOptions.Substring(0, 1); if (FdlgSeparator.ShowDialog() == DialogResult.OK) { string[] FdlgSeparatorVal = new string[] { FdlgSeparator.SelectedSeparator, FdlgSeparator.DateFormat, FdlgSeparator.NumberFormat }; Application.UseWaitCursor = true; //New set of budgets to be loaded dlgStatus.Show(); dlgStatus.Heading = Catalog.GetString("Budget Import"); dlgStatus.CurrentStatus = Catalog.GetString("Importing budgets from '" + fileTitle + "' ..."); // read contents of file string ImportString = File.ReadAllText(OFDialog.FileName); //TODO return the budget from the year, and -99 for fail BudgetsImported = TRemote.MFinance.Budget.WebConnectors.ImportBudgets(FLedgerNumber, ImportString, OFDialog.FileName, FdlgSeparatorVal, ref AMainDS, out BudgetsAdded, out BudgetsUpdated, out BudgetsFailed, out Messages); dlgStatus.Visible = false; Application.UseWaitCursor = false; ShowMessages(Messages, BudgetsImported, BudgetsAdded, BudgetsUpdated, BudgetsFailed); } // We save the defaults even if ok is false - because the client will probably want to try and import // the same file again after correcting any errors SaveUserDefaults(OFDialog, ImportOptions); } catch (Exception ex) { TLogging.LogException(ex, Utilities.GetMethodSignature()); throw; } finally { Application.UseWaitCursor = false; } // update grid if ((BudgetsAdded + BudgetsUpdated) > 0) { try { dlgStatus.CurrentStatus = Catalog.GetString("Updating budget period data..."); dlgStatus.Visible = true; Application.UseWaitCursor = true; UpdateABudgetPeriodAmounts(AMainDS, ACurrentBudgetYear); FUserControl.SetBudgetDefaultView(AMainDS); } finally { Application.UseWaitCursor = false; dlgStatus.Close(); } FPetraUtilsObject.SetChangedFlag(); } else { dlgStatus.Close(); } } }
/// <summary> /// using the calendar of the ledger to determine the financial period at the given date. /// </summary> /// <param name="ALedgerNumber"></param> /// <param name="ADateToTest"></param> /// <param name="AFinancialYear"></param> /// <param name="AFinancialPeriod"></param> /// <param name="ATransaction"></param> /// <param name="ADoFixDate">do you want to fix the date if it is outside the open periods; /// if the date is outside of the open periods, the date will be changed to the most appropriate date: /// if the original date is before the posting period, the first available date in the posting period will be returned, /// otherwise the last possible date</param> /// <returns>false if date needed to change</returns> public static bool GetLedgerDatePostingPeriod(Int32 ALedgerNumber, ref DateTime ADateToTest, out Int32 AFinancialYear, out Int32 AFinancialPeriod, TDBTransaction ATransaction, bool ADoFixDate) { #region Validate Arguments if (ALedgerNumber <= 0) { throw new EFinanceSystemInvalidLedgerNumberException(String.Format(Catalog.GetString( "Function:{0} - The Ledger number must be greater than 0!"), Utilities.GetMethodName(true)), ALedgerNumber); } else if (ATransaction == null) { throw new EFinanceSystemDBTransactionNullException(String.Format(Catalog.GetString( "Function:{0} - Database Transaction must not be NULL!"), Utilities.GetMethodName(true))); } #endregion Validate Arguments bool RetVal = false; AFinancialPeriod = -1; AFinancialYear = -1; AAccountingPeriodRow currentPeriodRow = null; AAccountingPeriodRow lastAllowedPeriodRow = null; ALedgerTable LedgerTable = ALedgerAccess.LoadByPrimaryKey(ALedgerNumber, ATransaction); AAccountingPeriodTable AccountingPeriodTable = AAccountingPeriodAccess.LoadViaALedger(ALedgerNumber, ATransaction); #region Validate Data if ((LedgerTable == null) || (LedgerTable.Count == 0)) { throw new EFinanceSystemDataTableReturnedNoDataException(String.Format(Catalog.GetString( "Function:{0} - Ledger data for Ledger number {1} does not exist or could not be accessed!"), Utilities.GetMethodName(true), ALedgerNumber)); } else if ((AccountingPeriodTable == null) || (AccountingPeriodTable.Count == 0)) { throw new EFinanceSystemDataTableReturnedNoDataException(String.Format(Catalog.GetString( "Function:{0} - Accounting Period data for Ledger number {1} does not exist or could not be accessed!"), Utilities.GetMethodName(true), ALedgerNumber)); } #endregion Validate Data try { int aCurrentPeriod = LedgerTable[0].CurrentPeriod; int anAllowedForwardPeriod = aCurrentPeriod + LedgerTable[0].NumberFwdPostingPeriods; foreach (AAccountingPeriodRow row in AccountingPeriodTable.Rows) { if (row.AccountingPeriodNumber == aCurrentPeriod) { currentPeriodRow = row; } if (row.AccountingPeriodNumber == anAllowedForwardPeriod) { lastAllowedPeriodRow = row; } if ((row.PeriodStartDate <= ADateToTest) && (ADateToTest <= row.PeriodEndDate)) { // check if this period is either the current period or one of the forward posting periods if (LedgerTable.Count == 1) { AFinancialPeriod = row.AccountingPeriodNumber; //This is the number of the period to which the "DateToTest" belongs //This can be // 1.) before the current period or in the last financial year // => FIX Date to be the first day of the current period // 2.) greater oder eqal currentperiod but within AllowedForwardperiod = no FIX required // 3.) after the allowed Forward period or even in a future financial year: = FIX Date to be the last day of the last allowed forward period if ((AFinancialPeriod >= aCurrentPeriod) && (AFinancialPeriod <= anAllowedForwardPeriod)) { AFinancialYear = LedgerTable[0].CurrentFinancialYear; RetVal = true; break; } } } } if (ADoFixDate && !RetVal) { if (ADateToTest < currentPeriodRow.PeriodStartDate) { ADateToTest = currentPeriodRow.PeriodStartDate; AFinancialYear = LedgerTable[0].CurrentFinancialYear; AFinancialPeriod = currentPeriodRow.AccountingPeriodNumber; } else { if (lastAllowedPeriodRow == null) { lastAllowedPeriodRow = AccountingPeriodTable[AccountingPeriodTable.Rows.Count - 1]; } if (ADateToTest > lastAllowedPeriodRow.PeriodEndDate) { ADateToTest = lastAllowedPeriodRow.PeriodEndDate; AFinancialYear = LedgerTable[0].CurrentFinancialYear; AFinancialPeriod = lastAllowedPeriodRow.AccountingPeriodNumber; } } } } catch (Exception ex) { TLogging.LogException(ex, Utilities.GetMethodSignature()); throw; } return(RetVal); }
/// <summary> /// Deletes the current row and optionally populates a completion message /// </summary> /// <param name="ARowToDelete">the currently selected row to delete</param> /// <param name="AFPrevRow">Is FPreviouslySelectedDetailRow</param> /// <param name="ACompletionMessage">if specified, is the deletion completion message</param> /// <returns>true if row deletion is successful</returns> public bool DeleteRowManual(ARecurringGiftBatchRow ARowToDelete, ref ARecurringGiftBatchRow AFPrevRow, ref string ACompletionMessage) { bool DeletionSuccessful = false; if (ARowToDelete == null) { return(DeletionSuccessful); } int BatchNumber = ARowToDelete.BatchNumber; ACompletionMessage = string.Empty; bool RowToDeleteIsNew = (ARowToDelete.RowState == DataRowState.Added); //Backup the Dataset for reversion purposes GiftBatchTDS BackupMainDS = (GiftBatchTDS)FMainDS.Copy(); BackupMainDS.Merge(FMainDS); if (!RowToDeleteIsNew) { //Return modified row to last saved state to avoid validation failures ARowToDelete.RejectChanges(); if (!FMyForm.SaveChangesManual(TExtraGiftBatchChecks.GiftBatchAction.DELETING)) { MessageBox.Show(Catalog.GetString("Error in trying to save prior to deleting current recurring gift batch!"), Catalog.GetString("Deletion Error"), MessageBoxButtons.OK, MessageBoxIcon.Error); return(DeletionSuccessful); } } try { FMyForm.Cursor = Cursors.WaitCursor; ACompletionMessage = String.Format(Catalog.GetString("Batch no.: {0} deleted successfully."), BatchNumber); //clear any transactions currently being editied in the Transaction Tab FMyForm.GetTransactionsControl().ClearCurrentSelection(); if (!RowToDeleteIsNew) { //Load tables afresh FMainDS.Merge(TRemote.MFinance.Gift.WebConnectors.LoadRecurringGiftTransactionsForBatch(FLedgerNumber, BatchNumber)); } FMyForm.GetTransactionsControl().DeleteCurrentRecurringBatchGiftData(BatchNumber); // Delete the recurring batch row. ARowToDelete.Delete(); AFPrevRow = null; DeletionSuccessful = true; } catch (Exception ex) { //Revert to previous state FMainDS.Merge(BackupMainDS); ACompletionMessage = ex.Message; MessageBox.Show(ACompletionMessage, "Deletion Error", MessageBoxButtons.OK, MessageBoxIcon.Error); TLogging.LogException(ex, Utilities.GetMethodSignature()); throw; } finally { FMyForm.Cursor = Cursors.Default; } return(DeletionSuccessful); }
/// <summary> /// Send an email message /// </summary> /// <param name="AEmail">On successful sending, the header is modified with the sent date.</param> /// <returns>True if email was sent successfully.</returns> public bool SendMessage(MimeMessage AEmail) { if (AEmail.Headers["Date-Sent"] != null) { // don't send emails several times return(false); } FFailedRecipients.Clear(); //Attempt to send the email // FIXME!! Some SMTP servers have a message rate limit, so if a message is rejected because we have exceeded the maximum number // of messages per minute, we need to wait and retry (https://tracker.openpetra.org/view.php?id=3179). Unfortunately the solution // here doesn't check what _kind_ of error occurred. So for a permanent error like incorrect credentials... for 100 HOSAs... it // will happily retry one after another for 5 hours before telling the user they all failed. // // You can catch the SmtpClient exceptions and check the StatusCode enum to get a better idea of the problem. The numeric values of // the enum match SMTP error codes as shown below. Codes in the 400 range are generally 'temporary' failures while codes in the 500 // range are usually'permanent'. It's more complicated than it should be because: // i) If a MimeMessage has one To: address, failure is returned in a SmtpFailedRecipientException. // If a MimeMessage has one To: address and one CC: address, failure is returned in a SmtpFailedRecipientsException (note the plural). // This contains an InnerExceptions property containing the individual SmtpFailedRecipientExceptions which Microsoft say is "not // intended to be used directly from your code". // ii) There are different kinds of "permanent" errors and SMTP servers aren't consistent about how they report things. For example, // for an authentication error, mail.smtp2go.com returns "Mailbox Unavailable. The server response was: Relay denied for unauthenticated sender". // You need to check the exception Message text to see whether the error is to do with the recipient mailbox (so mail to a // different recipient may work) or the sender account (so nothing will work and you may as well abort the whole process now). // // SmtpStatusCode Enumeration with numeric values: // -1 GeneralFailure // 211 SystemStatus // 214 HelpMessage // 220 ServiceReady // 221 ServiceClosingTransmissionChannel // 250 Ok // 251 UserNotLocalWillForward // 252 CannotVerifyUserWillAttemptDelivery // 354 StartMailInput // 421 ServiceNotAvailable // 450 MailboxBusy // 451 LocalErrorInProcessing // 452 InsufficientStorage // 454 ClientNotPermitted // 500 CommandUnrecognized // 501 SyntaxError // 502 CommandNotImplemented // 503 BadCommandSequence // 504 CommandParameterNotImplemented // 530 MustIssueStartTlsFirst // 550 MailboxUnavailable // 551 UserNotLocalTryAlternatePath // 552 ExceededStorageAllocation // 553 MailboxNameNotAllowed // 554 TransactionFailed try { int AttemptCount = 3; while (AttemptCount > 0) { AttemptCount--; try { TLogging.LogAtLevel(1, "Trying to send E-Mail to " + AEmail.To.ToString() + " from " + AEmail.From.ToString()); if (!AEmail.From.ToString().Substring(AEmail.From.ToString().IndexOf("@")).Contains(".")) { // invalid Email domain, eg. local return(false); } // for office365, this takes about 15 seconds FSmtpClient.Send(AEmail); AEmail.Headers.Add("Date-Sent", DateTime.Now.ToString()); TLogging.LogAtLevel(1, "E-Mail was sent successfully"); return(true); } catch (Exception ex) { if (AttemptCount > 0) { Thread.Sleep(TimeSpan.FromMinutes(1)); } else { TLogging.LogException(ex, Utilities.GetMethodSignature()); throw; } } } } catch (SmtpCommandException frEx) // If the SMTP server knows that the send failed because of failed recipients, { // I can produce a list of failed recipient addresses, and return false. // The caller can then retrieve the list and inform the user. TLogging.Log("SmtpEmail: Email to the following addresses did not succeed:"); if (frEx.ErrorCode == SmtpErrorCode.RecipientNotAccepted) { TsmtpFailedRecipient FailureDetails = new TsmtpFailedRecipient(); FailureDetails.FailedAddress = frEx.Mailbox.ToString(); FailureDetails.FailedMessage = "Recipient not accepted"; FFailedRecipients.Add(FailureDetails); TLogging.Log(FailureDetails.FailedAddress + " : " + FailureDetails.FailedMessage); } return(false); } catch (Exception ex) { // SSL authentication error: RemoteCertificateNotAvailable // see http://mono.1490590.n4.nabble.com/SSL-authentication-error-RemoteCertificateNotAvailable-RemoteCertificateChainErrors-td1755733.html // and http://www.mono-project.com/FAQ:_Security#Does_SSL_works_for_SMTP.2C_like_GMail_.3F // on Mono command prompt: // mozroots --import --ask-remove --machine // mozroots --import --ask-remove // certmgr -ssl smtps://tim00.hostsharing.net:443 TLogging.Log("There has been a problem sending the email"); TLogging.Log(ex.ToString() + " " + ex.Message); TLogging.Log(ex.StackTrace); throw; } return(false); }
public static DataTable GetAvailableGLYearEnds(Int32 ALedgerNumber, Int32 ADiffPeriod, bool AIncludeNextYear, out String ADisplayMember, out String AValueMember) { const string INTL_DATE_FORMAT = "yyyy-MM-dd"; //Create the table to populate the combobox DataTable ReturnTable = null; AValueMember = "YearNumber"; ADisplayMember = "YearEndDate"; TDBTransaction Transaction = null; try { DBAccess.GDBAccessObj.GetNewOrExistingAutoReadTransaction(IsolationLevel.ReadCommitted, TEnforceIsolationLevel.eilMinimum, ref Transaction, delegate { DateTime yearEndDate; DateTime currentYearEndDate; int yearNumber; int currentFinancialYear; ALedgerTable LedgerTable = null; AAccountingPeriodTable AccountingPeriods = null; LedgerTable = ALedgerAccess.LoadByPrimaryKey(ALedgerNumber, Transaction); AccountingPeriods = AAccountingPeriodAccess.LoadViaALedger(ALedgerNumber, Transaction); #region Validate Data if ((LedgerTable == null) || (LedgerTable.Count == 0)) { throw new EFinanceSystemDataTableReturnedNoDataException(String.Format(Catalog.GetString( "Function:{0} - Ledger data for Ledger number {1} does not exist or could not be accessed!"), Utilities.GetMethodName(true), ALedgerNumber)); } else if ((AccountingPeriods == null) || (AccountingPeriods.Count == 0)) { throw new EFinanceSystemDataTableReturnedNoDataException(String.Format(Catalog.GetString( "Function:{0} - AAccount Period data for Ledger number {1} does not exist or could not be accessed!"), Utilities.GetMethodName(true), ALedgerNumber)); } #endregion Validate Data ALedgerRow ledgerRow = (ALedgerRow)LedgerTable[0]; currentFinancialYear = ledgerRow.CurrentFinancialYear; currentYearEndDate = GetPeriodEndDate(ALedgerNumber, currentFinancialYear, ADiffPeriod, ledgerRow.NumberOfAccountingPeriods); //Filter to highest period number AccountingPeriods.DefaultView.RowFilter = String.Format("{0}={1}", AAccountingPeriodTable.GetAccountingPeriodNumberDBName(), ledgerRow.NumberOfAccountingPeriods); //Get last period row AAccountingPeriodRow periodRow = (AAccountingPeriodRow)AccountingPeriods.DefaultView[0].Row; //Create the table to populate the combobox ReturnTable = new DataTable(); ReturnTable.Columns.Add("YearNumber", typeof(System.Int32)); ReturnTable.Columns.Add("YearEndDate", typeof(String)); ReturnTable.Columns.Add("YearEndDateLong", typeof(String)); ReturnTable.PrimaryKey = new DataColumn[] { ReturnTable.Columns[0] }; //Add the current year to the table yearNumber = currentFinancialYear; yearEndDate = periodRow.PeriodEndDate; DataRow ResultRow = ReturnTable.NewRow(); ResultRow[0] = yearNumber; ResultRow[1] = yearEndDate.ToString(INTL_DATE_FORMAT); ResultRow[2] = yearEndDate.ToLongDateString(); ReturnTable.Rows.Add(ResultRow); //Retrieve all previous years string sql = String.Format("SELECT DISTINCT {0} AS batchYear" + " FROM PUB_{1}" + " WHERE {2} = {3} And {0} < {4}" + " ORDER BY 1 DESC", ABatchTable.GetBatchYearDBName(), ABatchTable.GetTableDBName(), ABatchTable.GetLedgerNumberDBName(), ALedgerNumber, yearNumber); DataTable BatchYearTable = DBAccess.GDBAccessObj.SelectDT(sql, "BatchYearTable", Transaction); BatchYearTable.DefaultView.Sort = String.Format("batchYear DESC"); foreach (DataRowView row in BatchYearTable.DefaultView) { DataRow currentBatchYearRow = row.Row; Int32 currentBatchYear = Convert.ToInt32(currentBatchYearRow[0]); if (yearNumber != currentBatchYear) { yearNumber -= 1; yearEndDate = DecrementYear(yearEndDate); if (yearNumber != currentBatchYear) { //Gap in year numbers throw new Exception(String.Format(Catalog.GetString("Year {0} not found for Ledger {1}"), yearNumber, ALedgerNumber)); } } DataRow ResultRow2 = ReturnTable.NewRow(); ResultRow2[0] = yearNumber; ResultRow2[1] = yearEndDate.ToString(INTL_DATE_FORMAT); ReturnTable.Rows.Add(ResultRow2); } if (AIncludeNextYear && (ReturnTable.Rows.Find(currentFinancialYear + 1) == null)) { DataRow resultRow = ReturnTable.NewRow(); resultRow[0] = currentFinancialYear + 1; resultRow[1] = currentYearEndDate.AddYears(1).ToString(INTL_DATE_FORMAT); //resultRow[2] = currentYearEndDate.ToString("dd-MMM-yyyy"); ReturnTable.Rows.InsertAt(resultRow, 0); } }); // Get NewOrExisting AutoReadTransaction } catch (Exception ex) { TLogging.LogException(ex, Utilities.GetMethodSignature()); throw; } return(ReturnTable); }
private void DeleteAllGifts(System.Object sender, EventArgs e) { TFrmRecurringGiftBatch FMyForm = (TFrmRecurringGiftBatch)this.ParentForm; string CompletionMessage = string.Empty; int BatchNumberToClear = FBatchNumber; if ((FPreviouslySelectedDetailRow == null)) { return; } else if (!FFilterAndFindObject.IsActiveFilterEqualToBase) { MessageBox.Show(Catalog.GetString("Please remove the filter before attempting to delete all Recurring Gifts in this batch."), Catalog.GetString("Delete All Recurring Gifts")); return; } //Backup the Dataset for reversion purposes GiftBatchTDS BackupDS = (GiftBatchTDS)FMainDS.Copy(); BackupDS.Merge(FMainDS); if (MessageBox.Show(String.Format(Catalog.GetString( "You have chosen to delete all Gifts from Recurring Batch: {0}.{1}{1}Are you sure you want to delete all?"), BatchNumberToClear, Environment.NewLine), Catalog.GetString("Confirm Delete All"), MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) != System.Windows.Forms.DialogResult.Yes) { return; } try { this.Cursor = Cursors.WaitCursor; //Specify current action FMyForm.FCurrentGiftBatchAction = Logic.TExtraGiftBatchChecks.GiftBatchAction.DELETINGTRANS; //clear any transactions currently being editied in the Transaction Tab ClearCurrentSelection(0, false); //Now delete all Recurring Gift data for current batch DeleteRecurringBatchGiftData(BatchNumberToClear); FBatchRow.BatchTotal = 0; txtBatchTotal.NumberValueDecimal = 0; // Be sure to set the last Recurring Gift number in the parent table before saving all the changes FBatchRow.LastGiftNumber = 0; FPetraUtilsObject.SetChangedFlag(); // save changes if (((TFrmRecurringGiftBatch)ParentForm).SaveChangesManual()) { CompletionMessage = Catalog.GetString("All Recurring Gifts and their details deleted successfully."); MessageBox.Show(CompletionMessage, Catalog.GetString("Recurring Gifts Deletion"), MessageBoxButtons.OK, MessageBoxIcon.Information); } else { CompletionMessage = Catalog.GetString("All Recurring Gifts and their details have been deleted but saving the changes failed!"); MessageBox.Show(CompletionMessage, Catalog.GetString("All Gifts Deletion"), MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } } catch (Exception ex) { //Revert to previous state RevertDataSet(FMainDS, BackupDS); TLogging.LogException(ex, Utilities.GetMethodSignature()); throw; } finally { FMyForm.FCurrentGiftBatchAction = Logic.TExtraGiftBatchChecks.GiftBatchAction.NONE; this.Cursor = Cursors.Default; } SetGiftDetailDefaultView(); FFilterAndFindObject.ApplyFilter(); if (grdDetails.Rows.Count < 2) { ShowDetails(null); UpdateControlsProtection(); } UpdateRecordNumberDisplay(); }
private void SubmitBatch(System.Object sender, System.EventArgs e) { bool Success = false; if ((GetSelectedRowIndex() < 0) || (FPreviouslySelectedDetailRow == null)) { MessageBox.Show(Catalog.GetString("Please select a Recurring Gift Batch before submitting!")); return; } TFrmRecurringGiftBatch MainForm = (TFrmRecurringGiftBatch)ParentForm; TFrmStatusDialog dlgStatus = new TFrmStatusDialog(FPetraUtilsObject.GetForm()); bool LoadDialogVisible = false; try { Cursor = Cursors.WaitCursor; MainForm.FCurrentGiftBatchAction = TExtraGiftBatchChecks.GiftBatchAction.SUBMITTING; dlgStatus.Show(); LoadDialogVisible = true; dlgStatus.Heading = String.Format(Catalog.GetString("Recurring Gift Batch {0}"), FSelectedBatchNumber); dlgStatus.CurrentStatus = Catalog.GetString("Loading gifts ready for submitting..."); if (!LoadAllBatchData(FSelectedBatchNumber)) { Cursor = Cursors.Default; MessageBox.Show(Catalog.GetString("The Recurring Gift Batch is empty!"), Catalog.GetString("Submit Gift Batch"), MessageBoxButtons.OK, MessageBoxIcon.Stop); dlgStatus.Close(); LoadDialogVisible = false; return; } dlgStatus.Close(); LoadDialogVisible = false; Success = FSubmitLogicObject.SubmitBatch(FPreviouslySelectedDetailRow, FWarnOfInactiveValuesOnSubmitting, FDonorZeroIsValid, FRecipientZeroIsValid); } catch (Exception ex) { TLogging.LogException(ex, Utilities.GetMethodSignature()); throw; } finally { if (LoadDialogVisible) { dlgStatus.Close(); LoadDialogVisible = false; } MainForm.FCurrentGiftBatchAction = TExtraGiftBatchChecks.GiftBatchAction.NONE; Cursor = Cursors.Default; } }
private void StewardshipCalculation(Object Sender, EventArgs e) { if (!ValidReportPeriod()) { return; } TVerificationResultCollection VerificationResult = null; try { Cursor = Cursors.WaitCursor; List <Int32> glBatchNumbers; Boolean retVal = TRemote.MFinance.ICH.WebConnectors.PerformStewardshipCalculation( FLedgerNumber, cmbReportPeriod.GetSelectedInt32(), out glBatchNumbers, out VerificationResult); TFrmBatchPostingRegister ReportGui = new TFrmBatchPostingRegister(null); foreach (Int32 glBatchNumber in glBatchNumbers) { if (glBatchNumber > 0) { ReportGui.PrintReportNoUi(FLedgerNumber, glBatchNumber); } } Cursor = Cursors.Default; String ResultMsg = (retVal ? Catalog.GetString("Stewardship Calculation Completed Successfully") : Catalog.GetString("UNSUCCESSFUL Stewardship Calculation!")); MessageBox.Show(Messages.BuildMessageFromVerificationResult(ResultMsg, VerificationResult), Catalog.GetString("Stewardship Calculation"), MessageBoxButtons.OK, MessageBoxIcon.Information); if (retVal) { Close(); } else { btnCancel.Text = "Close"; } } catch (Exception ex) { Cursor = Cursors.Default; TLogging.LogException(ex, Utilities.GetMethodSignature()); MessageBox.Show(String.Format(Catalog.GetString( "An unexpected error occurred when trying to perform the Stewardship Calculation!{0}{0}Error: {1}"), Environment.NewLine, ex.Message), Catalog.GetString("Stewardship Calculation"), MessageBoxButtons.OK, MessageBoxIcon.Error); } }
/// <summary> /// Public method to export GL batches /// </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 Batches"), 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 GL 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.ValidDate()) || (!dtpDateTo.ValidDate())) { 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); } // Save the defaults SaveUserDefaults(); String dateFormatString = cmbDateFormat.GetSelectedString(); // might be called from the main navigation window (FMainDS is null), or from the GL Batch screen (reusing MainDS) if (FMainDS == null) { FMainDS = new Ict.Petra.Shared.MFinance.GL.Data.GLBatchTDS(); FMainDS.Merge(TRemote.MFinance.GL.WebConnectors.LoadABatch(FLedgerNumber, -1, -1)); } Int32 ALedgerNumber = 0; ArrayList batches = new ArrayList(); foreach (ABatchRow batch in FMainDS.ABatch.Rows) { // check conditions for exporting this batch // Batch Status bool exportThisBatch = batch.BatchStatus.Equals(MFinanceConstants.BATCH_POSTED) || (chkIncludeUnposted.Checked && batch.BatchStatus.Equals(MFinanceConstants.BATCH_UNPOSTED)); if (rbtBatchNumberSelection.Checked) { exportThisBatch &= (batch.BatchNumber >= txtBatchNumberStart.NumberValueInt); exportThisBatch &= (batch.BatchNumber <= txtBatchNumberEnd.NumberValueInt); } else { exportThisBatch &= (batch.DateEffective >= dtpDateFrom.Date); exportThisBatch &= (batch.DateEffective <= dtpDateTo.Date); } if (exportThisBatch) { batches.Add(batch.BatchNumber); } ALedgerNumber = batch.LedgerNumber; } if (batches.Count == 0) { MessageBox.Show(Catalog.GetString("There are no batches matching your criteria"), Catalog.GetString("Error"), MessageBoxButtons.OK, MessageBoxIcon.Error); return(false); } // Do the actual export work try { Hashtable requestParams = new Hashtable(); requestParams.Add("ALedgerNumber", ALedgerNumber); requestParams.Add("Delimiter", delimiter); requestParams.Add("DateFormatString", dateFormatString); requestParams.Add("Summary", rbtSummary.Checked); requestParams.Add("bUseBaseCurrency", rbtBaseCurrency.Checked); requestParams.Add("BaseCurrency", FMainDS.ALedger[0].BaseCurrency); requestParams.Add("TransactionsOnly", chkTransactionsOnly.Checked); requestParams.Add("bDontSummarize", chkDontSummarize.Checked); requestParams.Add("DontSummarizeAccount", cmbDontSummarizeAccount.GetSelectedString()); requestParams.Add("DateForSummary", dtpDateSummary.Date); requestParams.Add("NumberFormat", numberFormat); String exportString = null; Thread ExportThread = new Thread(() => ExportAllGLBatchData(batches, requestParams, out exportString)); using (TProgressDialog ExportDialog = new TProgressDialog(ExportThread)) { ExportDialog.ShowDialog(); } // Now we have the string we can write it to the file StreamWriter sw1 = new StreamWriter(ExportFileName); sw1.Write(exportString); sw1.Close(); } catch (Exception ex) { TLogging.LogException(ex, Utilities.GetMethodSignature()); throw; } bool ShowExportedFileInExplorer = false; if (AWithInteractionOnSuccess) { if (MessageBox.Show(Catalog.GetString( "GL Batches Exported successfully. Would you like to open the file in your default application?"), Catalog.GetString("GL 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( "GL 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( "GL Export"), MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } } } return(true); }
/// <summary> /// this submits the given Batch number /// Each line starts with a type specifier, B for batch, T for transaction /// </summary> private void SubmitBatch(object sender, EventArgs e) { //Need to run this here just in case the user presses <ENTER> on keyboard // after changing the date but no OnLeave event occurs for the date box. CheckBatchEffectiveDate(null, null); // This should never happen - but ... if (txtExchangeRateToBase.NumberValueDecimal <= 0.0m) { MessageBox.Show(Catalog.GetString("The exchange rate must be a number greater than 0.0!"), Catalog.GetString("Submit Recurring Gift Batch"), MessageBoxButtons.OK, MessageBoxIcon.Exclamation); btnGetSetExchangeRate.Enabled = true; return; } //check the gift batch date else if ((dtpEffectiveDate.Date < FStartDateCurrentPeriod) || (dtpEffectiveDate.Date > FEndDateLastForwardingPeriod)) { MessageBox.Show(String.Format(Catalog.GetString( "The batch date is outside the allowed posting period start/end date range: {0} to {1}!"), FStartDateCurrentPeriod.ToShortDateString(), FEndDateLastForwardingPeriod.ToShortDateString()), Catalog.GetString("Submit Recurring Gift Batch"), MessageBoxButtons.OK, MessageBoxIcon.Exclamation); dtpEffectiveDate.Focus(); dtpEffectiveDate.SelectAll(); return; } Hashtable requestParams = new Hashtable(); requestParams.Add("ALedgerNumber", FLedgerNumber); requestParams.Add("ABatchNumber", FBatchNumber); requestParams.Add("AEffectiveDate", dtpEffectiveDate.Date.Value); requestParams.Add("AExchangeRateToBase", FExchangeRateToBase); requestParams.Add("AExchangeRateIntlToBase", FExchangeRateIntlToBase); int CreatedGiftBatchNumber = 0; try { if (TRemote.MFinance.Gift.WebConnectors.SubmitRecurringGiftBatch(requestParams, out CreatedGiftBatchNumber)) { string successMessage = String.Format(Catalog.GetString( "Your recurring batch was submitted successfully as new Gift Batch {0}!{1}{1}" + "If the Gift Batches form is open it will try to refresh its data."), CreatedGiftBatchNumber, Environment.NewLine); MessageBox.Show(successMessage, Catalog.GetString("Submit Recurring Gift Batch"), MessageBoxButtons.OK, MessageBoxIcon.Information); // refresh gift batch screen TFormsMessage broadcastMessage = new TFormsMessage(TFormsMessageClassEnum.mcRefreshGiftBatches, this.ToString()); TFormsList.GFormsList.BroadcastFormMessage(broadcastMessage); Close(); } else { MessageBox.Show(Catalog.GetString("The recurring Gift Batch failed to submit!"), Catalog.GetString("Submit Recurring Gift Batch"), MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } } catch (Exception ex) { string errMsg = String.Format(Catalog.GetString("Unexpected error trying to submit recurring Gift Batch: {0}:{1}{1}{2}{1}{1}{3}"), FBatchNumber, Environment.NewLine, ex.Message, Catalog.GetString("Refer to the Server.Log text file for more details.")); MessageBox.Show(errMsg, Catalog.GetString("Submit Recurring Gift Batch"), MessageBoxButtons.OK, MessageBoxIcon.Warning); TLogging.LogException(ex, Utilities.GetMethodSignature()); throw; } }
public static bool GiftRevertAdjust(Hashtable requestParams, out int AAdjustmentBatchNumber, GiftBatchTDS AGiftDS) { AAdjustmentBatchNumber = 0; int AdjustmentBatchNo = AAdjustmentBatchNumber; if ((AGiftDS == null) || (AGiftDS.AGiftDetail == null) || (AGiftDS.AGiftDetail.Rows.Count == 0)) { TLogging.Log("Empty dataset sent to GiftRevertAdjust"); return(false); } Int32 ALedgerNumber = (Int32)requestParams["ALedgerNumber"]; Boolean BatchSelected = (Boolean)requestParams["NewBatchSelected"]; GiftAdjustmentFunctionEnum Function = (GiftAdjustmentFunctionEnum)requestParams["Function"]; Int32 GiftDetailNumber = (Int32)requestParams["GiftDetailNumber"]; bool NoReceipt = (Boolean)requestParams["NoReceipt"]; DateTime DateEffective; decimal batchGiftTotal = 0; Int32 ANewBatchNumber = (BatchSelected ? (Int32)requestParams["NewBatchNumber"] : 0); TDBTransaction Transaction = null; bool SubmissionOK = false; try { DBAccess.GDBAccessObj.GetNewOrExistingAutoTransaction(IsolationLevel.Serializable, ref Transaction, ref SubmissionOK, delegate { ALedgerTable ledgerTable = ALedgerAccess.LoadByPrimaryKey(ALedgerNumber, Transaction); AGiftBatchRow giftBatch; // if we need to create a new gift batch if (!BatchSelected) { giftBatch = CreateNewGiftBatch(requestParams, ref AGiftDS, out DateEffective, ref ledgerTable, Transaction); } else // using an existing gift batch { AGiftBatchAccess.LoadByPrimaryKey(AGiftDS, ALedgerNumber, ANewBatchNumber, Transaction); giftBatch = AGiftDS.AGiftBatch[0]; DateEffective = giftBatch.GlEffectiveDate; //If into an existing batch, then retrive the existing batch total batchGiftTotal = giftBatch.BatchTotal; } AdjustmentBatchNo = giftBatch.BatchNumber; //assuming new elements are added after these static borders AGiftDS.AGift.DefaultView.Sort = string.Format("{0}, {1}", AGiftTable.GetBatchNumberDBName(), AGiftTable.GetGiftTransactionNumberDBName()); AGiftDS.AGiftDetail.DefaultView.Sort = string.Format("{0}, {1}, {2}", AGiftDetailTable.GetBatchNumberDBName(), AGiftDetailTable.GetGiftTransactionNumberDBName(), AGiftDetailTable.GetDetailNumberDBName()); foreach (DataRowView giftRow in AGiftDS.AGift.DefaultView) { int cycle = 0; // first cycle creates gift reversal; second cycle creates new adjusted gift (if needed) do { AGiftRow oldGift = (AGiftRow)giftRow.Row; if (oldGift.RowState != DataRowState.Added) { AGiftRow gift = AGiftDS.AGift.NewRowTyped(true); DataUtilities.CopyAllColumnValuesWithoutPK(oldGift, gift); gift.LedgerNumber = giftBatch.LedgerNumber; gift.BatchNumber = giftBatch.BatchNumber; gift.DateEntered = DateEffective; gift.GiftTransactionNumber = giftBatch.LastGiftNumber + 1; giftBatch.LastGiftNumber++; gift.LinkToPreviousGift = (cycle != 0); gift.LastDetailNumber = 0; // do not print a receipt for reversed gifts if (cycle == 0) { gift.ReceiptPrinted = true; gift.PrintReceipt = false; } else { gift.ReceiptPrinted = false; gift.PrintReceipt = !NoReceipt; } AGiftDS.AGift.Rows.Add(gift); foreach (DataRowView giftDetailRow in AGiftDS.AGiftDetail.DefaultView) { AGiftDetailRow oldGiftDetail = (AGiftDetailRow)giftDetailRow.Row; // if gift detail belongs to gift if ((oldGiftDetail.GiftTransactionNumber == oldGift.GiftTransactionNumber) && (oldGiftDetail.BatchNumber == oldGift.BatchNumber) && (!Function.Equals(GiftAdjustmentFunctionEnum.ReverseGiftDetail) || (oldGiftDetail.DetailNumber == GiftDetailNumber))) { AddDuplicateGiftDetailToGift(ref AGiftDS, ref gift, oldGiftDetail, cycle == 0, Transaction, requestParams); batchGiftTotal += oldGiftDetail.GiftTransactionAmount * ((cycle == 0) ? -1 : 1); // original gift also gets marked as a reversal oldGiftDetail.ModifiedDetail = true; } } } cycle++; } while ((cycle < 2) && (Function.Equals(GiftAdjustmentFunctionEnum.AdjustGift) || Function.Equals(GiftAdjustmentFunctionEnum.FieldAdjust) || Function.Equals(GiftAdjustmentFunctionEnum.TaxDeductiblePctAdjust))); } //When reversing into a new or existing batch, set batch total if (!Function.Equals(GiftAdjustmentFunctionEnum.AdjustGift)) { giftBatch.BatchTotal = batchGiftTotal; } // save everything at the end AGiftBatchAccess.SubmitChanges(AGiftDS.AGiftBatch, Transaction); ALedgerAccess.SubmitChanges(ledgerTable, Transaction); AGiftAccess.SubmitChanges(AGiftDS.AGift, Transaction); AGiftDetailAccess.SubmitChanges(AGiftDS.AGiftDetail, Transaction); AGiftDS.AGiftBatch.AcceptChanges(); SubmissionOK = true; }); } catch (Exception ex) { TLogging.LogException(ex, Utilities.GetMethodSignature()); throw new EOPAppException(Catalog.GetString("Gift Reverse/Adjust failed."), ex); } AAdjustmentBatchNumber = AdjustmentBatchNo; return(SubmissionOK); }
public static void ReversedGiftReset(Int32 ALedgerNumber, List <string> AModifiedDetailKeys) { #region Validate Arguments if (ALedgerNumber <= 0) { throw new EFinanceSystemInvalidLedgerNumberException(String.Format(Catalog.GetString( "Function:{0} - The Ledger number must be greater than 0!"), Utilities.GetMethodName(true)), ALedgerNumber); } else if (AModifiedDetailKeys.Count == 0) { //Not an error condition, just return. return; } #endregion Validate Arguments TDBTransaction Transaction = null; bool SubmissionOK = false; try { DBAccess.GDBAccessObj.GetNewOrExistingAutoTransaction(IsolationLevel.Serializable, ref Transaction, ref SubmissionOK, delegate { foreach (string ModifiedDetailKey in AModifiedDetailKeys) { //Sometimes the underlying ModifiedDetailKeys field is set to empty string if (ModifiedDetailKey.Length == 0) { continue; } string[] GiftDetailFields = ModifiedDetailKey.Split('|'); int giftBatchNumber = Convert.ToInt32(GiftDetailFields[1]); int giftNumber = Convert.ToInt32(GiftDetailFields[2]); int giftDetailNumber = Convert.ToInt32(GiftDetailFields[3]); AGiftDetailTable GiftDetailTable = AGiftDetailAccess.LoadByPrimaryKey(ALedgerNumber, giftBatchNumber, giftNumber, giftDetailNumber, Transaction); #region Validate Data if ((GiftDetailTable == null) || (GiftDetailTable.Count == 0)) { throw new EFinanceSystemDataTableReturnedNoDataException(String.Format(Catalog.GetString( "Function:{0} - Data for Gift Detail {1}, from Gift {2} in Batch {3} and Ledger {4}, does not exist or could not be accessed!"), Utilities.GetMethodName(true), giftDetailNumber, giftNumber, giftBatchNumber, ALedgerNumber)); } #endregion Validate Data GiftDetailTable[0].ModifiedDetail = false; AGiftDetailAccess.SubmitChanges(GiftDetailTable, Transaction); } SubmissionOK = true; }); } catch (Exception ex) { TLogging.LogException(ex, Utilities.GetMethodSignature()); throw; } }
private bool AllowInactiveFieldValues(int ABatchNumber) { bool RetVal = false; TVerificationResultCollection VerificationResult = new TVerificationResultCollection(); string VerificationMessage = string.Empty; DataView TransDV = new DataView(FMainDS.ARecurringTransaction); DataView AttribDV = new DataView(FMainDS.ARecurringTransAnalAttrib); int TotalNumInactiveValues = 0; int NumInactiveAccounts = 0; int NumInactiveCostCentres = 0; int NumInactiveAccountTypes = 0; int NumInactiveAccountValues = 0; try { //Check for inactive account or cost centre codes TransDV.RowFilter = String.Format("{0}={1}", ARecurringTransactionTable.GetBatchNumberDBName(), ABatchNumber); TransDV.Sort = String.Format("{0} ASC, {1} ASC", ARecurringTransactionTable.GetJournalNumberDBName(), ARecurringTransactionTable.GetTransactionNumberDBName()); foreach (DataRowView drv in TransDV) { ARecurringTransactionRow transRow = (ARecurringTransactionRow)drv.Row; if (!AccountIsActive(transRow.AccountCode)) { VerificationMessage += String.Format(" Account '{0}' in Journal:{1} Transaction:{2}.{3}", transRow.AccountCode, transRow.JournalNumber, transRow.TransactionNumber, Environment.NewLine); NumInactiveAccounts++; } if (!CostCentreIsActive(transRow.CostCentreCode)) { VerificationMessage += String.Format(" Cost Centre '{0}' in Journal:{1} Transaction:{2}.{3}", transRow.CostCentreCode, transRow.JournalNumber, transRow.TransactionNumber, Environment.NewLine); NumInactiveCostCentres++; } } //Check anlysis attributes AttribDV.RowFilter = String.Format("{0}={1}", ARecurringTransAnalAttribTable.GetBatchNumberDBName(), ABatchNumber); AttribDV.Sort = String.Format("{0} ASC, {1} ASC, {2} ASC", ARecurringTransAnalAttribTable.GetJournalNumberDBName(), ARecurringTransAnalAttribTable.GetTransactionNumberDBName(), ARecurringTransAnalAttribTable.GetAnalysisTypeCodeDBName()); foreach (DataRowView drv2 in AttribDV) { ARecurringTransAnalAttribRow analAttribRow = (ARecurringTransAnalAttribRow)drv2.Row; if (!AnalysisCodeIsActive(analAttribRow.AccountCode, analAttribRow.AnalysisTypeCode)) { VerificationMessage += String.Format(" Analysis Code '{0}' in Journal:{1} Transaction:{2}.{3}", analAttribRow.AnalysisTypeCode, analAttribRow.JournalNumber, analAttribRow.TransactionNumber, Environment.NewLine); NumInactiveAccountTypes++; } if (!AnalysisAttributeValueIsActive(analAttribRow.AnalysisTypeCode, analAttribRow.AnalysisAttributeValue)) { VerificationMessage += String.Format(" Analysis Value '{0}' in Journal:{1} Transaction:{2}.{3}", analAttribRow.AnalysisAttributeValue, analAttribRow.JournalNumber, analAttribRow.TransactionNumber, Environment.NewLine); NumInactiveAccountValues++; } } } catch (Exception ex) { TLogging.LogException(ex, Utilities.GetMethodSignature()); throw; } TotalNumInactiveValues = (NumInactiveAccounts + NumInactiveCostCentres + NumInactiveAccountTypes + NumInactiveAccountValues); if (TotalNumInactiveValues > 0) { VerificationResult.Add(new TVerificationResult(string.Format(Catalog.GetString("Inactive Values:{0}"), Environment.NewLine), VerificationMessage, TResultSeverity.Resv_Noncritical)); StringBuilder errorMessages = new StringBuilder(); errorMessages.AppendFormat(Catalog.GetString("{0} inactive value(s) found in Recurring GL Batch {1}. Do you still want to submit?{2}"), TotalNumInactiveValues, ABatchNumber, Environment.NewLine); foreach (TVerificationResult message in VerificationResult) { errorMessages.AppendFormat("{0}{1}", Environment.NewLine, message.ResultText); } TFrmExtendedMessageBox extendedMessageBox = new TFrmExtendedMessageBox(FPetraUtilsObject.GetForm()); RetVal = (extendedMessageBox.ShowDialog(errorMessages.ToString(), Catalog.GetString("Submit Batch"), string.Empty, TFrmExtendedMessageBox.TButtons.embbYesNo, TFrmExtendedMessageBox.TIcon.embiQuestion) == TFrmExtendedMessageBox.TResult.embrYes); } else { RetVal = true; } return(RetVal); }
/// <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; 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> /// Call the code to consolidate all budgets /// </summary> /// <param name="AParentWindow"></param> /// <param name="ALedgerNumber"></param> public static void ConsolidateBudgets(Form AParentWindow, Int32 ALedgerNumber) //, TVerificationResultCollection AVerificationResult = null) /// <param name="AVerificationResult"></param> { string Msg = string.Empty; Msg = "You can either consolidate all of your budgets"; Msg += " or just those that have changed since the last consolidation." + "\n\r\n\r"; Msg += "Do you want to consolidate all of your budgets?"; DialogResult DlgRes; DlgRes = MessageBox.Show(Msg, "Consolidate Budgets", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2, MessageBoxOptions.DefaultDesktopOnly, false); if (DlgRes == DialogResult.Cancel) { return; } bool ConsolidateAll = (DlgRes == DialogResult.Yes); TFrmStatusDialog DlgStatus = null; try { Cursor.Current = Cursors.WaitCursor; DlgStatus = new TFrmStatusDialog(AParentWindow); DlgStatus.Show(); DlgStatus.Heading = Catalog.GetString("Consolidating Budgets"); DlgStatus.CurrentStatus = Catalog.GetString("Loading budget data..."); TRemote.MFinance.Budget.WebConnectors.LoadBudgetForConsolidate(ALedgerNumber); DlgStatus.CurrentStatus = Catalog.GetString("Consolidating" + (ConsolidateAll ? " all " : " changed ") + "budget data..."); TRemote.MFinance.Budget.WebConnectors.ConsolidateBudgets(ALedgerNumber, ConsolidateAll); DlgStatus.Close(); DlgStatus = null; MessageBox.Show("Budget Consolidation Complete.", "Consolidate Budgets"); } catch (Exception ex) { TLogging.LogException(ex, Utilities.GetMethodSignature()); throw; } finally { Cursor.Current = Cursors.Default; if (DlgStatus != null) { DlgStatus.Close(); DlgStatus = null; } } }
/// <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> /// 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); }
private bool OnDeleteRowManual(GiftBatchTDSARecurringGiftDetailRow ARowToDelete, ref string ACompletionMessage) { //TODO: Make this like deleton on GL Transactions form // e.g. pass copy to delete method on server... //GiftBatchTDS TempDS = (GiftBatchTDS)FMainDS.Copy(); //TempDS.Merge(FMainDS); bool DeletionSuccessful = false; ACompletionMessage = string.Empty; if (FBatchRow == null) { FBatchRow = GetRecurringBatchRow(); } if (ARowToDelete == null) { return(false); } int CurrentBatchNo = ARowToDelete.BatchNumber; bool RowToDeleteIsNew = (ARowToDelete.RowState == DataRowState.Added); int CurrentRowIndex = GetSelectedRowIndex(); TFrmRecurringGiftBatch FMyForm = (TFrmRecurringGiftBatch)this.ParentForm; GiftBatchTDS BackupMainDS = null; int SelectedDetailNumber = ARowToDelete.DetailNumber; int RecurringGiftToDeleteTransNo = 0; string FilterAllRecurringGiftsOfBatch = String.Empty; string FilterAllRecurringGiftDetailsOfBatch = String.Empty; int DetailRowCount = FGiftDetailView.Count; try { this.Cursor = Cursors.WaitCursor; //Specify current action FMyForm.FCurrentGiftBatchAction = Logic.TExtraGiftBatchChecks.GiftBatchAction.DELETINGTRANS; //Speeds up deletion of larger gift sets FMainDS.EnforceConstraints = false; // temporarily disable New Donor Warning FMyForm.NewDonorWarning = false; //Backup the Dataset for reversion purposes BackupMainDS = (GiftBatchTDS)FMainDS.GetChangesTyped(false); //Don't run an inactive fields check on this batch FMyForm.GetBatchControl().UpdateRecurringBatchDictionary(CurrentBatchNo); //Delete current row ARowToDelete.RejectChanges(); if (!RowToDeleteIsNew) { ShowDetails(ARowToDelete); } ARowToDelete.Delete(); //If there existed (before the delete row above) more than one detail row, then no need to delete Recurring Gift header row if (DetailRowCount > 1) { ACompletionMessage = Catalog.GetString("Recurring Gift Detail row deleted successfully!"); FGiftSelectedForDeletionFlag = false; foreach (DataRowView rv in FGiftDetailView) { GiftBatchTDSARecurringGiftDetailRow row = (GiftBatchTDSARecurringGiftDetailRow)rv.Row; if (row.DetailNumber > SelectedDetailNumber) { row.DetailNumber--; } } FGift.LastDetailNumber--; } else { ACompletionMessage = Catalog.GetString("Recurring Gift deleted successfully!"); RecurringGiftToDeleteTransNo = FGift.GiftTransactionNumber; // Reduce all Recurring Gift Detail row Transaction numbers by 1 if they are greater then Recurring Gift to be deleted FilterAllRecurringGiftDetailsOfBatch = String.Format("{0}={1} And {2}>{3}", ARecurringGiftDetailTable.GetBatchNumberDBName(), FBatchNumber, ARecurringGiftDetailTable.GetGiftTransactionNumberDBName(), RecurringGiftToDeleteTransNo); DataView RecurringGiftDetailView = new DataView(FMainDS.ARecurringGiftDetail); RecurringGiftDetailView.RowFilter = FilterAllRecurringGiftDetailsOfBatch; RecurringGiftDetailView.Sort = String.Format("{0} ASC", ARecurringGiftDetailTable.GetGiftTransactionNumberDBName()); foreach (DataRowView rv in RecurringGiftDetailView) { GiftBatchTDSARecurringGiftDetailRow row = (GiftBatchTDSARecurringGiftDetailRow)rv.Row; row.GiftTransactionNumber--; } //Cannot delete the Recurring Gift row, just copy the data of rows above down by 1 row // and then mark the top row for deletion //In other words, bubble the Recurring Gift row to be deleted to the top FilterAllRecurringGiftsOfBatch = String.Format("{0}={1} And {2}>={3}", ARecurringGiftTable.GetBatchNumberDBName(), FBatchNumber, ARecurringGiftTable.GetGiftTransactionNumberDBName(), RecurringGiftToDeleteTransNo); DataView RecurringGiftView = new DataView(FMainDS.ARecurringGift); RecurringGiftView.RowFilter = FilterAllRecurringGiftsOfBatch; RecurringGiftView.Sort = String.Format("{0} ASC", ARecurringGiftTable.GetGiftTransactionNumberDBName()); ARecurringGiftRow RecurringGiftRowToReceive = null; ARecurringGiftRow RecurringGiftRowToCopyDown = null; ARecurringGiftRow RecurringGiftRowCurrent = null; int currentRecurringGiftTransNo = 0; foreach (DataRowView gv in RecurringGiftView) { RecurringGiftRowCurrent = (ARecurringGiftRow)gv.Row; currentRecurringGiftTransNo = RecurringGiftRowCurrent.GiftTransactionNumber; if (currentRecurringGiftTransNo > RecurringGiftToDeleteTransNo) { RecurringGiftRowToCopyDown = RecurringGiftRowCurrent; //Copy column values down for (int j = 3; j < RecurringGiftRowToCopyDown.Table.Columns.Count; j++) { //Update all columns except the pk fields that remain the same if (!RecurringGiftRowToCopyDown.Table.Columns[j].ColumnName.EndsWith("_text")) { RecurringGiftRowToReceive[j] = RecurringGiftRowToCopyDown[j]; } } } if (currentRecurringGiftTransNo == FBatchRow.LastGiftNumber) { //Mark last record for deletion RecurringGiftRowCurrent.ChargeStatus = MFinanceConstants.MARKED_FOR_DELETION; } //Will always be previous row RecurringGiftRowToReceive = RecurringGiftRowCurrent; } FPreviouslySelectedDetailRow = null; FGiftSelectedForDeletionFlag = true; FBatchRow.LastGiftNumber--; } //Save and check for inactive values and ex-workers and anonymous gifts // in other unsaved Batches FPetraUtilsObject.SetChangedFlag(); if (!FMyForm.SaveChangesManual(Logic.TExtraGiftBatchChecks.GiftBatchAction.DELETINGTRANS, false, false)) { FMyForm.GetBatchControl().UpdateRecurringBatchDictionary(); MessageBox.Show(Catalog.GetString("The gift detail has been deleted but the changes are not saved!"), Catalog.GetString("Deletion Warning"), MessageBoxButtons.OK, MessageBoxIcon.Warning); ACompletionMessage = string.Empty; if (FGiftSelectedForDeletionFlag) { FGiftSelectedForDeletionFlag = false; SetBatchLastGiftNumber(); UpdateControlsProtection(); } UpdateTotals(); return(false); } //Clear current batch's gift data and reload from server RefreshRecurringBatchGiftData(FBatchNumber, true); DeletionSuccessful = true; } catch (Exception ex) { //Revert to previous state RevertDataSet(FMainDS, BackupMainDS, CurrentRowIndex); TLogging.LogException(ex, Utilities.GetMethodSignature()); throw; } finally { FMyForm.NewDonorWarning = true; FMainDS.EnforceConstraints = true; FMyForm.FCurrentGiftBatchAction = Logic.TExtraGiftBatchChecks.GiftBatchAction.NONE; this.Cursor = Cursors.Default; } SetGiftDetailDefaultView(); FFilterAndFindObject.ApplyFilter(); UpdateRecordNumberDisplay(); return(DeletionSuccessful); }
/// <summary> /// get more details of the last gift of the partner /// </summary> /// <param name="APartnerKey"></param> /// <param name="ALastGiftDate"></param> /// <param name="ALastGiftAmount"></param> /// <param name="ALastGiftGivenToPartnerKey"></param> /// <param name="ALastGiftRecipientLedger"></param> /// <param name="ALastGiftCurrencyCode"></param> /// <param name="ALastGiftDisplayFormat"></param> /// <param name="ALastGiftGivenToShortName"></param> /// <param name="ALastGiftRecipientLedgerShortName"></param> /// <param name="ARestrictedOrConfidentialGiftAccessDenied"></param> /// <returns></returns> public static Boolean GetLastGiftDetails(Int64 APartnerKey, out DateTime ALastGiftDate, out decimal ALastGiftAmount, out Int64 ALastGiftGivenToPartnerKey, out Int64 ALastGiftRecipientLedger, out String ALastGiftCurrencyCode, out String ALastGiftDisplayFormat, out String ALastGiftGivenToShortName, out String ALastGiftRecipientLedgerShortName, out Boolean ARestrictedOrConfidentialGiftAccessDenied) { DataSet LastGiftDS; AGiftDetailTable GiftDetailDT; SGroupGiftTable GroupGiftDT; SUserGroupTable UserGroupDT; AGiftRow GiftDR; AGiftBatchRow GiftBatchDR; AGiftDetailRow GiftDetailDR; ACurrencyRow CurrencyDR; Int16 Counter; Boolean AccessToGift = false; DataRow[] FoundUserGroups; ALastGiftAmount = 0; ALastGiftCurrencyCode = ""; ALastGiftDisplayFormat = ""; ALastGiftDate = DateTime.MinValue; ALastGiftGivenToPartnerKey = 0; ALastGiftGivenToShortName = ""; ALastGiftRecipientLedger = 0; ALastGiftRecipientLedgerShortName = ""; ARestrictedOrConfidentialGiftAccessDenied = false; DateTime tmpLastGiftDate = ALastGiftDate; decimal tmpLastGiftAmount = ALastGiftAmount; Int64 tmpLastGiftGivenToPartnerKey = ALastGiftGivenToPartnerKey; Int64 tmpLastGiftRecipientLedger = ALastGiftRecipientLedger; String tmpLastGiftCurrencyCode = ALastGiftCurrencyCode; String tmpLastGiftDisplayFormat = ALastGiftDisplayFormat; String tmpLastGiftGivenToShortName = ALastGiftGivenToShortName; String tmpLastGiftRecipientLedgerShortName = ALastGiftRecipientLedgerShortName; Boolean tmpRestrictedOrConfidentialGiftAccessDenied = ARestrictedOrConfidentialGiftAccessDenied; if ((UserInfo.GUserInfo.IsInModule(SharedConstants.PETRAMODULE_FINANCE1) || UserInfo.GUserInfo.IsInModule(SharedConstants.PETRAMODULE_DEVUSER)) == false) { // User hasn't got access to FINANCE-1 module or Financial Development module return(false); } // Set up temp DataSet LastGiftDS = new DataSet("LastGiftDetails"); LastGiftDS.Tables.Add(new AGiftTable()); LastGiftDS.Tables.Add(new AGiftBatchTable()); LastGiftDS.Tables.Add(new AGiftDetailTable()); LastGiftDS.Tables.Add(new ACurrencyTable()); LastGiftDS.Tables.Add(new PPartnerTable()); TDBTransaction Transaction = null; bool SubmissionOK = true; // Important: The IsolationLevel here needs to correspond with the IsolationLevel in the // Ict.Petra.Server.MPartner.Partner.UIConnectors.TPartnerEditUIConnector.LoadData Method // as otherwise the attempt of taking-out of a DB Transaction here will lead to Bug #4167! DBAccess.GDBAccessObj.GetNewOrExistingAutoTransaction(IsolationLevel.ReadCommitted, TEnforceIsolationLevel.eilMinimum, ref Transaction, ref SubmissionOK, delegate { try { try { AGiftAccess.LoadViaPPartner(LastGiftDS, APartnerKey, null, Transaction, StringHelper.InitStrArr(new String[] { "ORDER BY", AGiftTable.GetDateEnteredDBName() + " DESC" }), 0, 1); } catch (ESecurityDBTableAccessDeniedException) { // User hasn't got access to a_gift Table in the DB return; } catch (Exception ex) { TLogging.LogException(ex, Utilities.GetMethodSignature()); throw; } if (LastGiftDS.Tables[AGiftTable.GetTableName()].Rows.Count == 0) { // Partner hasn't given any Gift so far return; } // Get the last gift GiftDR = ((AGiftTable)LastGiftDS.Tables[AGiftTable.GetTableName()])[0]; if (GiftDR.Restricted) { AccessToGift = false; GroupGiftDT = SGroupGiftAccess.LoadViaAGift( GiftDR.LedgerNumber, GiftDR.BatchNumber, GiftDR.GiftTransactionNumber, Transaction); UserGroupDT = SUserGroupAccess.LoadViaSUser(UserInfo.GUserInfo.UserID, Transaction); // Loop over all rows of GroupGiftDT for (Counter = 0; Counter <= GroupGiftDT.Rows.Count - 1; Counter += 1) { // To be able to view a Gift, ReadAccess must be granted if (GroupGiftDT[Counter].ReadAccess) { // Find out whether the user has a row in s_user_group with the // GroupID of the GroupGift row FoundUserGroups = UserGroupDT.Select(SUserGroupTable.GetGroupIdDBName() + " = '" + GroupGiftDT[Counter].GroupId + "'"); if (FoundUserGroups.Length != 0) { // Access to gift can be granted AccessToGift = true; continue; // don't evaluate further GroupGiftDT rows } } } } else { AccessToGift = true; } if (AccessToGift) { tmpLastGiftDate = GiftDR.DateEntered; // Console.WriteLine('GiftDR.LedgerNumber: ' + GiftDR.LedgerNumber.ToString + '; ' + // 'GiftDR.BatchNumber: ' + GiftDR.BatchNumber.ToString); // Load Gift Batch AGiftBatchAccess.LoadByPrimaryKey(LastGiftDS, GiftDR.LedgerNumber, GiftDR.BatchNumber, StringHelper.InitStrArr(new String[] { AGiftBatchTable.GetCurrencyCodeDBName() }), Transaction, null, 0, 0); if (LastGiftDS.Tables[AGiftBatchTable.GetTableName()].Rows.Count != 0) { GiftBatchDR = ((AGiftBatchRow)LastGiftDS.Tables[AGiftBatchTable.GetTableName()].Rows[0]); tmpLastGiftCurrencyCode = GiftBatchDR.CurrencyCode; // Get Currency ACurrencyAccess.LoadByPrimaryKey(LastGiftDS, GiftBatchDR.CurrencyCode, Transaction); if (LastGiftDS.Tables[ACurrencyTable.GetTableName()].Rows.Count != 0) { CurrencyDR = (ACurrencyRow)(LastGiftDS.Tables[ACurrencyTable.GetTableName()].Rows[0]); tmpLastGiftCurrencyCode = CurrencyDR.CurrencyCode; tmpLastGiftDisplayFormat = CurrencyDR.DisplayFormat; } else { tmpLastGiftCurrencyCode = ""; tmpLastGiftDisplayFormat = ""; } } else { // missing Currency tmpLastGiftCurrencyCode = ""; tmpLastGiftDisplayFormat = ""; } // Load Gift Detail AGiftDetailAccess.LoadViaAGift(LastGiftDS, GiftDR.LedgerNumber, GiftDR.BatchNumber, GiftDR.GiftTransactionNumber, StringHelper.InitStrArr(new String[] { AGiftDetailTable.GetGiftTransactionAmountDBName(), AGiftDetailTable.GetRecipientKeyDBName(), AGiftDetailTable. GetRecipientLedgerNumberDBName(), AGiftDetailTable.GetConfidentialGiftFlagDBName() }), Transaction, null, 0, 0); GiftDetailDT = (AGiftDetailTable)LastGiftDS.Tables[AGiftDetailTable.GetTableName()]; if (GiftDetailDT.Rows.Count != 0) { if (GiftDR.LastDetailNumber > 1) { // Gift is a Split Gift tmpLastGiftAmount = 0; for (Counter = 0; Counter <= GiftDetailDT.Rows.Count - 1; Counter += 1) { GiftDetailDR = (AGiftDetailRow)GiftDetailDT.Rows[Counter]; // Check for confidential gift and whether the current user is allowed to see it if (GiftDetailDR.ConfidentialGiftFlag) { if (!((UserInfo.GUserInfo.IsInGroup(SharedConstants.PETRAGROUP_FINANCE2)) || (UserInfo.GUserInfo.IsInGroup(SharedConstants.PETRAGROUP_FINANCE3)))) { // User isn't allowed to see the gift tmpRestrictedOrConfidentialGiftAccessDenied = true; tmpLastGiftAmount = 0; return; } } tmpLastGiftAmount = tmpLastGiftAmount + GiftDetailDR.GiftTransactionAmount; } tmpLastGiftGivenToShortName = ""; tmpLastGiftRecipientLedgerShortName = ""; tmpLastGiftGivenToPartnerKey = -1; tmpLastGiftRecipientLedger = -1; } else { // Gift isn't a Split Gift GiftDetailDR = (AGiftDetailRow)GiftDetailDT.Rows[0]; // Check for confidential gift and whether the current user is allowed to see it if (GiftDetailDR.ConfidentialGiftFlag) { if (!((UserInfo.GUserInfo.IsInGroup(SharedConstants.PETRAGROUP_FINANCE2)) || (UserInfo.GUserInfo.IsInGroup(SharedConstants.PETRAGROUP_FINANCE3)))) { // User isn't allowed to see the gift tmpRestrictedOrConfidentialGiftAccessDenied = true; return; } } tmpLastGiftAmount = GiftDetailDR.GiftTransactionAmount; tmpLastGiftGivenToPartnerKey = GiftDetailDR.RecipientKey; // Get Partner ShortName PPartnerAccess.LoadByPrimaryKey(LastGiftDS, GiftDetailDR.RecipientKey, StringHelper.InitStrArr(new String[] { PPartnerTable.GetPartnerShortNameDBName() }), Transaction, null, 0, 0); if (LastGiftDS.Tables[PPartnerTable.GetTableName()].Rows.Count != 0) { tmpLastGiftGivenToShortName = ((PPartnerRow)(LastGiftDS.Tables[PPartnerTable.GetTableName()].Rows[0])).PartnerShortName; } else { // missing Partner tmpLastGiftGivenToShortName = ""; } // Get rid of last record because we are about to select again into the same DataTable... LastGiftDS.Tables[PPartnerTable.GetTableName()].Rows.Clear(); // Get Recipient Ledger PPartnerAccess.LoadByPrimaryKey(LastGiftDS, GiftDetailDR.RecipientLedgerNumber, StringHelper.InitStrArr(new String[] { PPartnerTable.GetPartnerShortNameDBName() }), Transaction, null, 0, 0); if (LastGiftDS.Tables[PPartnerTable.GetTableName()].Rows.Count != 0) { tmpLastGiftRecipientLedgerShortName = ((PPartnerRow)(LastGiftDS.Tables[PPartnerTable.GetTableName()].Rows[0])).PartnerShortName; } else { // missing Ledger tmpLastGiftRecipientLedgerShortName = ""; } } } else { // missing Gift Detail tmpLastGiftAmount = 0; tmpLastGiftGivenToShortName = ""; tmpLastGiftRecipientLedgerShortName = ""; tmpLastGiftGivenToPartnerKey = -1; tmpLastGiftRecipientLedger = -1; } } else { // Gift is a restriced Gift and the current user isn't allowed to see it tmpRestrictedOrConfidentialGiftAccessDenied = true; } } finally { TLogging.LogAtLevel(7, "TGift.GetLastGiftDetails: committed own transaction."); } }); ALastGiftDate = tmpLastGiftDate; ALastGiftAmount = tmpLastGiftAmount; ALastGiftGivenToPartnerKey = tmpLastGiftGivenToPartnerKey; ALastGiftRecipientLedger = tmpLastGiftRecipientLedger; ALastGiftCurrencyCode = tmpLastGiftCurrencyCode; ALastGiftDisplayFormat = tmpLastGiftDisplayFormat; ALastGiftGivenToShortName = tmpLastGiftGivenToShortName; ALastGiftRecipientLedgerShortName = tmpLastGiftRecipientLedgerShortName; ARestrictedOrConfidentialGiftAccessDenied = tmpRestrictedOrConfidentialGiftAccessDenied; return(AccessToGift); }
/// <summary> /// get the default bank account for this ledger /// </summary> public string GetDefaultBankAccount() { #region Validate Arguments if (FLedgerNumber <= 0) { throw new EFinanceSystemInvalidLedgerNumberException(String.Format(Catalog.GetString( "Function:{0} - The Ledger number must be greater than 0!"), Utilities.GetMethodName(true)), FLedgerNumber); } #endregion Validate Arguments TDataBase db = DBAccess.Connect("GetDefaultBankAccount", FDataBase); TDBTransaction readTransaction = new TDBTransaction(); string BankAccountCode = new TSystemDefaults(db).GetStringDefault( SharedConstants.SYSDEFAULT_GIFTBANKACCOUNT + FLedgerNumber.ToString()); if (BankAccountCode.Length == 0) { try { db.ReadTransaction( ref readTransaction, delegate { // use the first bank account AAccountPropertyTable accountProperties = AAccountPropertyAccess.LoadViaALedger(FLedgerNumber, readTransaction); accountProperties.DefaultView.RowFilter = AAccountPropertyTable.GetPropertyCodeDBName() + " = '" + MFinanceConstants.ACCOUNT_PROPERTY_BANK_ACCOUNT + "' and " + AAccountPropertyTable.GetPropertyValueDBName() + " = 'true'"; if (accountProperties.DefaultView.Count > 0) { BankAccountCode = ((AAccountPropertyRow)accountProperties.DefaultView[0].Row).AccountCode; } else { string SQLQuery = "SELECT a_gift_batch.a_bank_account_code_c" + " FROM a_gift_batch " + " WHERE a_gift_batch.a_ledger_number_i =" + FLedgerNumber + " AND a_gift_batch.a_gift_type_c = '" + MFinanceConstants.GIFT_TYPE_GIFT + "'" + " ORDER BY a_gift_batch.a_batch_number_i DESC" + " LIMIT 1;"; DataTable latestAccountCode = db.SelectDT(SQLQuery, "LatestAccountCode", readTransaction); // use the Bank Account of the previous Gift Batch if ((latestAccountCode != null) && (latestAccountCode.Rows.Count > 0)) { BankAccountCode = latestAccountCode.Rows[0][AGiftBatchTable.GetBankAccountCodeDBName()].ToString(); //"a_bank_account_code_c" } // if this is the first ever gift batch (this should happen only once!) then use the first appropriate Account Code in the database else { AAccountTable accountTable = AAccountAccess.LoadViaALedger(FLedgerNumber, readTransaction); #region Validate Data if ((accountTable == null) || (accountTable.Count == 0)) { throw new EFinanceSystemDataTableReturnedNoDataException(String.Format(Catalog.GetString( "Function:{0} - Account data for Ledger number {1} does not exist or could not be accessed!"), Utilities.GetMethodName(true), FLedgerNumber)); } #endregion Validate Data DataView dv = accountTable.DefaultView; dv.Sort = AAccountTable.GetAccountCodeDBName() + " ASC"; //a_account_code_c dv.RowFilter = String.Format("{0} = true AND {1} = true", AAccountTable.GetAccountActiveFlagDBName(), AAccountTable.GetPostingStatusDBName()); // "a_account_active_flag_l = true AND a_posting_status_l = true"; DataTable sortedDT = dv.ToTable(); TGetAccountHierarchyDetailInfo accountHierarchyTools = new TGetAccountHierarchyDetailInfo(FLedgerNumber); List <string> children = accountHierarchyTools.GetChildren(MFinanceConstants.CASH_ACCT); foreach (DataRow account in sortedDT.Rows) { // check if this account reports to the CASH account if (children.Contains(account["a_account_code_c"].ToString())) { BankAccountCode = account["a_account_code_c"].ToString(); break; } } } } }); if (FDataBase == null) { db.CloseDBConnection(); } } catch (Exception ex) { TLogging.LogException(ex, Utilities.GetMethodSignature()); throw; } } return(BankAccountCode); }
private void DeleteAllGifts(System.Object sender, EventArgs e) { string CompletionMessage = string.Empty; int BatchNumberToClear = FBatchNumber; if ((FPreviouslySelectedDetailRow == null)) { return; } else if (!FFilterAndFindObject.IsActiveFilterEqualToBase) { MessageBox.Show(Catalog.GetString("Please remove the filter before attempting to delete all Recurring Gifts in this batch."), Catalog.GetString("Delete All Recurring Gifts")); return; } //Backup the Dataset for reversion purposes GiftBatchTDS BackupMainDS = (GiftBatchTDS)FMainDS.Copy(); BackupMainDS.Merge(FMainDS); if (MessageBox.Show(String.Format(Catalog.GetString( "You have chosen to delete all Gifts from Recurring Batch ({0}).{1}{1}Are you sure you want to delete all?"), BatchNumberToClear, Environment.NewLine), Catalog.GetString("Confirm Delete All"), MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == System.Windows.Forms.DialogResult.Yes) { try { this.Cursor = Cursors.WaitCursor; //Normally need to set the message parameters before the delete is performed if requiring any of the row values CompletionMessage = String.Format(Catalog.GetString("All Recurring Gifts and details deleted successfully."), FPreviouslySelectedDetailRow.BatchNumber); //clear any transactions currently being editied in the Transaction Tab ClearCurrentSelection(false); //Now delete all Recurring Gift data for current batch DeleteCurrentRecurringBatchGiftData(BatchNumberToClear); FBatchRow.BatchTotal = 0; txtBatchTotal.NumberValueDecimal = 0; // Be sure to set the last Recurring Gift number in the parent table before saving all the changes FBatchRow.LastGiftNumber = 0; FPetraUtilsObject.SetChangedFlag(); // save first, then post if (((TFrmRecurringGiftBatch)ParentForm).SaveChangesManual()) { MessageBox.Show(CompletionMessage, "All Recurring Gifts Deleted.", MessageBoxButtons.OK, MessageBoxIcon.Information); } else { throw new Exception("Unable to save after deleting all Recurring Gifts!"); } } catch (Exception ex) { //Revert to previous state RevertDataSet(FMainDS, BackupMainDS); TLogging.LogException(ex, Utilities.GetMethodSignature()); throw; } finally { SetGiftDetailDefaultView(); FFilterAndFindObject.ApplyFilter(); this.Cursor = Cursors.Default; } } if (grdDetails.Rows.Count < 2) { ShowDetails(null); UpdateControlsProtection(); } UpdateRecordNumberDisplay(); }
/// <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(); }
private bool OnDeleteRowManual(GiftBatchTDSARecurringGiftDetailRow ARowToDelete, ref string ACompletionMessage) { bool DeletionSuccessful = false; ACompletionMessage = string.Empty; if (ARowToDelete == null) { return(DeletionSuccessful); } bool RowToDeleteIsNew = (ARowToDelete.RowState == DataRowState.Added); if (!RowToDeleteIsNew) { try { // temporarily disable New Donor Warning ((TFrmRecurringGiftBatch)this.ParentForm).NewDonorWarning = false; //Return modified row to last saved state to avoid validation failures ARowToDelete.RejectChanges(); ShowDetails(ARowToDelete); if (!((TFrmRecurringGiftBatch)this.ParentForm).SaveChanges()) { MessageBox.Show(Catalog.GetString("Error in trying to save prior to deleting current Gift detail!"), Catalog.GetString("Deletion Error"), MessageBoxButtons.OK, MessageBoxIcon.Error); return(DeletionSuccessful); } } finally { ((TFrmRecurringGiftBatch)this.ParentForm).NewDonorWarning = true; } } //Backup the Dataset for reversion purposes GiftBatchTDS BackupMainDS = (GiftBatchTDS)FMainDS.Copy(); BackupMainDS.Merge(FMainDS); //To be used later....Pass copy to delete method. //RecurringGiftBatchTDS TempDS = (RecurringGiftBatchTDS)FMainDS.Copy(); //TempDS.Merge(FMainDS); int SelectedDetailNumber = ARowToDelete.DetailNumber; int RecurringGiftToDeleteTransNo = 0; string FilterAllRecurringGiftsOfBatch = String.Empty; string FilterAllRecurringGiftDetailsOfBatch = String.Empty; int DetailRowCount = FGiftDetailView.Count; try { this.Cursor = Cursors.WaitCursor; //Speeds up deletion of larger Recurring Gift sets FMainDS.EnforceConstraints = false; //Delete current detail row ARowToDelete.Delete(); //If there existed (before the delete row above) more than one detail row, then no need to delete Recurring Gift header row if (DetailRowCount > 1) { ACompletionMessage = Catalog.GetString("Recurring Gift Detail row deleted successfully!"); FGiftSelectedForDeletion = false; foreach (DataRowView rv in FGiftDetailView) { GiftBatchTDSARecurringGiftDetailRow row = (GiftBatchTDSARecurringGiftDetailRow)rv.Row; if (row.DetailNumber > SelectedDetailNumber) { row.DetailNumber--; } } FGift.LastDetailNumber--; FPetraUtilsObject.SetChangedFlag(); } else { ACompletionMessage = Catalog.GetString("Recurring Gift deleted successfully!"); RecurringGiftToDeleteTransNo = FGift.GiftTransactionNumber; // Reduce all Recurring Gift Detail row Transaction numbers by 1 if they are greater then Recurring Gift to be deleted FilterAllRecurringGiftDetailsOfBatch = String.Format("{0}={1} And {2}>{3}", ARecurringGiftDetailTable.GetBatchNumberDBName(), FBatchNumber, ARecurringGiftDetailTable.GetGiftTransactionNumberDBName(), RecurringGiftToDeleteTransNo); DataView RecurringGiftDetailView = new DataView(FMainDS.ARecurringGiftDetail); RecurringGiftDetailView.RowFilter = FilterAllRecurringGiftDetailsOfBatch; RecurringGiftDetailView.Sort = String.Format("{0} ASC", ARecurringGiftDetailTable.GetGiftTransactionNumberDBName()); foreach (DataRowView rv in RecurringGiftDetailView) { GiftBatchTDSARecurringGiftDetailRow row = (GiftBatchTDSARecurringGiftDetailRow)rv.Row; row.GiftTransactionNumber--; } //Cannot delete the Recurring Gift row, just copy the data of rows above down by 1 row // and then mark the top row for deletion //In other words, bubble the Recurring Gift row to be deleted to the top FilterAllRecurringGiftsOfBatch = String.Format("{0}={1} And {2}>={3}", ARecurringGiftTable.GetBatchNumberDBName(), FBatchNumber, ARecurringGiftTable.GetGiftTransactionNumberDBName(), RecurringGiftToDeleteTransNo); DataView RecurringGiftView = new DataView(FMainDS.ARecurringGift); RecurringGiftView.RowFilter = FilterAllRecurringGiftsOfBatch; RecurringGiftView.Sort = String.Format("{0} ASC", ARecurringGiftTable.GetGiftTransactionNumberDBName()); ARecurringGiftRow RecurringGiftRowToReceive = null; ARecurringGiftRow RecurringGiftRowToCopyDown = null; ARecurringGiftRow RecurringGiftRowCurrent = null; int currentRecurringGiftTransNo = 0; foreach (DataRowView gv in RecurringGiftView) { RecurringGiftRowCurrent = (ARecurringGiftRow)gv.Row; currentRecurringGiftTransNo = RecurringGiftRowCurrent.GiftTransactionNumber; if (currentRecurringGiftTransNo > RecurringGiftToDeleteTransNo) { RecurringGiftRowToCopyDown = RecurringGiftRowCurrent; //Copy column values down for (int j = 3; j < RecurringGiftRowToCopyDown.Table.Columns.Count; j++) { //Update all columns except the pk fields that remain the same if (!RecurringGiftRowToCopyDown.Table.Columns[j].ColumnName.EndsWith("_text")) { RecurringGiftRowToReceive[j] = RecurringGiftRowToCopyDown[j]; } } } if (currentRecurringGiftTransNo == FBatchRow.LastGiftNumber) { //Mark last record for deletion RecurringGiftRowCurrent.ChargeStatus = MFinanceConstants.MARKED_FOR_DELETION; } //Will always be previous row RecurringGiftRowToReceive = RecurringGiftRowCurrent; } FPreviouslySelectedDetailRow = null; FPetraUtilsObject.SetChangedFlag(); FGiftSelectedForDeletion = true; FBatchRow.LastGiftNumber--; } //Try to save changes if (((TFrmRecurringGiftBatch)this.ParentForm).SaveChangesManual()) { //Clear current batch's Recurring Gift data and reload from server RefreshCurrentRecurringBatchGiftData(FBatchNumber, true); } else { throw new Exception("Unable to save after deleting a Recurring Gift!"); } DeletionSuccessful = true; } catch (Exception ex) { //Revert to previous state RevertDataSet(FMainDS, BackupMainDS); TLogging.LogException(ex, Utilities.GetMethodSignature()); throw; } finally { FMainDS.EnforceConstraints = true; SetGiftDetailDefaultView(); FFilterAndFindObject.ApplyFilter(); this.Cursor = Cursors.Default; } UpdateRecordNumberDisplay(); return(DeletionSuccessful); }
/// <summary> /// export all the Data of the batches matching the parameters to a String /// </summary> /// <param name="ARequestParams">Hashtable containing the given params </param> /// <param name="AExportString">Big parts of the export file as a simple String</param> /// <param name="AVerificationMessages">Additional messages to display in a messagebox</param> /// <returns>number of exported batches, -1 if cancelled, -2 if error</returns> public Int32 ExportAllGiftBatchData( Hashtable ARequestParams, out String AExportString, out TVerificationResultCollection AVerificationMessages) { //Return number of exported batches, -1 if cancelled, -2 if error int ReturnGiftBatchCount = 0; FStringWriter = new StringWriter(); FMainDS = new GiftBatchTDS(); FDelimiter = (String)ARequestParams["Delimiter"]; FLedgerNumber = (Int32)ARequestParams["ALedgerNumber"]; FDateFormatString = (String)ARequestParams["DateFormatString"]; Boolean Summary = (Boolean)ARequestParams["Summary"]; FUseBaseCurrency = (Boolean)ARequestParams["bUseBaseCurrency"]; FDateForSummary = (DateTime)ARequestParams["DateForSummary"]; String NumberFormat = (String)ARequestParams["NumberFormat"]; FCultureInfo = new CultureInfo(NumberFormat.Equals("American") ? "en-US" : "de-DE"); FTransactionsOnly = (Boolean)ARequestParams["TransactionsOnly"]; FExtraColumns = (Boolean)ARequestParams["ExtraColumns"]; Int64 recipientNumber = (Int64)ARequestParams["RecipientNumber"]; String RecipientFilter = (recipientNumber != 0) ? " AND PUB_a_gift_detail.p_recipient_key_n = " + recipientNumber : ""; Int64 fieldNumber = (Int64)ARequestParams["FieldNumber"]; String FieldFilter = (fieldNumber != 0) ? " AND PUB_a_gift_detail.a_recipient_ledger_number_n = " + fieldNumber : ""; Boolean IncludeUnposted = (Boolean)ARequestParams["IncludeUnposted"]; String StatusFilter = (IncludeUnposted) ? " AND (PUB_a_gift_batch.a_batch_status_c = 'Posted' OR PUB_a_gift_batch.a_batch_status_c = 'Unposted')" : " AND PUB_a_gift_batch.a_batch_status_c = 'Posted'"; try { DBAccess.GDBAccessObj.BeginAutoReadTransaction(IsolationLevel.ReadCommitted, ref FTransaction, delegate { try { ALedgerAccess.LoadByPrimaryKey(FMainDS, FLedgerNumber, FTransaction); String BatchRangeFilter = (ARequestParams.ContainsKey( "BatchNumberStart")) ? " AND (PUB_a_gift_batch.a_batch_number_i >= " + (Int32)ARequestParams["BatchNumberStart"] + " AND PUB_a_gift_batch.a_batch_number_i <= " + (Int32)ARequestParams["BatchNumberEnd"] + ")" : ""; // If I've specified a BatchRange, I can't also have a DateRange: String DateRangeFilter = (BatchRangeFilter == "") ? " AND (PUB_a_gift_batch.a_gl_effective_date_d >= '" + ((DateTime)ARequestParams["BatchDateFrom"]).ToString( "yyyy-MM-dd") + "' AND PUB_a_gift_batch.a_gl_effective_date_d <= '" + ((DateTime)ARequestParams["BatchDateTo"]).ToString("yyyy-MM-dd") + "')" : ""; string StatementCore = " FROM PUB_a_gift_batch, PUB_a_gift, PUB_a_gift_detail" + " WHERE PUB_a_gift_batch.a_ledger_number_i = " + FLedgerNumber + RecipientFilter + FieldFilter + DateRangeFilter + BatchRangeFilter + StatusFilter + " AND PUB_a_gift.a_ledger_number_i = PUB_a_gift_batch.a_ledger_number_i" + " AND PUB_a_gift.a_batch_number_i = PUB_a_gift_batch.a_batch_number_i" + " AND PUB_a_gift_detail.a_ledger_number_i = PUB_a_gift_batch.a_ledger_number_i" + " AND PUB_a_gift_detail.a_batch_number_i = PUB_a_gift_batch.a_batch_number_i" + " AND PUB_a_gift_detail.a_gift_transaction_number_i = PUB_a_gift.a_gift_transaction_number_i"; string sqlStatement = "SELECT DISTINCT PUB_a_gift_batch.* " + StatementCore + " ORDER BY " + AGiftBatchTable.GetBatchNumberDBName(); TProgressTracker.SetCurrentState(DomainManager.GClientID.ToString(), Catalog.GetString("Retrieving gift batch records"), 5); if (TProgressTracker.GetCurrentState(DomainManager.GClientID.ToString()).CancelJob == true) { TProgressTracker.FinishJob(DomainManager.GClientID.ToString()); throw new ApplicationException(Catalog.GetString("Export of Batches was cancelled by user")); } DBAccess.GDBAccessObj.Select(FMainDS, sqlStatement, FMainDS.AGiftBatch.TableName, FTransaction ); TProgressTracker.SetCurrentState(DomainManager.GClientID.ToString(), Catalog.GetString("Retrieving gift records"), 10); if (TProgressTracker.GetCurrentState(DomainManager.GClientID.ToString()).CancelJob == true) { TProgressTracker.FinishJob(DomainManager.GClientID.ToString()); throw new ApplicationException(Catalog.GetString("Export of Batches was cancelled by user")); } sqlStatement = "SELECT DISTINCT PUB_a_gift.* " + StatementCore + " ORDER BY " + AGiftBatchTable.GetBatchNumberDBName() + ", " + AGiftTable.GetGiftTransactionNumberDBName(); DBAccess.GDBAccessObj.Select(FMainDS, sqlStatement, FMainDS.AGift.TableName, FTransaction); TProgressTracker.SetCurrentState(DomainManager.GClientID.ToString(), Catalog.GetString("Retrieving gift detail records"), 15); if (TProgressTracker.GetCurrentState(DomainManager.GClientID.ToString()).CancelJob == true) { TProgressTracker.FinishJob(DomainManager.GClientID.ToString()); throw new ApplicationException(Catalog.GetString("Export of Batches was cancelled by user")); } sqlStatement = "SELECT DISTINCT PUB_a_gift_detail.* " + StatementCore; DBAccess.GDBAccessObj.Select(FMainDS, sqlStatement, FMainDS.AGiftDetail.TableName, FTransaction); } catch (Exception ex) { TLogging.LogException(ex, Utilities.GetMethodSignature()); throw; } }); TProgressTracker.InitProgressTracker(DomainManager.GClientID.ToString(), Catalog.GetString("Exporting Gift Batches"), 100); TProgressTracker.SetCurrentState(DomainManager.GClientID.ToString(), Catalog.GetString("Retrieving records"), 5); string BaseCurrency = FMainDS.ALedger[0].BaseCurrency; FCurrencyCode = BaseCurrency; // Depending on FUseBaseCurrency, this will be overwritten for each gift. SortedDictionary <String, AGiftSummaryRow> sdSummary = new SortedDictionary <String, AGiftSummaryRow>(); UInt32 counter = 0; // TProgressTracker Variables UInt32 GiftCounter = 0; AGiftSummaryRow giftSummary = null; FMainDS.AGiftDetail.DefaultView.Sort = AGiftDetailTable.GetLedgerNumberDBName() + "," + AGiftDetailTable.GetBatchNumberDBName() + "," + AGiftDetailTable.GetGiftTransactionNumberDBName(); foreach (AGiftBatchRow giftBatch in FMainDS.AGiftBatch.Rows) { if (TProgressTracker.GetCurrentState(DomainManager.GClientID.ToString()).CancelJob == true) { TProgressTracker.FinishJob(DomainManager.GClientID.ToString()); throw new ApplicationException(Catalog.GetString("Export of Batches was cancelled by user")); } ReturnGiftBatchCount++; TProgressTracker.SetCurrentState(DomainManager.GClientID.ToString(), string.Format(Catalog.GetString("Batch {0}"), giftBatch.BatchNumber), 20); GiftCounter = 0; if (!FTransactionsOnly & !Summary) { WriteGiftBatchLine(giftBatch); } foreach (AGiftRow gift in FMainDS.AGift.Rows) { if (gift.BatchNumber.Equals(giftBatch.BatchNumber) && gift.LedgerNumber.Equals(giftBatch.LedgerNumber)) { if (TProgressTracker.GetCurrentState(DomainManager.GClientID.ToString()).CancelJob == true) { TProgressTracker.FinishJob(DomainManager.GClientID.ToString()); throw new ApplicationException(Catalog.GetString("Export of Batches was cancelled by user")); } // Update progress tracker every 25 records if (++GiftCounter % 25 == 0) { TProgressTracker.SetCurrentState(DomainManager.GClientID.ToString(), string.Format(Catalog.GetString("Batch {0} - Exporting gifts"), giftBatch.BatchNumber), (GiftCounter / 25 + 4) * 5 > 90 ? 90 : (GiftCounter / 25 + 4) * 5); } DataRowView[] selectedRowViews = FMainDS.AGiftDetail.DefaultView.FindRows( new object[] { gift.LedgerNumber, gift.BatchNumber, gift.GiftTransactionNumber }); foreach (DataRowView rv in selectedRowViews) { AGiftDetailRow giftDetail = (AGiftDetailRow)rv.Row; if (Summary) { FCurrencyCode = FUseBaseCurrency ? BaseCurrency : giftBatch.CurrencyCode; decimal mapExchangeRateToBase = FUseBaseCurrency ? 1 : giftBatch.ExchangeRateToBase; counter++; String DictionaryKey = FCurrencyCode + ";" + giftBatch.BankCostCentre + ";" + giftBatch.BankAccountCode + ";" + giftDetail.RecipientKey + ";" + giftDetail.MotivationGroupCode + ";" + giftDetail.MotivationDetailCode; if (sdSummary.TryGetValue(DictionaryKey, out giftSummary)) { giftSummary.GiftTransactionAmount += giftDetail.GiftTransactionAmount; giftSummary.GiftAmount += giftDetail.GiftAmount; } else { giftSummary = new AGiftSummaryRow(); /* * summary_data.a_transaction_currency_c = lv_stored_currency_c * summary_data.a_bank_cost_centre_c = a_gift_batch.a_bank_cost_centre_c * summary_data.a_bank_account_code_c = a_gift_batch.a_bank_account_code_c * summary_data.a_recipient_key_n = a_gift_detail.p_recipient_key_n * summary_data.a_motivation_group_code_c = a_gift_detail.a_motivation_group_code_c * summary_data.a_motivation_detail_code_c = a_gift_detail.a_motivation_detail_code_c * summary_data.a_exchange_rate_to_base_n = lv_exchange_rate_n * summary_data.a_gift_type_c = a_gift_batch.a_gift_type_c */ giftSummary.CurrencyCode = FCurrencyCode; giftSummary.BankCostCentre = giftBatch.BankCostCentre; giftSummary.BankAccountCode = giftBatch.BankAccountCode; giftSummary.RecipientKey = giftDetail.RecipientKey; giftSummary.MotivationGroupCode = giftDetail.MotivationGroupCode; giftSummary.MotivationDetailCode = giftDetail.MotivationDetailCode; giftSummary.GiftTransactionAmount = giftDetail.GiftTransactionAmount; giftSummary.GiftAmount = giftDetail.GiftAmount; sdSummary.Add(DictionaryKey, giftSummary); } //overwrite always because we want to have the last giftSummary.ExchangeRateToBase = mapExchangeRateToBase; } else // not summary { WriteGiftLine(gift, giftDetail); } } } } } if (Summary) { TProgressTracker.SetCurrentState(DomainManager.GClientID.ToString(), Catalog.GetString("Export Summary"), 95); bool first = true; foreach (KeyValuePair <string, AGiftSummaryRow> kvp in sdSummary) { if (!FTransactionsOnly && first) { WriteGiftBatchSummaryLine(kvp.Value); first = false; } WriteGiftSummaryLine(kvp.Value); } } TProgressTracker.SetCurrentState(DomainManager.GClientID.ToString(), Catalog.GetString("Gift batch export successful"), 100); TProgressTracker.FinishJob(DomainManager.GClientID.ToString()); } catch (ApplicationException) { //Show cancel condition ReturnGiftBatchCount = -1; TProgressTracker.CancelJob(DomainManager.GClientID.ToString()); } catch (Exception ex) { TLogging.Log(ex.ToString()); //Show error condition ReturnGiftBatchCount = -2; FMessages.Add(new TVerificationResult( "Exporting Gift Batches Terminated Unexpectedly", ex.Message, "An unexpected error occurred during the export of gift batches", string.Empty, TResultSeverity.Resv_Critical, Guid.Empty)); TProgressTracker.CancelJob(DomainManager.GClientID.ToString()); } if (ReturnGiftBatchCount > 0) { AExportString = FStringWriter.ToString(); } else { AExportString = string.Empty; } AVerificationMessages = FMessages; return(ReturnGiftBatchCount); } // ExportAllGiftBatchData
private static void PopulateLedgerDictionaries(int ALedgerNumber, TDataBase ADataBase = null) { bool LedgerDictPrePopulated = (FLedgerNamesDict.Count > 0); if (LedgerDictPrePopulated && FLedgerNamesDict.ContainsKey(ALedgerNumber)) { return; } //Prepare a temp dictionaries for minimum time in lock Dictionary <int, string> LedgerNamesDictTemp = new Dictionary <int, string>(); Dictionary <int, string> LedgerCountryCodesDictTemp = new Dictionary <int, string>(); Dictionary <int, string> LedgerBaseCurrencyDictTemp = new Dictionary <int, string>(); //Take a backup for reversion purposes if error occurs Dictionary <int, string> LedgerNamesDictBackup = null; Dictionary <int, string> LedgerCountryCodesDictBackup = null; Dictionary <int, string> LedgerBaseCurrencyDictBackup = null; TDBTransaction Transaction = null; try { DBAccess.GetDBAccessObj(ADataBase).GetNewOrExistingAutoReadTransaction(IsolationLevel.ReadCommitted, TEnforceIsolationLevel.eilMinimum, ref Transaction, delegate { String strSql = "SELECT a_ledger_number_i, p_partner_short_name_c, a_country_code_c, a_base_currency_c" + " FROM PUB_a_ledger, PUB_p_partner" + " WHERE PUB_a_ledger.p_partner_key_n = PUB_p_partner.p_partner_key_n;"; DataTable ledgerData = DBAccess.GetDBAccessObj(ADataBase).SelectDT(strSql, "GetLedgerName_TempTable", Transaction); #region Validate Data if ((ledgerData == null) || (ledgerData.Rows.Count == 0)) { throw new EFinanceSystemDataTableReturnedNoDataException(String.Format(Catalog.GetString( "Function:{0} - Ledger and Partner data does not exist or could not be accessed!"), Utilities.GetMethodName(true))); } #endregion Validate Data int currentLedger = 0; string currentLedgerName = string.Empty; string currentLedgerCountryCode = string.Empty; string currentLedgerBaseCurrency = string.Empty; for (int i = 0; i < ledgerData.Rows.Count; i++) { currentLedger = Convert.ToInt32(ledgerData.Rows[i][ALedgerTable.GetLedgerNumberDBName()]); currentLedgerName = Convert.ToString(ledgerData.Rows[i][PPartnerTable.GetPartnerShortNameDBName()]); currentLedgerCountryCode = Convert.ToString(ledgerData.Rows[i][ALedgerTable.GetCountryCodeDBName()]); currentLedgerBaseCurrency = Convert.ToString(ledgerData.Rows[i][ALedgerTable.GetBaseCurrencyDBName()]); LedgerNamesDictTemp.Add(currentLedger, currentLedgerName); LedgerCountryCodesDictTemp.Add(currentLedger, currentLedgerCountryCode); LedgerBaseCurrencyDictTemp.Add(currentLedger, currentLedgerBaseCurrency); } bool lockEntered = false; try { if (FReadWriteLock.TryEnterWriteLock(10)) { lockEntered = true; if (LedgerDictPrePopulated) { //Backup dictionaries LedgerNamesDictBackup = new Dictionary <int, string>(FLedgerNamesDict); LedgerCountryCodesDictBackup = new Dictionary <int, string>(FLedgerCountryCodeDict); LedgerBaseCurrencyDictBackup = new Dictionary <int, string>(FLedgerBaseCurrencyDict); FLedgerNamesDict.Clear(); FLedgerCountryCodeDict.Clear(); FLedgerBaseCurrencyDict.Clear(); } FLedgerNamesDict = new Dictionary <int, string>(LedgerNamesDictTemp); FLedgerCountryCodeDict = new Dictionary <int, string>(LedgerCountryCodesDictTemp); FLedgerBaseCurrencyDict = new Dictionary <int, string>(LedgerBaseCurrencyDictTemp); } } finally { if (lockEntered) { FReadWriteLock.ExitWriteLock(); } } }); } catch (Exception ex) { if (LedgerNamesDictBackup != null) { FLedgerNamesDict = new Dictionary <int, string>(LedgerNamesDictBackup); FLedgerCountryCodeDict = new Dictionary <int, string>(LedgerCountryCodesDictBackup); FLedgerBaseCurrencyDict = new Dictionary <int, string>(LedgerBaseCurrencyDictBackup); } TLogging.LogException(ex, Utilities.GetMethodSignature()); throw; } }
/// <summary> /// Clear the gift data of the current batch without marking records for delete /// </summary> private bool RefreshBatchGiftData(Int32 ABatchNumber, bool AAcceptChanges = false, bool AHandleDataSetBackup = false) { bool RetVal = false; //Copy and backup the current dataset GiftBatchTDS BackupDS = null; GiftBatchTDS TempDS = (GiftBatchTDS)FMainDS.Copy(); TempDS.Merge(FMainDS); if (AHandleDataSetBackup) { BackupDS = (GiftBatchTDS)FMainDS.GetChangesTyped(false); } try { this.Cursor = Cursors.WaitCursor; //Remove current batch gift data DataView giftDetailView = new DataView(TempDS.AGiftDetail); giftDetailView.RowFilter = String.Format("{0}={1}", AGiftDetailTable.GetBatchNumberDBName(), ABatchNumber); giftDetailView.Sort = String.Format("{0} DESC, {1} DESC", AGiftDetailTable.GetGiftTransactionNumberDBName(), AGiftDetailTable.GetDetailNumberDBName()); foreach (DataRowView dr in giftDetailView) { dr.Delete(); } DataView giftView = new DataView(TempDS.AGift); giftView.RowFilter = String.Format("{0}={1}", AGiftTable.GetBatchNumberDBName(), ABatchNumber); giftView.Sort = String.Format("{0} DESC", AGiftTable.GetGiftTransactionNumberDBName()); foreach (DataRowView dr in giftView) { dr.Delete(); } TempDS.AcceptChanges(); //Clear all gift data from Main dataset gift tables FMainDS.AGiftDetail.Clear(); FMainDS.AGift.Clear(); //Bring data back in from other batches if it exists if (TempDS.AGift.Count > 0) { FMainDS.AGift.Merge(TempDS.AGift); FMainDS.AGiftDetail.Merge(TempDS.AGiftDetail); } //TODO: Confirm I need to AcceptChanges FMainDS.Merge(TRemote.MFinance.Gift.WebConnectors.LoadGiftTransactionsForBatch(FLedgerNumber, ABatchNumber)); if (AAcceptChanges) { FMainDS.AcceptChanges(); } RetVal = true; } catch (Exception ex) { //If not revert on error then calling method will if (AHandleDataSetBackup) { RevertDataSet(FMainDS, BackupDS); } TLogging.LogException(ex, Utilities.GetMethodSignature()); throw; } finally { this.Cursor = Cursors.Default; } return(RetVal); }
/// <summary> /// Method to cancel a specified batch /// </summary> /// <param name="ABatchRowToCancel">The row to cancel</param> /// <returns></returns> public bool CancelBatch(ABatchRow ABatchRowToCancel) { bool CancellationSuccessful = false; if ((ABatchRowToCancel == null) || (ABatchRowToCancel.BatchStatus != MFinanceConstants.BATCH_UNPOSTED)) { return(false); } int CurrentBatchNo = ABatchRowToCancel.BatchNumber; bool CurrentBatchJournalsLoadedAndCurrent = false; bool CurrentBatchTransactionsLoadedAndCurrent = false; string CancelMessage = string.Empty; string CompletionMessage = string.Empty; CancelMessage = String.Format(Catalog.GetString("Are you sure you want to cancel GL Batch {0}?"), CurrentBatchNo); if ((MessageBox.Show(CancelMessage, "Cancel GL Batch", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) != System.Windows.Forms.DialogResult.Yes)) { return(false); } //Backup the Dataset for reversion purposes GLBatchTDS BackupMainDS = null; try { FMyForm.Cursor = Cursors.WaitCursor; //Backup the Dataset for reversion purposes BackupMainDS = (GLBatchTDS)FMainDS.GetChangesTyped(false); //Don't run an inactive fields check on this batch FMyForm.GetBatchControl().UpdateUnpostedBatchDictionary(CurrentBatchNo); //Check if current batch details are currently loaded CurrentBatchJournalsLoadedAndCurrent = (FMyForm.GetJournalsControl().FBatchNumber == CurrentBatchNo); CurrentBatchTransactionsLoadedAndCurrent = (FMyForm.GetTransactionsControl().FBatchNumber == CurrentBatchNo); //Save and check for inactive values in other unsaved Batches FPetraUtilsObject.SetChangedFlag(); if (!FMyForm.SaveChangesManual(FMyForm.FCurrentGLBatchAction, !CurrentBatchJournalsLoadedAndCurrent, !CurrentBatchTransactionsLoadedAndCurrent)) { FMyForm.GetBatchControl().UpdateUnpostedBatchDictionary(); CompletionMessage = String.Format(Catalog.GetString("GL Batch {0} has not been cancelled."), CurrentBatchNo); MessageBox.Show(CompletionMessage, Catalog.GetString("GL Batch Cancellation"), MessageBoxButtons.OK, MessageBoxIcon.Information); return(false); } //Remove any changes to current batch that may cause validation issues FMyForm.GetBatchControl().PrepareBatchDataForCancelling(CurrentBatchNo, true); //Clear the journal and trans tabs if current batch data is displayed there if (CurrentBatchJournalsLoadedAndCurrent) { //Clear any transactions currently being edited in the Transaction Tab FMyForm.GetJournalsControl().ClearCurrentSelection(CurrentBatchNo); } if (CurrentBatchTransactionsLoadedAndCurrent) { //Clear any transactions currently being edited in the Transaction Tab FMyForm.GetTransactionsControl().ClearCurrentSelection(CurrentBatchNo); } //Delete transactions and attributes FMyForm.GetTransactionsControl().DeleteTransactionData(CurrentBatchNo); //Journals are not deleted. Update Journal totals and status foreach (AJournalRow journal in FMainDS.AJournal.Rows) { if (journal.BatchNumber == CurrentBatchNo) { journal.BeginEdit(); journal.JournalCreditTotal = 0; journal.JournalDebitTotal = 0; journal.LastTransactionNumber = 0; journal.JournalStatus = MFinanceConstants.BATCH_CANCELLED; journal.EndEdit(); } } // Edit the batch row ABatchRowToCancel.BeginEdit(); ABatchRowToCancel.BatchCreditTotal = 0; ABatchRowToCancel.BatchDebitTotal = 0; ABatchRowToCancel.BatchControlTotal = 0; ABatchRowToCancel.BatchStatus = MFinanceConstants.BATCH_CANCELLED; ABatchRowToCancel.EndEdit(); FPetraUtilsObject.SetChangedFlag(); FMyForm.SaveChangesManual(); CompletionMessage = String.Format(Catalog.GetString("Batch no.: {0} cancelled successfully."), CurrentBatchNo); MessageBox.Show(CompletionMessage, Catalog.GetString("Batch Cancelled"), MessageBoxButtons.OK, MessageBoxIcon.Information); FMyForm.DisableTransactions(); FMyForm.DisableJournals(); CancellationSuccessful = true; } catch (Exception ex) { //Revert to previous state if (BackupMainDS != null) { FMainDS.RejectChanges(); FMainDS.Merge(BackupMainDS); FMyForm.GetBatchControl().ShowDetailsRefresh(); } TLogging.LogException(ex, Utilities.GetMethodSignature()); throw; } finally { FMyForm.Cursor = Cursors.Default; } return(CancellationSuccessful); }