/// <summary> /// First loads the extractTable needed. Goes throught all the Partners in the extract, If the partner already has the subscription, returns all those partners back to client. If the partner doesn't have the subscription, saves this /// subscription to those partners. /// </summary> /// <returns>void</returns> private void SubmitChangesInternal() { TDBTransaction SubmitChangesTransaction = null; TSubmitChangesResult SubmissionResult = TSubmitChangesResult.scrNothingToBeSaved; MExtractTable ExtractDT; PSubscriptionTable SubscriptionTable; PPartnerTable PartnerTable; Int32 RowCounter; Int32 PartnersInExtract; StringCollection RequiredColumns; StringCollection RequiredColumns2; if (FInspectDT != null) { // Initialisations FVerificationResult = new TVerificationResultCollection(); ExtractDT = new MExtractTable(); SubscriptionTable = new PSubscriptionTable(); FSubmissionDT = SubscriptionTable.Clone(); ((TTypedDataTable)FSubmissionDT).InitVars(); PartnerTable = new PPartnerTable(); RequiredColumns = new StringCollection(); RequiredColumns.Add(MExtractTable.GetPartnerKeyDBName()); RequiredColumns2 = new StringCollection(); RequiredColumns2.Add(PPartnerTable.GetPartnerKeyDBName()); RequiredColumns2.Add(PPartnerTable.GetPartnerShortNameDBName()); RowCounter = 0; // Set up asynchronous execution TProgressTracker.SetCurrentState(FProgressID, "Checking Partners' Subscriptions...", 0.0m); DBAccess.GDBAccessObj.BeginAutoTransaction(IsolationLevel.Serializable, ref SubmitChangesTransaction, ref SubmissionResult, delegate { try { // TLogging.LogAtLevel(7, "TExtractsAddSubscriptionsUIConnector.SubmitChangesInternal: loading Subscriptions for ExtractID " + FExtractID.ToString() + "..."); ExtractDT = MExtractAccess.LoadViaMExtractMaster(FExtractID, RequiredColumns, SubmitChangesTransaction); PartnersInExtract = ExtractDT.Rows.Count; // TLogging.LogAtLevel(7, "TExtractsAddSubscriptionsUIConnector.SubmitChangesInternal: ExtractID has " + PartnersInExtract.ToString() + " Partners."); // Go throught all the Partners in the extract foreach (MExtractRow ExtractRow in ExtractDT.Rows) { RowCounter = RowCounter + 1; // Calculate how much Partners we have checked. Let all Partners be a maximum of 70%. TProgressTracker.SetCurrentState( FProgressID, string.Empty, Convert.ToInt16((((double)RowCounter / (double)PartnersInExtract) * 100) * (MAX_PERCENTAGE_CHECKS / 100.0))); TLogging.LogAtLevel(7, "TExtractsAddSubscriptionsUIConnector.SubmitChangesInternal: loadbyPrimaryKey"); SubscriptionTable = PSubscriptionAccess.LoadByPrimaryKey( FInspectDT[0].PublicationCode, ExtractRow.PartnerKey, SubmitChangesTransaction); // if the Partner does not yet have the subscription, add the subscription to this partner. if (SubscriptionTable.Rows.Count == 0) { TLogging.LogAtLevel( 7, "TExtractsAddSubscriptionsUIConnector.SubmitChangesInternal: will add Subscription to Partner with PartnerKey " + ExtractRow.PartnerKey.ToString()); FInspectDT[0].PartnerKey = ExtractRow.PartnerKey; TLogging.LogAtLevel(7, "TExtractsAddSubscriptionsUIConnector.SubmitChangesInternal: importing Row into FSubmissionDT..."); FSubmissionDT.ImportRow(FInspectDT[0]); } else { // The partner already has this Subscription: add the partner to the ResponseTable // TLogging.LogAtLevel(7, "TExtractsAddSubscriptionsUIConnector.SubmitChangesInternal: won't add Subscription to Partner with PartnerKey " + ExtractRow.PartnerKey.ToString()); PartnerTable = PPartnerAccess.LoadByPrimaryKey(ExtractRow.PartnerKey, RequiredColumns2, SubmitChangesTransaction); if (FResponseDT == null) { FResponseDT = PartnerTable.Clone(); } FResponseDT.ImportRow(PartnerTable[0]); } } TLogging.LogAtLevel(7, "TExtractsAddSubscriptionsUIConnector.SubmitChangesInternal: Finished checking Partner's Subscriptions."); if (FSubmissionDT.Rows.Count > 0) { // Submit the Partners with new Subscriptions to the PSubscription Table. TProgressTracker.SetCurrentState( FProgressID, "Adding Subscriptions to " + FSubmissionDT.Rows.Count.ToString() + " Partners...", MAX_PERCENTAGE_CHECKS); // TLogging.LogAtLevel(7, "TExtractsAddSubscriptionsUIConnector.SubmitChangesInternal: " + FAsyncExecProgress.ProgressInformation); PSubscriptionAccess.SubmitChanges((PSubscriptionTable)FSubmissionDT, SubmitChangesTransaction); } else { TLogging.LogAtLevel( 7, "TExtractsAddSubscriptionsUIConnector.SubmitChangesInternal: no Subscriptions were added to Partners because all the Partners in the Extract already had this Subscription."); } SubmissionResult = TSubmitChangesResult.scrOK; } catch (Exception Exp) { TLogging.LogAtLevel(7, "TExtractsAddSubscriptionsUIConnector.SubmitChangesInternal: Exception occured, Transaction will get ROLLED BACK. Exception: " + Exp.ToString()); SubmissionResult = TSubmitChangesResult.scrError; FSubmitResult = SubmissionResult; FSubmitException = Exp; TProgressTracker.CancelJob(FProgressID); return; } }); } // if no values at response table, it needs to be created. If not creates, will raise exeption at client side. if (FResponseDT == null) { FResponseDT = new DataTable(); } TProgressTracker.FinishJob(FProgressID); FSubmitResult = SubmissionResult; }
/// <summary> /// export all the Data of the batches matching the parameters to a String /// </summary> /// <param name="requestParams">Hashtable containing the given params </param> /// <param name="exportString">Big parts of the export file as a simple String</param> /// <param name="AMessages">Additional messages to display in a messagebox</param> /// <returns>number of exported batches</returns> public Int32 ExportAllGiftBatchData( Hashtable requestParams, out String exportString, out TVerificationResultCollection AMessages) { FStringWriter = new StringWriter(); FMainDS = new GiftBatchTDS(); FDelimiter = (String)requestParams["Delimiter"]; FLedgerNumber = (Int32)requestParams["ALedgerNumber"]; FDateFormatString = (String)requestParams["DateFormatString"]; bool Summary = (bool)requestParams["Summary"]; FUseBaseCurrency = (bool)requestParams["bUseBaseCurrency"]; FDateForSummary = (DateTime)requestParams["DateForSummary"]; String NumberFormat = (String)requestParams["NumberFormat"]; FCultureInfo = new CultureInfo(NumberFormat.Equals("American") ? "en-US" : "de-DE"); FTransactionsOnly = (bool)requestParams["TransactionsOnly"]; FExtraColumns = (bool)requestParams["ExtraColumns"]; FTransaction = DBAccess.GDBAccessObj.BeginTransaction(IsolationLevel.ReadCommitted); TProgressTracker.InitProgressTracker(DomainManager.GClientID.ToString(), Catalog.GetString("Exporting Gift Batches"), 100); TProgressTracker.SetCurrentState(DomainManager.GClientID.ToString(), Catalog.GetString("Retrieving records"), 5); try { ALedgerAccess.LoadByPrimaryKey(FMainDS, FLedgerNumber, FTransaction); List <OdbcParameter> parameters = new List <OdbcParameter>(); SortedList <String, String> SQLCommandDefines = new SortedList <string, string>(); if ((bool)requestParams["IncludeUnposted"]) { SQLCommandDefines.Add("INCLUDEUNPOSTED", string.Empty); } OdbcParameter param = new OdbcParameter("LedgerNumber", OdbcType.Int); param.Value = FLedgerNumber; parameters.Add(param); Int64 recipientNumber = (Int64)requestParams["RecipientNumber"]; Int64 fieldNumber = (Int64)requestParams["FieldNumber"]; if (recipientNumber != 0) { SQLCommandDefines.Add("BYRECIPIENT", string.Empty); param = new OdbcParameter("RecipientNumber", OdbcType.Int); param.Value = recipientNumber; parameters.Add(param); } if (fieldNumber != 0) { SQLCommandDefines.Add("BYFIELD", string.Empty); param = new OdbcParameter("fieldNumber", OdbcType.Int); param.Value = fieldNumber; parameters.Add(param); } if (requestParams.ContainsKey("BatchNumberStart")) { SQLCommandDefines.Add("BYBATCHNUMBER", string.Empty); param = new OdbcParameter("BatchNumberStart", OdbcType.Int); param.Value = (Int32)requestParams["BatchNumberStart"]; parameters.Add(param); param = new OdbcParameter("BatchNumberEnd", OdbcType.Int); param.Value = (Int32)requestParams["BatchNumberEnd"]; parameters.Add(param); } else { SQLCommandDefines.Add("BYDATERANGE", string.Empty); param = new OdbcParameter("BatchDateFrom", OdbcType.DateTime); param.Value = (DateTime)requestParams["BatchDateFrom"]; parameters.Add(param); param = new OdbcParameter("BatchDateTo", OdbcType.DateTime); param.Value = (DateTime)requestParams["BatchDateTo"]; parameters.Add(param); } string sqlStatement = TDataBase.ReadSqlFile("Gift.GetGiftsToExport.sql", SQLCommandDefines); DBAccess.GDBAccessObj.Select(FMainDS, "SELECT DISTINCT PUB_a_gift_batch.* " + sqlStatement + " ORDER BY " + AGiftBatchTable.GetBatchNumberDBName(), FMainDS.AGiftBatch.TableName, FTransaction, parameters.ToArray()); TProgressTracker.SetCurrentState(DomainManager.GClientID.ToString(), Catalog.GetString("Retrieving gift records"), 10); DBAccess.GDBAccessObj.Select(FMainDS, "SELECT DISTINCT PUB_a_gift.* " + sqlStatement + " ORDER BY " + AGiftBatchTable.GetBatchNumberDBName() + ", " + AGiftTable.GetGiftTransactionNumberDBName(), FMainDS.AGift.TableName, FTransaction, parameters.ToArray()); TProgressTracker.SetCurrentState(DomainManager.GClientID.ToString(), Catalog.GetString("Retrieving gift detail records"), 15); DBAccess.GDBAccessObj.Select(FMainDS, "SELECT DISTINCT PUB_a_gift_detail.* " + sqlStatement, FMainDS.AGiftDetail.TableName, FTransaction, parameters.ToArray()); } finally { DBAccess.GDBAccessObj.RollbackTransaction(); } string BaseCurrency = FMainDS.ALedger[0].BaseCurrency; FCurrencyCode = BaseCurrency; // Depending on FUseBaseCurrency, this will be overwritten for each gift. SortedDictionary <String, AGiftSummaryRow> sdSummary = new SortedDictionary <String, AGiftSummaryRow>(); UInt32 counter = 0; // TProgressTracker Variables UInt32 GiftCounter = 0; AGiftSummaryRow giftSummary = null; FMainDS.AGiftDetail.DefaultView.Sort = AGiftDetailTable.GetLedgerNumberDBName() + "," + AGiftDetailTable.GetBatchNumberDBName() + "," + AGiftDetailTable.GetGiftTransactionNumberDBName(); foreach (AGiftBatchRow giftBatch in FMainDS.AGiftBatch.Rows) { TProgressTracker.SetCurrentState(DomainManager.GClientID.ToString(), string.Format(Catalog.GetString("Batch {0}"), giftBatch.BatchNumber), 20); GiftCounter = 0; if (!FTransactionsOnly & !Summary) { WriteGiftBatchLine(giftBatch); } foreach (AGiftRow gift in FMainDS.AGift.Rows) { if (gift.BatchNumber.Equals(giftBatch.BatchNumber) && gift.LedgerNumber.Equals(giftBatch.LedgerNumber)) { // Update progress tracker every 25 records if (++GiftCounter % 25 == 0) { TProgressTracker.SetCurrentState(DomainManager.GClientID.ToString(), string.Format(Catalog.GetString("Batch {0} - Exporting gifts"), giftBatch.BatchNumber), (GiftCounter / 25 + 4) * 5 > 90 ? 90 : (GiftCounter / 25 + 4) * 5); } DataRowView[] selectedRowViews = FMainDS.AGiftDetail.DefaultView.FindRows( new object[] { gift.LedgerNumber, gift.BatchNumber, gift.GiftTransactionNumber }); foreach (DataRowView rv in selectedRowViews) { AGiftDetailRow giftDetail = (AGiftDetailRow)rv.Row; if (Summary) { FCurrencyCode = FUseBaseCurrency ? BaseCurrency : giftBatch.CurrencyCode; decimal mapExchangeRateToBase = FUseBaseCurrency ? 1 : giftBatch.ExchangeRateToBase; counter++; String DictionaryKey = FCurrencyCode + ";" + giftBatch.BankCostCentre + ";" + giftBatch.BankAccountCode + ";" + giftDetail.RecipientKey + ";" + giftDetail.MotivationGroupCode + ";" + giftDetail.MotivationDetailCode; if (sdSummary.TryGetValue(DictionaryKey, out giftSummary)) { giftSummary.GiftTransactionAmount += giftDetail.GiftTransactionAmount; giftSummary.GiftAmount += giftDetail.GiftAmount; } else { giftSummary = new AGiftSummaryRow(); /* * summary_data.a_transaction_currency_c = lv_stored_currency_c * summary_data.a_bank_cost_centre_c = a_gift_batch.a_bank_cost_centre_c * summary_data.a_bank_account_code_c = a_gift_batch.a_bank_account_code_c * summary_data.a_recipient_key_n = a_gift_detail.p_recipient_key_n * summary_data.a_motivation_group_code_c = a_gift_detail.a_motivation_group_code_c * summary_data.a_motivation_detail_code_c = a_gift_detail.a_motivation_detail_code_c * summary_data.a_exchange_rate_to_base_n = lv_exchange_rate_n * summary_data.a_gift_type_c = a_gift_batch.a_gift_type_c */ giftSummary.CurrencyCode = FCurrencyCode; giftSummary.BankCostCentre = giftBatch.BankCostCentre; giftSummary.BankAccountCode = giftBatch.BankAccountCode; giftSummary.RecipientKey = giftDetail.RecipientKey; giftSummary.MotivationGroupCode = giftDetail.MotivationGroupCode; giftSummary.MotivationDetailCode = giftDetail.MotivationDetailCode; giftSummary.GiftTransactionAmount = giftDetail.GiftTransactionAmount; giftSummary.GiftAmount = giftDetail.GiftAmount; sdSummary.Add(DictionaryKey, giftSummary); } //overwrite always because we want to have the last giftSummary.ExchangeRateToBase = mapExchangeRateToBase; } else // not summary { WriteGiftLine(gift, giftDetail); } } } } } if (Summary) { TProgressTracker.SetCurrentState(DomainManager.GClientID.ToString(), Catalog.GetString("Export Summary"), 95); bool first = true; foreach (KeyValuePair <string, AGiftSummaryRow> kvp in sdSummary) { if (!FTransactionsOnly && first) { WriteGiftBatchSummaryLine(kvp.Value); first = false; } WriteGiftSummaryLine(kvp.Value); } } TProgressTracker.SetCurrentState(DomainManager.GClientID.ToString(), Catalog.GetString("Gift batch export successful"), 100); TProgressTracker.FinishJob(DomainManager.GClientID.ToString()); exportString = FStringWriter.ToString(); AMessages = FMessages; return(FMainDS.AGiftBatch.Count); }
public static bool DeleteConference(Int64 AConferenceKey, out TVerificationResultCollection AVerificationResult) { TVerificationResultCollection VerificationResult = null; TProgressTracker.InitProgressTracker(DomainManager.GClientID.ToString(), Catalog.GetString("Deleting conference"), 100); TDBTransaction Transaction = new TDBTransaction(); TDataBase db = DBAccess.Connect("DeleteConference"); bool SubmissionOK = false; db.WriteTransaction(ref Transaction, ref SubmissionOK, delegate { try { string[] TableNames = new string[] { PcAttendeeTable.GetTableDBName(), PcConferenceCostTable.GetTableDBName(), PcConferenceOptionTable.GetTableDBName(), PcConferenceVenueTable.GetTableDBName(), PcDiscountTable.GetTableDBName(), PcEarlyLateTable.GetTableDBName(), PcExtraCostTable.GetTableDBName(), PcGroupTable.GetTableDBName(), PcSupplementTable.GetTableDBName() }; OdbcParameter[] ConferenceParameter = new OdbcParameter[] { new OdbcParameter("conferencekey", OdbcType.BigInt) }; ConferenceParameter[0].Value = AConferenceKey; int Progress = 0; foreach (string Table in TableNames) { TProgressTracker.SetCurrentState(DomainManager.GClientID.ToString(), Catalog.GetString("Deleting: ") + Table, 10 * Progress); Transaction.DataBaseObj.ExecuteNonQuery( String.Format("DELETE FROM PUB_{0} WHERE pc_conference_key_n = ?", Table), Transaction, ConferenceParameter); Progress++; } TProgressTracker.SetCurrentState(DomainManager.GClientID.ToString(), Catalog.GetString("Deleting: Conference"), 90); PcConferenceAccess.DeleteByPrimaryKey(AConferenceKey, Transaction); if (TProgressTracker.GetCurrentState(DomainManager.GClientID.ToString()).CancelJob == false) { SubmissionOK = true; } TProgressTracker.FinishJob(DomainManager.GClientID.ToString()); } catch (Exception e) { TLogging.Log(e.ToString()); VerificationResult = new TVerificationResultCollection(); VerificationResult.Add(new TVerificationResult( "Problems deleting conference " + AConferenceKey.ToString("0000000000"), e.Message, "Cannot delete conference", string.Empty, TResultSeverity.Resv_Critical, Guid.Empty)); TProgressTracker.CancelJob(DomainManager.GClientID.ToString()); } }); AVerificationResult = VerificationResult; return(SubmissionOK); }
public static bool ResetDatabase(string AZippedNewDatabaseData) { TDataBase DBConnectionObj = null; List <string> tables = TTableList.GetDBNames(); bool SubmissionResult = false; TDBTransaction ReadWriteTransaction = new TDBTransaction(); SortedList <int, string> CurrencyPerLedger = new SortedList <int, string>(); string ClientID = "ClientID"; try { ClientID = DomainManager.GClientID.ToString(); } catch (Exception) { } try { // Open a separate DB Connection for the importing of the data... DBConnectionObj = DBAccess.Connect("ExportAllTables"); // ...and start a DB Transaction on that separate DB Connection DBConnectionObj.WriteTransaction(ref ReadWriteTransaction, ref SubmissionResult, delegate { try { TProgressTracker.InitProgressTracker(ClientID, Catalog.GetString("Restoring Database..."), tables.Count + 3); tables.Reverse(); // ignore s_session table, to avoid locking during the restore tables.Remove("s_session"); TProgressTracker.SetCurrentState(ClientID, Catalog.GetString("Deleting current data..."), 0); // need to reset connection between s_user and p_partner to avoid broken foreign key ReadWriteTransaction.DataBaseObj.ExecuteNonQuery("UPDATE pub_s_user SET p_partner_key_n = NULL", ReadWriteTransaction); foreach (string table in tables) { ReadWriteTransaction.DataBaseObj.ExecuteNonQuery("DELETE FROM pub_" + table, ReadWriteTransaction); } if (TProgressTracker.GetCurrentState(ClientID).CancelJob == true) { TProgressTracker.FinishJob(ClientID); // As SubmissionResult is still false, a DB Transaction Rollback will get // executed automatically and the Method will be exited with return value 'false'! return; } TSimpleYmlParser ymlParser = new TSimpleYmlParser(PackTools.UnzipString(AZippedNewDatabaseData)); ymlParser.ParseCaptions(); tables.Reverse(); TProgressTracker.SetCurrentState(ClientID, Catalog.GetString("Loading initial tables..."), 1); // one transaction to import the user table and user permissions. otherwise logging in will not be possible if other import fails? bool success = true; success = success && LoadTable("s_user", ymlParser, ReadWriteTransaction, ref CurrencyPerLedger); success = success && LoadTable("s_module", ymlParser, ReadWriteTransaction, ref CurrencyPerLedger); success = success && LoadTable("s_user_module_access_permission", ymlParser, ReadWriteTransaction, ref CurrencyPerLedger); success = success && LoadTable("s_system_defaults", ymlParser, ReadWriteTransaction, ref CurrencyPerLedger); success = success && LoadTable("s_system_status", ymlParser, ReadWriteTransaction, ref CurrencyPerLedger); // make sure we have the correct database version TFileVersionInfo serverExeInfo = new TFileVersionInfo(TSrvSetting.ApplicationVersion); ReadWriteTransaction.DataBaseObj.ExecuteNonQuery(String.Format( "UPDATE PUB_s_system_defaults SET s_default_value_c = '{0}' WHERE s_default_code_c = 'CurrentDatabaseVersion'", serverExeInfo.ToString()), ReadWriteTransaction); if (!success) { // As SubmissionResult is still TSubmitChangesResult.scrError, a DB Transaction Rollback will get // executed automatically and the Method will be exited with return value 'false'! return; } if (TProgressTracker.GetCurrentState(ClientID).CancelJob == true) { TProgressTracker.FinishJob(ClientID); // As SubmissionResult is still false, a DB Transaction Rollback will get // executed automatically and the Method will be exited with return value 'false'! return; } tables.Remove("s_user"); tables.Remove("s_module"); tables.Remove("s_user_module_access_permission"); tables.Remove("s_system_defaults"); tables.Remove("s_system_status"); int tableCounter = 2; foreach (string table in tables) { TProgressTracker.SetCurrentState(ClientID, String.Format(Catalog.GetString("Loading Table {0}..."), table), tableCounter); tableCounter++; if (TProgressTracker.GetCurrentState(ClientID).CancelJob == true) { TProgressTracker.FinishJob(ClientID); // As SubmissionResult is still false, a DB Transaction Rollback will get // executed automatically and the Method will be exited with return value 'false'! return; } LoadTable(table, ymlParser, ReadWriteTransaction, ref CurrencyPerLedger); } TProgressTracker.SetCurrentState(ClientID, Catalog.GetString("Loading Sequences..."), tables.Count + 5 + 3); // set sequences appropriately, not lagging behind the imported data foreach (string seq in TTableList.GetDBSequenceNames()) { LoadSequence(seq, ymlParser, ReadWriteTransaction); } TProgressTracker.SetCurrentState(ClientID, Catalog.GetString("Finishing Restore..."), tables.Count + 5 + 4); SubmissionResult = true; // reset all cached tables TCacheableTablesManager.GCacheableTablesManager.MarkAllCachedTableNeedsRefreshing(); TProgressTracker.FinishJob(ClientID); } catch (Exception e) { TLogging.Log("Problem in ResetDatabase: " + e.ToString()); TLogging.LogStackTrace(TLoggingType.ToLogfile); throw; } }); } finally { if (DBConnectionObj != null) { DBConnectionObj.CloseDBConnection(); } } return(SubmissionResult); }
/// <summary> /// run the report /// </summary> private void Run(string ASessionID) { // need to initialize the database session TSession.InitThread(ASessionID); IsolationLevel Level; if (FParameterList.Get("IsolationLevel").ToString().ToLower() == "readuncommitted") { // for long reports, that should not take out locks; // the data does not need to be consistent or will most likely not be changed during the generation of the report Level = IsolationLevel.ReadUncommitted; } else if (FParameterList.Get("IsolationLevel").ToString().ToLower() == "repeatableread") { // for financial reports: it is important to have consistent data; e.g. for totals Level = IsolationLevel.RepeatableRead; } else if (FParameterList.Get("IsolationLevel").ToString().ToLower() == "serializable") { // for creating extracts: we need to write to the database Level = IsolationLevel.Serializable; } else { // default behaviour for normal reports Level = IsolationLevel.ReadCommitted; } FSuccess = false; TDBTransaction Transaction = null; bool SubmissionOK = false; try { DBAccess.GDBAccessObj.BeginAutoTransaction(Level, ref Transaction, ref SubmissionOK, delegate { if (FDatacalculator.GenerateResult(ref FParameterList, ref FResultList, ref FErrorMessage, ref FException)) { FSuccess = true; SubmissionOK = true; } else { TLogging.Log(FErrorMessage); } }); } catch (Exception Exc) { TLogging.Log("Problem calculating report: " + Exc.ToString()); TLogging.Log(Exc.StackTrace, TLoggingType.ToLogfile); FSuccess = false; FErrorMessage = Exc.Message; FException = Exc; } if (TDBExceptionHelper.IsTransactionSerialisationException(FException)) { // do nothing - we want this exception to bubble up } else if (FException is Exception && FException.InnerException is EOPDBException) { EOPDBException DbExc = (EOPDBException)FException.InnerException; if (DbExc.InnerException is Exception) { if (DbExc.InnerException is PostgresException) { PostgresException PgExc = (PostgresException)DbExc.InnerException; if (PgExc.SqlState == "57014") // SQL statement timeout problem { FErrorMessage = Catalog.GetString( "Error - Database took too long to respond. Try different parameters to return fewer results."); } } else { FErrorMessage = DbExc.InnerException.Message; } FException = null; } } TProgressTracker.FinishJob(FProgressID); }
/// <summary> /// export all the Data of the batches matching the parameters to an Excel file /// </summary> /// <param name="ALedgerNumber"></param> /// <param name="ABatchNumberStart"></param> /// <param name="ABatchNumberEnd"></param> /// <param name="ABatchDateFrom"></param> /// <param name="ABatchDateTo"></param> /// <param name="ADateFormatString"></param> /// <param name="ASummary"></param> /// <param name="AUseBaseCurrency"></param> /// <param name="ADateForSummary"></param> /// <param name="ANumberFormat">American or European</param> /// <param name="ATransactionsOnly"></param> /// <param name="AExtraColumns"></param> /// <param name="ARecipientNumber"></param> /// <param name="AFieldNumber"></param> /// <param name="AIncludeUnposted"></param> /// <param name="AExportExcel">the export file as Excel file</param> /// <param name="AVerificationMessages">Additional messages to display in a messagebox</param> /// <returns>number of exported batches, -1 if cancelled, -2 if error</returns> public Int32 ExportAllGiftBatchData( Int32 ALedgerNumber, Int32 ABatchNumberStart, Int32 ABatchNumberEnd, DateTime?ABatchDateFrom, DateTime?ABatchDateTo, string ADateFormatString, bool ASummary, bool AUseBaseCurrency, DateTime?ADateForSummary, string ANumberFormat, bool ATransactionsOnly, bool AExtraColumns, Int64 ARecipientNumber, Int64 AFieldNumber, bool AIncludeUnposted, out String AExportExcel, out TVerificationResultCollection AVerificationMessages) { int ReturnGiftBatchCount = 0; AExportExcel = string.Empty; FStringWriter = new StringWriter(); FMainDS = new GiftBatchTDS(); FDelimiter = ","; FLedgerNumber = ALedgerNumber; FDateFormatString = ADateFormatString; Boolean Summary = ASummary; FUseBaseCurrency = AUseBaseCurrency; FDateForSummary = ADateForSummary; FCultureInfo = new CultureInfo(ANumberFormat.Equals("American") ? "en-US" : "de-DE"); FTransactionsOnly = ATransactionsOnly; FExtraColumns = AExtraColumns; String RecipientFilter = (ARecipientNumber != 0) ? " AND PUB_a_gift_detail.p_recipient_key_n = " + ARecipientNumber.ToString() : ""; String FieldFilter = (AFieldNumber != 0) ? " AND PUB_a_gift_detail.a_recipient_ledger_number_n = " + AFieldNumber.ToString() : ""; String StatusFilter = (AIncludeUnposted) ? " AND (PUB_a_gift_batch.a_batch_status_c = 'Posted' OR PUB_a_gift_batch.a_batch_status_c = 'Unposted')" : " AND PUB_a_gift_batch.a_batch_status_c = 'Posted'"; if (ABatchNumberStart == ABatchNumberEnd) { StatusFilter = ""; } TDataBase db = DBAccess.Connect("ExportAllGiftBatchData"); try { db.ReadTransaction( ref FTransaction, delegate { try { myStringHelper.CurrencyFormatTable = db.SelectDT("SELECT * FROM PUB_a_currency", "a_currency", FTransaction); ALedgerAccess.LoadByPrimaryKey(FMainDS, FLedgerNumber, FTransaction); String BatchRangeFilter = (ABatchNumberStart > -1) ? " AND (PUB_a_gift_batch.a_batch_number_i >= " + ABatchNumberStart.ToString() + " AND PUB_a_gift_batch.a_batch_number_i <= " + ABatchNumberEnd.ToString() + ")" : ""; // If I've specified a BatchRange, I can't also have a DateRange: String DateRangeFilter = (BatchRangeFilter == "") ? " AND (PUB_a_gift_batch.a_gl_effective_date_d >= '" + ABatchDateFrom.Value.ToString("yyyy-MM-dd") + "' AND PUB_a_gift_batch.a_gl_effective_date_d <= '" + ABatchDateTo.Value.ToString("yyyy-MM-dd") + "')" : ""; string StatementCore = " FROM PUB_a_gift_batch, PUB_a_gift, PUB_a_gift_detail" + " WHERE PUB_a_gift_batch.a_ledger_number_i = " + FLedgerNumber + RecipientFilter + FieldFilter + DateRangeFilter + BatchRangeFilter + StatusFilter + " AND PUB_a_gift.a_ledger_number_i = PUB_a_gift_batch.a_ledger_number_i" + " AND PUB_a_gift.a_batch_number_i = PUB_a_gift_batch.a_batch_number_i" + " AND PUB_a_gift_detail.a_ledger_number_i = PUB_a_gift_batch.a_ledger_number_i" + " AND PUB_a_gift_detail.a_batch_number_i = PUB_a_gift_batch.a_batch_number_i" + " AND PUB_a_gift_detail.a_gift_transaction_number_i = PUB_a_gift.a_gift_transaction_number_i"; string sqlStatement = "SELECT DISTINCT PUB_a_gift_batch.* " + StatementCore + " ORDER BY " + AGiftBatchTable.GetBatchNumberDBName(); TProgressTracker.SetCurrentState(DomainManager.GClientID.ToString(), Catalog.GetString("Retrieving gift batch records"), 5); if (TProgressTracker.GetCurrentState(DomainManager.GClientID.ToString()).CancelJob == true) { TProgressTracker.FinishJob(DomainManager.GClientID.ToString()); throw new ApplicationException(Catalog.GetString("Export of Batches was cancelled by user")); } db.Select(FMainDS, sqlStatement, FMainDS.AGiftBatch.TableName, FTransaction ); TProgressTracker.SetCurrentState(DomainManager.GClientID.ToString(), Catalog.GetString("Retrieving gift records"), 10); if (TProgressTracker.GetCurrentState(DomainManager.GClientID.ToString()).CancelJob == true) { TProgressTracker.FinishJob(DomainManager.GClientID.ToString()); throw new ApplicationException(Catalog.GetString("Export of Batches was cancelled by user")); } sqlStatement = "SELECT DISTINCT PUB_a_gift.* " + StatementCore + " ORDER BY " + AGiftBatchTable.GetBatchNumberDBName() + ", " + AGiftTable.GetGiftTransactionNumberDBName(); db.Select(FMainDS, sqlStatement, FMainDS.AGift.TableName, FTransaction); TProgressTracker.SetCurrentState(DomainManager.GClientID.ToString(), Catalog.GetString("Retrieving gift detail records"), 15); if (TProgressTracker.GetCurrentState(DomainManager.GClientID.ToString()).CancelJob == true) { TProgressTracker.FinishJob(DomainManager.GClientID.ToString()); throw new ApplicationException(Catalog.GetString("Export of Batches was cancelled by user")); } sqlStatement = "SELECT DISTINCT PUB_a_gift_detail.* " + StatementCore; db.Select(FMainDS, sqlStatement, FMainDS.AGiftDetail.TableName, FTransaction); } catch (Exception ex) { TLogging.LogException(ex, Utilities.GetMethodSignature()); throw; } }); TProgressTracker.InitProgressTracker(DomainManager.GClientID.ToString(), Catalog.GetString("Exporting Gift Batches"), 100); TProgressTracker.SetCurrentState(DomainManager.GClientID.ToString(), Catalog.GetString("Retrieving records"), 5); string BaseCurrency = FMainDS.ALedger[0].BaseCurrency; FCurrencyCode = BaseCurrency; // Depending on FUseBaseCurrency, this will be overwritten for each gift. SortedDictionary <String, AGiftSummaryRow> sdSummary = new SortedDictionary <String, AGiftSummaryRow>(); UInt32 counter = 0; // TProgressTracker Variables UInt32 GiftCounter = 0; AGiftSummaryRow giftSummary = null; FMainDS.AGiftDetail.DefaultView.Sort = AGiftDetailTable.GetLedgerNumberDBName() + "," + AGiftDetailTable.GetBatchNumberDBName() + "," + AGiftDetailTable.GetGiftTransactionNumberDBName(); foreach (AGiftBatchRow giftBatch in FMainDS.AGiftBatch.Rows) { if (TProgressTracker.GetCurrentState(DomainManager.GClientID.ToString()).CancelJob == true) { TProgressTracker.FinishJob(DomainManager.GClientID.ToString()); throw new ApplicationException(Catalog.GetString("Export of Batches was cancelled by user")); } ReturnGiftBatchCount++; TProgressTracker.SetCurrentState(DomainManager.GClientID.ToString(), string.Format(Catalog.GetString("Batch {0}"), giftBatch.BatchNumber), 20); GiftCounter = 0; if (!FTransactionsOnly & !Summary) { WriteGiftBatchLine(giftBatch); } foreach (AGiftRow gift in FMainDS.AGift.Rows) { if (gift.BatchNumber.Equals(giftBatch.BatchNumber) && gift.LedgerNumber.Equals(giftBatch.LedgerNumber)) { if (TProgressTracker.GetCurrentState(DomainManager.GClientID.ToString()).CancelJob == true) { TProgressTracker.FinishJob(DomainManager.GClientID.ToString()); throw new ApplicationException(Catalog.GetString("Export of Batches was cancelled by user")); } // Update progress tracker every 25 records if (++GiftCounter % 25 == 0) { TProgressTracker.SetCurrentState(DomainManager.GClientID.ToString(), string.Format(Catalog.GetString("Batch {0} - Exporting gifts"), giftBatch.BatchNumber), (GiftCounter / 25 + 4) * 5 > 90 ? 90 : (GiftCounter / 25 + 4) * 5); } DataRowView[] selectedRowViews = FMainDS.AGiftDetail.DefaultView.FindRows( new object[] { gift.LedgerNumber, gift.BatchNumber, gift.GiftTransactionNumber }); foreach (DataRowView rv in selectedRowViews) { AGiftDetailRow giftDetail = (AGiftDetailRow)rv.Row; if (Summary) { FCurrencyCode = FUseBaseCurrency ? BaseCurrency : giftBatch.CurrencyCode; decimal mapExchangeRateToBase = FUseBaseCurrency ? 1 : giftBatch.ExchangeRateToBase; counter++; String DictionaryKey = FCurrencyCode + ";" + giftBatch.BankCostCentre + ";" + giftBatch.BankAccountCode + ";" + giftDetail.RecipientKey + ";" + giftDetail.MotivationGroupCode + ";" + giftDetail.MotivationDetailCode; if (sdSummary.TryGetValue(DictionaryKey, out giftSummary)) { giftSummary.GiftTransactionAmount += giftDetail.GiftTransactionAmount; giftSummary.GiftAmount += giftDetail.GiftAmount; } else { giftSummary = new AGiftSummaryRow(); /* * summary_data.a_transaction_currency_c = lv_stored_currency_c * summary_data.a_bank_cost_centre_c = a_gift_batch.a_bank_cost_centre_c * summary_data.a_bank_account_code_c = a_gift_batch.a_bank_account_code_c * summary_data.a_recipient_key_n = a_gift_detail.p_recipient_key_n * summary_data.a_motivation_group_code_c = a_gift_detail.a_motivation_group_code_c * summary_data.a_motivation_detail_code_c = a_gift_detail.a_motivation_detail_code_c * summary_data.a_exchange_rate_to_base_n = lv_exchange_rate_n * summary_data.a_gift_type_c = a_gift_batch.a_gift_type_c */ giftSummary.CurrencyCode = FCurrencyCode; giftSummary.BankCostCentre = giftBatch.BankCostCentre; giftSummary.BankAccountCode = giftBatch.BankAccountCode; giftSummary.RecipientKey = giftDetail.RecipientKey; giftSummary.MotivationGroupCode = giftDetail.MotivationGroupCode; giftSummary.MotivationDetailCode = giftDetail.MotivationDetailCode; giftSummary.GiftTransactionAmount = giftDetail.GiftTransactionAmount; giftSummary.GiftAmount = giftDetail.GiftAmount; sdSummary.Add(DictionaryKey, giftSummary); } //overwrite always because we want to have the last giftSummary.ExchangeRateToBase = mapExchangeRateToBase; } else // not summary { WriteGiftLine(gift, giftDetail); } } } } } if (Summary) { TProgressTracker.SetCurrentState(DomainManager.GClientID.ToString(), Catalog.GetString("Export Summary"), 95); bool first = true; foreach (KeyValuePair <string, AGiftSummaryRow> kvp in sdSummary) { if (!FTransactionsOnly && first) { WriteGiftBatchSummaryLine(kvp.Value); first = false; } WriteGiftSummaryLine(kvp.Value); } } TProgressTracker.SetCurrentState(DomainManager.GClientID.ToString(), Catalog.GetString("Gift batch export successful"), 100); TProgressTracker.FinishJob(DomainManager.GClientID.ToString()); } catch (ApplicationException) { //Show cancel condition ReturnGiftBatchCount = -1; TProgressTracker.CancelJob(DomainManager.GClientID.ToString()); } catch (Exception ex) { TLogging.Log(ex.ToString()); //Show error condition ReturnGiftBatchCount = -2; FMessages.Add(new TVerificationResult( "Exporting Gift Batches Terminated Unexpectedly", ex.Message, "An unexpected error occurred during the export of gift batches", string.Empty, TResultSeverity.Resv_Critical, Guid.Empty)); TProgressTracker.CancelJob(DomainManager.GClientID.ToString()); } if (ReturnGiftBatchCount > 0) { MemoryStream mstream = new MemoryStream(); if (TCsv2Xml.CSV2ExcelStream(FStringWriter.ToString(), mstream, FDelimiter, "giftbatch")) { AExportExcel = Convert.ToBase64String(mstream.ToArray()); } } AVerificationMessages = FMessages; return(ReturnGiftBatchCount); } // ExportAllGiftBatchData
/// <summary> /// export all the Data of the batches array list to a String /// </summary> /// <param name="batches"></param> /// <param name="requestParams"></param> /// <param name="exportString"></param> /// <returns>false if batch does not exist at all</returns> public bool ExportAllGLBatchData(ref ArrayList batches, Hashtable requestParams, out String exportString) { FStringWriter = new StringWriter(); FMainDS = new GLBatchTDS(); FDelimiter = (String)requestParams["Delimiter"]; FLedgerNumber = (Int32)requestParams["ALedgerNumber"]; FDateFormatString = (String)requestParams["DateFormatString"]; FSummary = (bool)requestParams["Summary"]; FUseBaseCurrency = (bool)requestParams["bUseBaseCurrency"]; FBaseCurrency = (String)requestParams["BaseCurrency"]; FDateForSummary = (DateTime)requestParams["DateForSummary"]; String NumberFormat = (String)requestParams["NumberFormat"]; FCultureInfo = new CultureInfo(NumberFormat.Equals("American") ? "en-US" : "de-DE"); FTransactionsOnly = (bool)requestParams["TransactionsOnly"]; FDontSummarize = (bool)requestParams["bDontSummarize"]; FDontSummarizeAccount = (String)requestParams["DontSummarizeAccount"]; SortedDictionary <String, AJournalSummaryRow> sdSummary = new SortedDictionary <String, AJournalSummaryRow>(); TDBTransaction Transaction = DBAccess.GDBAccessObj.BeginTransaction(IsolationLevel.ReadCommitted); UInt32 TProgressCounter = 0; UInt32 TProgressJournalCounter = 0; TProgressTracker.InitProgressTracker(DomainManager.GClientID.ToString(), Catalog.GetString("Exporting GL Batches"), 100); TProgressTracker.SetCurrentState(DomainManager.GClientID.ToString(), Catalog.GetString("Retrieving records"), 10); while (batches.Count > 0) { Int32 ABatchNumber = (Int32)batches[0]; ABatchAccess.LoadByPrimaryKey(FMainDS, FLedgerNumber, ABatchNumber, Transaction); AJournalAccess.LoadViaABatch(FMainDS, FLedgerNumber, ABatchNumber, Transaction); foreach (AJournalRow journal in FMainDS.AJournal.Rows) { if (journal.BatchNumber.Equals(ABatchNumber) && journal.LedgerNumber.Equals(FLedgerNumber)) { ATransactionAccess.LoadViaAJournal(FMainDS, journal.LedgerNumber, journal.BatchNumber, journal.JournalNumber, Transaction); } } foreach (ATransactionRow trans in FMainDS.ATransaction.Rows) { if (trans.BatchNumber.Equals(ABatchNumber) && trans.LedgerNumber.Equals(FLedgerNumber)) { ATransAnalAttribAccess.LoadViaATransaction(FMainDS, trans.LedgerNumber, trans.BatchNumber, trans.JournalNumber, trans.TransactionNumber, Transaction); } } batches.RemoveAt(0); } DBAccess.GDBAccessObj.RollbackTransaction(); UInt32 counter = 0; AJournalSummaryRow journalSummary = null; foreach (ABatchRow batch in FMainDS.ABatch.Rows) { TProgressCounter = 0; TProgressTracker.SetCurrentState(DomainManager.GClientID.ToString(), String.Format(Catalog.GetString("Batch {0}"), batch.BatchNumber), 20); if (!FTransactionsOnly & !FSummary) { WriteBatchLine(batch); } //foreach (AJournalRow journal in journalDS.AJournal.Rows) foreach (AJournalRow journal in FMainDS.AJournal.Rows) { if (journal.BatchNumber.Equals(batch.BatchNumber) && journal.LedgerNumber.Equals(batch.LedgerNumber)) { TProgressJournalCounter = 0; TProgressTracker.SetCurrentState(DomainManager.GClientID.ToString(), String.Format(Catalog.GetString("Batch {0}, Journal {1}"), batch.BatchNumber, journal.JournalNumber), (TProgressCounter / 25 + 4) * 5 > 90 ? 90 : (TProgressCounter / 25 + 4) * 5); if (FSummary) { String mapCurrency = FUseBaseCurrency ? FBaseCurrency : journal.TransactionCurrency; decimal mapExchangeRateToBase = FUseBaseCurrency ? 1 : journal.ExchangeRateToBase; if (!sdSummary.TryGetValue(mapCurrency, out journalSummary)) { journalSummary = new AJournalSummaryRow(); sdSummary.Add(mapCurrency, journalSummary); } //overwrite always because we want to have the last journalSummary.ExchangeRateToBase = mapExchangeRateToBase; journalSummary.TransactionCurrency = mapCurrency; } else { if (!FTransactionsOnly) { WriteJournalLine(journal); } } FMainDS.ATransaction.DefaultView.Sort = ATransactionTable.GetTransactionNumberDBName(); FMainDS.ATransaction.DefaultView.RowFilter = String.Format("{0}={1} and {2}={3} and {4}={5}", ATransactionTable.GetLedgerNumberDBName(), journal.LedgerNumber, ATransactionTable.GetBatchNumberDBName(), journal.BatchNumber, ATransactionTable.GetJournalNumberDBName(), journal.JournalNumber); foreach (DataRowView dv in FMainDS.ATransaction.DefaultView) { TProgressJournalCounter++; if (++TProgressCounter % 25 == 0) { TProgressTracker.SetCurrentState(DomainManager.GClientID.ToString(), String.Format(Catalog.GetString("Batch {0}, Journal {1} - {2}"), batch.BatchNumber, journal.JournalNumber, TProgressJournalCounter), (TProgressCounter / 25 + 4) * 5 > 90 ? 90 : (TProgressCounter / 25 + 4) * 5); } ATransactionRow transaction = (ATransactionRow)dv.Row; if (FSummary) { ATransactionSummaryRow transactionSummary; counter++; String DictionaryKey = transaction.CostCentreCode + ";" + transaction.AccountCode; int signum = transaction.DebitCreditIndicator ? 1 : -1; bool bDontSummarizeAccount = FDontSummarize && FDontSummarizeAccount != null && FDontSummarizeAccount.Length > 0 && transaction.AccountCode.Equals(FDontSummarizeAccount); if (bDontSummarizeAccount) { DictionaryKey += ";" + counter.ToString("X"); } if (journalSummary.TransactionSummaries.TryGetValue(DictionaryKey, out transactionSummary)) { transactionSummary.TransactionAmount += signum * transaction.TransactionAmount; transactionSummary.AmountInBaseCurrency += signum * transaction.AmountInBaseCurrency; } else { transactionSummary = new ATransactionSummaryRow(); transactionSummary.CostCentreCode = transaction.CostCentreCode; transactionSummary.AccountCode = transaction.AccountCode; transactionSummary.TransactionAmount = signum * transaction.TransactionAmount; transactionSummary.AmountInBaseCurrency = signum * transaction.AmountInBaseCurrency; if (bDontSummarizeAccount) { transactionSummary.Narrative = transaction.Narrative; transactionSummary.Reference = transaction.Reference; } else { transactionSummary.Narrative = summarizedData; transactionSummary.Reference = ""; } journalSummary.TransactionSummaries.Add(DictionaryKey, transactionSummary); } } else { WriteTransactionLine(transaction); } } } } } if (FSummary) { TProgressTracker.SetCurrentState(DomainManager.GClientID.ToString(), Catalog.GetString("Summarising"), 95); //To simplify matters this is always written even if there are no batches if (!FTransactionsOnly) { // no batch summary line if only transactions are to be exported WriteBatchSummaryLine(); } foreach (KeyValuePair <string, AJournalSummaryRow> kvp in sdSummary) { if (!FTransactionsOnly) { // no journal summary line if only transactions are to be exported WriteJournalSummaryLine(kvp.Value); } foreach (KeyValuePair <string, ATransactionSummaryRow> kvpt in kvp.Value.TransactionSummaries) { WriteTransactionSummaryLine(kvpt.Value); } } } exportString = FStringWriter.ToString(); TProgressTracker.SetCurrentState(DomainManager.GClientID.ToString(), Catalog.GetString("GL batch export successful"), 100); TProgressTracker.FinishJob(DomainManager.GClientID.ToString()); return(true); }