// // Put Methods for the validation of Personnel Module WebConnectors in this code file. // static partial void ValidatePersonnelStaffManual(ref TVerificationResultCollection AVerificationResult, TTypedDataTable ASubmitTable) { TValidationControlsDict ValidationControlsDict = new TValidationControlsDict(); ValidationControlsDict.Add(ASubmitTable.Columns[PmStaffDataTable.ColumnReceivingFieldId], new TValidationControlsData(null, PmStaffDataTable.GetReceivingFieldDBName())); ValidationControlsDict.Add(ASubmitTable.Columns[PmStaffDataTable.ColumnStartOfCommitmentId], new TValidationControlsData(null, PmStaffDataTable.GetStartOfCommitmentDBName())); ValidationControlsDict.Add(ASubmitTable.Columns[PmStaffDataTable.ColumnEndOfCommitmentId], new TValidationControlsData(null, PmStaffDataTable.GetEndOfCommitmentDBName(), null, PmStaffDataTable.GetStartOfCommitmentDBName())); ValidationControlsDict.Add(ASubmitTable.Columns[PmStaffDataTable.ColumnStatusCodeId], new TValidationControlsData(null, PmStaffDataTable.GetStatusCodeDBName())); ValidationControlsDict.Add(ASubmitTable.Columns[PmStaffDataTable.ColumnHomeOfficeId], new TValidationControlsData(null, PmStaffDataTable.GetHomeOfficeDBName())); ValidationControlsDict.Add(ASubmitTable.Columns[PmStaffDataTable.ColumnOfficeRecruitedById], new TValidationControlsData(null, PmStaffDataTable.GetOfficeRecruitedByDBName())); for (int Counter = 0; Counter < ASubmitTable.Rows.Count; Counter++) { TSharedPersonnelValidation_Personnel.ValidateCommitmentManual("TPersonnelWebConnector" + " (Error in Row #" + Counter.ToString() + ")", // No translation of message text since the server's messages should be all in English (PmStaffDataRow)ASubmitTable.Rows[Counter], ref AVerificationResult, ValidationControlsDict); } }
static partial void ValidateGiftDetailManual(ref TVerificationResultCollection AVerificationResult, TTypedDataTable ASubmitTable) { TValidationControlsDict ValidationControlsDict = new TValidationControlsDict(); ValidationControlsDict.Add(ASubmitTable.Columns[AGiftDetailTable.ColumnGiftCommentOneId], new TValidationControlsData(null, AGiftDetailTable.GetGiftCommentOneDBName())); TPartnerClass RecipientPartnerClass; string RecipientDescription; for (int Counter = 0; Counter < ASubmitTable.Rows.Count; Counter++) { if (ASubmitTable.Rows[Counter].RowState != DataRowState.Deleted) { TPartnerServerLookups.GetPartnerShortName(((GiftBatchTDSAGiftDetailRow)ASubmitTable.Rows[Counter]).RecipientKey, out RecipientDescription, out RecipientPartnerClass); TSharedFinanceValidation_Gift.ValidateGiftDetailManual("TTransactionWebConnector" + " (Error in Row #" + Counter.ToString() + ")", // No translation of message text since the server's messages should be all in English (GiftBatchTDSAGiftDetailRow)ASubmitTable.Rows[Counter], ref AVerificationResult, ValidationControlsDict, RecipientPartnerClass); } } }
/// <summary> /// Saves the data to the server /// </summary> /// <param name="ATable">The typed table from the data set</param> /// <param name="ATableChanges">The changes table</param> /// <param name="ATableDbName">The server table name to write to</param> /// <returns></returns> public static bool SaveChanges(TTypedDataTable ATable, TTypedDataTable ATableChanges, string ATableDbName) { TSubmitChangesResult SubmissionResult; TVerificationResultCollection VerificationResult; if (ATableChanges == null) { // There is nothing to be saved. return true; } // Submit changes to the PETRAServer try { SubmissionResult = TRemote.MCommon.DataReader.WebConnectors.SaveData(ATableDbName, ref ATableChanges, out VerificationResult); } catch (ESecurityDBTableAccessDeniedException) { Console.WriteLine("Error saving data prior to test: Access denied"); return false; } catch (EDBConcurrencyException) { Console.WriteLine("Error saving data prior to test: Concurrency exception"); return false; } catch (Exception Exp) { Console.WriteLine("Error saving data prior to test: General exception: {0}", Exp.Message); return false; } switch (SubmissionResult) { case TSubmitChangesResult.scrOK: // Call AcceptChanges to get rid now of any deleted columns before we Merge with the result from the Server ATable.AcceptChanges(); // Merge back with data from the Server (eg. for getting Sequence values) ATableChanges.AcceptChanges(); ATable.Merge(ATableChanges, false); // need to accept the new modification ID ATable.AcceptChanges(); return true; case TSubmitChangesResult.scrNothingToBeSaved: return true; case TSubmitChangesResult.scrError: Console.WriteLine("Error saving data prior to test: Submission of data failed"); break; case TSubmitChangesResult.scrInfoNeeded: Console.WriteLine("Error saving data prior to test: Info Needed"); break; } return false; }
/// <summary> /// /// </summary> /// <param name="AExchangeRateDT">The corporate or daily exchange rate table</param> /// <param name="AImportMode">Determines whether corporate or daily exchange rates specified - either 'Daily' or 'Corporate'</param> /// <param name="AResultCollection">A validation collection to which errors will be added</param> /// <returns>The number of rows that were actually imported. Rows that duplicate existing rows do not count. /// This is usually because this is an attempt to import again after a failed previous attempt.</returns> public static int ImportCurrencyExRates(TTypedDataTable AExchangeRateDT, string AImportMode, TVerificationResultCollection AResultCollection) { OpenFileDialog DialogBox = new OpenFileDialog(); DialogBox.Title = Catalog.GetString("Import exchange rates from spreadsheet file"); DialogBox.Filter = Catalog.GetString("Spreadsheet files (*.csv)|*.csv"); if (DialogBox.ShowDialog() == DialogResult.OK) { String dateFormatString = TUserDefaults.GetStringDefault("Imp Date", "MDY"); String impOptions = TUserDefaults.GetStringDefault("Imp Options", ";" + TDlgSelectCSVSeparator.NUMBERFORMAT_AMERICAN); TDlgSelectCSVSeparator DlgSeparator = new TDlgSelectCSVSeparator(false); Boolean fileCanOpen = DlgSeparator.OpenCsvFile(DialogBox.FileName); if (!fileCanOpen) { MessageBox.Show(Catalog.GetString("Unable to open file."), Catalog.GetString("Import Exchange Rates"), MessageBoxButtons.OK, MessageBoxIcon.Stop); return 0; } DlgSeparator.DateFormat = dateFormatString; if (impOptions.Length > 1) { DlgSeparator.NumberFormat = impOptions.Substring(1); } DlgSeparator.SelectedSeparator = impOptions.Substring(0, 1); if (DlgSeparator.ShowDialog() == DialogResult.OK) { // Save the settings that we specified impOptions = DlgSeparator.SelectedSeparator; impOptions += DlgSeparator.NumberFormat; TUserDefaults.SetDefault("Imp Options", impOptions); TUserDefaults.SetDefault("Imp Date", DlgSeparator.DateFormat); TUserDefaults.SaveChangedUserDefaults(); // Do the import and retuen the number of rows imported and any messages return ImportCurrencyExRatesFromCSV(AExchangeRateDT, DialogBox.FileName, DlgSeparator.SelectedSeparator, DlgSeparator.NumberFormat, DlgSeparator.DateFormat, AImportMode, AResultCollection); } } return 0; }
/// <summary> /// simple data reader; /// checks for permissions of the current user; /// </summary> /// <param name="ATablename"></param> /// <param name="ASearchCriteria">a set of search criteria</param> /// <param name="AResultTable">returns typed datatable</param> /// <returns></returns> public static bool GetData(string ATablename, TSearchCriteria[] ASearchCriteria, out TTypedDataTable AResultTable) { if (FDelegateSharedGetData != null) { return FDelegateSharedGetData(ATablename, ASearchCriteria, out AResultTable); } else { throw new InvalidOperationException("Delegate 'TSharedGetData' must be initialised before calling this Method"); } }
// // Put Methods for the validation of Partner Edit screen data in this code file. // static partial void ValidatePPartnerManual(ref TVerificationResultCollection AVerificationResult, TTypedDataTable ASubmitTable) { TValidationControlsDict ValidationControlsDict = new TValidationControlsDict(); ValidationControlsDict.Add(ASubmitTable.Columns[PPartnerTable.ColumnStatusCodeId], new TValidationControlsData(null, Catalog.GetString("Partner &Status"))); for (int Counter = 0; Counter < ASubmitTable.Rows.Count; Counter++) { TSharedPartnerValidation_Partner.ValidatePartnerManual("TPartnerEditUIConnector" + " (Error in Row #" + Counter.ToString() + ")", // No translation of message text since the server's messages should be all in English (PPartnerRow)ASubmitTable.Rows[Counter], ref AVerificationResult, ValidationControlsDict); } }
// // Put Methods for the validation of AP EditTransaction in this code file. // static partial void ValidateApDocumentDetailManual(ref TVerificationResultCollection AVerificationResult, TTypedDataTable ASubmitTable) { TValidationControlsDict ValidationControlsDict = new TValidationControlsDict(); ValidationControlsDict.Add(ASubmitTable.Columns[AApDocumentDetailTable.ColumnAmountId], new TValidationControlsData(null, AApDocumentDetailTable.GetAmountDBName())); for (int Counter = 0; Counter < ASubmitTable.Rows.Count; Counter++) { TSharedFinanceValidation_AP.ValidateApDocumentDetailManual("TTransactionWebConnector" + " (Error in Row #" + Counter.ToString() + ")", // No translation of message text since the server's messages should be all in English (AApDocumentDetailRow)ASubmitTable.Rows[Counter], ref AVerificationResult, ValidationControlsDict); } }
// // Put Methods for the validation of Cacheable DataTables in this code file. // partial void ValidateMaritalStatusListManual(ref TVerificationResultCollection AVerificationResult, TTypedDataTable ASubmitTable) { TValidationControlsDict ValidationControlsDict = new TValidationControlsDict(); ValidationControlsDict.Add(ASubmitTable.Columns[PtMaritalStatusTable.ColumnAssignableDateId], new TValidationControlsData(null, PtMaritalStatusTable.GetAssignableDateDBName())); for (int Counter = 0; Counter < ASubmitTable.Rows.Count; Counter++) { if (ASubmitTable.Rows[Counter].RowState != DataRowState.Deleted) { TSharedValidation_CacheableDataTables.ValidateMaritalStatus(this.GetType().Name + " (Error in Row #" + Counter.ToString() + ")", // No translation of message text since the server's messages should be all in English (PtMaritalStatusRow)ASubmitTable.Rows[Counter], ref AVerificationResult, ValidationControlsDict); } } }
// // Put Methods for the validation of Gift Transactions in this code file. // static partial void ValidateGiftBatchManual(ref TVerificationResultCollection AVerificationResult, TTypedDataTable ASubmitTable) { TValidationControlsDict ValidationControlsDict = new TValidationControlsDict(); ValidationControlsDict.Add(ASubmitTable.Columns[AGiftBatchTable.ColumnBatchDescriptionId], new TValidationControlsData(null, AGiftBatchTable.GetBatchDescriptionDBName())); ValidationControlsDict.Add(ASubmitTable.Columns[AGiftBatchTable.ColumnExchangeRateToBaseId], new TValidationControlsData(null, AGiftBatchTable.GetExchangeRateToBaseDBName())); for (int Counter = 0; Counter < ASubmitTable.Rows.Count; Counter++) { TSharedFinanceValidation_Gift.ValidateGiftBatchManual("TTransactionWebConnector" + " (Error in Row #" + Counter.ToString() + ")", // No translation of message text since the server's messages should be all in English (AGiftBatchRow)ASubmitTable.Rows[Counter], ref AVerificationResult, ValidationControlsDict); } }
// // Put Methods for the validation of Common Module WebConnectors and DataReaders in this code file. // static partial void ValidateInternationalPostalTypeManual(ref TVerificationResultCollection AVerificationResult, TTypedDataTable ASubmitTable) { TValidationControlsDict ValidationControlsDict = new TValidationControlsDict(); ValidationControlsDict.Add(ASubmitTable.Columns[(short)PInternationalPostalTypeTable.ColumnInternatPostalTypeCodeId], new TValidationControlsData(null, PInternationalPostalTypeTable.GetInternatPostalTypeCodeDBName())); ValidationControlsDict.Add(ASubmitTable.Columns[(short)PInternationalPostalTypeTable.ColumnDescriptionId], new TValidationControlsData(null, PInternationalPostalTypeTable.GetDescriptionDBName())); ValidationControlsDict.Add(ASubmitTable.Columns[(short)PInternationalPostalTypeTable.ColumnDeletableId], new TValidationControlsData(null, PInternationalPostalTypeTable.GetDeletableDBName())); for (int Counter = 0; Counter < ASubmitTable.Rows.Count; Counter++) { PInternationalPostalTypeValidation.Validate("TCommonDataReader.ValidateInternationalPostalTypeManual" + " (Error in Row #" + Counter.ToString() + ")", // No translation of message text since the server's messages should be all in English (PInternationalPostalTypeRow)ASubmitTable.Rows[Counter], ref AVerificationResult, ValidationControlsDict); } }
// // Put Methods for the validation of Cacheable DataTables in this code file. // partial void ValidateCountryListManual(ref TVerificationResultCollection AVerificationResult, TTypedDataTable ASubmitTable) { TValidationControlsDict ValidationControlsDict = new TValidationControlsDict(); ValidationControlsDict.Add(ASubmitTable.Columns[PCountryTable.ColumnInternatTelephoneCodeId], new TValidationControlsData(null, PCountryTable.GetInternatTelephoneCodeDBName())); ValidationControlsDict.Add(ASubmitTable.Columns[PCountryTable.ColumnInternatPostalTypeCodeId], new TValidationControlsData(null, PCountryTable.GetInternatAccessCodeDBName())); ValidationControlsDict.Add(ASubmitTable.Columns[PCountryTable.ColumnTimeZoneMinimumId], new TValidationControlsData(null, PCountryTable.GetTimeZoneMinimumDBName(), null, PCountryTable.GetTimeZoneMaximumDBName())); for (int Counter = 0; Counter < ASubmitTable.Rows.Count; Counter++) { TSharedValidation_CacheableDataTables.ValidateCountrySetupManual(this.GetType().Name + " (Error in Row #" + Counter.ToString() + ")", // No translation of message text since the server's messages should be all in English (PCountryRow)ASubmitTable.Rows[Counter], ref AVerificationResult, ValidationControlsDict); } }
public static bool GetData(string ATablename, TSearchCriteria[] ASearchCriteria, out TTypedDataTable AResultTable) { // TODO: check access permissions for the current user TDBTransaction ReadTransaction = null; TTypedDataTable tempTable = null; DBAccess.GDBAccessObj.GetNewOrExistingAutoReadTransaction(IsolationLevel.RepeatableRead, TEnforceIsolationLevel.eilMinimum, ref ReadTransaction, delegate { // TODO: auto generate if (ATablename == AApSupplierTable.GetTableDBName()) { tempTable = AApSupplierAccess.LoadUsingTemplate(ASearchCriteria, ReadTransaction); } else if (ATablename == AApDocumentTable.GetTableDBName()) { tempTable = AApDocumentAccess.LoadUsingTemplate(ASearchCriteria, ReadTransaction); } else if (ATablename == ATransactionTypeTable.GetTableDBName()) { tempTable = ATransactionTypeAccess.LoadUsingTemplate(ASearchCriteria, ReadTransaction); } else if (ATablename == ACurrencyTable.GetTableDBName()) { tempTable = ACurrencyAccess.LoadAll(ReadTransaction); } else if (ATablename == ADailyExchangeRateTable.GetTableDBName()) { tempTable = ADailyExchangeRateAccess.LoadAll(ReadTransaction); } else if (ATablename == ACorporateExchangeRateTable.GetTableDBName()) { tempTable = ACorporateExchangeRateAccess.LoadAll(ReadTransaction); } else if (ATablename == ACurrencyLanguageTable.GetTableDBName()) { tempTable = ACurrencyLanguageAccess.LoadAll(ReadTransaction); } else if (ATablename == AFeesPayableTable.GetTableDBName()) { tempTable = AFeesPayableAccess.LoadAll(ReadTransaction); } else if (ATablename == AFeesReceivableTable.GetTableDBName()) { tempTable = AFeesReceivableAccess.LoadAll(ReadTransaction); } else if (ATablename == AAnalysisTypeTable.GetTableDBName()) { tempTable = AAnalysisTypeAccess.LoadUsingTemplate(ASearchCriteria, ReadTransaction); } else if (ATablename == AGiftBatchTable.GetTableDBName()) { tempTable = AGiftBatchAccess.LoadAll(ReadTransaction); } else if (ATablename == AJournalTable.GetTableDBName()) { tempTable = AJournalAccess.LoadAll(ReadTransaction); } else if (ATablename == ALedgerTable.GetTableDBName()) { tempTable = ALedgerAccess.LoadAll(ReadTransaction); } else if (ATablename == MExtractMasterTable.GetTableDBName()) { if (ASearchCriteria == null) { tempTable = MExtractMasterAccess.LoadAll(ReadTransaction); } else { tempTable = MExtractMasterAccess.LoadUsingTemplate(ASearchCriteria, ReadTransaction); } } else if (ATablename == MExtractTable.GetTableDBName()) { // it does not make sense to load ALL extract rows for all extract masters so search criteria needs to be set if (ASearchCriteria != null) { tempTable = MExtractAccess.LoadUsingTemplate(ASearchCriteria, ReadTransaction); } } else if (ATablename == PcAttendeeTable.GetTableDBName()) { tempTable = PcAttendeeAccess.LoadUsingTemplate(ASearchCriteria, ReadTransaction); } else if (ATablename == PcConferenceCostTable.GetTableDBName()) { tempTable = PcConferenceCostAccess.LoadUsingTemplate(ASearchCriteria, ReadTransaction); } else if (ATablename == PcEarlyLateTable.GetTableDBName()) { tempTable = PcEarlyLateAccess.LoadUsingTemplate(ASearchCriteria, ReadTransaction); } else if (ATablename == PcSupplementTable.GetTableDBName()) { tempTable = PcSupplementAccess.LoadUsingTemplate(ASearchCriteria, ReadTransaction); } else if (ATablename == PcDiscountTable.GetTableDBName()) { tempTable = PcDiscountAccess.LoadUsingTemplate(ASearchCriteria, ReadTransaction); } else if (ATablename == PFormTable.GetTableDBName()) { string[] columns = TTypedDataTable.GetColumnStringList(PFormTable.TableId); StringCollection fieldList = new StringCollection(); for (int i = 0; i < columns.Length; i++) { // Do not load the template document - we don't display it and it is big! if (columns[i] != PFormTable.GetTemplateDocumentDBName()) { fieldList.Add(columns[i]); } } tempTable = PFormAccess.LoadAll(fieldList, ReadTransaction); } else if (ATablename == PInternationalPostalTypeTable.GetTableDBName()) { tempTable = PInternationalPostalTypeAccess.LoadAll(ReadTransaction); } else if (ATablename == PtApplicationTypeTable.GetTableDBName()) { tempTable = PtApplicationTypeAccess.LoadAll(ReadTransaction); } else if (ATablename == PFormalityTable.GetTableDBName()) { tempTable = PFormalityAccess.LoadAll(ReadTransaction); } else if (ATablename == PMailingTable.GetTableDBName()) { tempTable = PMailingAccess.LoadAll(ReadTransaction); } else if (ATablename == PPartnerGiftDestinationTable.GetTableDBName()) { tempTable = PPartnerGiftDestinationAccess.LoadUsingTemplate(ASearchCriteria, ReadTransaction); } else if (ATablename == PmDocumentTypeTable.GetTableDBName()) { tempTable = PmDocumentTypeAccess.LoadAll(ReadTransaction); } else if (ATablename == SGroupTable.GetTableDBName()) { tempTable = SGroupAccess.LoadAll(ReadTransaction); } else { throw new Exception("TCommonDataReader.GetData: unknown table " + ATablename); } }); // Accept row changes here so that the Client gets 'unmodified' rows tempTable.AcceptChanges(); // return the table AResultTable = tempTable; return true; }
public static TSubmitChangesResult SaveData(string ATablename, ref TTypedDataTable ASubmitTable, out TVerificationResultCollection AVerificationResult) { TDBTransaction SubmitChangesTransaction = null; bool SubmissionOK = false; TTypedDataTable SubmitTable = ASubmitTable; TVerificationResultCollection VerificationResult = null; // TODO: check write permissions if (ASubmitTable != null) { VerificationResult = new TVerificationResultCollection(); DBAccess.GDBAccessObj.BeginAutoTransaction(IsolationLevel.Serializable, ref SubmitChangesTransaction, ref SubmissionOK, delegate { try { if (ATablename == AAccountingPeriodTable.GetTableDBName()) { AAccountingPeriodAccess.SubmitChanges((AAccountingPeriodTable)SubmitTable, SubmitChangesTransaction); TCacheableTablesManager.GCacheableTablesManager.MarkCachedTableNeedsRefreshing( TCacheableFinanceTablesEnum.AccountingPeriodList.ToString()); } else if (ATablename == ACurrencyTable.GetTableDBName()) { ACurrencyAccess.SubmitChanges((ACurrencyTable)SubmitTable, SubmitChangesTransaction); } else if (ATablename == ADailyExchangeRateTable.GetTableDBName()) { ADailyExchangeRateAccess.SubmitChanges((ADailyExchangeRateTable)SubmitTable, SubmitChangesTransaction); } else if (ATablename == ACorporateExchangeRateTable.GetTableDBName()) { ACorporateExchangeRateAccess.SubmitChanges((ACorporateExchangeRateTable)SubmitTable, SubmitChangesTransaction); } else if (ATablename == ACurrencyLanguageTable.GetTableDBName()) { ACurrencyLanguageAccess.SubmitChanges((ACurrencyLanguageTable)SubmitTable, SubmitChangesTransaction); } else if (ATablename == AFeesPayableTable.GetTableDBName()) { AFeesPayableAccess.SubmitChanges((AFeesPayableTable)SubmitTable, SubmitChangesTransaction); TCacheableTablesManager.GCacheableTablesManager.MarkCachedTableNeedsRefreshing( TCacheableFinanceTablesEnum.FeesPayableList.ToString()); } else if (ATablename == AFeesReceivableTable.GetTableDBName()) { AFeesReceivableAccess.SubmitChanges((AFeesReceivableTable)SubmitTable, SubmitChangesTransaction); TCacheableTablesManager.GCacheableTablesManager.MarkCachedTableNeedsRefreshing( TCacheableFinanceTablesEnum.FeesReceivableList.ToString()); } else if (ATablename == AGiftBatchTable.GetTableDBName()) { // This method is called from ADailyExchangeRate Setup - please do not remove // The method is not required for changes made to the gift batch screens, which use a TDS AGiftBatchAccess.SubmitChanges((AGiftBatchTable)SubmitTable, SubmitChangesTransaction); } else if (ATablename == AJournalTable.GetTableDBName()) { // This method is called from ADailyExchangeRate Setup - please do not remove // The method is not required for changes made to the journal screens, which use a TDS AJournalAccess.SubmitChanges((AJournalTable)SubmitTable, SubmitChangesTransaction); } else if (ATablename == ARecurringJournalTable.GetTableDBName()) { // This method is called from Submit Recurring GL Batch form - please do not remove // The method is not required for changes made to the journal screens, which use a TDS ARecurringJournalAccess.SubmitChanges((ARecurringJournalTable)SubmitTable, SubmitChangesTransaction); } else if (ATablename == ALedgerTable.GetTableDBName()) { // This method is called from ADailyExchangeRate Testing - please do not remove ALedgerAccess.SubmitChanges((ALedgerTable)SubmitTable, SubmitChangesTransaction); } else if (ATablename == AAnalysisTypeTable.GetTableDBName()) { AAnalysisTypeAccess.SubmitChanges((AAnalysisTypeTable)SubmitTable, SubmitChangesTransaction); } else if (ATablename == ASuspenseAccountTable.GetTableDBName()) { ASuspenseAccountAccess.SubmitChanges((ASuspenseAccountTable)SubmitTable, SubmitChangesTransaction); TCacheableTablesManager.GCacheableTablesManager.MarkCachedTableNeedsRefreshing( TCacheableFinanceTablesEnum.SuspenseAccountList.ToString()); } else if (ATablename == PcAttendeeTable.GetTableDBName()) { PcAttendeeAccess.SubmitChanges((PcAttendeeTable)SubmitTable, SubmitChangesTransaction); } else if (ATablename == PcConferenceTable.GetTableDBName()) { PcConferenceAccess.SubmitChanges((PcConferenceTable)SubmitTable, SubmitChangesTransaction); } else if (ATablename == PcConferenceCostTable.GetTableDBName()) { PcConferenceCostAccess.SubmitChanges((PcConferenceCostTable)SubmitTable, SubmitChangesTransaction); } else if (ATablename == PcEarlyLateTable.GetTableDBName()) { PcEarlyLateAccess.SubmitChanges((PcEarlyLateTable)SubmitTable, SubmitChangesTransaction); } else if (ATablename == PcSupplementTable.GetTableDBName()) { PcSupplementAccess.SubmitChanges((PcSupplementTable)SubmitTable, SubmitChangesTransaction); } else if (ATablename == PcDiscountTable.GetTableDBName()) { PcDiscountAccess.SubmitChanges((PcDiscountTable)SubmitTable, SubmitChangesTransaction); } else if (ATablename == PInternationalPostalTypeTable.GetTableDBName()) { ValidateInternationalPostalType(ref VerificationResult, SubmitTable); ValidateInternationalPostalTypeManual(ref VerificationResult, SubmitTable); if (TVerificationHelper.IsNullOrOnlyNonCritical(VerificationResult)) { PInternationalPostalTypeAccess.SubmitChanges((PInternationalPostalTypeTable)SubmitTable, SubmitChangesTransaction); } } else if (ATablename == PtApplicationTypeTable.GetTableDBName()) { PtApplicationTypeAccess.SubmitChanges((PtApplicationTypeTable)SubmitTable, SubmitChangesTransaction); // mark dependent lists for needing to be refreshed since there was a change in base list TCacheableTablesManager.GCacheableTablesManager.MarkCachedTableNeedsRefreshing( TCacheablePersonTablesEnum.EventApplicationTypeList.ToString()); TCacheableTablesManager.GCacheableTablesManager.MarkCachedTableNeedsRefreshing( TCacheablePersonTablesEnum.FieldApplicationTypeList.ToString()); } else if (ATablename == PFormTable.GetTableDBName()) { PFormAccess.SubmitChanges((PFormTable)SubmitTable, SubmitChangesTransaction); } else if (ATablename == PFormalityTable.GetTableDBName()) { PFormalityAccess.SubmitChanges((PFormalityTable)SubmitTable, SubmitChangesTransaction); } else if (ATablename == PMailingTable.GetTableDBName()) { PMailingAccess.SubmitChanges((PMailingTable)SubmitTable, SubmitChangesTransaction); } else if (ATablename == PPartnerGiftDestinationTable.GetTableDBName()) { PPartnerGiftDestinationAccess.SubmitChanges((PPartnerGiftDestinationTable)SubmitTable, SubmitChangesTransaction); } else if (ATablename == PmDocumentTypeTable.GetTableDBName()) { PmDocumentTypeAccess.SubmitChanges((PmDocumentTypeTable)SubmitTable, SubmitChangesTransaction); } else if (ATablename == SGroupTable.GetTableDBName()) { SGroupAccess.SubmitChanges((SGroupTable)SubmitTable, SubmitChangesTransaction); } else { throw new EOPAppException("TCommonDataReader.SaveData: unknown table '" + ATablename + "'"); } SubmissionOK = true; } catch (Exception Exc) { VerificationResult.Add( new TVerificationResult(null, "Cannot SubmitChanges:" + Environment.NewLine + Exc.Message, "UNDEFINED", TResultSeverity.Resv_Critical)); } }); } ASubmitTable = SubmitTable; AVerificationResult = VerificationResult; if ((AVerificationResult != null) && (AVerificationResult.Count > 0)) { // Downgrade TScreenVerificationResults to TVerificationResults in order to allow // Serialisation (needed for .NET Remoting). TVerificationResultCollection.DowngradeScreenVerificationResults(AVerificationResult); return AVerificationResult.HasCriticalErrors ? TSubmitChangesResult.scrError : TSubmitChangesResult.scrOK; } return TSubmitChangesResult.scrOK; }
static partial void ValidateInternationalPostalTypeManual(ref TVerificationResultCollection AVerificationResult, TTypedDataTable ASubmitTable);
partial void ValidateFeesReceivableListManual(ref TVerificationResultCollection AVerificationResult, TTypedDataTable ASubmitTable) { Type DataTableType; AFeesPayableTable otherTable = (AFeesPayableTable)TCacheableTablesManager.GCacheableTablesManager.GetCachedDataTable("FeesPayableList", out DataTableType); otherTable.DefaultView.Sort = String.Format("{0}, {1} ASC", AFeesPayableTable.GetLedgerNumberDBName(), AFeesPayableTable.GetFeeCodeDBName()); for (int i = 0; i < ASubmitTable.Rows.Count; i++) { DataRow row = ASubmitTable.Rows[i]; if ((row.RowState == DataRowState.Added) || (row.RowState == DataRowState.Modified)) { string feeCode = row[AFeesReceivableTable.ColumnFeeCodeId].ToString(); int ledgerNumber = Convert.ToInt32(row[AFeesReceivableTable.ColumnLedgerNumberId]); int otherRowNum = otherTable.DefaultView.Find(new object[] { ledgerNumber, feeCode }); if (otherRowNum >= 0) { AFeesPayableRow otherRow = (AFeesPayableRow)(otherTable.DefaultView[otherRowNum].Row); string otherUser = otherRow.CreatedBy; if (!String.IsNullOrEmpty(otherRow.ModifiedBy)) { otherUser = otherRow.ModifiedBy; } // The message text doesn't get back to the user - but maybe one day it will throw new EDBConcurrencyException(String.Format(Catalog.GetString( "While you were editing this screen another user created a fee code '{0}' for the Grants Payable screen. You will have to close and re-open the Grants Receivable screen and make your changes again."), feeCode), "write", otherTable.TableName, otherUser, otherRow.ModificationId); } } } }
static partial void ValidatePBankManual(ref TVerificationResultCollection AVerificationResult, TTypedDataTable ASubmitTable);
public static int GetNonCacheableRecordReferenceCountManual(TTypedDataTable ADataTable, object[] APrimaryKeyValues, out TVerificationResultCollection AVerificationResult) { int ReturnValue = 0; Boolean NewTransaction; TDBTransaction ReadTransaction = DBAccess.GDBAccessObj.GetNewOrExistingTransaction( IsolationLevel.ReadCommitted, TEnforceIsolationLevel.eilMinimum, out NewTransaction); try { if (ADataTable is PcConferenceTable) { ReturnValue = CountByPrimaryKey(APrimaryKeyValues, ReadTransaction, true, out AVerificationResult); } else { AVerificationResult = new TVerificationResultCollection(); } } finally { if (NewTransaction) { DBAccess.GDBAccessObj.CommitTransaction(); TLogging.LogAtLevel(9, ADataTable.TableName + ": GetNonCacheableRecordReferenceCount: committed own transaction."); } } return ReturnValue; }
static partial void ValidateRecurringGiftDetailManual(ref TVerificationResultCollection AVerificationResult, TTypedDataTable ASubmitTable);
/// <summary> /// This over-ride should be used for testing purposes. It reads from the specified test file and always uses US numbers and date/time. /// You supply the separator character as a single character string /// </summary> /// <param name="AExchangeRateDT">The corporate or daily exchange rate table</param> /// <param name="AImportFileName">The test file to import</param> /// <param name="ACSVSeparator">The separator that the file uses</param> /// <param name="AImportMode">Determines whether corporate or daily exchange rates specified - either 'Daily' or 'Corporate'</param> /// <param name="AResultCollection">A validation collection to which errors will be added</param> /// <returns>The number of rows that were actually imported. Rows that duplicate existing rows do not count. /// This is usually because this is an attempt to import again after a failed previous attempt.</returns> public static int ImportCurrencyExRates(TTypedDataTable AExchangeRateDT, string AImportFileName, string ACSVSeparator, string AImportMode, TVerificationResultCollection AResultCollection) { // Test import always uses standard file with US formats return ImportCurrencyExRatesFromCSV(AExchangeRateDT, AImportFileName, ACSVSeparator, TDlgSelectCSVSeparator.NUMBERFORMAT_AMERICAN, "MM/dd/yyyy", AImportMode, AResultCollection); }
/// <summary> /// Imports currency exchange rates, daily and corporate, /// from a one-of-two-styles formatted CSV file /// </summary> /// <param name="AExchangeRDT">Daily or Corporate exchange rate table</param> /// <param name="ADataFilename">The .CSV file to process</param> /// <param name="ACSVSeparator"></param> /// <param name="ANumberFormat"></param> /// <param name="ADateFormat"></param> /// <param name="AImportMode">Daily or Corporate</param> /// <param name="AResultCollection">A validation collection to which errors will be added</param> /// <returns>The number of rows that were actually imported. Rows that duplicate existing rows do not count. /// This is usually because this is an attempt to import again after a failed previous attempt.</returns> private static int ImportCurrencyExRatesFromCSV(TTypedDataTable AExchangeRDT, string ADataFilename, string ACSVSeparator, string ANumberFormat, string ADateFormat, string AImportMode, TVerificationResultCollection AResultCollection) { if ((AImportMode != "Corporate") && (AImportMode != "Daily")) { throw new ArgumentException("Invalid value '" + AImportMode + "' for mode argument: Valid values are Corporate and Daily"); } else if ((AImportMode == "Corporate") && (AExchangeRDT.GetType() != typeof(ACorporateExchangeRateTable))) { throw new ArgumentException("Invalid type of exchangeRateDT argument for mode: 'Corporate'. Needs to be: ACorporateExchangeRateTable"); } else if ((AImportMode == "Daily") && (AExchangeRDT.GetType() != typeof(ADailyExchangeRateTable))) { throw new ArgumentException("Invalid type of exchangeRateDT argument for mode: 'Daily'. Needs to be: ADailyExchangeRateTable"); } bool IsShortFileFormat; int x, y; // To store the From and To currencies // Use an array to store these to make for easy // inverting of the two currencies when calculating // the inverse value. string[] Currencies = new string[2]; Type DataTableType; int RowsImported = 0; ACurrencyTable allCurrencies = new ACurrencyTable(); DataTable CacheDT = TDataCache.GetCacheableDataTableFromCache("CurrencyCodeList", String.Empty, null, out DataTableType); allCurrencies.Merge(CacheDT); using (StreamReader DataFile = new StreamReader(ADataFilename, System.Text.Encoding.Default)) { string ThousandsSeparator = (ANumberFormat == TDlgSelectCSVSeparator.NUMBERFORMAT_AMERICAN ? "," : "."); string DecimalSeparator = (ANumberFormat == TDlgSelectCSVSeparator.NUMBERFORMAT_AMERICAN ? "." : ","); CultureInfo MyCultureInfoDate = new CultureInfo("en-GB"); MyCultureInfoDate.DateTimeFormat.ShortDatePattern = ADateFormat; // TODO: disconnect the grid from the datasource to avoid flickering? string FileNameWithoutExtension = Path.GetFileNameWithoutExtension(ADataFilename); if ((FileNameWithoutExtension.IndexOf("_") == 3) && (FileNameWithoutExtension.LastIndexOf("_") == 3) && (FileNameWithoutExtension.Length == 7)) { // File name format assumed to be like this: USD_HKD.csv IsShortFileFormat = true; Currencies = FileNameWithoutExtension.Split(new char[] { '_' }); } else { IsShortFileFormat = false; } int LineNumber = 0; while (!DataFile.EndOfStream) { string Line = DataFile.ReadLine(); LineNumber++; // See if the first line is a special case?? if (LineNumber == 1) { // see if the first line is a text header - look for digits // A valid header would look like: From,To,Date,Rate bool bFoundDigit = false; for (int i = 0; i < Line.Length; i++) { char c = Line[i]; if ((c >= '0') && (c <= '9')) { bFoundDigit = true; break; } } if (!bFoundDigit) { // No digits so we will assume the line is a header continue; } } //Convert separator to a char char Sep = ACSVSeparator[0]; //Turn current line into string array of column values string[] CsvColumns = Line.Split(Sep); int NumCols = CsvColumns.Length; //If number of columns is not 4 then import csv file is wrongly formed. if (IsShortFileFormat && (NumCols < 2)) { // raise an error string resultText = String.Format(Catalog.GetString("Failed to import the CSV currency file:{0} {1}{0}{0}"), Environment.NewLine, ADataFilename); resultText += String.Format(Catalog.GetString( "Line #{1} contains {2} column(s). Import files with names like 'USD_HKD.csv', where the From and To currencies are given in the name, should contain 2 or 3 columns:{0}{0}"), Environment.NewLine, LineNumber, NumCols.ToString()); resultText += String.Format(Catalog.GetString( " 1. Effective Date{0} 2. Exchange Rate{0} 3. Effective time in seconds (Optional for Daily Rate only)"), Environment.NewLine); TVerificationResult result = new TVerificationResult(AImportMode, resultText, CommonErrorCodes.ERR_INFORMATIONMISSING, TResultSeverity.Resv_Critical); AResultCollection.Add(result); return RowsImported; } else if (!IsShortFileFormat && (NumCols < 4)) { string resultText = String.Format(Catalog.GetString("Failed to import the CSV currency file:{0} {1}{0}{0}"), Environment.NewLine, ADataFilename); resultText += String.Format(Catalog.GetString("Line #{1} contains {2} column(s). It should have 4 or 5 as follows:{0}{0}"), Environment.NewLine, LineNumber, NumCols.ToString()); resultText += String.Format(Catalog.GetString( " 1. From Currency{0} 2. To Currency{0} 3. Effective Date{0} 4. Exchange Rate{0} 5. Effective time in seconds (Optional for Daily Rate only)"), Environment.NewLine); TVerificationResult result = new TVerificationResult(AImportMode, resultText, CommonErrorCodes.ERR_INFORMATIONMISSING, TResultSeverity.Resv_Critical); AResultCollection.Add(result); return RowsImported; } if (!IsShortFileFormat) { //Read the values for the current line //From currency Currencies[0] = StringHelper.GetNextCSV(ref Line, ACSVSeparator, false, true).ToString(); //To currency Currencies[1] = StringHelper.GetNextCSV(ref Line, ACSVSeparator, false, true).ToString(); } // Perform validation on the From and To currencies at this point!! if ((allCurrencies.Rows.Find(Currencies[0]) == null) || (allCurrencies.Rows.Find(Currencies[1]) == null)) { // raise an error string resultText = String.Format(Catalog.GetString("Invalid currency in import file in line #{0}"), LineNumber.ToString()); TVerificationResult result = new TVerificationResult(AImportMode, resultText, CommonErrorCodes.ERR_INCONGRUOUSSTRINGS, TResultSeverity.Resv_Critical); AResultCollection.Add(result); return RowsImported; } // Date parsing as in Petra 2.x instead of using XML date format!!! string DateEffectiveStr = StringHelper.GetNextCSV(ref Line, ACSVSeparator, false, true).Replace("\"", String.Empty); DateTime DateEffective; if (!DateTime.TryParse(DateEffectiveStr, MyCultureInfoDate, DateTimeStyles.None, out DateEffective)) { // raise an error string resultText = String.Format(Catalog.GetString( "Invalid date ({0}) in import file in line #{1}"), DateEffectiveStr, LineNumber.ToString()); TVerificationResult result = new TVerificationResult(AImportMode, resultText, CommonErrorCodes.ERR_INVALIDDATE, TResultSeverity.Resv_Critical); AResultCollection.Add(result); return RowsImported; } decimal ExchangeRate = 0.0m; try { string ExchangeRateString = StringHelper.GetNextCSV(ref Line, ACSVSeparator, false, true).Replace(ThousandsSeparator, "").Replace( DecimalSeparator, ".").Replace("\"", String.Empty); ExchangeRate = Convert.ToDecimal(ExchangeRateString, System.Globalization.CultureInfo.InvariantCulture); } catch (Exception) { // raise an error string resultText = String.Format(Catalog.GetString( "Invalid rate of exchange in import file in line #{0}"), LineNumber.ToString()); TVerificationResult result = new TVerificationResult(AImportMode, resultText, CommonErrorCodes.ERR_INVALIDNUMBER, TResultSeverity.Resv_Critical); AResultCollection.Add(result); return RowsImported; } int TimeEffective = 7200; if (AImportMode == "Daily") { // Daily rate imports can have an optional final column which is the time // Otherwise we assume the time is a default of 7200 (02:00am) if ((IsShortFileFormat && (NumCols == 3)) || (!IsShortFileFormat && (NumCols == 5))) { string timeEffectiveStr = StringHelper.GetNextCSV(ref Line, ACSVSeparator, false, true); int t = (int)new Ict.Common.TypeConverter.TShortTimeConverter().ConvertTo(timeEffectiveStr, typeof(int)); if (t < 0) { // it wasn't in the format 02:00 if (!Int32.TryParse(timeEffectiveStr, out t)) { // Not a regular Int32 either t = -1; } } if ((t >= 0) && (t < 86400)) { TimeEffective = t; } else { // raise an error string resultText = String.Format(Catalog.GetString( "Invalid effective time in import file in line #{0}"), LineNumber.ToString()); TVerificationResult result = new TVerificationResult(AImportMode, resultText, CommonErrorCodes.ERR_INVALIDINTEGERTIME, TResultSeverity.Resv_Critical); AResultCollection.Add(result); return RowsImported; } } } if ((AImportMode == "Corporate") && AExchangeRDT is ACorporateExchangeRateTable) { ACorporateExchangeRateTable ExchangeRateDT = (ACorporateExchangeRateTable)AExchangeRDT; // run this code in the loop twice to get ExchangeRate value and its inverse for (int i = 0; i <= 1; i++) { //this will cause x and y to go from 0 to 1 and 1 to 0 respectively x = i; y = Math.Abs(i - 1); ACorporateExchangeRateRow ExchangeRow = (ACorporateExchangeRateRow)ExchangeRateDT.Rows. Find(new object[] { Currencies[x], Currencies[y], DateEffective }); if (ExchangeRow == null) // remove 0 for Corporate { ExchangeRow = (ACorporateExchangeRateRow)ExchangeRateDT.NewRowTyped(); ExchangeRow.FromCurrencyCode = Currencies[x]; ExchangeRow.ToCurrencyCode = Currencies[y]; ExchangeRow.DateEffectiveFrom = DateEffective; ExchangeRateDT.Rows.Add(ExchangeRow); RowsImported++; } if (i == 0) { ExchangeRow.RateOfExchange = ExchangeRate; } else { ExchangeRow.RateOfExchange = 1 / ExchangeRate; } } } else if ((AImportMode == "Daily") && AExchangeRDT is ADailyExchangeRateTable) { ADailyExchangeRateTable ExchangeRateDT = (ADailyExchangeRateTable)AExchangeRDT; // run this code in the loop twice to get ExchangeRate value and its inverse for (int i = 0; i <= 1; i++) { //this will cause x and y to go from 0 to 1 and 1 to 0 respectively x = i; y = Math.Abs(i - 1); ADailyExchangeRateRow ExchangeRow = (ADailyExchangeRateRow)ExchangeRateDT.Rows. Find(new object[] { Currencies[x], Currencies[y], DateEffective, TimeEffective }); if (ExchangeRow == null) // remove 0 for Corporate { ExchangeRow = (ADailyExchangeRateRow)ExchangeRateDT.NewRowTyped(); ExchangeRow.FromCurrencyCode = Currencies[x]; ExchangeRow.ToCurrencyCode = Currencies[y]; ExchangeRow.DateEffectiveFrom = DateEffective; ExchangeRow.TimeEffectiveFrom = TimeEffective; ExchangeRateDT.Rows.Add(ExchangeRow); RowsImported++; } if (i == 0) { ExchangeRow.RateOfExchange = ExchangeRate; } else { ExchangeRow.RateOfExchange = 1 / ExchangeRate; } } } } DataFile.Close(); return RowsImported; } }
/// <summary> /// submit those rows in the table that have been modified or created or deleted /// </summary> /// <param name="ATable"></param> /// <param name="ATransaction"></param> /// <param name="ASelectedOperations"></param> /// <param name="AUserId">the current user, for auditing</param> /// <param name="ASequenceName"></param> /// <param name="ASequenceField"></param> /// <returns></returns> public static void SubmitChanges( TTypedDataTable ATable, TDBTransaction ATransaction, eSubmitChangesOperations ASelectedOperations, string AUserId, string ASequenceName, string ASequenceField) { // allow this method to be called with null values, eg. when saving complex TypedDataSets with some removed empty tables if (ATable == null) { return; } short TableId = Convert.ToInt16(ATable.GetType().GetField("TableId").GetValue(null)); if (!ATable.ThrowAwayAfterSubmitChanges && !ATable.DontThrowAwayAfterSubmitChanges && (ATable.Rows.Count > 1000)) { TLogging.Log( "Warning to the developer: Saving " + ATable.Rows.Count.ToString() + " records to table " + ATable.TableName + " without ThrowAwayAfterSubmitChanges is quite slow"); TLogging.Log( "It is recommended to use either ThrowAwayAfterSubmitChanges and Reload all data at once, or GetChanges to have less queries for updated modification timestamp"); TLogging.LogStackTrace(TLoggingType.ToLogfile); } List <OdbcParameter>InsertParameters = new List <OdbcParameter>(); StringBuilder InsertStatement = new StringBuilder(); for (RowCount = 0; (RowCount != ATable.Rows.Count); RowCount++) { DataRow TheRow = ATable.Rows[RowCount]; if ((TheRow.RowState == DataRowState.Added) && ((ASelectedOperations & eSubmitChangesOperations.eInsert) != 0)) { bool TreatRowAsAdded = false; if (ASequenceField.Length > 0) { // only insert next sequence value if the field has negative value. // this is needed when creating location 0 for a new site/ledger if (Convert.ToInt64(TheRow[ASequenceField]) < 0) { // accept changes for the row, so that we can update the dataset on the client and still know the negative temp sequence number TheRow.AcceptChanges(); TheRow[ASequenceField] = (System.Object)DBAccess.GDBAccessObj.GetNextSequenceValue(ASequenceName, ATransaction); TreatRowAsAdded = true; // setting this variable to 'true' is *vital* for the retrieval of the s_modification_id_t for that record once it is saved! } } if (ATable.ThrowAwayAfterSubmitChanges) { TTypedDataAccess.InsertRow(TableId, ref TheRow, AUserId, InsertStatement, InsertParameters); } else { TTypedDataAccess.InsertRow(TableId, ref TheRow, ATransaction, AUserId, TreatRowAsAdded); } } else { bool hasPrimaryKey = TTypedDataTable.GetPrimaryKeyColumnOrdList(TableId).Length > 0; if ((TheRow.RowState == DataRowState.Modified) && ((ASelectedOperations & eSubmitChangesOperations.eUpdate) != 0)) { if (!hasPrimaryKey) { throw new EDBSubmitException( "[TTypedDataAccess.SubmitChanges] NO PRIMARY KEY --- Cannot update record because table " + TTypedDataTable.GetTableName(TableId) + " has no primary key.", eSubmitChangesOperations.eUpdate); } else { TTypedDataAccess.UpdateRow(TableId, ATable.ThrowAwayAfterSubmitChanges, ref TheRow, ATransaction, AUserId); } } if ((TheRow.RowState == DataRowState.Deleted) && ((ASelectedOperations & eSubmitChangesOperations.eDelete) != 0)) { if (!hasPrimaryKey) { throw new EDBSubmitException( "[TTypedDataAccess.SubmitChanges] NO PRIMARY KEY --- Cannot delete record because table " + TTypedDataTable.GetTableName(TableId) + " has no primary key.", eSubmitChangesOperations.eDelete); } else { TTypedDataAccess.DeleteRow(TableId, TheRow, ATransaction); } } } if (InsertParameters.Count > MAX_SQL_PARAMETERS) { // Inserts in one query if (0 == DBAccess.GDBAccessObj.ExecuteNonQuery(InsertStatement.ToString(), ATransaction, InsertParameters.ToArray())) { throw new EDBSubmitException("[TTypedDataAccess.SubmitChanges] Problems INSERTing a row [#1]", eSubmitChangesOperations.eInsert); } InsertStatement = new StringBuilder(); InsertParameters = new List <OdbcParameter>(); } } if (InsertStatement.Length > 0) { // Inserts in one query if (0 == DBAccess.GDBAccessObj.ExecuteNonQuery(InsertStatement.ToString(), ATransaction, InsertParameters.ToArray())) { throw new EDBSubmitException("[TTypedDataAccess.SubmitChanges] Problems INSERTing a row [#2]", eSubmitChangesOperations.eInsert); } } }
public static bool GetData(string ATablename, TSearchCriteria[] ASearchCriteria, out TTypedDataTable AResultTable) { // TODO: check access permissions for the current user bool NewTransaction = false; TDBTransaction ReadTransaction; TTypedDataTable tempTable = null; try { ReadTransaction = DBAccess.GDBAccessObj.GetNewOrExistingTransaction(IsolationLevel.RepeatableRead, TEnforceIsolationLevel.eilMinimum, out NewTransaction); // TODO: auto generate if (ATablename == AApSupplierTable.GetTableDBName()) { tempTable = AApSupplierAccess.LoadUsingTemplate(ASearchCriteria, ReadTransaction); } else if (ATablename == AApDocumentTable.GetTableDBName()) { tempTable = AApDocumentAccess.LoadUsingTemplate(ASearchCriteria, ReadTransaction); } else if (ATablename == ATransactionTypeTable.GetTableDBName()) { tempTable = ATransactionTypeAccess.LoadUsingTemplate(ASearchCriteria, ReadTransaction); } else if (ATablename == ACurrencyTable.GetTableDBName()) { tempTable = ACurrencyAccess.LoadAll(ReadTransaction); } else if (ATablename == ADailyExchangeRateTable.GetTableDBName()) { tempTable = ADailyExchangeRateAccess.LoadAll(ReadTransaction); } else if (ATablename == ACorporateExchangeRateTable.GetTableDBName()) { tempTable = ACorporateExchangeRateAccess.LoadAll(ReadTransaction); } else if (ATablename == ACurrencyLanguageTable.GetTableDBName()) { tempTable = ACurrencyLanguageAccess.LoadAll(ReadTransaction); } else if (ATablename == AFeesPayableTable.GetTableDBName()) { tempTable = AFeesPayableAccess.LoadAll(ReadTransaction); } else if (ATablename == AFeesReceivableTable.GetTableDBName()) { tempTable = AFeesReceivableAccess.LoadAll(ReadTransaction); } else if (ATablename == AAnalysisTypeTable.GetTableDBName()) { tempTable = AAnalysisTypeAccess.LoadAll(ReadTransaction); } else if (ATablename == AGiftBatchTable.GetTableDBName()) { tempTable = AGiftBatchAccess.LoadAll(ReadTransaction); } else if (ATablename == AJournalTable.GetTableDBName()) { tempTable = AJournalAccess.LoadAll(ReadTransaction); } else if (ATablename == ALedgerTable.GetTableDBName()) { tempTable = ALedgerAccess.LoadAll(ReadTransaction); } else if (ATablename == MExtractMasterTable.GetTableDBName()) { if (ASearchCriteria == null) { tempTable = MExtractMasterAccess.LoadAll(ReadTransaction); } else { tempTable = MExtractMasterAccess.LoadUsingTemplate(ASearchCriteria, ReadTransaction); } } else if (ATablename == MExtractTable.GetTableDBName()) { // it does not make sense to load ALL extract rows for all extract masters so search criteria needs to be set if (ASearchCriteria != null) { tempTable = MExtractAccess.LoadUsingTemplate(ASearchCriteria, ReadTransaction); } } else if (ATablename == PcAttendeeTable.GetTableDBName()) { tempTable = PcAttendeeAccess.LoadUsingTemplate(ASearchCriteria, ReadTransaction); } else if (ATablename == PcConferenceCostTable.GetTableDBName()) { tempTable = PcConferenceCostAccess.LoadUsingTemplate(ASearchCriteria, ReadTransaction); } else if (ATablename == PcEarlyLateTable.GetTableDBName()) { tempTable = PcEarlyLateAccess.LoadUsingTemplate(ASearchCriteria, ReadTransaction); } else if (ATablename == PcSupplementTable.GetTableDBName()) { tempTable = PcSupplementAccess.LoadUsingTemplate(ASearchCriteria, ReadTransaction); } else if (ATablename == PcDiscountTable.GetTableDBName()) { tempTable = PcDiscountAccess.LoadUsingTemplate(ASearchCriteria, ReadTransaction); } else if (ATablename == PInternationalPostalTypeTable.GetTableDBName()) { tempTable = PInternationalPostalTypeAccess.LoadAll(ReadTransaction); } else if (ATablename == PtApplicationTypeTable.GetTableDBName()) { tempTable = PtApplicationTypeAccess.LoadAll(ReadTransaction); } else if (ATablename == PMailingTable.GetTableDBName()) { tempTable = PMailingAccess.LoadAll(ReadTransaction); } else if (ATablename == PPartnerGiftDestinationTable.GetTableDBName()) { tempTable = PPartnerGiftDestinationAccess.LoadUsingTemplate(ASearchCriteria, ReadTransaction); } else if (ATablename == PmDocumentTypeTable.GetTableDBName()) { tempTable = PmDocumentTypeAccess.LoadAll(ReadTransaction); } else if (ATablename == SGroupTable.GetTableDBName()) { tempTable = SGroupAccess.LoadAll(ReadTransaction); } else { throw new Exception("TCommonDataReader.GetData: unknown table " + ATablename); } } catch (Exception Exp) { DBAccess.GDBAccessObj.RollbackTransaction(); TLogging.Log("TCommonDataReader.GetData exception: " + Exp.ToString(), TLoggingType.ToLogfile); TLogging.Log(Exp.StackTrace, TLoggingType.ToLogfile); throw; } finally { if (NewTransaction) { DBAccess.GDBAccessObj.CommitTransaction(); TLogging.LogAtLevel(7, "TCommonDataReader.GetData: committed own transaction."); } } // Accept row changes here so that the Client gets 'unmodified' rows tempTable.AcceptChanges(); // return the table AResultTable = tempTable; return true; }
/// <summary> /// overloaded version without ASelectedOperations /// </summary> public static void SubmitChanges( TTypedDataTable ATable, TDBTransaction ATransaction, string AUserId, string ASequenceName, string ASequenceField) { SubmitChanges( ATable, ATransaction, eSubmitChangesOperations.eAll, AUserId, ASequenceName, ASequenceField); }
/// <summary> /// overloaded version without sequence, but with ASelectedOperations /// </summary> public static void SubmitChanges( TTypedDataTable ATable, TDBTransaction ATransaction, eSubmitChangesOperations ASelectedOperations, string AUserId) { SubmitChanges(ATable, ATransaction, ASelectedOperations, AUserId, "", ""); }
/// <summary> /// Imports currency exchange rates, daily and corporate, /// from a one-of-two-styles formatted CSV file /// </summary> /// <param name="AExchangeRDT">Daily or Corporate exchange rate table</param> /// <param name="ADataFilename">The .CSV file to process</param> /// <param name="ACSVSeparator"></param> /// <param name="ANumberFormat"></param> /// <param name="ADateFormat"></param> /// <param name="AImportMode">Daily or Corporate</param> /// <param name="AResultCollection">A validation collection to which errors will be added</param> /// <returns>The number of rows that were actually imported. Rows that duplicate existing rows do not count. /// This is usually because this is an attempt to import again after a failed previous attempt.</returns> private static int ImportCurrencyExRatesFromCSV(TTypedDataTable AExchangeRDT, string ADataFilename, string ACSVSeparator, string ANumberFormat, string ADateFormat, string AImportMode, TVerificationResultCollection AResultCollection) { // Keep a list of errors/warnings and severity List <Tuple <string, TResultSeverity>>InvalidRows = new List <Tuple <string, TResultSeverity>>(); // keep a variable that becomes true if any row has an invalid column count, so we can show a helpful message bool InvalidColumnCount = false; // Check our method parameters if ((AImportMode != "Corporate") && (AImportMode != "Daily")) { throw new ArgumentException("Invalid value '" + AImportMode + "' for mode argument: Valid values are Corporate and Daily"); } else if ((AImportMode == "Corporate") && !(AExchangeRDT is ACorporateExchangeRateTable)) { throw new ArgumentException("Invalid type of exchangeRateDT argument for mode: 'Corporate'. Needs to be: ACorporateExchangeRateTable"); } else if ((AImportMode == "Daily") && !(AExchangeRDT is ADailyExchangeRateTable)) { throw new ArgumentException("Invalid type of exchangeRateDT argument for mode: 'Daily'. Needs to be: ADailyExchangeRateTable"); } bool IsShortFileFormat; int x, y; // To store the From and To currencies // Use an array to store these to make for easy // inverting of the two currencies when calculating // the inverse value. string[] Currencies = new string[2]; Type DataTableType; int RowsImported = 0; // This table will tell us the base currencies used by the current set of ledgers ALedgerTable ledgers = TRemote.MFinance.Setup.WebConnectors.GetAvailableLedgers(); List <string>allBaseCurrencies = new List <string>(); DateTime maxRecommendedEffectiveDate = DateTime.MaxValue; DateTime minRecommendedEffectiveDate = DateTime.MinValue; int preferredPeriodStartDay = 0; // Use the ledger table rows to get a list of base currencies and current period end dates for (int i = 0; i < ledgers.Rows.Count; i++) { ALedgerRow ledger = (ALedgerRow)ledgers.Rows[i]; string code = ledger.BaseCurrency; if (ledger.LedgerStatus == true) { if (allBaseCurrencies.Contains(code) == false) { allBaseCurrencies.Add(code); } DataTable AccountingPeriods = TDataCache.TMFinance.GetCacheableFinanceTable(TCacheableFinanceTablesEnum.AccountingPeriodList, ledger.LedgerNumber); AAccountingPeriodRow currentPeriodRow = (AAccountingPeriodRow)AccountingPeriods.Rows.Find(new object[] { ledger.LedgerNumber, ledger.CurrentPeriod }); AAccountingPeriodRow forwardPeriodRow = (AAccountingPeriodRow)AccountingPeriods.Rows.Find( new object[] { ledger.LedgerNumber, ledger.CurrentPeriod + ledger.NumberFwdPostingPeriods }); if ((forwardPeriodRow != null) && ((maxRecommendedEffectiveDate == DateTime.MaxValue) || (forwardPeriodRow.PeriodEndDate > maxRecommendedEffectiveDate))) { maxRecommendedEffectiveDate = forwardPeriodRow.PeriodEndDate; } if ((currentPeriodRow != null) && ((minRecommendedEffectiveDate == DateTime.MinValue) || (currentPeriodRow.PeriodStartDate > minRecommendedEffectiveDate))) { minRecommendedEffectiveDate = currentPeriodRow.PeriodStartDate; } if ((currentPeriodRow != null) && (preferredPeriodStartDay == 0)) { preferredPeriodStartDay = currentPeriodRow.PeriodStartDate.Day; } else if ((currentPeriodRow != null) && (currentPeriodRow.PeriodStartDate.Day != preferredPeriodStartDay)) { preferredPeriodStartDay = -1; } } } // This will tell us the complete list of all available currencies ACurrencyTable allCurrencies = new ACurrencyTable(); DataTable CacheDT = TDataCache.GetCacheableDataTableFromCache("CurrencyCodeList", String.Empty, null, out DataTableType); allCurrencies.Merge(CacheDT); allCurrencies.CaseSensitive = true; // Start reading the file using (StreamReader DataFile = new StreamReader(ADataFilename, System.Text.Encoding.Default)) { string ThousandsSeparator = (ANumberFormat == TDlgSelectCSVSeparator.NUMBERFORMAT_AMERICAN ? "," : "."); string DecimalSeparator = (ANumberFormat == TDlgSelectCSVSeparator.NUMBERFORMAT_AMERICAN ? "." : ","); CultureInfo MyCultureInfoDate = new CultureInfo("en-GB"); MyCultureInfoDate.DateTimeFormat.ShortDatePattern = ADateFormat; // TODO: disconnect the grid from the datasource to avoid flickering? string FileNameWithoutExtension = Path.GetFileNameWithoutExtension(ADataFilename).ToUpper(); if ((FileNameWithoutExtension.IndexOf("_") == 3) && (FileNameWithoutExtension.LastIndexOf("_") == 3) && (FileNameWithoutExtension.Length == 7)) { // File name format assumed to be like this: USD_HKD.csv IsShortFileFormat = true; Currencies = FileNameWithoutExtension.Split(new char[] { '_' }); } else { IsShortFileFormat = false; } int LineNumber = 0; while (!DataFile.EndOfStream) { string Line = DataFile.ReadLine(); LineNumber++; // See if the first line is a special case?? if (LineNumber == 1) { // see if the first line is a text header - look for digits // A valid header would look like: From,To,Date,Rate bool bFoundDigit = false; for (int i = 0; i < Line.Length; i++) { char c = Line[i]; if ((c >= '0') && (c <= '9')) { bFoundDigit = true; break; } } if (!bFoundDigit) { // No digits so we will assume the line is a header continue; } } //Convert separator to a char char Sep = ACSVSeparator[0]; //Turn current line into string array of column values string[] CsvColumns = Line.Split(Sep); int NumCols = CsvColumns.Length; // Do we have the correct number of columns? int minColCount = IsShortFileFormat ? 2 : 4; int maxColCount = (AImportMode == "Daily") ? minColCount + 1 : minColCount; if ((NumCols < minColCount) || (NumCols > maxColCount)) { // raise an error string resultText = String.Format(Catalog.GetPluralString( "Line {0}: contains 1 column", "Line {0}: contains {1} columns", NumCols, true), LineNumber, NumCols.ToString()); InvalidRows.Add(new Tuple <string, TResultSeverity>(resultText, TResultSeverity.Resv_Critical)); InvalidColumnCount = true; continue; } if (!IsShortFileFormat) { //Read the values for the current line //From currency Currencies[0] = StringHelper.GetNextCSV(ref Line, ACSVSeparator, false, true).ToString().ToUpper(); //To currency Currencies[1] = StringHelper.GetNextCSV(ref Line, ACSVSeparator, false, true).ToString().ToUpper(); } // Perform validation on the From and To currencies at this point!! if ((allCurrencies.Rows.Find(Currencies[0]) == null) && (allCurrencies.Rows.Find(Currencies[1]) == null)) { // raise an error string resultText = String.Format(Catalog.GetString( "Line {0}: invalid currency codes ({1} and {2})"), LineNumber.ToString(), Currencies[0], Currencies[1]); InvalidRows.Add(new Tuple <string, TResultSeverity>(resultText, TResultSeverity.Resv_Critical)); continue; } else if (allCurrencies.Rows.Find(Currencies[0]) == null) { // raise an error string resultText = String.Format(Catalog.GetString( "Line {0}: invalid currency code ({1})"), LineNumber.ToString(), Currencies[0]); InvalidRows.Add(new Tuple <string, TResultSeverity>(resultText, TResultSeverity.Resv_Critical)); continue; } else if (allCurrencies.Rows.Find(Currencies[1]) == null) { // raise an error string resultText = String.Format(Catalog.GetString( "Line {0}: invalid currency code ({1})"), LineNumber.ToString(), Currencies[1]); InvalidRows.Add(new Tuple <string, TResultSeverity>(resultText, TResultSeverity.Resv_Critical)); continue; } if ((allBaseCurrencies.Contains(Currencies[0]) == false) && (allBaseCurrencies.Contains(Currencies[1]) == false)) { //raise a non-critical error string resultText = String.Format(Catalog.GetString( "Line {0}: Warning: One of '{1}' and '{2}' should be a base currency in one of the active ledgers."), LineNumber.ToString(), Currencies[0], Currencies[1]); InvalidRows.Add(new Tuple <string, TResultSeverity>(resultText, TResultSeverity.Resv_Noncritical)); } // Date parsing as in Petra 2.x instead of using XML date format!!! string DateEffectiveStr = StringHelper.GetNextCSV(ref Line, ACSVSeparator, false, true).Replace("\"", String.Empty); DateTime DateEffective; if (!DateTime.TryParse(DateEffectiveStr, MyCultureInfoDate, DateTimeStyles.None, out DateEffective)) { // raise an error string resultText = String.Format(Catalog.GetString( "Line {0}: invalid date ({1})"), LineNumber.ToString(), DateEffectiveStr); InvalidRows.Add(new Tuple <string, TResultSeverity>(resultText, TResultSeverity.Resv_Critical)); continue; } if (DateEffective > maxRecommendedEffectiveDate) { // raise a warning string resultText = String.Format(Catalog.GetString( "Line {0}: Warning: The date '{1}' is after the latest forwarding period of any active ledger"), LineNumber.ToString(), DateEffectiveStr); InvalidRows.Add(new Tuple <string, TResultSeverity>(resultText, TResultSeverity.Resv_Noncritical)); } else if (DateEffective < minRecommendedEffectiveDate) { // raise a warning string resultText = String.Format(Catalog.GetString( "Line {0}: Warning: The date '{1}' is before the current accounting period of any active ledger"), LineNumber.ToString(), DateEffectiveStr); InvalidRows.Add(new Tuple <string, TResultSeverity>(resultText, TResultSeverity.Resv_Noncritical)); } if (AImportMode == "Corporate") { if ((preferredPeriodStartDay >= 1) && (DateEffective.Day != preferredPeriodStartDay)) { // raise a warning string resultText = String.Format(Catalog.GetString( "Line {0}: Warning: The date '{1}' should be the first day of an accounting period used by all the active ledgers."), LineNumber.ToString(), DateEffectiveStr); InvalidRows.Add(new Tuple <string, TResultSeverity>(resultText, TResultSeverity.Resv_Noncritical)); } } decimal ExchangeRate = 0.0m; try { string ExchangeRateString = StringHelper.GetNextCSV(ref Line, ACSVSeparator, false, true).Replace(ThousandsSeparator, "").Replace( DecimalSeparator, ".").Replace("\"", String.Empty); ExchangeRate = Convert.ToDecimal(ExchangeRateString, System.Globalization.CultureInfo.InvariantCulture); if (ExchangeRate == 0) { throw new Exception(); } } catch (Exception) { // raise an error string resultText = String.Format(Catalog.GetString( "Line {0}: invalid rate of exchange ({1})"), LineNumber.ToString(), ExchangeRate); InvalidRows.Add(new Tuple <string, TResultSeverity>(resultText, TResultSeverity.Resv_Critical)); continue; } int TimeEffective = 7200; if (AImportMode == "Daily") { // Daily rate imports can have an optional final column which is the time // Otherwise we assume the time is a default of 7200 (02:00am) if ((IsShortFileFormat && (NumCols == 3)) || (!IsShortFileFormat && (NumCols == 5))) { string timeEffectiveStr = StringHelper.GetNextCSV(ref Line, ACSVSeparator, false, true); int t = (int)new Ict.Common.TypeConverter.TShortTimeConverter().ConvertTo(timeEffectiveStr, typeof(int)); if (t < 0) { // it wasn't in the format 02:00 if (!Int32.TryParse(timeEffectiveStr, out t)) { // Not a regular Int32 either t = -1; } } if ((t >= 0) && (t < 86400)) { TimeEffective = t; } else { // raise an error string resultText = String.Format(Catalog.GetString( "Line {0}: invalid effective time ({1})"), LineNumber.ToString(), t); InvalidRows.Add(new Tuple <string, TResultSeverity>(resultText, TResultSeverity.Resv_Critical)); continue; } } } if ((AImportMode == "Corporate") && AExchangeRDT is ACorporateExchangeRateTable) { ACorporateExchangeRateTable ExchangeRateDT = (ACorporateExchangeRateTable)AExchangeRDT; // run this code in the loop twice to get ExchangeRate value and its inverse for (int i = 0; i <= 1; i++) { //this will cause x and y to go from 0 to 1 and 1 to 0 respectively x = i; y = Math.Abs(i - 1); ACorporateExchangeRateRow ExchangeRow = (ACorporateExchangeRateRow)ExchangeRateDT.Rows. Find(new object[] { Currencies[x], Currencies[y], DateEffective }); if (ExchangeRow == null) // remove 0 for Corporate { ExchangeRow = (ACorporateExchangeRateRow)ExchangeRateDT.NewRowTyped(); ExchangeRow.FromCurrencyCode = Currencies[x]; ExchangeRow.ToCurrencyCode = Currencies[y]; ExchangeRow.DateEffectiveFrom = DateEffective; ExchangeRateDT.Rows.Add(ExchangeRow); RowsImported++; } if (i == 0) { ExchangeRow.RateOfExchange = ExchangeRate; } else { ExchangeRow.RateOfExchange = Math.Round(1 / ExchangeRate, 10); } } } else if ((AImportMode == "Daily") && AExchangeRDT is ADailyExchangeRateTable) { ADailyExchangeRateTable ExchangeRateDT = (ADailyExchangeRateTable)AExchangeRDT; // run this code in the loop twice to get ExchangeRate value and its inverse for (int i = 0; i <= 1; i++) { //this will cause x and y to go from 0 to 1 and 1 to 0 respectively x = i; y = Math.Abs(i - 1); ADailyExchangeRateRow ExchangeRow = (ADailyExchangeRateRow)ExchangeRateDT.Rows. Find(new object[] { Currencies[x], Currencies[y], DateEffective, TimeEffective }); if (ExchangeRow == null) // remove 0 for Corporate { ExchangeRow = (ADailyExchangeRateRow)ExchangeRateDT.NewRowTyped(); ExchangeRow.FromCurrencyCode = Currencies[x]; ExchangeRow.ToCurrencyCode = Currencies[y]; ExchangeRow.DateEffectiveFrom = DateEffective; ExchangeRow.TimeEffectiveFrom = TimeEffective; ExchangeRateDT.Rows.Add(ExchangeRow); RowsImported++; } if (i == 0) { ExchangeRow.RateOfExchange = ExchangeRate; } else { ExchangeRow.RateOfExchange = Math.Round(1 / ExchangeRate, 10); } } } } // if there are rows that could not be imported if ((InvalidRows != null) && (InvalidRows.Count > 0)) { int errorCount = 0; int warningCount = 0; // Go through once just to count the errors and warnings foreach (Tuple <string, TResultSeverity>Row in InvalidRows) { if (Row.Item2 == TResultSeverity.Resv_Noncritical) { warningCount++; } else { errorCount++; } } string resultText = String.Empty; bool messageListIsFull = false; int counter = 0; if (errorCount > 0) { resultText = string.Format(Catalog.GetPluralString("1 row was not imported due to invalid data:", "{0} rows were not imported due to invalid data:", errorCount, true), errorCount) + Environment.NewLine; } if (warningCount > 0) { resultText = string.Format(Catalog.GetPluralString("There was 1 warning associated with the imported rows:", "There were {0} warnings associated with the imported rows:", warningCount, true), warningCount) + Environment.NewLine; } // Now go through again itemising each one foreach (Tuple <string, TResultSeverity>Row in InvalidRows) { counter++; if (counter <= MAX_MESSAGE_COUNT) { resultText += Environment.NewLine + Row.Item1; } else if (!messageListIsFull) { resultText += String.Format(Catalog.GetString( "{0}{0}{1} errors/warnings were reported in total. This message contains the first {2}."), Environment.NewLine, InvalidRows.Count, MAX_MESSAGE_COUNT); messageListIsFull = true; } } // additional message if one or more rows has an invalid number of columns if (InvalidColumnCount && IsShortFileFormat) { resultText += String.Format("{0}{0}" + Catalog.GetString("Each row should contain 2 or 3 columns as follows:") + "{0}" + Catalog.GetString( " 1. Effective Date{0} 2. Exchange Rate{0} 3. Effective time in seconds (Optional for Daily Rate only)"), Environment.NewLine); } else if (InvalidColumnCount && !IsShortFileFormat) { resultText += String.Format("{0}{0}" + Catalog.GetString("Each row should contain 4 or 5 columns as follows:") + "{0}" + Catalog.GetString( " 1. From Currency{0} 2. To Currency{0} 3. Effective Date{0} 4. Exchange Rate{0} 5. Effective time in seconds (Optional for Daily Rate only)"), Environment.NewLine); } TVerificationResult result = new TVerificationResult(AImportMode, resultText, CommonErrorCodes.ERR_INCONGRUOUSSTRINGS, (errorCount > 0) ? TResultSeverity.Resv_Critical : TResultSeverity.Resv_Noncritical); AResultCollection.Add(result); } DataFile.Close(); return RowsImported; } }
static partial void ValidateApDocumentDetailManual(ref TVerificationResultCollection AVerificationResult, TTypedDataTable ASubmitTable);
static partial void ValidateGiftBatch(ref TVerificationResultCollection AVerificationResult, TTypedDataTable ASubmitTable);
static partial void ValidatePersonnelStaff(ref TVerificationResultCollection AVerificationResult, TTypedDataTable ASubmitTable);
/// <summary> /// simple data reader; /// checks for permissions of the current user; /// </summary> /// <param name="ATablename"></param> /// <param name="ASearchCriteria">a set of search criteria</param> /// <param name="AResultTable">returns typed datatable</param> /// <returns></returns> public static bool GetData(string ATablename, TSearchCriteria[] ASearchCriteria, out TTypedDataTable AResultTable) { return TRemote.MCommon.DataReader.WebConnectors.GetData(ATablename, ASearchCriteria, out AResultTable); }
void FPetraUtilsObject_DataSaved(object Sender, TDataSavedEventArgs e) { // Do not save anything if the main table did not save correctly if (!e.Success) { return; } // Ensure we get the current row's information if (FPreviouslySelectedDetailRow != null) { FPreviouslySelectedDetailRow[UsedByColumnOrdinal] = clbUsedBy.GetCheckedStringList(); } // Now we need to save the PDataLabelUse table info using our data from our UsedBy column // Go round all the rows, seeing which rows have a new UsedBy value foreach (PDataLabelRow labelRow in FMainDS.PDataLabel.Rows) { if ((labelRow.RowState != DataRowState.Deleted) && (labelRow[UsedByColumnOrdinal].ToString() != labelRow[UsedByColumnOrdinal - 1].ToString())) { // This row's UsedBy column has been edited // Get the key and the list of usedBy's for this row int key = labelRow.Key; string usedByList = labelRow[UsedByColumnOrdinal].ToString(); string[] uses = usedByList.Split(','); // Get the usedBy's that are in the database at the moment DataRow[] UseRows = FExtraDS.PDataLabelUse.Select("p_data_label_key_i=" + key.ToString()); // For each current UsedBy, make sure it has a row in the database. // If not, we need to add a new row, using an Idx1 value greater than anything used before foreach (string use in uses) { bool bUseExistsAlready = false; foreach (DataRow r in UseRows) { string tryUse = r.ItemArray[PDataLabelUseTable.ColumnUseId].ToString(); if (String.Compare(tryUse, use, true) == 0) { bUseExistsAlready = true; break; } } if (!bUseExistsAlready) { PDataLabelUseRow newRow = FExtraDS.PDataLabelUse.NewRowTyped(); newRow.DataLabelKey = key; newRow.Use = use; newRow.Idx1 = ++MaxIdx1Value; FExtraDS.PDataLabelUse.Rows.Add(newRow); } } // Now go round the other way // Go round each database row and check if its UsedBy is still in our current usedBy List // If we don't find it in the current list we need to delete this row foreach (DataRow r in UseRows) { string tryUse = r.ItemArray[PDataLabelUseTable.ColumnUseId].ToString(); bool bUseStillExists = false; foreach (string use in uses) { if (String.Compare(tryUse, use, true) == 0) { bUseStillExists = true; break; } } if (!bUseStillExists) { // We no longer need this row for this usedBy/LabelKey r.Delete(); } } } } Ict.Common.Data.TTypedDataTable SubmitDT = FExtraDS.PDataLabelUse.GetChangesTyped(); if (SubmitDT == null) { return; // nothing to save } SaveDataLabelUseChanges(SubmitDT); }
private void SaveDataLabelUseChanges(TTypedDataTable ASubmitChanges) { // Submit changes to the PETRAServer for the DataLabelUse table // This code is basically lifted from a typical auto-generated equivalent // TODO: If the standard code changes because TODO's get done, we will need to change this manual code TSubmitChangesResult SubmissionResult; TVerificationResultCollection VerificationResult; try { SubmissionResult = TDataCache.SaveChangedCacheableDataTableToPetraServer("DataLabelUseList", ref ASubmitChanges, out VerificationResult); } catch (ESecurityDBTableAccessDeniedException Exp) { FPetraUtilsObject.WriteToStatusBar(MCommonResourcestrings.StrSavingDataException); this.Cursor = Cursors.Default; TMessages.MsgSecurityException(Exp, this.GetType()); return; } catch (EDBConcurrencyException Exp) { FPetraUtilsObject.WriteToStatusBar(MCommonResourcestrings.StrSavingDataException); this.Cursor = Cursors.Default; TMessages.MsgDBConcurrencyException(Exp, this.GetType()); return; } catch (Exception exp) { TLogging.Log( "An error occured while saving the 'used by' data" + Environment.NewLine + exp.ToString(), TLoggingType.ToLogfile); MessageBox.Show( Catalog.GetString("An error occured while saving the 'used by' data") + Environment.NewLine + Catalog.GetString("For details see the log file: ") + TLogging.GetLogFileName(), Catalog.GetString("Failed to Save 'Used By' Data"), MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } switch (SubmissionResult) { case TSubmitChangesResult.scrOK: // Call AcceptChanges to get rid now of any deleted columns before we Merge with the result from the Server FExtraDS.PDataLabelUse.AcceptChanges(); // Merge back with data from the Server (eg. for getting Sequence values) ASubmitChanges.AcceptChanges(); FExtraDS.PDataLabelUse.Merge(ASubmitChanges, false); // need to accept the new modification ID FExtraDS.PDataLabelUse.AcceptChanges(); // need to refresh the cacheable DataTable 'DataLabelsForPartnerClassesList' (used by Partner Find's Maintain Menu) TDataCache.TMPartner.RefreshCacheablePartnerTable(TCacheablePartnerTablesEnum.DataLabelsForPartnerClassesList); return; case TSubmitChangesResult.scrNothingToBeSaved: return; case TSubmitChangesResult.scrError: MessageBox.Show(Catalog.GetString( "The 'UsedBy' part of the data could not be saved! There has been an error while making changes to the table."), Catalog.GetString("Submit Changes to Table Error"), MessageBoxButtons.OK, MessageBoxIcon.Warning); break; case TSubmitChangesResult.scrInfoNeeded: MessageBox.Show(Catalog.GetString( "The 'UsedBy' part of the data could not be saved! Insufficient information was provided when making changes to the table."), Catalog.GetString("Submit Changes to Table Error"), MessageBoxButtons.OK, MessageBoxIcon.Warning); break; } }