private void StartCheck(Object Sender, EventArgs e) { // run in thread so we can have Progress Dialog Thread t = new Thread(() => TRemote.MPartner.Mailroom.WebConnectors.FindAddressDuplicates(ref FDuplicateLocations, chkNumber.Checked)); using (TProgressDialog dialog = new TProgressDialog(t)) { dialog.ShowDialog(); } DataView myDataView = FDuplicateLocations.DefaultView; myDataView.Sort = "SiteKeyA ASC, LocationKeyA ASC, SiteKeyB ASC, LocationKeyB ASC"; myDataView.AllowNew = false; grdResults.DataSource = new DevAge.ComponentModel.BoundDataView(myDataView); grdResults.AutoResizeGrid(); UpdateRecordNumberDisplay(); if (FDuplicateLocations.Rows.Count > 0) { btnMergeAddresses.Enabled = true; btnPrintReport.Enabled = true; mniFilePrint.Enabled = true; grdResults.SelectRowInGrid(1); } else { btnMergeAddresses.Enabled = false; btnPrintReport.Enabled = false; mniFilePrint.Enabled = false; } }
private void TrainingLastMonth(object sender, EventArgs e) { Thread t = new Thread(() => TrainBankStatementsLastMonth()); using (TProgressDialog dialog = new TProgressDialog(t)) { if (dialog.ShowDialog() == DialogResult.Cancel) { MessageBox.Show("Das Trainieren wurde abgebrochen"); } if (dialog.ShowDialog() == DialogResult.OK) { MessageBox.Show("Das Trainieren war erfolgreich"); } } }
/// <summary> /// this will delete the current database, and reset it with the data selected /// </summary> /// <param name="AParentForm"></param> public static void RestoreDatabase(Form AParentForm) { string StrImportCancelledMsg = Catalog.GetString("Restoring of database got cancelled; no existing data has been deleted or modified!"); string StrImportCancelledTitle = Catalog.GetString("Restore Cancelled"); DialogResult r = MessageBox.Show( Catalog.GetString( "WARNING: This will THROW AWAY ALL CURRENT DATA that is held in the database (including the users and passwords!) and replace it with the data that was previously backed up and which you chose to restore!\r\n\r\nDo you REALLY want to restore that data?"), Catalog.GetString("WARNING: Replace All Data With Previously Backed Up Data?"), MessageBoxButtons.YesNo, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2); if (r == DialogResult.Yes) { string zippedYml = TImportExportDialogs.ImportWithDialogYMLGz(Catalog.GetString("Select Backup File to Restore From")); if (zippedYml != null) { Thread ResetDBThread = new Thread(() => ResetDatabaseInThread(zippedYml)); using (TProgressDialog dialog = new TProgressDialog(ResetDBThread)) { if (dialog.ShowDialog() == DialogResult.Cancel) { MessageBox.Show(StrImportCancelledMsg, StrImportCancelledTitle, MessageBoxButtons.OK, MessageBoxIcon.Information); return; } } // Ensure that WebConnectorResult got set in Method 'ResetDatabaseInThread' before we get to the if statement below... ResetDBThread.Join(); if (WebConnectorResult) { // TODO: reset all caches? for comboboxes etc MessageBox.Show(Catalog.GetString( "The data was successfully restored.\r\n\r\nPlease restart your OpenPetra Client immediately!"), Catalog.GetString("Restore Successful"), MessageBoxButtons.OK, MessageBoxIcon.Information); } else { MessageBox.Show(Catalog.GetString("The restoring of the data FAILED. No existing data has been deleted or modified!\r\n\r\n" + "Please check the Server.log file on the server for errors!"), Catalog.GetString("Restore Failed"), MessageBoxButtons.OK, MessageBoxIcon.Error); } } else { MessageBox.Show(StrImportCancelledMsg, StrImportCancelledTitle, MessageBoxButtons.OK, MessageBoxIcon.Information); } } }
/// delete ledger public static void DeleteLedger(Form AMainWindow, Int32 ALedgerNumber) { string LedgerNameAndNumber = TFinanceControls.GetLedgerNumberAndName(ALedgerNumber); if (MessageBox.Show(Catalog.GetString("Please save a backup of your database first!!!") + Environment.NewLine + string.Format(Catalog.GetString("Do you REALLY want to delete ledger '{0}'?"), LedgerNameAndNumber), Catalog.GetString("Delete Ledger"), MessageBoxButtons.YesNoCancel, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button3 ) == DialogResult.Yes) { // ledger cannot be deleted if there are any transactions existing for it if (TRemote.MFinance.Setup.WebConnectors.ContainsTransactions(ALedgerNumber)) { MessageBox.Show( string.Format(Catalog.GetString("There are still transactions associated with Ledger '{0}'. \r\n\r\nNothing has been done."), LedgerNameAndNumber), Catalog.GetString("Deletion not possible"), MessageBoxButtons.OK, MessageBoxIcon.Error); } else { Thread t = new Thread(() => ProcessDeletion(AMainWindow, ALedgerNumber, LedgerNameAndNumber)); using (TProgressDialog dialog = new TProgressDialog(t)) { dialog.AllowCancellation = false; dialog.ShowDialog(); } // reload list of Ledger names TDataCache.TMFinance.RefreshCacheableFinanceTable(TCacheableFinanceTablesEnum.LedgerNameList); // reload navigation // Setting the "CurrentLedger" to -1 isn't strictly needed, but it eradicates the Ledger // we have presently deleted to make sure the Main Menu isn't working any further with a // Ledger that doesn't exist anymore. PropertyInfo CurrentLedgerProperty = AMainWindow.GetType().GetProperty("CurrentLedger"); CurrentLedgerProperty.SetValue(AMainWindow, -1, null); MethodInfo method = AMainWindow.GetType().GetMethod("LoadNavigationUI"); if (method != null) { method.Invoke(AMainWindow, new object[] { false }); method = AMainWindow.GetType().GetMethod("SelectFinanceFolder"); method.Invoke(AMainWindow, new object[] { }); } } } }
private void StartCheck(Object Sender, EventArgs e) { // run in thread so we can have Progress Dialog Thread t = new Thread(() => TRemote.MPartner.Mailroom.WebConnectors.FindAddressDuplicates(ref FDuplicateLocations, chkNumber.Checked)); using (TProgressDialog dialog = new TProgressDialog(t)) { dialog.ShowDialog(); } DataView myDataView = FDuplicateLocations.DefaultView; myDataView.Sort = "SiteKeyA ASC, LocationKeyA ASC, SiteKeyB ASC, LocationKeyB ASC"; myDataView.AllowNew = false; grdResults.DataSource = new DevAge.ComponentModel.BoundDataView(myDataView); grdResults.AutoResizeGrid(); UpdateRecordNumberDisplay(); if (FDuplicateLocations.Rows.Count >= 500) { System.Windows.Forms.MessageBox.Show( Catalog.GetString( "Too many duplicates found (maximum 500). Please deal with these first, then re-run the report for more."), Catalog.GetString("Duplicate Address Check"), System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Information); } if (FDuplicateLocations.Rows.Count > 0) { btnMergeAddresses.Enabled = true; btnPrintReport.Enabled = true; mniFilePrint.Enabled = true; grdResults.SelectRowInGrid(1); } else { btnMergeAddresses.Enabled = false; btnPrintReport.Enabled = false; mniFilePrint.Enabled = false; } }
/// <summary> /// this will delete the current database, and reset it with the data selected /// </summary> /// <param name="AParentForm"></param> public static void ImportAllData(Form AParentForm) { DialogResult r = MessageBox.Show( Catalog.GetString("WARNING: this will reset the database! Do you really want to delete the current database?"), Catalog.GetString("WARNING: this will reset the database!"), MessageBoxButtons.YesNo, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2); if (r == DialogResult.Yes) { string zippedYml = TImportExportDialogs.ImportWithDialogYMLGz(Catalog.GetString("Please select the file to import from")); if (zippedYml != null) { Thread t = new Thread(() => ResetDatabaseInThread(zippedYml)); using (TProgressDialog dialog = new TProgressDialog(t)) { if (dialog.ShowDialog() == DialogResult.Cancel) { return; } } if (WebConnectorResult) { // TODO: reset all caches? for comboboxes etc MessageBox.Show(Catalog.GetString("Import of database was successful. Please restart your OpenPetra client")); } else { MessageBox.Show(Catalog.GetString("Failed import of database. Please check the Server.log file on the server")); } } } }
/// delete the complete conference including all conference data public static void DeleteConference(Form AMainWindow, Int64 AConferenceKey, string AConferenceName) { if (MessageBox.Show(Catalog.GetString("Please save a backup of your database first!!!") + Environment.NewLine + string.Format(Catalog.GetString("Do you REALLY want to delete conference '{0}'?"), AConferenceName), Catalog.GetString("Delete Conference"), MessageBoxButtons.YesNo, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2 ) == DialogResult.Yes) { Thread t = new Thread(() => ProcessDeletion(AMainWindow, AConferenceKey, AConferenceName)); using (TProgressDialog dialog = new TProgressDialog(t)) { dialog.ShowDialog(); } if (AConferenceKey == TUserDefaults.GetInt64Default("LASTCONFERENCEWORKEDWITH")) { // update user defaults table TUserDefaults.SetDefault(TUserDefaults.CONFERENCE_LASTCONFERENCEWORKEDWITH, 0); // reload navigation PropertyInfo CurrentConferenceProperty = AMainWindow.GetType().GetProperty("SelectedConferenceKey"); CurrentConferenceProperty.SetValue(AMainWindow, 0, null); MethodInfo method = AMainWindow.GetType().GetMethod("LoadNavigationUI"); if (method != null) { method.Invoke(AMainWindow, new object[] { false }); method = AMainWindow.GetType().GetMethod("SelectConferenceFolder"); method.Invoke(AMainWindow, new object[] { }); } } } }
/// <summary> /// Main method to post a specified batch /// </summary> /// <param name="ACurrentBatchRow">The batch row to post</param> /// <param name="ARefreshGUIAfterPosting">Will be set to true if the GUI should be updated. Can be true even if Posting fails /// <param name="AWarnOfInactiveValues">True means user is warned if inactive values exist</param> /// <param name="ADonorZeroIsValid"></param> /// <param name="ARecipientZeroIsValid"></param> /// <param name="APostingAlreadyConfirmed">True means ask user if they want to post</param> /// if the server gets a SerializableTransactionException</param> /// <returns>True if the batch was successfully posted</returns> public bool PostBatch(AGiftBatchRow ACurrentBatchRow, out bool ARefreshGUIAfterPosting, bool AWarnOfInactiveValues = true, bool ADonorZeroIsValid = false, bool ARecipientZeroIsValid = false, bool APostingAlreadyConfirmed = false) { ARefreshGUIAfterPosting = false; if ((ACurrentBatchRow == null) || (ACurrentBatchRow.BatchStatus != MFinanceConstants.BATCH_UNPOSTED)) { return(false); } FSelectedBatchNumber = ACurrentBatchRow.BatchNumber; //Make sure that all control data is in dataset FMyForm.GetLatestControlData(); //Copy all batch data to new table GiftBatchTDSAGiftDetailTable BatchGiftDetails = new GiftBatchTDSAGiftDetailTable(); DataView BatchGiftDetailsDV = new DataView(FMainDS.AGiftDetail); BatchGiftDetailsDV.RowFilter = string.Format("{0}={1}", AGiftDetailTable.GetBatchNumberDBName(), FSelectedBatchNumber); BatchGiftDetailsDV.Sort = string.Format("{0} ASC, {1} ASC, {2} ASC", AGiftDetailTable.GetBatchNumberDBName(), AGiftDetailTable.GetGiftTransactionNumberDBName(), AGiftDetailTable.GetDetailNumberDBName()); foreach (DataRowView drv in BatchGiftDetailsDV) { GiftBatchTDSAGiftDetailRow gBRow = (GiftBatchTDSAGiftDetailRow)drv.Row; BatchGiftDetails.Rows.Add((object[])gBRow.ItemArray.Clone()); } //Save and check for inactive values and ex-workers and anonymous gifts if (FPetraUtilsObject.HasChanges) { //Keep this conditional check separate from the one above so that it only gets called // when necessary and doesn't result in the executon of the same method if (!FMyForm.SaveChangesForPosting(BatchGiftDetails)) { return(false); } else { APostingAlreadyConfirmed = true; } } else { //This has to be called here because if there are no changes then the DataSavingValidating // method which calls the method below, will not run. if (!FMyForm.GetBatchControl().AllowInactiveFieldValues(ref APostingAlreadyConfirmed, TExtraGiftBatchChecks.GiftBatchAction.POSTING) || FMyForm.GiftHasExWorkerOrAnon(BatchGiftDetails) ) { return(false); } } //Check hash total validity if ((ACurrentBatchRow.HashTotal != 0) && (ACurrentBatchRow.BatchTotal != ACurrentBatchRow.HashTotal)) { MessageBox.Show(String.Format(Catalog.GetString( "The gift batch total ({0}) for batch {1} does not equal the hash total ({2})!"), StringHelper.FormatUsingCurrencyCode(ACurrentBatchRow.BatchTotal, ACurrentBatchRow.CurrencyCode), ACurrentBatchRow.BatchNumber, StringHelper.FormatUsingCurrencyCode(ACurrentBatchRow.HashTotal, ACurrentBatchRow.CurrencyCode)), "Post Gift Batch"); return(false); } //Check for missing international exchange rate bool IsTransactionInIntlCurrency = false; FMyForm.WarnAboutMissingIntlExchangeRate = true; if (FMyForm.InternationalCurrencyExchangeRate(ACurrentBatchRow, out IsTransactionInIntlCurrency, true) == 0) { return(false); } //Check for zero Donors or Recipients if (!ADonorZeroIsValid) { DataView batchGiftDV = new DataView(FMainDS.AGift); batchGiftDV.RowFilter = string.Format("{0}={1} And {2}=0", AGiftTable.GetBatchNumberDBName(), FSelectedBatchNumber, AGiftTable.GetDonorKeyDBName()); int numDonorZeros = batchGiftDV.Count; if (numDonorZeros > 0) { string messageListOfOffendingGifts = String.Format(Catalog.GetString( "Gift Batch {0} contains {1} gift detail(s) with Donor 0000000. Please fix before posting!{2}{2}"), FSelectedBatchNumber, numDonorZeros, Environment.NewLine); string listOfOffendingRows = string.Empty; listOfOffendingRows += "Gift" + Environment.NewLine; listOfOffendingRows += "------------"; foreach (DataRowView drv in batchGiftDV) { AGiftRow giftRow = (AGiftRow)drv.Row; listOfOffendingRows += String.Format("{0}{1:0000}", Environment.NewLine, giftRow.GiftTransactionNumber); } TFrmExtendedMessageBox extendedMessageBox = new TFrmExtendedMessageBox(FMyForm); extendedMessageBox.ShowDialog((messageListOfOffendingGifts + listOfOffendingRows), Catalog.GetString("Post Batch Error"), string.Empty, TFrmExtendedMessageBox.TButtons.embbOK, TFrmExtendedMessageBox.TIcon.embiWarning); return(false); } } if (!ARecipientZeroIsValid) { DataView batchGiftDetailsDV = new DataView(FMainDS.AGiftDetail); batchGiftDetailsDV.RowFilter = string.Format("{0}={1} And {2}=0", AGiftDetailTable.GetBatchNumberDBName(), FSelectedBatchNumber, AGiftDetailTable.GetRecipientKeyDBName()); int numRecipientZeros = batchGiftDetailsDV.Count; if (numRecipientZeros > 0) { string messageListOfOffendingGifts = String.Format(Catalog.GetString( "Gift Batch {0} contains {1} gift detail(s) with Recipient 0000000. Please fix before posting!{2}{2}"), FSelectedBatchNumber, numRecipientZeros, Environment.NewLine); string listOfOffendingRows = string.Empty; listOfOffendingRows += "Gift Detail" + Environment.NewLine; listOfOffendingRows += "-------------------"; foreach (DataRowView drv in batchGiftDetailsDV) { AGiftDetailRow giftDetailRow = (AGiftDetailRow)drv.Row; listOfOffendingRows += String.Format("{0}{1:0000} {2:00}", Environment.NewLine, giftDetailRow.GiftTransactionNumber, giftDetailRow.DetailNumber); } TFrmExtendedMessageBox extendedMessageBox = new TFrmExtendedMessageBox(FMyForm); extendedMessageBox.ShowDialog((messageListOfOffendingGifts + listOfOffendingRows), Catalog.GetString("Post Batch Error"), string.Empty, TFrmExtendedMessageBox.TButtons.embbOK, TFrmExtendedMessageBox.TIcon.embiWarning); return(false); } } //Check for inactive KeyMinistries DataTable GiftsWithInactiveKeyMinistries; bool ModifiedDetails = false; if (AWarnOfInactiveValues && TRemote.MFinance.Gift.WebConnectors.InactiveKeyMinistriesFoundInBatch(FLedgerNumber, FSelectedBatchNumber, out GiftsWithInactiveKeyMinistries, false)) { int numInactiveValues = GiftsWithInactiveKeyMinistries.Rows.Count; string messageNonModifiedBatch = String.Format(Catalog.GetString("Gift Batch {0} contains {1} inactive key ministries. Please fix before posting!{2}{2}"), FSelectedBatchNumber, numInactiveValues, Environment.NewLine); string messageModifiedBatch = String.Format(Catalog.GetString( "Reversal/Adjustment Gift Batch {0} contains {1} inactive key ministries. Do you still want to post?{2}{2}"), FSelectedBatchNumber, numInactiveValues, Environment.NewLine); string listOfOffendingRows = string.Empty; listOfOffendingRows += "Gift Detail Recipient KeyMinistry" + Environment.NewLine; listOfOffendingRows += "-------------------------------------------------------------------------------"; foreach (DataRow dr in GiftsWithInactiveKeyMinistries.Rows) { listOfOffendingRows += String.Format("{0}{1:0000} {2:00} {3:00000000000} {4}", Environment.NewLine, dr[0], dr[1], dr[2], dr[3]); bool isModified = Convert.ToBoolean(dr[4]); if (isModified) { ModifiedDetails = true; } } TFrmExtendedMessageBox extendedMessageBox = new TFrmExtendedMessageBox(FMyForm); if (ModifiedDetails) { if (extendedMessageBox.ShowDialog((messageModifiedBatch + listOfOffendingRows), Catalog.GetString("Post Batch"), string.Empty, TFrmExtendedMessageBox.TButtons.embbYesNo, TFrmExtendedMessageBox.TIcon.embiWarning) == TFrmExtendedMessageBox.TResult.embrYes) { APostingAlreadyConfirmed = true; } else { return(false); } } else { extendedMessageBox.ShowDialog((messageNonModifiedBatch + listOfOffendingRows), Catalog.GetString("Post Batch Error"), string.Empty, TFrmExtendedMessageBox.TButtons.embbOK, TFrmExtendedMessageBox.TIcon.embiWarning); return(false); } } // ask if the user really wants to post the batch if (!APostingAlreadyConfirmed && (MessageBox.Show(String.Format(Catalog.GetString("Do you really want to post gift batch {0}?"), FSelectedBatchNumber), Catalog.GetString("Confirm posting of Gift Batch"), MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)) { return(false); } TVerificationResultCollection Verifications = new TVerificationResultCollection(); try { FPostingInProgress = true; Thread postingThread = new Thread(() => PostGiftBatch(out Verifications)); postingThread.SetApartmentState(ApartmentState.STA); using (TProgressDialog dialog = new TProgressDialog(postingThread)) { dialog.ShowDialog(); } if (TVerificationHelper.ResultsContainErrorCode(Verifications, PetraErrorCodes.ERR_DB_SERIALIZATION_EXCEPTION)) { TConcurrentServerTransactions.ShowTransactionSerializationExceptionDialog(); ARefreshGUIAfterPosting = true; return(false); } else if (!TVerificationHelper.IsNullOrOnlyNonCritical(Verifications)) { TFrmExtendedMessageBox extendedMessageBox = new TFrmExtendedMessageBox(FMyForm); StringBuilder errorMessages = new StringBuilder(); int counter = 0; errorMessages.AppendLine(Catalog.GetString("________________________Gift Posting Errors________________________")); errorMessages.AppendLine(); foreach (TVerificationResult verif in Verifications) { counter++; errorMessages.AppendLine(counter.ToString("000") + " - " + verif.ResultText); errorMessages.AppendLine(); } extendedMessageBox.ShowDialog(errorMessages.ToString(), Catalog.GetString("Post Batch Error"), string.Empty, TFrmExtendedMessageBox.TButtons.embbOK, TFrmExtendedMessageBox.TIcon.embiWarning); } else { MessageBox.Show(Catalog.GetString("The batch has been posted successfully!")); ARefreshGUIAfterPosting = true; } } catch (Exception ex) { TLogging.LogException(ex, Utilities.GetMethodSignature()); throw; } finally { FPostingInProgress = false; } return(true); }
/// <summary> /// Import a transactions file or a clipboard equivalent /// </summary> /// <param name="ACurrentBatchRow">The batch to import to</param> /// <param name="AImportSource">The import source - eg File or Clipboard</param> /// <returns>True if the import was successful</returns> public bool ImportTransactions(AGiftBatchRow ACurrentBatchRow, TGiftImportDataSourceEnum AImportSource) { bool ok = false; String importString; String impOptions; OpenFileDialog dialog = null; Boolean IsPlainText = false; if (FPetraUtilsObject.HasChanges) { // saving failed, therefore do not try to import MessageBox.Show(Catalog.GetString("Please save before calling this function!"), Catalog.GetString( "Gift Import"), MessageBoxButtons.OK, MessageBoxIcon.Error); return(false); } if ((ACurrentBatchRow == null) || (ACurrentBatchRow.BatchStatus != MFinanceConstants.BATCH_UNPOSTED)) { MessageBox.Show(Catalog.GetString("Please select an unposted batch to import transactions."), Catalog.GetString( "Gift Import"), MessageBoxButtons.OK, MessageBoxIcon.Error); return(false); } if (ACurrentBatchRow.LastGiftNumber > 0) { if (MessageBox.Show(Catalog.GetString( "The current batch already contains some gift transactions. Do you really want to add more transactions to this batch?"), Catalog.GetString("Gift Transaction Import"), MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.No) { return(false); } } FdlgSeparator = new TDlgSelectCSVSeparator(false); if (AImportSource == TGiftImportDataSourceEnum.FromClipboard) { importString = Clipboard.GetText(TextDataFormat.UnicodeText); if ((importString == null) || (importString.Length == 0)) { MessageBox.Show(Catalog.GetString("Please first copy data from your spreadsheet application!"), Catalog.GetString("Failure"), MessageBoxButtons.OK, MessageBoxIcon.Error); return(false); } impOptions = TUserDefaults.GetStringDefault("Imp Options", ";American"); String dateFormatString = TUserDefaults.GetStringDefault("Imp Date", "MDY"); FdlgSeparator = new TDlgSelectCSVSeparator(false); FdlgSeparator.SelectedSeparator = "\t"; FdlgSeparator.CSVData = importString; FdlgSeparator.DateFormat = dateFormatString; if (impOptions.Length > 1) { FdlgSeparator.NumberFormat = impOptions.Substring(1); } } else if (AImportSource == TGiftImportDataSourceEnum.FromFile) { dialog = new OpenFileDialog(); string exportPath = TClientSettings.GetExportPath(); string fullPath = TUserDefaults.GetStringDefault("Imp Filename", exportPath + Path.DirectorySeparatorChar + "import.csv"); TImportExportDialogs.SetOpenFileDialogFilePathAndName(dialog, fullPath, exportPath); dialog.Title = Catalog.GetString("Import Transactions from CSV File"); dialog.Filter = Catalog.GetString("Gift Transactions files (*.csv)|*.csv|Text Files (*.txt)|*.txt"); impOptions = TUserDefaults.GetStringDefault("Imp Options", ";" + TDlgSelectCSVSeparator.NUMBERFORMAT_AMERICAN); // This call fixes Windows7 Open File Dialogs. It must be the line before ShowDialog() TWin7FileOpenSaveDialog.PrepareDialog(Path.GetFileName(fullPath)); if (dialog.ShowDialog() == DialogResult.OK) { Boolean fileCanOpen = FdlgSeparator.OpenCsvFile(dialog.FileName); if (!fileCanOpen) { MessageBox.Show(Catalog.GetString("Unable to open file."), Catalog.GetString("Gift Import"), MessageBoxButtons.OK, MessageBoxIcon.Stop); return(false); } importString = File.ReadAllText(dialog.FileName, Encoding.Default); IsPlainText = (Path.GetExtension(dialog.FileName).ToLower() == ".txt"); String dateFormatString = TUserDefaults.GetStringDefault("Imp Date", "MDY"); FdlgSeparator.DateFormat = dateFormatString; if (impOptions.Length > 1) { FdlgSeparator.NumberFormat = impOptions.Substring(1); } FdlgSeparator.SelectedSeparator = impOptions.Substring(0, 1); } else { return(false); } } else { // unknown source!! The following need a value... impOptions = String.Empty; importString = String.Empty; } if (IsPlainText || (FdlgSeparator.ShowDialog() == DialogResult.OK)) { Hashtable requestParams = new Hashtable(); requestParams.Add("ALedgerNumber", FLedgerNumber); requestParams.Add("Delimiter", FdlgSeparator.SelectedSeparator); requestParams.Add("DateFormatString", FdlgSeparator.DateFormat); requestParams.Add("NumberFormat", FdlgSeparator.NumberFormat); requestParams.Add("NewLine", Environment.NewLine); bool Repeat = true; while (Repeat) { Repeat = false; TVerificationResultCollection AMessages = new TVerificationResultCollection(); GiftBatchTDSAGiftDetailTable NeedRecipientLedgerNumber = new GiftBatchTDSAGiftDetailTable(); Thread ImportThread = new Thread(() => ImportGiftTransactions( requestParams, importString, ACurrentBatchRow.BatchNumber, out AMessages, out ok, out NeedRecipientLedgerNumber)); using (TProgressDialog ImportDialog = new TProgressDialog(ImportThread)) { ImportDialog.ShowDialog(); } ShowMessages(AMessages); // if the import contains gifts with Motivation Group 'GIFT' and that have a Family recipient with no Gift Destination // then the import will have failed and we need to alert the user if (NeedRecipientLedgerNumber.Rows.Count > 0) { bool OfferToRunImportAgain = true; // for each gift in which the recipient needs a Git Destination foreach (GiftBatchTDSAGiftDetailRow Row in NeedRecipientLedgerNumber.Rows) { if (MessageBox.Show(string.Format( Catalog.GetString( "Gift Import has been cancelled as the recipient '{0}' ({1}) has no Gift Destination assigned."), Row.RecipientDescription, Row.RecipientKey) + "\n\n" + Catalog.GetString("Do you want to assign a Gift Destination to this partner now?"), Catalog.GetString("Gift Import"), MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes) { // allow the user to assign a Gift Destingation TFrmGiftDestination GiftDestinationForm = new TFrmGiftDestination(FPetraUtilsObject.GetForm(), Row.RecipientKey); GiftDestinationForm.ShowDialog(); } else { OfferToRunImportAgain = false; } } // if the user has clicked yes to assigning Gift Destinations then offer to restart the import if (OfferToRunImportAgain && (MessageBox.Show(Catalog.GetString("Would you like to import these Gift Transactions again?"), Catalog.GetString("Gift Import"), MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1) == DialogResult.Yes)) { Repeat = true; } } } // We save the defaults even if ok is false - because the client will probably want to try and import // the same file again after correcting any errors SaveUserDefaults(dialog, impOptions); } if (ok) { MessageBox.Show(Catalog.GetString("Your data was imported successfully!"), Catalog.GetString("Gift Import"), MessageBoxButtons.OK, MessageBoxIcon.Information); //FMyUserControl.LoadBatchesForCurrentYear(); FPetraUtilsObject.DisableSaveButton(); } return(ok); }
/// <summary> /// this supports the batch export files from Petra 2.x. /// Each line starts with a type specifier, B for batch, J for journal, T for transaction /// The code handles importing from file or clipboard /// </summary> public void ImportBatches(TImportDataSourceEnum AImportDataSource) { bool ok = false; bool RefreshGUIAfterImport = false; OpenFileDialog dialog = null; if (FPetraUtilsObject.HasChanges) { // saving failed, therefore do not try to import MessageBox.Show(Catalog.GetString("Please save before calling this function!"), Catalog.GetString( "Failure"), MessageBoxButtons.OK, MessageBoxIcon.Error); return; } try { FMyForm.FCurrentGLBatchAction = TGLBatchEnums.GLBatchAction.IMPORTING; bool datesMayBeIntegers = TUserDefaults.GetBooleanDefault(MCommonConstants.USERDEFAULT_IMPORTEDDATESMAYBEINTEGERS, false); FdlgSeparator = new TDlgSelectCSVSeparator(false); FdlgSeparator.DateMayBeInteger = datesMayBeIntegers; if (AImportDataSource == TImportDataSourceEnum.FromClipboard) { string importString = Clipboard.GetText(TextDataFormat.UnicodeText); if ((importString == null) || (importString.Length == 0)) { MessageBox.Show(Catalog.GetString("Please first copy data from your spreadsheet application!"), Catalog.GetString("Failure"), MessageBoxButtons.OK, MessageBoxIcon.Error); return; } FdlgSeparator.CSVData = importString; } else if (AImportDataSource == TImportDataSourceEnum.FromFile) { dialog = new OpenFileDialog(); string exportPath = TClientSettings.GetExportPath(); string fullPath = TUserDefaults.GetStringDefault("Imp Filename", exportPath + Path.DirectorySeparatorChar + "import.csv"); TImportExportDialogs.SetOpenFileDialogFilePathAndName(dialog, fullPath, exportPath); dialog.Title = Catalog.GetString("Import Batches from CSV File"); dialog.Filter = Catalog.GetString("GL Batch Files (*.csv)|*.csv|Text Files (*.txt)|*.txt"); // This call fixes Windows7 Open File Dialogs. It must be the line before ShowDialog() TWin7FileOpenSaveDialog.PrepareDialog(Path.GetFileName(fullPath)); if (dialog.ShowDialog() == DialogResult.OK) { Boolean fileCanOpen = FdlgSeparator.OpenCsvFile(dialog.FileName); if (!fileCanOpen) { MessageBox.Show(Catalog.GetString("Unable to open file."), Catalog.GetString("Batch Import"), MessageBoxButtons.OK, MessageBoxIcon.Stop); return; } } else { return; } } else { // unknown source!! return; } String impOptions = TUserDefaults.GetStringDefault("Imp Options", ";" + TDlgSelectCSVSeparator.NUMBERFORMAT_AMERICAN); String dateFormatString = TUserDefaults.GetStringDefault("Imp Date", "MDY"); FdlgSeparator.DateFormat = dateFormatString; FdlgSeparator.NumberFormat = (impOptions.Length > 1) ? impOptions.Substring(1) : TDlgSelectCSVSeparator.NUMBERFORMAT_AMERICAN; FdlgSeparator.SelectedSeparator = StringHelper.GetCSVSeparator(FdlgSeparator.FileContent) ?? ((impOptions.Length > 0) ? impOptions.Substring(0, 1) : ";"); if (FdlgSeparator.ShowDialog() == DialogResult.OK) { Hashtable requestParams = new Hashtable(); requestParams.Add("ALedgerNumber", FLedgerNumber); requestParams.Add("Delimiter", FdlgSeparator.SelectedSeparator); requestParams.Add("DateFormatString", FdlgSeparator.DateFormat); requestParams.Add("DatesMayBeIntegers", datesMayBeIntegers); requestParams.Add("NumberFormat", FdlgSeparator.NumberFormat); requestParams.Add("NewLine", Environment.NewLine); TVerificationResultCollection AMessages = new TVerificationResultCollection(); Thread ImportThread = new Thread(() => ImportGLBatches( requestParams, FdlgSeparator.FileContent, out AMessages, out ok, out RefreshGUIAfterImport)); using (TProgressDialog ImportDialog = new TProgressDialog(ImportThread)) { ImportDialog.ShowDialog(); } if (TVerificationHelper.ResultsContainErrorCode(AMessages, PetraErrorCodes.ERR_DB_SERIALIZATION_EXCEPTION)) { TConcurrentServerTransactions.ShowTransactionSerializationExceptionDialog(); } else { ShowMessages(AMessages); } } // We save the defaults even if ok is false - because the client will probably want to try and import // the same file again after correcting any errors SaveUserDefaults(dialog); if (ok) { MessageBox.Show(Catalog.GetString("Your data was imported successfully!"), Catalog.GetString("Batch Import"), MessageBoxButtons.OK, MessageBoxIcon.Information); } if (ok) { FMyUserControl.ReloadBatches(); FMyForm.GetBatchControl().SelectRowInGrid(1); FPetraUtilsObject.SetChangedFlag(); FMyForm.SaveChangesManual(FMyForm.FCurrentGLBatchAction); } else if (RefreshGUIAfterImport) { // The import failed and the server needs us to refresh the GUI FMyUserControl.ReloadBatches(true); FMyForm.GetBatchControl().SelectRowInGrid(1); } } finally { FMyForm.FCurrentGLBatchAction = TGLBatchEnums.GLBatchAction.NONE; } }
/// <summary> /// this supports the batch export files from Petra 2.x. /// Each line starts with a type specifier, B for batch, J for journal, T for transaction /// </summary> public void ImportBatches(TGiftImportDataSourceEnum AImportSource, GiftBatchTDS AMainDS) { bool ImportOK = false; bool RefreshGUIAfterImport = false; OpenFileDialog OFileDialog = null; if (FPetraUtilsObject.HasChanges) { // saving failed, therefore do not try to import MessageBox.Show(Catalog.GetString("Please save before calling this function!"), Catalog.GetString( "Failure"), MessageBoxButtons.OK, MessageBoxIcon.Error); return; } ALedgerRow LedgerRow = (ALedgerRow)AMainDS.ALedger.Rows[0]; int CurrentTopBatchNumber = LedgerRow.LastGiftBatchNumber; try { FMyForm.FCurrentGiftBatchAction = Logic.TExtraGiftBatchChecks.GiftBatchAction.IMPORTING; bool datesMayBeIntegers = TUserDefaults.GetBooleanDefault(MCommonConstants.USERDEFAULT_IMPORTEDDATESMAYBEINTEGERS, false); FdlgSeparator = new TDlgSelectCSVSeparator(false); FdlgSeparator.DateMayBeInteger = datesMayBeIntegers; if (AImportSource == TGiftImportDataSourceEnum.FromClipboard) { string ImportString = Clipboard.GetText(TextDataFormat.UnicodeText); if ((ImportString == null) || (ImportString.Length == 0)) { MessageBox.Show(Catalog.GetString("Please first copy data from your spreadsheet application!"), Catalog.GetString("Failure"), MessageBoxButtons.OK, MessageBoxIcon.Error); return; } FdlgSeparator.CSVData = ImportString; } else if (AImportSource == TGiftImportDataSourceEnum.FromFile) { OFileDialog = new OpenFileDialog(); string exportPath = TClientSettings.GetExportPath(); string fullPath = TUserDefaults.GetStringDefault("Imp Filename", exportPath + Path.DirectorySeparatorChar + "import.csv"); TImportExportDialogs.SetOpenFileDialogFilePathAndName(OFileDialog, fullPath, exportPath); OFileDialog.Title = Catalog.GetString("Import Batches from CSV File"); OFileDialog.Filter = Catalog.GetString("Gift Batch Files(*.csv)|*.csv|Text Files(*.txt)|*.txt"); // This call fixes Windows7 Open File Dialogs. It must be the line before ShowDialog() TWin7FileOpenSaveDialog.PrepareDialog(Path.GetFileName(fullPath)); if (OFileDialog.ShowDialog() == DialogResult.OK) { Boolean fileCanOpen = FdlgSeparator.OpenCsvFile(OFileDialog.FileName); if (!fileCanOpen) { MessageBox.Show(Catalog.GetString("Unable to open file."), Catalog.GetString("Gift Import"), MessageBoxButtons.OK, MessageBoxIcon.Stop); return; } } else { return; } } else { // unknown source!! return; } String impOptions = TUserDefaults.GetStringDefault("Imp Options", ";" + TDlgSelectCSVSeparator.NUMBERFORMAT_AMERICAN); String dateFormatString = TUserDefaults.GetStringDefault("Imp Date", "MDY"); FdlgSeparator.DateFormat = dateFormatString; FdlgSeparator.NumberFormat = (impOptions.Length > 1) ? impOptions.Substring(1) : TDlgSelectCSVSeparator.NUMBERFORMAT_AMERICAN; FdlgSeparator.SelectedSeparator = StringHelper.GetCSVSeparator(FdlgSeparator.FileContent) ?? ((impOptions.Length > 0) ? impOptions.Substring(0, 1) : ";"); if (FdlgSeparator.ShowDialog() == DialogResult.OK) { Hashtable requestParams = new Hashtable(); requestParams.Add("ALedgerNumber", FLedgerNumber); requestParams.Add("Delimiter", FdlgSeparator.SelectedSeparator); requestParams.Add("DateFormatString", FdlgSeparator.DateFormat); requestParams.Add("DatesMayBeIntegers", datesMayBeIntegers); requestParams.Add("NumberFormat", FdlgSeparator.NumberFormat); requestParams.Add("NewLine", Environment.NewLine); bool Repeat = true; while (Repeat) { Repeat = false; TVerificationResultCollection AMessages = new TVerificationResultCollection(); GiftBatchTDSAGiftDetailTable NeedRecipientLedgerNumber = new GiftBatchTDSAGiftDetailTable(); Thread ImportThread = new Thread(() => ImportGiftBatches( requestParams, FdlgSeparator.FileContent, out AMessages, out ImportOK, out RefreshGUIAfterImport, out NeedRecipientLedgerNumber)); using (TProgressDialog ImportDialog = new TProgressDialog(ImportThread)) { ImportDialog.ShowDialog(); } // If NeedRecipientLedgerNumber contains data then AMessages will only ever contain // one message alerting the user that no data has been imported. // We do not want to show this as we will be displaying another more detailed message. if (NeedRecipientLedgerNumber.Rows.Count == 0) { if (TVerificationHelper.ResultsContainErrorCode(AMessages, PetraErrorCodes.ERR_DB_SERIALIZATION_EXCEPTION)) { TConcurrentServerTransactions.ShowTransactionSerializationExceptionDialog(); } else { ShowMessages(AMessages); } } // if the import contains gifts with Motivation Group 'GIFT' and that have a Family recipient with no Gift Destination // then the import will have failed and we need to alert the user if (NeedRecipientLedgerNumber.Rows.Count > 0) { bool OfferToRunImportAgain = true; bool DoNotShowMessageBoxEverytime = false; TFrmExtendedMessageBox.TResult Result = TFrmExtendedMessageBox.TResult.embrUndefined; int count = 1; // for each gift in which the recipient needs a Git Destination foreach (GiftBatchTDSAGiftDetailRow Row in NeedRecipientLedgerNumber.Rows) { if (!DoNotShowMessageBoxEverytime) { string CheckboxText = string.Empty; // only show checkbox if there is at least one more occurrence of this error if (NeedRecipientLedgerNumber.Rows.Count - count > 0) { CheckboxText = string.Format( Catalog.GetString( "Do this for all further occurrences ({0})?"), NeedRecipientLedgerNumber.Rows.Count - count); } TFrmExtendedMessageBox extendedMessageBox = new TFrmExtendedMessageBox(FPetraUtilsObject.GetForm()); extendedMessageBox.ShowDialog(string.Format( Catalog.GetString( "Gift Import has been cancelled as the recipient '{0}' ({1}) has no Gift Destination assigned."), Row.RecipientDescription, Row.RecipientKey) + "\n\r\n\r\n\r" + Catalog.GetString("Do you want to assign a Gift Destination to this partner now?"), Catalog.GetString("Import Errors"), CheckboxText, TFrmExtendedMessageBox.TButtons.embbYesNo, TFrmExtendedMessageBox.TIcon.embiWarning); Result = extendedMessageBox.GetResult(out DoNotShowMessageBoxEverytime); } if (Result == TFrmExtendedMessageBox.TResult.embrYes) { // allow the user to assign a Gift Destingation TFrmGiftDestination GiftDestinationForm = new TFrmGiftDestination(FPetraUtilsObject.GetForm(), Row.RecipientKey); GiftDestinationForm.ShowDialog(); } else { OfferToRunImportAgain = false; if (DoNotShowMessageBoxEverytime) { break; } } count++; } // if the user has clicked yes to assigning Gift Destinations then offer to restart the import if (OfferToRunImportAgain && (MessageBox.Show(Catalog.GetString("Would you like to import this Gift Batch again?"), Catalog.GetString("Gift Import"), MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.Yes)) { Repeat = true; } } } } // We save the defaults even if ok is false - because the client will probably want to try and import // the same file again after correcting any errors SaveUserDefaults(OFileDialog); if (ImportOK) { MessageBox.Show(Catalog.GetString("Your data was imported successfully!"), Catalog.GetString("Gift Import"), MessageBoxButtons.OK, MessageBoxIcon.Information); } if (ImportOK) { FMyUserControl.LoadBatchesForCurrentYear(); FMyForm.GetBatchControl().SelectRowInBatchGrid(1); DataView allNewBatches = new DataView(AMainDS.AGiftBatch); allNewBatches.RowFilter = String.Format("{0} > {1}", AGiftBatchTable.GetBatchNumberDBName(), CurrentTopBatchNumber); foreach (DataRowView drv in allNewBatches) { drv.Row.SetModified(); } FPetraUtilsObject.SetChangedFlag(); //Force initial inactive values check FMyForm.SaveChangesManual(FMyForm.FCurrentGiftBatchAction); } else if (RefreshGUIAfterImport) { FMyUserControl.LoadBatchesForCurrentYear(); FMyForm.GetBatchControl().SelectRowInBatchGrid(1); } } finally { FMyForm.FCurrentGiftBatchAction = Logic.TExtraGiftBatchChecks.GiftBatchAction.NONE; } }
/// <summary> /// Main method to post a specified batch /// </summary> /// <param name="ACurrentBatchRow">The batch row to post</param> /// <returns>True if the batch was successfully posted</returns> public bool PostBatch(AGiftBatchRow ACurrentBatchRow) { if ((ACurrentBatchRow == null) || (ACurrentBatchRow.BatchStatus != MFinanceConstants.BATCH_UNPOSTED)) { return(false); } FSelectedBatchNumber = ACurrentBatchRow.BatchNumber; TVerificationResultCollection Verifications; try { FMyForm.EnsureGiftDataPresent(FLedgerNumber, FSelectedBatchNumber); GiftBatchTDSAGiftDetailTable BatchGiftDetails = new GiftBatchTDSAGiftDetailTable(); foreach (GiftBatchTDSAGiftDetailRow Row in FMainDS.AGiftDetail.Rows) { if (Row.BatchNumber == FSelectedBatchNumber) { BatchGiftDetails.Rows.Add((object[])Row.ItemArray.Clone()); } } // there are no gifts in this batch! if (BatchGiftDetails.Rows.Count == 0) { FMyForm.Cursor = Cursors.Default; MessageBox.Show(Catalog.GetString("Batch is empty!"), Catalog.GetString("Posting failed"), MessageBoxButtons.OK, MessageBoxIcon.Stop); return(false); } bool CancelledDueToExWorkerOrAnonDonor; // save first, then post if (!FMyForm.SaveChangesForPosting(BatchGiftDetails, out CancelledDueToExWorkerOrAnonDonor)) { FMyForm.Cursor = Cursors.Default; if (!CancelledDueToExWorkerOrAnonDonor) { // saving failed, therefore do not try to post MessageBox.Show(Catalog.GetString("The batch was not posted due to problems during saving; ") + Environment.NewLine + Catalog.GetString("Please first correct and save the batch, and then post it!")); } return(false); } } catch (Exception ex) { throw ex; } //Check for missing international exchange rate bool IsTransactionInIntlCurrency = false; if (FMyForm.InternationalCurrencyExchangeRate(ACurrentBatchRow, out IsTransactionInIntlCurrency, true) == 0) { return(false); } //Check for inactive KeyMinistries DataTable GiftsWithInactiveKeyMinistries; if (TRemote.MFinance.Gift.WebConnectors.InactiveKeyMinistriesFoundInBatch(FLedgerNumber, FSelectedBatchNumber, out GiftsWithInactiveKeyMinistries)) { string listOfOffendingRows = "Gift Detail Recipient KeyMinistry" + Environment.NewLine; listOfOffendingRows += "------------------------------------------------"; foreach (DataRow dr in GiftsWithInactiveKeyMinistries.Rows) { listOfOffendingRows += String.Format("{0}{1:0000} {2:00} {3:00000000000} {4}", Environment.NewLine, dr[0], dr[1], dr[2], dr[3]); } string msg = String.Format(Catalog.GetString("Cannot post Batch {0} as inactive Key Ministries found in gifts:{1}{1}{2}"), FSelectedBatchNumber, Environment.NewLine, listOfOffendingRows); MessageBox.Show(msg, Catalog.GetString("Inactive Key Ministries Found")); return(false); } // ask if the user really wants to post the batch if (MessageBox.Show(String.Format(Catalog.GetString("Do you really want to post gift batch {0}?"), FSelectedBatchNumber), Catalog.GetString("Confirm posting of Gift Batch"), MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel) { return(false); } Verifications = new TVerificationResultCollection(); try { FPostingInProgress = true; Thread postingThread = new Thread(() => PostGiftBatch(out Verifications)); using (TProgressDialog dialog = new TProgressDialog(postingThread)) { dialog.ShowDialog(); } if (!TVerificationHelper.IsNullOrOnlyNonCritical(Verifications)) { string ErrorMessages = String.Empty; foreach (TVerificationResult verif in Verifications) { ErrorMessages += "[" + verif.ResultContext + "] " + verif.ResultTextCaption + ": " + verif.ResultText + Environment.NewLine; } System.Windows.Forms.MessageBox.Show(ErrorMessages, Catalog.GetString("Posting failed")); } else { MessageBox.Show(Catalog.GetString("The batch has been posted successfully!")); return(true); } } catch (Exception ex) { string msg = (String.Format(Catalog.GetString("Unexpected error occurred during the posting of a Gift Batch!{0}{1}{2}{1} {3}"), Utilities.GetMethodSignature(), Environment.NewLine, ex.Message, ex.InnerException.Message)); TLogging.Log(msg); throw ex; //MessageBox.Show(msg, "Post Gift Batch Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } finally { FPostingInProgress = false; } return(false); }
/// <summary> /// this supports the batch export files from Petra 2.x. /// Each line starts with a type specifier, B for batch, J for journal, T for transaction /// </summary> /// <returns>True if the Export succeeded and a file was created, false otherwise</returns> public bool ExportBatches(bool AWithInteractionOnSuccess = true) { string ExportFileName = txtFilename.Text; if (ExportFileName == String.Empty) { MessageBox.Show(Catalog.GetString("Please choose a location for the Export File."), Catalog.GetString("Error"), MessageBoxButtons.OK, MessageBoxIcon.Error); return(false); } else if (!ExportFileName.EndsWith(".csv", StringComparison.CurrentCultureIgnoreCase) && !ExportFileName.EndsWith(".txt", StringComparison.CurrentCultureIgnoreCase)) { ExportFileName += ".csv"; txtFilename.Text = ExportFileName; } if (!Directory.Exists(Path.GetDirectoryName(ExportFileName))) { MessageBox.Show(Catalog.GetString("Please select an existing directory for this file!"), Catalog.GetString("Error"), MessageBoxButtons.OK, MessageBoxIcon.Error); txtFilename.Text = string.Empty; return(false); } if (File.Exists(ExportFileName)) { if (MessageBox.Show(Catalog.GetString("The file already exists. Is it OK to overwrite it?"), Catalog.GetString("Export Gifts"), MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == System.Windows.Forms.DialogResult.No) { return(false); } try { File.Delete(ExportFileName); } catch (Exception ex) { MessageBox.Show(String.Format( Catalog.GetString( "Failed to delete the file. Maybe it is already open in another application? The system message was:{0}{1}"), Environment.NewLine, ex.Message), Catalog.GetString("Export Gift Batches"), MessageBoxButtons.OK, MessageBoxIcon.Error); return(false); } } if (rbtBatchNumberSelection.Checked) { if (!txtBatchNumberStart.NumberValueInt.HasValue) { txtBatchNumberStart.NumberValueInt = 0; } if (!txtBatchNumberEnd.NumberValueInt.HasValue) { txtBatchNumberEnd.NumberValueInt = 999999; } } else { if ((dtpDateFrom.Text == string.Empty) || (dtpDateTo.Text == string.Empty)) { MessageBox.Show(Catalog.GetString("Start and end dates must be provided."), Catalog.GetString("Error"), MessageBoxButtons.OK, MessageBoxIcon.Error); return(false); } if ((!dtpDateFrom.ValidDate()) || (!dtpDateTo.ValidDate())) // If ValidDate fails, it displays a helpful message. { return(false); } } String numberFormat = ConvertNumberFormat(cmbNumberFormat); String delimiter = ConvertDelimiter(cmbDelimiter.GetSelectedString(), false); if (((numberFormat == "European") && (delimiter == ",")) || ((numberFormat == "American") && (delimiter == "."))) { MessageBox.Show(Catalog.GetString("Numeric Decimal cannot be the same as the delimiter."), Catalog.GetString("Error"), MessageBoxButtons.OK, MessageBoxIcon.Error); return(false); } try { Hashtable requestParams = new Hashtable(); requestParams.Add("ALedgerNumber", FLedgerNumber); requestParams.Add("Delimiter", delimiter); requestParams.Add("DateFormatString", cmbDateFormat.GetSelectedString()); requestParams.Add("Summary", rbtSummary.Checked); requestParams.Add("IncludeUnposted", chkIncludeUnposted.Checked); requestParams.Add("bUseBaseCurrency", rbtBaseCurrency.Checked); requestParams.Add("TransactionsOnly", chkTransactionsOnly.Checked); requestParams.Add("RecipientNumber", Convert.ToInt64(txtDetailRecipientKey.Text)); requestParams.Add("FieldNumber", Convert.ToInt64(txtDetailFieldKey.Text)); requestParams.Add("DateForSummary", dtpDateSummary.Date); requestParams.Add("NumberFormat", numberFormat); requestParams.Add("ExtraColumns", chkExtraColumns.Checked); if (rbtBatchNumberSelection.Checked) { requestParams.Add("BatchNumberStart", txtBatchNumberStart.NumberValueInt); requestParams.Add("BatchNumberEnd", txtBatchNumberEnd.NumberValueInt); } else { requestParams.Add("BatchDateFrom", dtpDateFrom.Date); requestParams.Add("BatchDateTo", dtpDateTo.Date); } TVerificationResultCollection AMessages = new TVerificationResultCollection(); String exportString = null; Int32 BatchCount = 0; Thread ExportThread = new Thread(() => ExportAllGiftBatchData( requestParams, out exportString, out AMessages, out BatchCount)); using (TProgressDialog ExportDialog = new TProgressDialog(ExportThread)) { ExportDialog.ShowDialog(); } if ((AMessages != null) && (AMessages.Count > 0)) { if (!TVerificationHelper.IsNullOrOnlyNonCritical(AMessages)) { MessageBox.Show(AMessages.BuildVerificationResultString(), Catalog.GetString("Error"), MessageBoxButtons.OK, MessageBoxIcon.Error); return(false); } else { MessageBox.Show(AMessages.BuildVerificationResultString(), Catalog.GetString("Warnings"), MessageBoxButtons.OK, MessageBoxIcon.Information); } } SaveUserDefaults(); //Process BatchCount value if (BatchCount == 0) { MessageBox.Show(Catalog.GetString("There are no batches matching your criteria"), Catalog.GetString("Export"), MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return(false); } else if (BatchCount == -1) { MessageBox.Show(Catalog.GetString("Gift batch export cancelled"), Catalog.GetString("Export"), MessageBoxButtons.OK, MessageBoxIcon.Information); return(false); } else if (BatchCount == -2) { MessageBox.Show(Catalog.GetString("Gift batch export failed"), Catalog.GetString("Export"), MessageBoxButtons.OK, MessageBoxIcon.Warning); return(false); } StreamWriter sw1 = new StreamWriter(ExportFileName, false, Encoding.GetEncoding(TAppSettingsManager.GetInt32("ExportGiftBatchEncoding", 1252))); sw1.Write(exportString); sw1.Close(); } catch (Exception ex) { TLogging.LogException(ex, Utilities.GetMethodSignature()); throw; } bool ShowExportedFileInExplorer = false; if (AWithInteractionOnSuccess) { if (MessageBox.Show(Catalog.GetString( "Gift Batches Exported successfully. Would you like to open the file in your default application?"), Catalog.GetString("Gift Batch Export"), MessageBoxButtons.YesNo, MessageBoxIcon.Information, MessageBoxDefaultButton.Button2) == System.Windows.Forms.DialogResult.Yes) { try { ProcessStartInfo si = new ProcessStartInfo(ExportFileName); si.UseShellExecute = true; si.Verb = "open"; Process p = new Process(); p.StartInfo = si; p.Start(); } catch { MessageBox.Show(Catalog.GetString( "Unable to launch the default application to open: '") + ExportFileName + "'!", Catalog.GetString( "Gift Export"), MessageBoxButtons.OK, MessageBoxIcon.Exclamation); ShowExportedFileInExplorer = true; } } } else { ShowExportedFileInExplorer = true; } if (ShowExportedFileInExplorer) { //If windows start Windows File Explorer TExecutingOSEnum osVersion = Utilities.DetermineExecutingOS(); if ((osVersion >= TExecutingOSEnum.eosWinXP) && (osVersion < TExecutingOSEnum.oesUnsupportedPlatform)) { try { Process.Start("explorer.exe", string.Format("/select,\"{0}\"", ExportFileName)); } catch { MessageBox.Show(Catalog.GetString( "Unable to launch Windows File Explorer to open: '") + ExportFileName + "'!", Catalog.GetString( "Gift Export"), MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } } } return(true); }
/// <summary> /// This is the main routine to import tax data from clipboard or file /// </summary> private void BtnOK_Click(Object Sender, EventArgs e) { if (!ValidateInputs()) { return; } TDlgSelectCSVSeparator dialog = new TDlgSelectCSVSeparator(chkFirstRowIsHeader.Checked); if (rbtFromClipboard.Checked) { dialog.CSVData = Clipboard.GetText(TextDataFormat.UnicodeText); dialog.SelectedSeparator = "\t"; } else { if (dialog.OpenCsvFile(txtFileName.Text) == false) { MessageBox.Show(Catalog.GetString("Could not open the file you have chosen. Maybe it is already open somewhere else."), this.Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return; } } // work out what the separator is... String impOptions = TUserDefaults.GetStringDefault("Imp Options", ";" + TDlgSelectCSVSeparator.NUMBERFORMAT_AMERICAN); string separator = StringHelper.GetCSVSeparator(dialog.FileContent) ?? ((impOptions.Length > 0) ? impOptions.Substring(0, 1) : ";"); string numberFormat = (impOptions.Length > 1) ? impOptions.Substring(1) : TDlgSelectCSVSeparator.NUMBERFORMAT_AMERICAN; // Now we need to convert the multi-column file/clipboard data to a simple two column list string twoColumnImport; if (ConvertInputTextToTwoColumns(dialog.FileContent, separator, Convert.ToInt16(nudPartnerKeyColumn.Value - 1), Convert.ToInt16(nudTaxCodeColumn.Value - 1), out twoColumnImport) == false) { // We got an error return; } dialog.CSVData = twoColumnImport; dialog.SelectedSeparator = separator; dialog.DateFormat = ""; // This will make the combo box empty // Show the Preview dialog DialogResult dialogResult = dialog.ShowDialog(); // Save the settings whether the result was OK or cancel TUserDefaults.SetDefault("Imp Options", dialog.SelectedSeparator + numberFormat); TUserDefaults.SaveChangedUserDefaults(); if (dialogResult != DialogResult.OK) { // It was cancelled return; } // Set up the inputs for the call to the server to do the actual import string importString = dialog.FileContent; string selectedSeparator = dialog.SelectedSeparator; int emptyCodeAction = rbtFailEmptyTaxCode.Checked ? 0 : rbtSkipEmptyTaxCode.Checked ? 1 : rbtDeleteEmptyTaxCode.Checked ? 2 : -1; Hashtable requestParams = new Hashtable(); requestParams.Add("Delimiter", dialog.SelectedSeparator); requestParams.Add("FirstRowIsHeader", chkFirstRowIsHeader.Checked); requestParams.Add("FailIfNotPerson", chkFailIfNotPerson.Checked); requestParams.Add("FailIfInvalidPartner", chkFailInvalidPartner.Checked); requestParams.Add("OverwriteExistingTaxCode", chkOverwriteExistingTaxCode.Checked); requestParams.Add("CreateExtract", chkCreateExtract.Checked); requestParams.Add("ExtractName", txtExtractName.Text); requestParams.Add("ExtractDescription", txtExtractDescription.Text); requestParams.Add("CreateOutFile", chkCreateOutFile.Checked); requestParams.Add("EmptyTaxCode", emptyCodeAction); requestParams.Add("TaxCodeType", FTaxGovIdKeyName); // we include partner details if the user does not want a output file because we will write a sneaky one in the logs folder requestParams.Add("IncludePartnerDetails", (chkCreateOutFile.Checked && chkIncludePartnerDetails.Checked) || (chkCreateOutFile.Checked == false)); // Get the server to parse the file and return our results bool success = false; TVerificationResultCollection errorMessages = null; List <string> outputLines = null; bool newExtractCreated = false; int newExtractId = -1; int newExtractKeyCount = -1; int taxCodesImported = -1; int taxCodesDeleted = -1; int taxCodeMismatchCount = -1; // Do the import on the server Thread ImportThread = new Thread(() => ImportPartnerTaxCodes( requestParams, importString, out success, out errorMessages, out outputLines, out newExtractCreated, out newExtractId, out newExtractKeyCount, out taxCodesImported, out taxCodesDeleted, out taxCodeMismatchCount)); // Show the progress dialog so that the user can cancel using (TProgressDialog ImportDialog = new TProgressDialog(ImportThread)) { ImportDialog.ShowDialog(); } if (success) { // Import was successful string msg = Catalog.GetString("The Import was successful. "); msg += string.Format(Catalog.GetPluralString("{0} tax code was imported. ", "{0} tax codes were imported. ", taxCodesImported, true), taxCodesImported); msg += string.Format(Catalog.GetPluralString("{0} tax code was deleted. ", "{0} tax codes were deleted. ", taxCodesDeleted, true), taxCodesDeleted); if (taxCodeMismatchCount > 0) { msg += string.Format(Catalog.GetPluralString( "{0} tax code was not imported because it did not match the existing code for the Partner. ", "{0} tax codes were not imported because they did not match the existing code for the Partner. ", taxCodeMismatchCount, true), taxCodeMismatchCount); } if (chkCreateOutFile.Checked) { //msg += " "; msg += Catalog.GetString("You can see full details in the output file."); } if (chkCreateExtract.Checked) { msg += Environment.NewLine + Environment.NewLine; if (newExtractCreated) { msg += string.Format(Catalog.GetString("In addition an extract was created containing {0} keys."), newExtractKeyCount); } else { msg += "WARNING! The creation of a new extract failed. Maybe the name was already in use."; } } MessageBox.Show(msg, this.Text, MessageBoxButtons.OK); } else { // Import failed if (TVerificationHelper.ResultsContainErrorCode(errorMessages, PetraErrorCodes.ERR_DB_SERIALIZATION_EXCEPTION)) { TConcurrentServerTransactions.ShowTransactionSerializationExceptionDialog(); return; } else if (errorMessages.HasCriticalErrors) { // A failed import should contain some critical errors. // Concatenate them and show them in an extended message box with scroll bar string msg = Catalog.GetString("The import failed") + Environment.NewLine + Environment.NewLine; for (int i = 0; i < errorMessages.Count; i++) { msg += string.Format("[{0}] - {1}", errorMessages[i].ResultContext, errorMessages[i].ResultText); msg += Environment.NewLine; } msg += Catalog.GetString("No data was imported into the database."); TFrmExtendedMessageBox msgBox = new TFrmExtendedMessageBox(this); msgBox.ShowDialog(msg, this.Text, "", TFrmExtendedMessageBox.TButtons.embbOK, TFrmExtendedMessageBox.TIcon.embiInformation); } else { // Should not end up wit a failed import and no error messages MessageBox.Show("Import failed", this.Text, MessageBoxButtons.OK); } } string pathToOutFile = null; if (chkCreateOutFile.Checked) { pathToOutFile = txtOutputFileName.Text; } else { // we try and write a log file anyway in the log folder string logPath = TAppSettingsManager.GetValue("OpenPetra.PathLog", ""); if (logPath.Length > 0) { pathToOutFile = logPath + Path.DirectorySeparatorChar + "ImportPartnerTaxCodes.log"; } } if (pathToOutFile != null) { // Write the output file using (StreamWriter sw = new StreamWriter(pathToOutFile)) { for (int i = 0; i < outputLines.Count; i++) { sw.WriteLine(outputLines[i]); } sw.Close(); } } if (chkCreateExtract.Checked) { // Tell the client about the new extract // refresh extract master screen if it is open TFormsMessage BroadcastMessage = new TFormsMessage(TFormsMessageClassEnum.mcExtractCreated); BroadcastMessage.SetMessageDataName(txtExtractName.Text); TFormsList.GFormsList.BroadcastFormMessage(BroadcastMessage); } // Save the GUI settings SaveGUISettings(); }
/// <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); }
static void Main(string[] args) { new TLogging("../../log/TestRemotingClient.log"); try { new TAppSettingsManager("../../etc/Client.config"); TLogging.DebugLevel = Convert.ToInt32(TAppSettingsManager.GetValue("Client.DebugLevel", "0")); new TClientSettings(); // initialize the client new TRemoteTest(); // need to call this as well to make the progress dialog work new TRemote(); // allow self signed ssl certificate for test purposes ServicePointManager.ServerCertificateValidationCallback = delegate { return(true); }; THttpConnector.InitConnection(TAppSettingsManager.GetValue("OpenPetra.HTTPServer")); TClientInfo.InitializeUnit(); Catalog.Init("en-GB", "en-GB"); SortedList <string, object> Parameters = new SortedList <string, object>(); Parameters.Add("username", "demo"); Parameters.Add("password", "demo"); Parameters.Add("version", TFileVersionInfo.GetApplicationVersion().ToString()); List <object> ResultList = THttpConnector.CallWebConnector("SessionManager", "LoginClient", Parameters, "list"); eLoginEnum Result = (eLoginEnum)ResultList[0]; if (Result != eLoginEnum.eLoginSucceeded) { // failed login return; } IMyUIConnector MyUIConnector = TRemoteTest.MyService.SubNamespace.MyUIConnector(); TRemoteTest.TMyService.TMySubNamespace test = TRemoteTest.MyService.SubNamespace; while (true) { try { TLogging.Log("before call"); TLogging.Log(TRemoteTest.MyService.HelloWorld("Hello World")); TLogging.Log("after call"); } catch (Exception e) { TLogging.Log("problem with MyService HelloWorld: " + Environment.NewLine + e.ToString()); } try { DateTime DateTomorrow; TLogging.Log("should show today's date: " + TRemoteTest.MyService.TestDateTime(DateTime.Today, out DateTomorrow).ToShortDateString()); TLogging.Log("should show tomorrow's date: " + DateTomorrow.ToShortDateString()); } catch (Exception e) { TLogging.Log("problem with TestDateTime: " + Environment.NewLine + e.ToString()); } try { TLogging.Log(test.HelloSubWorld("Hello SubWorld")); } catch (Exception e) { TLogging.Log("problem with sub namespace HelloSubWorld: " + Environment.NewLine + e.ToString()); } try { TLogging.Log(MyUIConnector.HelloWorldUIConnector()); } catch (Exception e) { TLogging.Log("problem with HelloWorldUIConnector: " + Environment.NewLine + e.ToString()); } // start long running job Thread t = new Thread(() => TRemoteTest.MyService.LongRunningJob()); using (TProgressDialog dialog = new TProgressDialog(t)) { if (dialog.ShowDialog() == DialogResult.Cancel) { return; } } Console.WriteLine("Press ENTER to say Hello World again... "); Console.WriteLine("Press CTRL-C to exit ..."); Console.ReadLine(); } } catch (Exception e) { TLogging.Log(e.ToString()); Console.ReadLine(); } }
/// <summary> /// export all partners in selected extract /// </summary> /// <param name="sender"></param> /// <param name="e"></param> /// <returns></returns> public bool ExportPartnersInExtract(System.Object sender, EventArgs e) { Boolean Result = false; if (!WarnIfNotSingleSelection(Catalog.GetString("Export Partners in Extract")) && (GetSelectedDetailRow() != null)) { String FileName = TImportExportDialogs.GetExportFilename(Catalog.GetString("Save Partners into File")); if (FileName.Length > 0) { bool ExportFamiliesPersons = false; bool ContainsFamily = TRemote.MPartner.ImportExport.WebConnectors.CheckExtractContainsFamily(GetSelectedDetailRow().ExtractId); if (ContainsFamily) { if (MessageBox.Show( Catalog.GetString("When exporting a FAMILY record do you want to also export all associated PERSON records?"), Catalog.GetString("Export Partners"), MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { ExportFamiliesPersons = true; } } this.Cursor = Cursors.WaitCursor; if (FileName.EndsWith("ext")) { string Doc = string.Empty; // run in thread so we can have Progress Dialog Thread t = new Thread(() => ExportToFile(ExportFamiliesPersons, ref Doc)); using (TProgressDialog dialog = new TProgressDialog(t)) { dialog.ShowDialog(); } // null if the user cancelled the operation if (Doc == null) { MessageBox.Show(Catalog.GetString("Export cancelled."), Catalog.GetString( "Export Partners"), MessageBoxButtons.OK, MessageBoxIcon.Information); this.Cursor = Cursors.Default; return(false); } Result = TImportExportDialogs.ExportTofile(Doc, FileName); if (!Result) { MessageBox.Show(Catalog.GetString("Export of Partners in Extract failed!"), Catalog.GetString( "Export Partners"), MessageBoxButtons.OK, MessageBoxIcon.Error); } else { MessageBox.Show(Catalog.GetString("Export of Partners in Extract finished"), Catalog.GetString( "Export Partners"), MessageBoxButtons.OK, MessageBoxIcon.Information); } } else { // XmlDocument doc = new XmlDocument(); MessageBox.Show(Catalog.GetString("Export with this format is not yet supported!"), Catalog.GetString( "Export Partners"), MessageBoxButtons.OK, MessageBoxIcon.Error); // doc.LoadXml(TRemote.MPartner.ImportExport.WebConnectors.ExportExtractPartners(GetSelectedDetailRow().ExtractId, false)); // Result = TImportExportDialogs.ExportTofile(doc, FileName); } this.Cursor = Cursors.Default; } return(Result); } return(false); }
/// <summary> /// Main method to post a specified batch /// </summary> /// <param name="ACurrentBatchRow">The batch row to post</param> /// <param name="APostingAlreadyConfirmed">True means ask user if they want to post</param> /// <param name="AWarnOfInactiveValues">True means user is warned if inactive values exist</param> /// <param name="ADonorZeroIsValid"></param> /// <param name="ARecipientZeroIsValid"></param> /// <returns>True if the batch was successfully posted</returns> public bool PostBatch(AGiftBatchRow ACurrentBatchRow, bool APostingAlreadyConfirmed = false, bool AWarnOfInactiveValues = true, bool ADonorZeroIsValid = false, bool ARecipientZeroIsValid = false) { //This assumes that all gift data etc is loaded into the batch before arriving here bool RetVal = false; if ((ACurrentBatchRow == null) || (ACurrentBatchRow.BatchStatus != MFinanceConstants.BATCH_UNPOSTED)) { return(RetVal); } FSelectedBatchNumber = ACurrentBatchRow.BatchNumber; TVerificationResultCollection Verifications; try { //Make sure that all control data is in dataset FMyForm.GetControlDataForPosting(); GiftBatchTDSAGiftDetailTable batchGiftDetails = new GiftBatchTDSAGiftDetailTable(); DataView batchGiftDetailsDV = new DataView(FMainDS.AGiftDetail); batchGiftDetailsDV.RowFilter = string.Format("{0}={1}", AGiftDetailTable.GetBatchNumberDBName(), FSelectedBatchNumber); batchGiftDetailsDV.Sort = string.Format("{0} ASC, {1} ASC, {2} ASC", AGiftDetailTable.GetBatchNumberDBName(), AGiftDetailTable.GetGiftTransactionNumberDBName(), AGiftDetailTable.GetDetailNumberDBName()); foreach (DataRowView drv in batchGiftDetailsDV) { GiftBatchTDSAGiftDetailRow gBRow = (GiftBatchTDSAGiftDetailRow)drv.Row; batchGiftDetails.Rows.Add((object[])gBRow.ItemArray.Clone()); } bool CancelledDueToExWorkerOrAnonDonor; // save first, then post if (!FMyForm.SaveChangesForPosting(batchGiftDetails, out CancelledDueToExWorkerOrAnonDonor)) { FMyForm.Cursor = Cursors.Default; if (!CancelledDueToExWorkerOrAnonDonor) { // saving failed, therefore do not try to post MessageBox.Show(Catalog.GetString("The batch was not posted due to problems during saving; ") + Environment.NewLine + Catalog.GetString("Please first correct and save the batch, and then post it!")); } return(RetVal); } } catch (Exception ex) { TLogging.LogException(ex, Utilities.GetMethodSignature()); throw; } //Check for missing international exchange rate bool IsTransactionInIntlCurrency = false; FMyForm.WarnAboutMissingIntlExchangeRate = true; if (FMyForm.InternationalCurrencyExchangeRate(ACurrentBatchRow, out IsTransactionInIntlCurrency, true) == 0) { return(RetVal); } //Check for zero Donors or Recipients if (!ADonorZeroIsValid) { DataView batchGiftDV = new DataView(FMainDS.AGift); batchGiftDV.RowFilter = string.Format("{0}={1} And {2}=0", AGiftTable.GetBatchNumberDBName(), FSelectedBatchNumber, AGiftTable.GetDonorKeyDBName()); int numDonorZeros = batchGiftDV.Count; if (numDonorZeros > 0) { string messageListOfOffendingGifts = String.Format(Catalog.GetString( "Gift Batch {0} contains {1} gift detail(s) with Donor 0000000. Please fix before posting!{2}{2}"), FSelectedBatchNumber, numDonorZeros, Environment.NewLine); string listOfOffendingRows = string.Empty; listOfOffendingRows += "Gift" + Environment.NewLine; listOfOffendingRows += "------------"; foreach (DataRowView drv in batchGiftDV) { AGiftRow giftRow = (AGiftRow)drv.Row; listOfOffendingRows += String.Format("{0}{1:0000}", Environment.NewLine, giftRow.GiftTransactionNumber); } TFrmExtendedMessageBox extendedMessageBox = new TFrmExtendedMessageBox(FMyForm); extendedMessageBox.ShowDialog((messageListOfOffendingGifts + listOfOffendingRows), Catalog.GetString("Post Batch Error"), string.Empty, TFrmExtendedMessageBox.TButtons.embbOK, TFrmExtendedMessageBox.TIcon.embiWarning); return(RetVal); } } if (!ARecipientZeroIsValid) { DataView batchGiftDetailsDV = new DataView(FMainDS.AGiftDetail); batchGiftDetailsDV.RowFilter = string.Format("{0}={1} And {2}=0", AGiftDetailTable.GetBatchNumberDBName(), FSelectedBatchNumber, AGiftDetailTable.GetRecipientKeyDBName()); int numRecipientZeros = batchGiftDetailsDV.Count; if (numRecipientZeros > 0) { string messageListOfOffendingGifts = String.Format(Catalog.GetString( "Gift Batch {0} contains {1} gift detail(s) with Recipient 0000000. Please fix before posting!{2}{2}"), FSelectedBatchNumber, numRecipientZeros, Environment.NewLine); string listOfOffendingRows = string.Empty; listOfOffendingRows += "Gift Detail" + Environment.NewLine; listOfOffendingRows += "-------------------"; foreach (DataRowView drv in batchGiftDetailsDV) { AGiftDetailRow giftDetailRow = (AGiftDetailRow)drv.Row; listOfOffendingRows += String.Format("{0}{1:0000} {2:00}", Environment.NewLine, giftDetailRow.GiftTransactionNumber, giftDetailRow.DetailNumber); } TFrmExtendedMessageBox extendedMessageBox = new TFrmExtendedMessageBox(FMyForm); extendedMessageBox.ShowDialog((messageListOfOffendingGifts + listOfOffendingRows), Catalog.GetString("Post Batch Error"), string.Empty, TFrmExtendedMessageBox.TButtons.embbOK, TFrmExtendedMessageBox.TIcon.embiWarning); return(RetVal); } } //Check for inactive KeyMinistries DataTable GiftsWithInactiveKeyMinistries; bool ModifiedDetails = false; if (AWarnOfInactiveValues && TRemote.MFinance.Gift.WebConnectors.InactiveKeyMinistriesFoundInBatch(FLedgerNumber, FSelectedBatchNumber, out GiftsWithInactiveKeyMinistries, false)) { int numInactiveValues = GiftsWithInactiveKeyMinistries.Rows.Count; string messageNonModifiedBatch = String.Format(Catalog.GetString("Gift Batch {0} contains {1} inactive key ministries. Please fix before posting!{2}{2}"), FSelectedBatchNumber, numInactiveValues, Environment.NewLine); string messageModifiedBatch = String.Format(Catalog.GetString( "Reversal/Adjustment Gift Batch {0} contains {1} inactive key ministries. Do you still want to post?{2}{2}"), FSelectedBatchNumber, numInactiveValues, Environment.NewLine); string listOfOffendingRows = string.Empty; listOfOffendingRows += "Gift Detail Recipient KeyMinistry" + Environment.NewLine; listOfOffendingRows += "-------------------------------------------------------------------------------"; foreach (DataRow dr in GiftsWithInactiveKeyMinistries.Rows) { listOfOffendingRows += String.Format("{0}{1:0000} {2:00} {3:00000000000} {4}", Environment.NewLine, dr[0], dr[1], dr[2], dr[3]); bool isModified = Convert.ToBoolean(dr[4]); if (isModified) { ModifiedDetails = true; } } TFrmExtendedMessageBox extendedMessageBox = new TFrmExtendedMessageBox(FMyForm); if (ModifiedDetails) { if (extendedMessageBox.ShowDialog((messageModifiedBatch + listOfOffendingRows), Catalog.GetString("Post Batch"), string.Empty, TFrmExtendedMessageBox.TButtons.embbYesNo, TFrmExtendedMessageBox.TIcon.embiWarning) == TFrmExtendedMessageBox.TResult.embrYes) { APostingAlreadyConfirmed = true; } else { return(RetVal); } } else { extendedMessageBox.ShowDialog((messageNonModifiedBatch + listOfOffendingRows), Catalog.GetString("Post Batch Error"), string.Empty, TFrmExtendedMessageBox.TButtons.embbOK, TFrmExtendedMessageBox.TIcon.embiWarning); return(RetVal); } } // ask if the user really wants to post the batch if (!APostingAlreadyConfirmed && (MessageBox.Show(String.Format(Catalog.GetString("Do you really want to post gift batch {0}?"), FSelectedBatchNumber), Catalog.GetString("Confirm posting of Gift Batch"), MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)) { return(RetVal); } Verifications = new TVerificationResultCollection(); try { FPostingInProgress = true; Thread postingThread = new Thread(() => PostGiftBatch(out Verifications)); using (TProgressDialog dialog = new TProgressDialog(postingThread)) { dialog.ShowDialog(); } if (!TVerificationHelper.IsNullOrOnlyNonCritical(Verifications)) { TFrmExtendedMessageBox extendedMessageBox = new TFrmExtendedMessageBox(FMyForm); StringBuilder errorMessages = new StringBuilder(); int counter = 0; errorMessages.AppendLine(Catalog.GetString("________________________Gift Posting Errors________________________")); errorMessages.AppendLine(); foreach (TVerificationResult verif in Verifications) { counter++; errorMessages.AppendLine(counter.ToString("000") + " - " + verif.ResultText); errorMessages.AppendLine(); } extendedMessageBox.ShowDialog(errorMessages.ToString(), Catalog.GetString("Post Batch Error"), string.Empty, TFrmExtendedMessageBox.TButtons.embbOK, TFrmExtendedMessageBox.TIcon.embiWarning); } else { MessageBox.Show(Catalog.GetString("The batch has been posted successfully!")); RetVal = true; } } catch (Exception ex) { TLogging.LogException(ex, Utilities.GetMethodSignature()); throw; } finally { FPostingInProgress = false; } return(RetVal); }
/// <summary> /// Export Partners from an Extract. /// </summary> /// <param name="AExtractId">Extract Identifier.</param> /// <param name="AOldPetraFormat">Set to true if old format should be used.</param> public static Boolean ExportPartnersInExtract(int AExtractId, Boolean AOldPetraFormat) { String SuggestedFileName = ""; Boolean Result = false; // prepare suggestion for file name: Extract name SuggestedFileName = "p_" + TRemote.MPartner.Partner.WebConnectors.GetExtractName(AExtractId); String FileName = TImportExportDialogs.GetExportFilename(Catalog.GetString("Save Partners into File"), SuggestedFileName); if (AExtractId < 0) { return(false); } if (FileName.Length > 0) { bool ExportFamiliesPersons = false; bool ContainsFamily = TRemote.MPartner.ImportExport.WebConnectors.CheckExtractContainsFamily(AExtractId); if (ContainsFamily) { if (MessageBox.Show( Catalog.GetString("When exporting a FAMILY record do you want to also export all associated PERSON records?"), Catalog.GetString("Export Partners"), MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { ExportFamiliesPersons = true; } } if (FileName.EndsWith("ext")) { string Doc = string.Empty; // run in thread so we can have Progress Dialog Thread t = new Thread(() => ExportExtractToString(AExtractId, ExportFamiliesPersons, ref Doc, AOldPetraFormat)); using (TProgressDialog dialog = new TProgressDialog(t)) { dialog.ShowDialog(); } // null if the user cancelled the operation if (Doc == null) { MessageBox.Show(Catalog.GetString("Export cancelled."), Catalog.GetString( "Export Partners"), MessageBoxButtons.OK, MessageBoxIcon.Information); return(false); } Result = TImportExportDialogs.ExportTofile(Doc, FileName, AOldPetraFormat); if (!Result) { MessageBox.Show(Catalog.GetString("Export of Partners in Extract failed!"), Catalog.GetString( "Export Partners"), MessageBoxButtons.OK, MessageBoxIcon.Error); } else { MessageBox.Show(Catalog.GetString("Export of Partners in Extract finished."), Catalog.GetString( "Export Partners"), MessageBoxButtons.OK, MessageBoxIcon.Information); } } else { // XmlDocument doc = new XmlDocument(); MessageBox.Show(Catalog.GetString("Export with this format is not yet supported!"), Catalog.GetString( "Export Partners"), MessageBoxButtons.OK, MessageBoxIcon.Error); // doc.LoadXml(TRemote.MPartner.ImportExport.WebConnectors.ExportExtractPartners(GetSelectedDetailRow().ExtractId, false)); // Result = TImportExportDialogs.ExportTofile(doc, FileName); } return(Result); } return(false); }
/// <summary> /// Import a transactions file or a clipboard equivalent /// </summary> /// <param name="ACurrentBatchRow">The batch to import to</param> /// <param name="AImportSource">The import source - eg File or Clipboard</param> /// <returns>True if the import was successful</returns> public bool ImportTransactions(AGiftBatchRow ACurrentBatchRow, TGiftImportDataSourceEnum AImportSource) { bool ok = false; bool RefreshGUIAfterImport = false; OpenFileDialog dialog = null; Boolean IsPlainText = false; if (FPetraUtilsObject.HasChanges) { // saving failed, therefore do not try to import MessageBox.Show(Catalog.GetString("Please save any changes before calling this function!"), Catalog.GetString( "Gift Import"), MessageBoxButtons.OK, MessageBoxIcon.Error); return(false); } if ((ACurrentBatchRow == null) || (ACurrentBatchRow.BatchStatus != MFinanceConstants.BATCH_UNPOSTED)) { MessageBox.Show(Catalog.GetString("Please select an unposted batch to import transactions."), Catalog.GetString( "Gift Import"), MessageBoxButtons.OK, MessageBoxIcon.Error); return(false); } if (ACurrentBatchRow.LastGiftNumber > 0) { if (MessageBox.Show(Catalog.GetString( "The current batch already contains some gift transactions. Do you really want to add more transactions to this batch?"), Catalog.GetString("Gift Transaction Import"), MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.No) { return(false); } } FdlgSeparator = new TDlgSelectCSVSeparator(false); FdlgSeparator.DateMayBeInteger = TUserDefaults.GetBooleanDefault(MCommonConstants.USERDEFAULT_IMPORTEDDATESMAYBEINTEGERS, false); if (AImportSource == TGiftImportDataSourceEnum.FromClipboard) { string importString = Clipboard.GetText(TextDataFormat.UnicodeText); if ((importString == null) || (importString.Length == 0)) { MessageBox.Show(Catalog.GetString("Please first copy data from your spreadsheet application!"), Catalog.GetString("Failure"), MessageBoxButtons.OK, MessageBoxIcon.Error); return(false); } FdlgSeparator.CSVData = importString; } else if (AImportSource == TGiftImportDataSourceEnum.FromFile) { dialog = new OpenFileDialog(); string exportPath = TClientSettings.GetExportPath(); string fullPath = TUserDefaults.GetStringDefault("Imp Filename", exportPath + Path.DirectorySeparatorChar + "import.csv"); TImportExportDialogs.SetOpenFileDialogFilePathAndName(dialog, fullPath, exportPath); dialog.Title = Catalog.GetString("Import Transactions from CSV File"); dialog.Filter = Catalog.GetString("Gift Transactions files (*.csv)|*.csv|Text Files (*.txt)|*.txt"); // This call fixes Windows7 Open File Dialogs. It must be the line before ShowDialog() TWin7FileOpenSaveDialog.PrepareDialog(Path.GetFileName(fullPath)); if (dialog.ShowDialog() == DialogResult.OK) { Boolean fileCanOpen = FdlgSeparator.OpenCsvFile(dialog.FileName); if (!fileCanOpen) { MessageBox.Show(Catalog.GetString("Unable to open file."), Catalog.GetString("Gift Import"), MessageBoxButtons.OK, MessageBoxIcon.Stop); return(false); } IsPlainText = (Path.GetExtension(dialog.FileName).ToLower() == ".txt"); } else { return(false); } } else { // unknown source!! The following need a value... return(false); } String impOptions = TUserDefaults.GetStringDefault("Imp Options", ";" + TDlgSelectCSVSeparator.NUMBERFORMAT_AMERICAN); String dateFormatString = TUserDefaults.GetStringDefault("Imp Date", "MDY"); FdlgSeparator.DateFormat = dateFormatString; FdlgSeparator.NumberFormat = (impOptions.Length > 1) ? impOptions.Substring(1) : TDlgSelectCSVSeparator.NUMBERFORMAT_AMERICAN; FdlgSeparator.SelectedSeparator = StringHelper.GetCSVSeparator(FdlgSeparator.FileContent) ?? ((impOptions.Length > 0) ? impOptions.Substring(0, 1) : ";"); if (IsPlainText || (FdlgSeparator.ShowDialog() == DialogResult.OK)) { Hashtable requestParams = new Hashtable(); requestParams.Add("ALedgerNumber", FLedgerNumber); requestParams.Add("Delimiter", FdlgSeparator.SelectedSeparator); requestParams.Add("DateFormatString", FdlgSeparator.DateFormat); requestParams.Add("NumberFormat", FdlgSeparator.NumberFormat); requestParams.Add("NewLine", Environment.NewLine); bool Repeat = true; while (Repeat) { Repeat = false; TVerificationResultCollection AMessages = new TVerificationResultCollection(); GiftBatchTDSAGiftDetailTable NeedRecipientLedgerNumber = new GiftBatchTDSAGiftDetailTable(); Thread ImportThread = new Thread(() => ImportGiftTransactions( requestParams, FdlgSeparator.FileContent, ACurrentBatchRow.BatchNumber, out AMessages, out ok, out RefreshGUIAfterImport, out NeedRecipientLedgerNumber)); using (TProgressDialog ImportDialog = new TProgressDialog(ImportThread)) { ImportDialog.ShowDialog(); } // if the import contains gifts with Motivation Group 'GIFT' and that have a Family recipient with no Gift Destination // then the import will have failed and we need to alert the user int numberOfMissingGiftDestinations = NeedRecipientLedgerNumber.Rows.Count; if (numberOfMissingGiftDestinations == 0) { if (TVerificationHelper.ResultsContainErrorCode(AMessages, PetraErrorCodes.ERR_DB_SERIALIZATION_EXCEPTION)) { TConcurrentServerTransactions.ShowTransactionSerializationExceptionDialog(); } else { ShowMessages(AMessages); } } if (numberOfMissingGiftDestinations > 0) { bool offerToRunImportAgain = true; int currentMissingGiftDestinationNo = 1; // for each gift in which the recipient needs a Git Destination foreach (GiftBatchTDSAGiftDetailRow Row in NeedRecipientLedgerNumber.Rows) { //Lookup the partner shortname string partnerShortName = string.Empty; TPartnerClass partnerClass; if (TServerLookup.TMPartner.GetPartnerShortName(Row.RecipientKey, out partnerShortName, out partnerClass)) { Row.RecipientDescription = partnerShortName; } if (MessageBox.Show(string.Format( Catalog.GetString( "Error: {0:0000} of {1:0000} - Recipient '{2}' ({3}) has no Gift Destination assigned."), currentMissingGiftDestinationNo, numberOfMissingGiftDestinations, Row.RecipientDescription, Row.RecipientKey) + "\n\n" + Catalog.GetString("Do you want to assign a Gift Destination to this partner now?"), Catalog.GetString("Gift Import Cancelled"), MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes) { // allow the user to assign a Gift Destingation TFrmGiftDestination GiftDestinationForm = new TFrmGiftDestination(FPetraUtilsObject.GetForm(), Row.RecipientKey); GiftDestinationForm.ShowDialog(); } else { offerToRunImportAgain = false; } currentMissingGiftDestinationNo++; } // if the user has clicked yes to assigning Gift Destinations then offer to restart the import if (offerToRunImportAgain && (MessageBox.Show(Catalog.GetString("Would you like to import these Gift Transactions again?"), Catalog.GetString("Gift Import"), MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1) == DialogResult.Yes)) { Repeat = true; } } } } // We save the defaults even if ok is false - because the client will probably want to try and import // the same file again after correcting any errors if (!IsPlainText) { SaveUserDefaults(dialog); } if (ok) { MessageBox.Show(Catalog.GetString("Your data was imported successfully!"), Catalog.GetString("Gift Import"), MessageBoxButtons.OK, MessageBoxIcon.Information); } if (ok || RefreshGUIAfterImport) { FMyUserControl.LoadBatchesForCurrentYear(); FPetraUtilsObject.DisableSaveButton(); return(true); // This completes the refresh } return(false); }
/// <summary> /// Helper function to load the Report Data in the standard case where no client-side processing is required. /// </summary> /// <param name="AUseProgressBar">Use a ProgressBar?</param> /// <param name="AReportName">The Name of the Report</param> /// <param name="AUseDataSet">True, if a ReportSet is used</param> /// <param name="ATableNames">The Names of the Tables</param> /// <param name="ACalc">ACalc object</param> /// <param name="AWindow">"Parent" Window</param> /// <param name="AUseColumnTab">"Parent" Window</param> /// <param name="AAddLedger">"Adds the Ledger Name to the Parameters"</param> /// <param name="ALedgerNumber">"The Ledger Number if used"</param> /// <param name="AMainTableName">Indicating Table (name) whether a report would be blank. Only if DataSet is used and Main Table isn't the first in the DataSet. </param> /// <param name="ASortBy">"Sort By..."</param> /// <returns></returns> public bool LoadReportData( bool AUseProgressBar, string AReportName, bool AUseDataSet, string[] ATableNames, TRptCalculator ACalc, Form AWindow, bool AUseColumnTab, bool AAddLedger = false, Int32 ALedgerNumber = -1, string AMainTableName = "", string ASortBy = "" ) { if (AUseColumnTab) { TColumnSettingCollection tcsc = new TColumnSettingCollection(); for (int counter = 0; counter <= ACalc.GetParameters().Get("MaxDisplayColumns").ToInt() - 1; counter += 1) { TColumnSetting tcs = new TColumnSetting(ACalc.GetParameters().Get("param_calculation", counter).ToString().Replace(" ", "").Replace("/", ""), float.Parse(ACalc.GetParameters().Get("ColumnWidth", counter).ToString()), counter + 1); tcsc.SetSettingForColumn(tcs); } ACalc.AddParameter("param_columns", tcsc.SerialiseCollection()); } //paramsDictionary also contains the selected columns as serialised string Dictionary <String, TVariant> paramsDictionary = ParamsToDictionary(ACalc); DataTable ReportTable = null; DataSet ReportSet = null; Thread t; bool ThreadFinished = false; if (AUseDataSet) { t = new Thread(() => ReportSet = GetReportDataSet(AReportName, paramsDictionary, ref ThreadFinished)); } else { t = new Thread(() => ReportTable = GetReportDataTable(AReportName, paramsDictionary, ref ThreadFinished)); } if (AUseProgressBar) { using (TProgressDialog dialog = new TProgressDialog(t)) { dialog.SetRefreshInterval(200); dialog.ShowDialog(); } // wait here until Thread is really finished while (!ThreadFinished) { Thread.Sleep(50); } } else { t.Start(); t.Join(); } if ((AWindow == null) || AWindow.IsDisposed) { return(false); } if ((ReportTable == null) && (ReportSet == null)) { FPetraUtilsObject.WriteToStatusBar("Report Cancelled."); return(false); } //Message if Report would be blank string Message = Catalog.GetString("No data has been found for the current selection."); if (AUseDataSet) { bool error = false; if (AMainTableName == String.Empty) { if (ReportSet.Tables[0].Rows.Count == 0) { error = true; } } else { if (ReportSet.Tables[AMainTableName].Rows.Count == 0) { error = true; } } if (error) { MessageBox.Show(Message, "Error"); FPetraUtilsObject.WriteToStatusBar(Catalog.GetString("No data found for current selection.")); return(false); } } else if (ReportTable.Rows.Count == 0) { MessageBox.Show(Message, "Error"); FPetraUtilsObject.WriteToStatusBar(Catalog.GetString("No data found for current selection.")); return(false); } if (AAddLedger) { DataTable LedgerNameTable = TDataCache.TMFinance.GetCacheableFinanceTable(TCacheableFinanceTablesEnum.LedgerNameList); DataView LedgerView = new DataView(LedgerNameTable); LedgerView.RowFilter = "LedgerNumber=" + ALedgerNumber; String LedgerName = ""; if (LedgerView.Count > 0) { LedgerName = LedgerView[0].Row["LedgerName"].ToString(); } ACalc.AddStringParameter("param_ledger_name", LedgerName); } if (!AUseDataSet && (ASortBy != "")) { DataView dv = ReportTable.DefaultView; dv.Sort = ASortBy; ReportTable = dv.ToTable(); } if (AUseDataSet) { foreach (string TableName in ATableNames) { RegisterData(ReportSet.Tables[TableName], TableName); } } else { RegisterData(ReportTable, ATableNames[0]); } return(true); }
/// <summary> /// this supports the batch export files from Petra 2.x. /// Each line starts with a type specifier, B for batch, J for journal, T for transaction /// </summary> private void ExportBatches(object sender, EventArgs e) { if (rbtBatchNumberSelection.Checked) { if (!txtBatchNumberStart.NumberValueInt.HasValue) { txtBatchNumberStart.NumberValueInt = 0; } if (!txtBatchNumberEnd.NumberValueInt.HasValue) { txtBatchNumberEnd.NumberValueInt = 999999; } } else { if ((!dtpDateFrom.ValidDate()) || (!dtpDateTo.ValidDate())) { return; } } if (File.Exists(txtFilename.Text)) { if (MessageBox.Show(Catalog.GetString("The file already exists. Is it OK to overwrite it?"), Catalog.GetString("Export Batches"), MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.No) { return; } } StreamWriter sw1 = null; try { sw1 = new StreamWriter(txtFilename.Text); } catch (Exception ex) { MessageBox.Show(ex.Message, Catalog.GetString("Failed to open file"), MessageBoxButtons.OK, MessageBoxIcon.Error); return; } 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; } Hashtable requestParams = new Hashtable(); requestParams.Add("ALedgerNumber", ALedgerNumber); requestParams.Add("Delimiter", ConvertDelimiter(cmbDelimiter.GetSelectedString(), false)); 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", ConvertNumberFormat(cmbNumberFormat)); String exportString = null; Thread ExportThread = new Thread(() => ExportAllGLBatchData(ref batches, requestParams, out exportString)); using (TProgressDialog ExportDialog = new TProgressDialog(ExportThread)) { ExportDialog.ShowDialog(); } sw1.Write(exportString); sw1.Close(); MessageBox.Show(Catalog.GetString("Your data was exported successfully!"), Catalog.GetString("Success"), MessageBoxButtons.OK, MessageBoxIcon.Information); SaveUserDefaults(); }
// starts the merge process private void BtnOK_Click(Object Sender, EventArgs e) { FFromPartnerKey = Convert.ToInt64(txtMergeFrom.Text); FToPartnerKey = Convert.ToInt64(txtMergeTo.Text); if (CheckPartnersCanBeMerged() && (MessageBox.Show(Catalog.GetString("WARNING: A Partner Merge operation cannot be undone and the From-Partner will be no longer " + "accessible after the Partner Merge operation!") + "\n\n" + Catalog.GetString("Are you sure you want to continue?"), Catalog.GetString("Merge Partners"), MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)) { bool[] Categories = new bool[25]; for (int i = 1; i < 25; i++) { Categories[i] = true; } FSiteKeys = null; FLocationKeys = null; FContactDetails = null; FMainBankingDetailsKey = -1; bool DifferentFamilies = false; // open a dialog to select which From Partner's addresses should be merged if (GetSelectedAddresses() == false) { MessageBox.Show(Catalog.GetString("Merge cancelled.")); return; } // open a dialog to select which From Partner's contact details should be merged if (GetSelectedContactDetails() == false) { MessageBox.Show(Catalog.GetString("Merge cancelled.")); return; } // open a dialog to select which bank account should be set to MAIN (if necessary) if (GetMainBankAccount() == false) { MessageBox.Show(Catalog.GetString("Merge cancelled.")); return; } // if ((((FFromPartnerClass == TPartnerClass.FAMILY) && (FToPartnerClass == TPartnerClass.FAMILY)) || (FFromPartnerClass == TPartnerClass.PERSON)) && (GiftDestinationToMerge(out Categories[0]) == false)) { MessageBox.Show(Catalog.GetString("Merge cancelled.")); return; } Thread t = new Thread(() => MergeTwoPartners(Categories, ref DifferentFamilies)); using (TProgressDialog dialog = new TProgressDialog(t)) { if ((dialog.ShowDialog() == DialogResult.Cancel) && (WebConnectorResult == true)) { MessageBox.Show(Catalog.GetString("Merge cancelled.")); return; } else if (!WebConnectorResult) // if merge is unsuccessful { MessageBox.Show(Catalog.GetString("Merge failed. Please check the Server.log file on the server.")); dialog.Close(); return; } } if (DifferentFamilies) { MessageBox.Show(String.Format(Catalog.GetString("Partners were in different families.")) + "\n\n" + Catalog.GetString("FAMILY relations of the From Partner are not taken over to the To Partner!") + "\n\n" + Catalog.GetString("Please check the family relations of the To Partner after completion."), Catalog.GetString("Merge Partners"), MessageBoxButtons.OK, MessageBoxIcon.Information); } MessageBox.Show(String.Format(Catalog.GetString("Merge of Partner {0} ({1}) into {2} ({3}) complete."), txtMergeFrom.LabelText, FFromPartnerKey, txtMergeTo.LabelText, FToPartnerKey) + "\n\n" + Catalog.GetString("If necessary, edit the merged Partner to correct any information that may not have been " + "merged and correct information that may have been overwritten.") + "\n\n" + Catalog.GetString("Tip: You can use the 'Work with Last Partner' command in the Partner module and the " + "'Work with Last Person' command in the Personnel module to view and edit the merged Partner."), Catalog.GetString("Merge Partners"), MessageBoxButtons.OK, MessageBoxIcon.Information); this.DialogResult = System.Windows.Forms.DialogResult.OK; this.Close(); } }
private Boolean LoadReportData(TRptCalculator ACalc) { // // I need the name of the ledger, and the currency formatter.. String LedgerName = TRemote.MFinance.Reporting.WebConnectors.GetLedgerName(FLedgerNumber); ACalc.AddStringParameter("param_ledger_name", LedgerName); ACalc.AddStringParameter("param_currency_formatter", "0,0.000"); ACalc.AddStringParameter("param_recipient", "All Recipients"); ArrayList reportParam = ACalc.GetParameters().Elems; Dictionary <String, TVariant> paramsDictionary = new Dictionary <string, TVariant>(); foreach (Shared.MReporting.TParameter p in reportParam) { if (p.name.StartsWith("param") && (p.name != "param_calculation") && !paramsDictionary.ContainsKey(p.name)) { paramsDictionary.Add(p.name, p.value); } } // get data for this report // Previous code: // DataSet ReportDataSet = TRemote.MReporting.WebConnectors.GetReportDataSet("DonorGiftStatement", paramsDictionary); DataSet ReportDataSet = null; Boolean ThreadFinished = false; Boolean ThreadOK = true; string ThreadFailMsg = "GetDGSDataSet completed successfully"; // This message should not be displayed! Hence it is not translated. Thread t = new Thread(() => GetDGSDataSet(ref ReportDataSet, paramsDictionary, ref ThreadFinished, ACalc)); using (TProgressDialog dialog = new TProgressDialog(t, AWaitForThreadComplete: true)) { dialog.ShowDialog(); if (dialog.Cancelled) { ThreadOK = false; ThreadFailMsg = Catalog.GetString("Query generation cancelled"); } } while (!ThreadFinished) { Thread.Sleep(50); } // if no Donors if (ThreadOK && ((ReportDataSet == null) || (ReportDataSet.Tables["Donors"] == null) || (ReportDataSet.Tables["Donors"].Rows.Count == 0))) { ThreadOK = false; ThreadFailMsg = Catalog.GetString("No Donors found."); } // so if ThreadOK was set false, show the user why. if (!ThreadOK) { MessageBox.Show(ThreadFailMsg, "Donor Gift Statement"); return(false); } if (TRemote.MReporting.WebConnectors.DataTableGenerationWasCancelled() || this.IsDisposed) { return(false); } return(ThreadOK); }
/// <summary> /// this supports the transaction export files from Petra 2.x. /// Lines do NOT start with T for transaction /// </summary> public void ImportTransactions(ABatchRow ACurrentBatchRow, AJournalRow ACurrentJournalRow, TImportDataSourceEnum AImportDataSource) { bool ok = false; bool RefreshGUIAfterImport = false; OpenFileDialog dialog = null; if (FPetraUtilsObject.HasChanges && !FMyForm.SaveChanges()) { // saving failed, therefore do not try to import MessageBox.Show(Catalog.GetString("Please save your changes before Importing new transactions"), Catalog.GetString( "Import GL Transactions"), MessageBoxButtons.OK, MessageBoxIcon.Error); return; } if ((ACurrentBatchRow == null) || (ACurrentJournalRow == null) || (ACurrentJournalRow.JournalStatus != MFinanceConstants.BATCH_UNPOSTED)) { MessageBox.Show(Catalog.GetString("Please select an unposted journal to import transactions."), Catalog.GetString("Import GL Transactions")); return; } if (ACurrentJournalRow.LastTransactionNumber > 0) { if (MessageBox.Show(Catalog.GetString( "The current journal already contains some transactions. Do you really want to add more transactions to this journal?"), Catalog.GetString("Import GL Transactions"), MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.No) { return; } } bool datesMayBeIntegers = TUserDefaults.GetBooleanDefault(MCommonConstants.USERDEFAULT_IMPORTEDDATESMAYBEINTEGERS, false); FdlgSeparator = new TDlgSelectCSVSeparator(false); FdlgSeparator.DateMayBeInteger = datesMayBeIntegers; if (AImportDataSource == TImportDataSourceEnum.FromClipboard) { string importString = Clipboard.GetText(TextDataFormat.UnicodeText); if ((importString == null) || (importString.Length == 0)) { MessageBox.Show(Catalog.GetString("Please first copy data from your spreadsheet application!"), Catalog.GetString("Failure"), MessageBoxButtons.OK, MessageBoxIcon.Error); return; } FdlgSeparator.CSVData = importString; } else if (AImportDataSource == TImportDataSourceEnum.FromFile) { dialog = new OpenFileDialog(); string exportPath = TClientSettings.GetExportPath(); string fullPath = TUserDefaults.GetStringDefault("Imp Filename", exportPath + Path.DirectorySeparatorChar + "import.csv"); TImportExportDialogs.SetOpenFileDialogFilePathAndName(dialog, fullPath, exportPath); dialog.Title = Catalog.GetString("Import Transactions from CSV File"); dialog.Filter = Catalog.GetString("GL Transactions files (*.csv)|*.csv|Text Files (*.txt)|*.txt"); // This call fixes Windows7 Open File Dialogs. It must be the line before ShowDialog() TWin7FileOpenSaveDialog.PrepareDialog(Path.GetFileName(fullPath)); if (dialog.ShowDialog() == DialogResult.OK) { Boolean fileCanOpen = FdlgSeparator.OpenCsvFile(dialog.FileName); if (!fileCanOpen) { MessageBox.Show(Catalog.GetString("Unable to open file."), Catalog.GetString("Transaction Import"), MessageBoxButtons.OK, MessageBoxIcon.Stop); return; } } else { return; } } else { // unknown source!! return; } String impOptions = TUserDefaults.GetStringDefault("Imp Options", ";" + TDlgSelectCSVSeparator.NUMBERFORMAT_AMERICAN); String dateFormatString = TUserDefaults.GetStringDefault("Imp Date", "MDY"); FdlgSeparator.DateFormat = dateFormatString; FdlgSeparator.NumberFormat = (impOptions.Length > 1) ? impOptions.Substring(1) : TDlgSelectCSVSeparator.NUMBERFORMAT_AMERICAN; FdlgSeparator.SelectedSeparator = StringHelper.GetCSVSeparator(FdlgSeparator.FileContent) ?? ((impOptions.Length > 0) ? impOptions.Substring(0, 1) : ";"); if (FdlgSeparator.ShowDialog() == DialogResult.OK) { Hashtable requestParams = new Hashtable(); requestParams.Add("ALedgerNumber", FLedgerNumber); requestParams.Add("Delimiter", FdlgSeparator.SelectedSeparator); requestParams.Add("DateFormatString", FdlgSeparator.DateFormat); requestParams.Add("DatesMayBeIntegers", datesMayBeIntegers); requestParams.Add("NumberFormat", FdlgSeparator.NumberFormat); requestParams.Add("NewLine", Environment.NewLine); requestParams.Add("LastTransactionNumber", ACurrentJournalRow.LastTransactionNumber); TVerificationResultCollection AMessages = new TVerificationResultCollection(); Thread ImportThread = new Thread(() => ImportGLTransactions(requestParams, FdlgSeparator.FileContent, ACurrentBatchRow.BatchNumber, ACurrentJournalRow.JournalNumber, out AMessages, out ok, out RefreshGUIAfterImport)); using (TProgressDialog ImportDialog = new TProgressDialog(ImportThread)) { ImportDialog.ShowDialog(); } ShowMessages(AMessages); } // It is important to save user defaults here, even if there were errors // because in that case the user will want to import the same file again after fixing it. SaveUserDefaults(dialog); if (ok || RefreshGUIAfterImport) { if (ok) { MessageBox.Show(Catalog.GetString("Your data was imported successfully!"), Catalog.GetString("Transactions Import"), MessageBoxButtons.OK, MessageBoxIcon.Information); } // Update the client side with new information from the server FMyForm.Cursor = Cursors.WaitCursor; FMainDS.Merge(TRemote.MFinance.GL.WebConnectors.LoadABatchAJournal(FLedgerNumber, ACurrentBatchRow.BatchNumber)); FMainDS.Merge(TRemote.MFinance.GL.WebConnectors.LoadATransactionAndRelatedTablesForJournal(FLedgerNumber, ACurrentBatchRow.BatchNumber, ACurrentJournalRow.JournalNumber)); FMainDS.AcceptChanges(); FMyForm.Cursor = Cursors.Default; FMyForm.GetTransactionsControl().SelectRow(1); } }
/// <summary> /// Public method to export GL batches /// </summary> /// <returns>True if the Export succeeded and a file was created, false otherwise</returns> public bool ExportBatches() { if (txtFilename.Text == String.Empty) { MessageBox.Show(Catalog.GetString("Please choose a location for the Export File."), Catalog.GetString("Error"), MessageBoxButtons.OK, MessageBoxIcon.Error); return(false); } if (!Directory.Exists(Path.GetDirectoryName(txtFilename.Text))) { 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(txtFilename.Text)) { 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(txtFilename.Text); } 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(txtFilename.Text); sw1.Write(exportString); sw1.Close(); } catch (Exception ex) { TLogging.Log("GLBatchExport.ManualCode: " + ex.ToString()); MessageBox.Show(ex.Message, Catalog.GetString("Error"), MessageBoxButtons.OK, MessageBoxIcon.Error); return(false); } // Offer the client the chance to open the file in Excel or whatever if (MessageBox.Show(Catalog.GetString("Your data was 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) { ProcessStartInfo si = new ProcessStartInfo(txtFilename.Text); si.UseShellExecute = true; si.Verb = "open"; Process p = new Process(); p.StartInfo = si; p.Start(); } return(true); }
/// <summary> /// this supports the batch export files from Petra 2.x. /// Each line starts with a type specifier, B for batch, J for journal, T for transaction /// The code handles importing from file or clipboard /// </summary> public void ImportBatches(TImportDataSourceEnum AImportDataSource) { bool ok = false; String importString; String impOptions; OpenFileDialog dialog = null; if (FPetraUtilsObject.HasChanges) { // saving failed, therefore do not try to import MessageBox.Show(Catalog.GetString("Please save before calling this function!"), Catalog.GetString( "Failure"), MessageBoxButtons.OK, MessageBoxIcon.Error); return; } FdlgSeparator = new TDlgSelectCSVSeparator(false); if (AImportDataSource == TImportDataSourceEnum.FromClipboard) { importString = Clipboard.GetText(TextDataFormat.UnicodeText); if ((importString == null) || (importString.Length == 0)) { MessageBox.Show(Catalog.GetString("Please first copy data from your spreadsheet application!"), Catalog.GetString("Failure"), MessageBoxButtons.OK, MessageBoxIcon.Error); return; } impOptions = TUserDefaults.GetStringDefault("Imp Options", ";American"); String dateFormatString = TUserDefaults.GetStringDefault("Imp Date", "MDY"); FdlgSeparator = new TDlgSelectCSVSeparator(false); FdlgSeparator.SelectedSeparator = "\t"; FdlgSeparator.CSVData = importString; FdlgSeparator.DateFormat = dateFormatString; if (impOptions.Length > 1) { FdlgSeparator.NumberFormat = impOptions.Substring(1); } } else if (AImportDataSource == TImportDataSourceEnum.FromFile) { dialog = new OpenFileDialog(); string exportPath = TClientSettings.GetExportPath(); string fullPath = TUserDefaults.GetStringDefault("Imp Filename", exportPath + Path.DirectorySeparatorChar + "import.csv"); TImportExportDialogs.SetOpenFileDialogFilePathAndName(dialog, fullPath, exportPath); dialog.Title = Catalog.GetString("Import Batches from CSV File"); dialog.Filter = Catalog.GetString("Text Files(*.txt) | *.txt | GL Batch Files(*.csv) | *.csv"); impOptions = TUserDefaults.GetStringDefault("Imp Options", ";" + TDlgSelectCSVSeparator.NUMBERFORMAT_AMERICAN); // This call fixes Windows7 Open File Dialogs. It must be the line before ShowDialog() TWin7FileOpenSaveDialog.PrepareDialog(Path.GetFileName(fullPath)); if (dialog.ShowDialog() == DialogResult.OK) { Boolean fileCanOpen = FdlgSeparator.OpenCsvFile(dialog.FileName); if (!fileCanOpen) { MessageBox.Show(Catalog.GetString("Unable to open file."), Catalog.GetString("Batch Import"), MessageBoxButtons.OK, MessageBoxIcon.Stop); return; } importString = File.ReadAllText(dialog.FileName, Encoding.Default); String dateFormatString = TUserDefaults.GetStringDefault("Imp Date", "MDY"); FdlgSeparator.DateFormat = dateFormatString; if (impOptions.Length > 1) { FdlgSeparator.NumberFormat = impOptions.Substring(1); } FdlgSeparator.SelectedSeparator = impOptions.Substring(0, 1); } else { return; } } else { // unknown source!! The following need a value... impOptions = String.Empty; importString = String.Empty; } if (FdlgSeparator.ShowDialog() == DialogResult.OK) { Hashtable requestParams = new Hashtable(); requestParams.Add("ALedgerNumber", FLedgerNumber); requestParams.Add("Delimiter", FdlgSeparator.SelectedSeparator); requestParams.Add("DateFormatString", FdlgSeparator.DateFormat); requestParams.Add("NumberFormat", FdlgSeparator.NumberFormat); requestParams.Add("NewLine", Environment.NewLine); TVerificationResultCollection AMessages = new TVerificationResultCollection(); Thread ImportThread = new Thread(() => ImportGLBatches( requestParams, importString, out AMessages, out ok)); using (TProgressDialog ImportDialog = new TProgressDialog(ImportThread)) { ImportDialog.ShowDialog(); } // We save the defaults even if ok is false - because the client will probably want to try and import // the same file again after correcting any errors SaveUserDefaults(dialog, impOptions); ShowMessages(AMessages); } if (ok) { MessageBox.Show(Catalog.GetString("Your data was imported successfully!"), Catalog.GetString("Batch Import"), MessageBoxButtons.OK, MessageBoxIcon.Information); FMyUserControl.ReloadBatches(); FPetraUtilsObject.DisableSaveButton(); } }
/// <summary> /// this supports the batch export files from Petra 2.x. /// Each line starts with a type specifier, B for batch, J for journal, T for transaction /// </summary> public void ExportBatches(object sender, EventArgs e) { if (File.Exists(txtFilename.Text)) { if (MessageBox.Show(Catalog.GetString("The file already exists. Is it OK to overwrite it?"), Catalog.GetString("Export Gifts"), MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.No) { return; } } StreamWriter sw1 = null; try { sw1 = new StreamWriter(txtFilename.Text, false, Encoding.GetEncoding(TAppSettingsManager.GetInt32("ExportGiftBatchEncoding", 1252))); } catch (Exception ex) { MessageBox.Show(ex.Message, Catalog.GetString("Failed to open file"), MessageBoxButtons.OK, MessageBoxIcon.Error); return; } try { if (rbtBatchNumberSelection.Checked) { if (!txtBatchNumberStart.NumberValueInt.HasValue) { txtBatchNumberStart.NumberValueInt = 0; } if (!txtBatchNumberEnd.NumberValueInt.HasValue) { txtBatchNumberEnd.NumberValueInt = 999999; } } else { if ((dtpDateFrom.Text == "") || (dtpDateTo.Text == "")) { MessageBox.Show(Catalog.GetString("Start and end dates must be provided."), Catalog.GetString("Error"), MessageBoxButtons.OK, MessageBoxIcon.Error); return; } if ((!dtpDateFrom.ValidDate()) || (!dtpDateTo.ValidDate())) // If ValidDate fails, it displays a helpful message. { return; } } String numberFormat = ConvertNumberFormat(cmbNumberFormat); String delimiter = ConvertDelimiter(cmbDelimiter.GetSelectedString(), false); if (((numberFormat == "European") && (delimiter == ",")) || ((numberFormat == "American") && (delimiter == "."))) { MessageBox.Show(Catalog.GetString("Numeric Decimal cannot be the same as the delimiter."), Catalog.GetString("Error"), MessageBoxButtons.OK, MessageBoxIcon.Error); return; } Hashtable requestParams = new Hashtable(); requestParams.Add("ALedgerNumber", FLedgerNumber); requestParams.Add("Delimiter", ConvertDelimiter(cmbDelimiter.GetSelectedString(), false)); requestParams.Add("DateFormatString", cmbDateFormat.GetSelectedString()); requestParams.Add("Summary", rbtSummary.Checked); requestParams.Add("IncludeUnposted", chkIncludeUnposted.Checked); requestParams.Add("bUseBaseCurrency", rbtBaseCurrency.Checked); requestParams.Add("TransactionsOnly", chkTransactionsOnly.Checked); requestParams.Add("RecipientNumber", Convert.ToInt64(txtDetailRecipientKey.Text)); requestParams.Add("FieldNumber", Convert.ToInt64(txtDetailFieldKey.Text)); requestParams.Add("DateForSummary", dtpDateSummary.Date); requestParams.Add("NumberFormat", ConvertNumberFormat(cmbNumberFormat)); requestParams.Add("ExtraColumns", chkExtraColumns.Checked); if (rbtBatchNumberSelection.Checked) { requestParams.Add("BatchNumberStart", txtBatchNumberStart.NumberValueInt); requestParams.Add("BatchNumberEnd", txtBatchNumberEnd.NumberValueInt); } else { requestParams.Add("BatchDateFrom", dtpDateFrom.Date); requestParams.Add("BatchDateTo", dtpDateTo.Date); } TVerificationResultCollection AMessages = new TVerificationResultCollection(); String exportString = null; Int32 BatchCount = 0; Thread ExportThread = new Thread(() => ExportAllGiftBatchData( requestParams, out exportString, out AMessages, out BatchCount)); using (TProgressDialog ExportDialog = new TProgressDialog(ExportThread)) { ExportDialog.ShowDialog(); } if ((AMessages != null) && (AMessages.Count > 0)) { if (!TVerificationHelper.IsNullOrOnlyNonCritical(AMessages)) { MessageBox.Show(AMessages.BuildVerificationResultString(), Catalog.GetString("Error"), MessageBoxButtons.OK, MessageBoxIcon.Error); return; } else { MessageBox.Show(AMessages.BuildVerificationResultString(), Catalog.GetString("Warnings"), MessageBoxButtons.OK, MessageBoxIcon.Information); } } if (BatchCount == 0) { MessageBox.Show(Catalog.GetString("There are no batches matching your criteria"), Catalog.GetString("Error"), MessageBoxButtons.OK, MessageBoxIcon.Error); return; } sw1.Write(exportString); sw1.Close(); SaveUserDefaults(); MessageBox.Show(Catalog.GetString("Gift Batches Exported successfully."), Catalog.GetString("Gift Batch Export"), MessageBoxButtons.OK, MessageBoxIcon.Information); } catch (Exception ex) { TLogging.Log("GiftBatchExport.ManualCode: " + ex.ToString()); MessageBox.Show(ex.Message, Catalog.GetString("Error"), MessageBoxButtons.OK, MessageBoxIcon.Error); } finally { sw1.Close(); } }
/// <summary> /// this supports the batch export files from Petra 2.x. /// Each line starts with a type specifier, B for batch, J for journal, T for transaction /// </summary> public void ImportBatches(TGiftImportDataSourceEnum AImportSource) { bool ok = false; String importString; String impOptions; OpenFileDialog dialog = null; if (FPetraUtilsObject.HasChanges) { // saving failed, therefore do not try to post MessageBox.Show(Catalog.GetString("Please save before calling this function!"), Catalog.GetString( "Failure"), MessageBoxButtons.OK, MessageBoxIcon.Error); return; } FdlgSeparator = new TDlgSelectCSVSeparator(false); if (AImportSource == TGiftImportDataSourceEnum.FromClipboard) { importString = Clipboard.GetText(TextDataFormat.UnicodeText); if ((importString == null) || (importString.Length == 0)) { MessageBox.Show(Catalog.GetString("Please first copy data from your spreadsheet application!"), Catalog.GetString("Failure"), MessageBoxButtons.OK, MessageBoxIcon.Error); return; } impOptions = TUserDefaults.GetStringDefault("Imp Options", ";American"); String dateFormatString = TUserDefaults.GetStringDefault("Imp Date", "MDY"); FdlgSeparator = new TDlgSelectCSVSeparator(false); FdlgSeparator.SelectedSeparator = "\t"; FdlgSeparator.CSVData = importString; FdlgSeparator.DateFormat = dateFormatString; if (impOptions.Length > 1) { FdlgSeparator.NumberFormat = impOptions.Substring(1); } } else if (AImportSource == TGiftImportDataSourceEnum.FromFile) { dialog = new OpenFileDialog(); string exportPath = TClientSettings.GetExportPath(); string fullPath = TUserDefaults.GetStringDefault("Imp Filename", exportPath + Path.DirectorySeparatorChar + "import.csv"); TImportExportDialogs.SetOpenFileDialogFilePathAndName(dialog, fullPath, exportPath); dialog.Title = Catalog.GetString("Import Batches from CSV File"); dialog.Filter = Catalog.GetString("Gift Batches files (*.csv)|*.csv"); impOptions = TUserDefaults.GetStringDefault("Imp Options", ";" + TDlgSelectCSVSeparator.NUMBERFORMAT_AMERICAN); // This call fixes Windows7 Open File Dialogs. It must be the line before ShowDialog() TWin7FileOpenSaveDialog.PrepareDialog(Path.GetFileName(fullPath)); if (dialog.ShowDialog() == DialogResult.OK) { Boolean fileCanOpen = FdlgSeparator.OpenCsvFile(dialog.FileName); if (!fileCanOpen) { MessageBox.Show(Catalog.GetString("Unable to open file."), Catalog.GetString("Gift Import"), MessageBoxButtons.OK, MessageBoxIcon.Stop); return; } importString = File.ReadAllText(dialog.FileName, Encoding.Default); String dateFormatString = TUserDefaults.GetStringDefault("Imp Date", "MDY"); FdlgSeparator.DateFormat = dateFormatString; if (impOptions.Length > 1) { FdlgSeparator.NumberFormat = impOptions.Substring(1); } FdlgSeparator.SelectedSeparator = impOptions.Substring(0, 1); } else { return; } } else { // unknown source!! The following need a value... impOptions = String.Empty; importString = String.Empty; } if (FdlgSeparator.ShowDialog() == DialogResult.OK) { Hashtable requestParams = new Hashtable(); requestParams.Add("ALedgerNumber", FLedgerNumber); requestParams.Add("Delimiter", FdlgSeparator.SelectedSeparator); requestParams.Add("DateFormatString", FdlgSeparator.DateFormat); requestParams.Add("NumberFormat", FdlgSeparator.NumberFormat); requestParams.Add("NewLine", Environment.NewLine); bool Repeat = true; while (Repeat) { Repeat = false; TVerificationResultCollection AMessages = new TVerificationResultCollection(); GiftBatchTDSAGiftDetailTable NeedRecipientLedgerNumber = new GiftBatchTDSAGiftDetailTable(); Thread ImportThread = new Thread(() => ImportGiftBatches( requestParams, importString, out AMessages, out ok, out NeedRecipientLedgerNumber)); using (TProgressDialog ImportDialog = new TProgressDialog(ImportThread)) { ImportDialog.ShowDialog(); } // If NeedRecipientLedgerNumber contains data then AMessages will only ever contain // one message alerting the user that no data has been imported. // We do not want to show this as we will be displaying another more detailed message. if (NeedRecipientLedgerNumber.Rows.Count == 0) { ShowMessages(AMessages); } // if the import contains gifts with Motivation Group 'GIFT' and that have a Family recipient with no Gift Destination // then the import will have failed and we need to alert the user if (NeedRecipientLedgerNumber.Rows.Count > 0) { bool OfferToRunImportAgain = true; bool DoNotShowMessageBoxEverytime = false; TFrmExtendedMessageBox.TResult Result = TFrmExtendedMessageBox.TResult.embrUndefined; int count = 1; // for each gift in which the recipient needs a Git Destination foreach (GiftBatchTDSAGiftDetailRow Row in NeedRecipientLedgerNumber.Rows) { if (!DoNotShowMessageBoxEverytime) { string CheckboxText = string.Empty; // only show checkbox if there is at least one more occurance of this error if (NeedRecipientLedgerNumber.Rows.Count - count > 0) { CheckboxText = string.Format( Catalog.GetString("Do this for all further occurances ({0})?"), NeedRecipientLedgerNumber.Rows.Count - count); } TFrmExtendedMessageBox extendedMessageBox = new TFrmExtendedMessageBox(FPetraUtilsObject.GetForm()); extendedMessageBox.ShowDialog(string.Format( Catalog.GetString( "Gift Import has been cancelled as the recipient '{0}' ({1}) has no Gift Destination assigned."), Row.RecipientDescription, Row.RecipientKey) + "\n\r\n\r\n\r" + Catalog.GetString("Do you want to assign a Gift Destination to this partner now?"), Catalog.GetString("Import Errors"), CheckboxText, TFrmExtendedMessageBox.TButtons.embbYesNo, TFrmExtendedMessageBox.TIcon.embiWarning); Result = extendedMessageBox.GetResult(out DoNotShowMessageBoxEverytime); } if (Result == TFrmExtendedMessageBox.TResult.embrYes) { // allow the user to assign a Gift Destingation TFrmGiftDestination GiftDestinationForm = new TFrmGiftDestination(FPetraUtilsObject.GetForm(), Row.RecipientKey); GiftDestinationForm.ShowDialog(); } else { OfferToRunImportAgain = false; if (DoNotShowMessageBoxEverytime) { break; } } count++; } // if the user has clicked yes to assigning Gift Destinations then offer to restart the import if (OfferToRunImportAgain && (MessageBox.Show(Catalog.GetString("Would you like to import this Gift Batch again?"), Catalog.GetString("Gift Import"), MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.Yes)) { Repeat = true; } } } // We save the defaults even if ok is false - because the client will probably want to try and import // the same file again after correcting any errors SaveUserDefaults(dialog, impOptions); } if (ok) { MessageBox.Show(Catalog.GetString("Your data was imported successfully!"), Catalog.GetString("Gift Import"), MessageBoxButtons.OK, MessageBoxIcon.Information); FMyUserControl.LoadBatchesForCurrentYear(); FPetraUtilsObject.DisableSaveButton(); } }
// starts the merge process private void BtnOK_Click(Object Sender, EventArgs e) { // Title for all message boxes string mergePartnersTitle = Catalog.GetString("Merge Partners"); string mergeCancelledText = Catalog.GetString("Merge cancelled."); FFromPartnerKey = Convert.ToInt64(txtMergeFrom.Text); FToPartnerKey = Convert.ToInt64(txtMergeTo.Text); if (CheckPartnersCanBeMerged() && (MessageBox.Show(Catalog.GetString("WARNING: A Partner Merge operation cannot be undone and the From-Partner will be no longer " + "accessible after the Partner Merge operation!") + "\n\n" + Catalog.GetString("Are you sure you want to continue?"), mergePartnersTitle, MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)) { bool[] Categories = new bool[25]; for (int i = 1; i < 25; i++) { Categories[i] = true; } FSiteKeys = null; FLocationKeys = null; FContactDetails = null; FMainBankingDetailsKey = -1; TFrmExtendedMessageBox msgBox = null; string msg = string.Empty; bool DifferentFamilies = false; // open a dialog to select which From Partner's addresses should be merged if (GetSelectedAddresses() == false) { MessageBox.Show(mergeCancelledText, mergePartnersTitle, MessageBoxButtons.OK, MessageBoxIcon.Information); return; } // open a dialog to select which From Partner's contact details should be merged if (GetSelectedContactDetails() == false) { MessageBox.Show(mergeCancelledText, mergePartnersTitle, MessageBoxButtons.OK, MessageBoxIcon.Information); return; } // open a dialog to select which bank account should be set to MAIN (if necessary) if (GetMainBankAccount() == false) { MessageBox.Show(mergeCancelledText, mergePartnersTitle, MessageBoxButtons.OK, MessageBoxIcon.Information); return; } // if ((((FFromPartnerClass == TPartnerClass.FAMILY) && (FToPartnerClass == TPartnerClass.FAMILY)) || (FFromPartnerClass == TPartnerClass.PERSON)) && (GiftDestinationToMerge(out Categories[0]) == false)) { MessageBox.Show(mergeCancelledText, mergePartnersTitle, MessageBoxButtons.OK, MessageBoxIcon.Information); return; } Thread t = new Thread(() => MergeTwoPartners(Categories, ref DifferentFamilies)); using (TProgressDialog dialog = new TProgressDialog(t)) { if ((dialog.ShowDialog() == DialogResult.Cancel) && (FWebConnectorResult == false)) { MessageBox.Show(mergeCancelledText, mergePartnersTitle, MessageBoxButtons.OK, MessageBoxIcon.Information); return; } else if (FWebConnectorResult == false) // if merge is unsuccessful { msg = Catalog.GetString("The merge operation failed"); // Anything to display from the verification results? if (FVerificationResultsOfMerge.Count > 0) { for (int i = 0; i < FVerificationResultsOfMerge.Count; i++) { if (FVerificationResultsOfMerge[i].ResultSeverity == TResultSeverity.Resv_Critical) { msg += Environment.NewLine; msg += FVerificationResultsOfMerge[i].ResultText; } } msg += Environment.NewLine; msg += Catalog.GetString("More information is available in the Server.log file on the server at the date and time shown."); msg += Environment.NewLine; msg += Catalog.GetString("You can copy this message to the clipboard by clicking the button below."); } msgBox = new TFrmExtendedMessageBox(this); msgBox.ShowDialog(msg, mergePartnersTitle, string.Empty, TFrmExtendedMessageBox.TButtons.embbOK, TFrmExtendedMessageBox.TIcon.embiError); dialog.Close(); return; } } if (DifferentFamilies) { MessageBox.Show(String.Format(Catalog.GetString("Partners were in different families.")) + "\n\n" + Catalog.GetString("FAMILY relations of the From Partner are not taken over to the To Partner!") + "\n\n" + Catalog.GetString("Please check the family relations of the To Partner after completion."), mergePartnersTitle, MessageBoxButtons.OK, MessageBoxIcon.Information); } msg = String.Format(Catalog.GetString("Merge of Partner {0} ({1}) into {2} ({3}) completed successfully."), txtMergeFrom.LabelText, FFromPartnerKey, txtMergeTo.LabelText, FToPartnerKey); if (FVerificationResultsOfMerge.Count > 0) { msg += Environment.NewLine; for (int i = 0; i < FVerificationResultsOfMerge.Count; i++) { msg += Environment.NewLine; msg += FVerificationResultsOfMerge[i].ResultText; } msg += Environment.NewLine; } msg += Environment.NewLine; msg += Catalog.GetString("If necessary, edit the merged Partner to correct any information that may not have been " + "merged and correct information that may have been overwritten.") + Environment.NewLine + Environment.NewLine; msg += Catalog.GetString("Tip: You can use the 'Work with Last Partner' command in the Partner module and the " + "'Work with Last Person' command in the Personnel module to view and edit the merged Partner.") + Environment.NewLine + Environment.NewLine; msg += Catalog.GetString("You can copy this message to the clipboard by clicking the button below."); msgBox = new TFrmExtendedMessageBox(this); msgBox.ShowDialog(msg, mergePartnersTitle, string.Empty, TFrmExtendedMessageBox.TButtons.embbOK, TFrmExtendedMessageBox.TIcon.embiInformation); this.DialogResult = System.Windows.Forms.DialogResult.OK; this.Close(); } }